qrhigles2.cpp 96.5 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
/****************************************************************************
**
** 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 "qrhigles2_p.h"
#include <QWindow>
#include <QOffscreenSurface>
#include <QOpenGLContext>
Laszlo Agocs's avatar
Laszlo Agocs committed
41
#include <QtGui/private/qopenglextensions_p.h>
42 43 44 45 46
#include <qmath.h>

QT_BEGIN_NAMESPACE

/*
Laszlo Agocs's avatar
Laszlo Agocs committed
47 48 49 50 51 52 53
  OpenGL ES 2.0 (3.0) + GLSL 100/120 backend. Binding vertex attribute
  locations and decomposing uniform buffers into uniforms (as expected by the
  GLSL 1xx shader generated by SPIRV-Cross) are handled transparently to the
  application via the reflection data (QShaderDescription). Textures and
  buffers feature no special logic, it's all just glTexSubImage2D and
  glBufferSubData (with "dynamic" buffers set to GL_DYNAMIC_DRAW). The
  swapchain and the associated renderbuffer for depth-stencil will be dummies
54 55 56 57 58 59
  since we have no control over the underlying buffers here. While we try to
  keep this backend clean GLES 2.0, some GL(ES) 3.0 features like multisample
  renderbuffers and blits are used when available. However, other GLES 3.0+
  features, such as uniform buffers, are highly undesirable and are unlikely to
  be supported ever, due to their instability on mobile/embedded GLES
  implementations.
60 61
*/

Laszlo Agocs's avatar
Laszlo Agocs committed
62 63 64
/*!
    \class QRhiGles2InitParams
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
65 66
    \brief OpenGL specific initialization parameters.

67 68 69
    An OpenGL-based QRhi needs an already created QOffscreenSurface at minimum.
    Additionally, while optional, it is recommended that the QWindow the first
    QRhiSwapChain will target is passed in as well.
Laszlo Agocs's avatar
Laszlo Agocs committed
70 71

    \badcode
72
        QOffscreenSurface *fallbackSurface = QRhiGles2InitParams::newFallbackSurface();
Laszlo Agocs's avatar
Laszlo Agocs committed
73 74
        QRhiGles2InitParams params;
        params.fallbackSurface = fallbackSurface;
75
        params.window = window;
Laszlo Agocs's avatar
Laszlo Agocs committed
76 77 78
        rhi = QRhi::create(QRhi::OpenGLES2, &params);
    \endcode

79 80 81
    By default QRhi creates a QOpenGLContext on its own. The QSurfaceFormat for
    this context is based on what was set via
    QSurfaceFormat::setDefaultSurfaceFormat().
Laszlo Agocs's avatar
Laszlo Agocs committed
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    \note The depth and stencil buffer sizes are set automatically to 24 and 8
    when no size was explicitly set for these buffers in the default surface
    format.

    This approach works well in most cases, included threaded scenarios, where
    there is a dedicated QRhi for each rendering thread. As there will be a
    QOpenGLContext for each QRhi, the OpenGL context requirements (a context
    can only be current on one thread) are satisfied. The implicitly created
    context is destroyed automatically together with the QRhi.

    A QOffscreenSurface has to be specified in \l fallbackSurface. In order to
    prevent mistakes in threaded situations, this is never created
    automatically by the QRhi since, like QWindow, QOffscreenSurface can only
    be created on the gui/main thread.

    As a convenience, applications can use newFallbackSurface() which creates
    and returns a QOffscreenSurface that is compatible with the QOpenGLContext
    that is going to be created by the QRhi afterwards. Note that the ownership
    of the returned QOffscreenSurface is transfered to the caller and the QRhi
    will not destroy it.
103

Laszlo Agocs's avatar
Laszlo Agocs committed
104 105 106
    \note QRhiSwapChain can only target QWindow instances that have their
    surface type set to QSurface::OpenGLSurface.

107
    \note \l window is optional. It is recommended to specify it whenever
Laszlo Agocs's avatar
Laszlo Agocs committed
108 109 110 111 112 113
    possible, in order to avoid problems on multi-adapter and multi-screen
    systems. When \l window is not set, the very first
    QOpenGLContext::makeCurrent() happens with \l fallbackSurface which may be
    an invisible window on some platforms (for example, Windows) and that may
    trigger unexpected problems in some cases.

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
    \section2 Working with existing OpenGL contexts

    When interoperating with another graphics engine, it may be necessary to
    get a QRhi instance that uses the same OpenGL context. This can be achieved
    by passing a pointer to a QRhiGles2NativeHandles to QRhi::create(). The
    \l{QRhiGles2NativeHandles::context}{context} must be set to a non-null
    value.

    An alternative approach is to create a QOpenGLContext that
    \l{QOpenGLContext::setShareContext()}{shares resources} with the other
    engine's context and passing in that context via QRhiGles2NativeHandles.

    The QRhi does not take ownership of the QOpenGLContext passed in via
    QRhiGles2NativeHandles.
 */

/*!
    \fn QOffscreenSurface *QRhiGles2InitParams::newFallbackSurface()

    \return a new QOffscreenSurface that can be used with a QRhi by passing it
    via a QRhiGles2InitParams.

    The \l{QOffscreenSurface::format()}{format} is adjusted as appropriate in
    order to avoid having problems afterwards due to an incompatible context
    and surface.

    \note This function must only be called on the gui/main thread.

    \note It is the application's responsibility to destroy the returned
    QOffscreenSurface on the gui/main thread once the associated QRhi has been
    destroyed. The QRhi will not destroy the QOffscreenSurface.
Laszlo Agocs's avatar
Laszlo Agocs committed
145 146 147 148 149
 */

/*!
    \class QRhiGles2NativeHandles
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
150
    \brief Holds the OpenGL context used by the QRhi.
Laszlo Agocs's avatar
Laszlo Agocs committed
151 152 153 154 155
 */

/*!
    \class QRhiGles2TextureNativeHandles
    \inmodule QtRhi
Laszlo Agocs's avatar
Laszlo Agocs committed
156
    \brief Holds the OpenGL texture object that is backing a QRhiTexture instance.
Laszlo Agocs's avatar
Laszlo Agocs committed
157 158
 */

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
#ifndef GL_BGRA
#define GL_BGRA                           0x80E1
#endif

#ifndef GL_R8
#define GL_R8                             0x8229
#endif

#ifndef GL_R16
#define GL_R16                            0x822A
#endif

#ifndef GL_RED
#define GL_RED                            0x1903
#endif

Laszlo Agocs's avatar
Laszlo Agocs committed
175 176 177 178 179 180 181 182
#ifndef GL_RGBA32F
#define GL_RGBA32F                        0x8814
#endif

#ifndef GL_RGBA16F
#define GL_RGBA16F                        0x881A
#endif

183 184 185 186 187 188 189 190
#ifndef GL_DEPTH_COMPONENT16
#define GL_DEPTH_COMPONENT16              0x81A5
#endif

#ifndef GL_DEPTH_COMPONENT32F
#define GL_DEPTH_COMPONENT32F             0x8CAC
#endif

191 192 193 194
#ifndef GL_PRIMITIVE_RESTART_FIXED_INDEX
#define GL_PRIMITIVE_RESTART_FIXED_INDEX  0x8D69
#endif

195 196 197 198
#ifndef GL_FRAMEBUFFER_SRGB
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#endif

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 227 228 229 230 231
static QSurfaceFormat qrhigles2_effectiveFormat()
{
    QSurfaceFormat fmt = QSurfaceFormat::defaultFormat();

    if (fmt.depthBufferSize() == -1)
        fmt.setDepthBufferSize(24);
    if (fmt.stencilBufferSize() == -1)
        fmt.setStencilBufferSize(8);

    return fmt;
}

QOffscreenSurface *QRhiGles2InitParams::newFallbackSurface()
{
    QSurfaceFormat fmt = qrhigles2_effectiveFormat();

    // To resolve all fields in the format as much as possible, create a context.
    // This may be heavy, but allows avoiding BAD_MATCH on some systems.
    QOpenGLContext tempContext;
    tempContext.setFormat(fmt);
    if (tempContext.create())
        fmt = tempContext.format();
    else
        qWarning("QRhiGles2: Failed to create temporary context");

    QOffscreenSurface *s = new QOffscreenSurface;
    s->setFormat(fmt);
    s->create();

    return s;
}

QRhiGles2::QRhiGles2(QRhiGles2InitParams *params, QRhiGles2NativeHandles *importDevice)
232
    : ofr(this)
233
{
234
    fallbackSurface = params->fallbackSurface;
235 236 237 238 239 240 241 242 243 244
    maybeWindow = params->window; // may be null

    importedContext = importDevice != nullptr;
    if (importedContext) {
        ctx = importDevice->context;
        if (!ctx) {
            qWarning("No OpenGL context given, cannot import");
            importedContext = false;
        }
    }
245 246
}

247
bool QRhiGles2::ensureContext(QSurface *surface) const
248 249 250 251 252 253 254 255 256 257
{
    bool nativeWindowGone = false;
    if (surface && surface->surfaceClass() == QSurface::Window && !surface->surfaceHandle()) {
        surface = fallbackSurface;
        nativeWindowGone = true;
    }

    if (!surface)
        surface = fallbackSurface;

258 259
    if (needsMakeCurrent)
        needsMakeCurrent = false;
260
    else if (!nativeWindowGone && QOpenGLContext::currentContext() == ctx && (surface == fallbackSurface || ctx->surface() == surface))
261
        return true;
262

263
    if (!ctx->makeCurrent(surface)) {
264
        qWarning("QRhiGles2: Failed to make context current. Expect bad things to happen.");
265 266 267 268
        return false;
    }

    return true;
269 270
}

271
bool QRhiGles2::create(QRhi::Flags flags)
272
{
273
    Q_UNUSED(flags);
274 275
    Q_ASSERT(fallbackSurface);

276
    const QSurfaceFormat effectiveFormat = qrhigles2_effectiveFormat();
Laszlo Agocs's avatar
Laszlo Agocs committed
277

278 279
    if (!importedContext) {
        ctx = new QOpenGLContext;
280
        ctx->setFormat(effectiveFormat);
281 282 283 284 285 286 287 288
        if (!ctx->create()) {
            qWarning("QRhiGles2: Failed to create context");
            delete ctx;
            ctx = nullptr;
            return false;
        }
    }

289
    if (!ensureContext(maybeWindow ? maybeWindow : fallbackSurface)) // see 'window' discussion in QRhiGles2InitParams comments
290
        return false;
291

Laszlo Agocs's avatar
Laszlo Agocs committed
292
    f = static_cast<QOpenGLExtensions *>(ctx->extraFunctions());
293 294 295 296 297 298

    const char *vendor = reinterpret_cast<const char *>(f->glGetString(GL_VENDOR));
    const char *renderer = reinterpret_cast<const char *>(f->glGetString(GL_RENDERER));
    const char *version = reinterpret_cast<const char *>(f->glGetString(GL_VERSION));
    if (vendor && renderer && version)
        qDebug("OpenGL VENDOR: %s RENDERER: %s VERSION: %s", vendor, renderer, version);
299 300 301 302 303 304

    GLint n = 0;
    f->glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &n);
    supportedCompressedFormats.resize(n);
    if (n > 0)
        f->glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, supportedCompressedFormats.data());
Laszlo Agocs's avatar
Laszlo Agocs committed
305

306 307
    f->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &caps.maxTextureSize);

Laszlo Agocs's avatar
Laszlo Agocs committed
308 309
    caps.msaaRenderBuffer = f->hasOpenGLExtension(QOpenGLExtensions::FramebufferMultisample)
            && f->hasOpenGLExtension(QOpenGLExtensions::FramebufferBlit);
310

311 312 313
    caps.npotTexture = f->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures);
    caps.npotTextureRepeat = f->hasOpenGLFeature(QOpenGLFunctions::NPOTTextureRepeat);

314
    const QSurfaceFormat actualFormat = ctx->format();
315
    if (actualFormat.renderableType() == QSurfaceFormat::OpenGLES)
316 317 318 319 320 321 322
        caps.fixedIndexPrimitiveRestart = actualFormat.version() >= qMakePair(3, 0);
    else
        caps.fixedIndexPrimitiveRestart = actualFormat.version() >= qMakePair(4, 3);

    if (caps.fixedIndexPrimitiveRestart)
        f->glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);

323 324
    caps.bgraExternalFormat = f->hasOpenGLExtension(QOpenGLExtensions::BGRATextureFormat);
    caps.bgraInternalFormat = caps.bgraExternalFormat && actualFormat.renderableType() == QSurfaceFormat::OpenGLES;
325 326
    caps.r8Format = f->hasOpenGLFeature(QOpenGLFunctions::TextureRGFormats);
    caps.r16Format = f->hasOpenGLExtension(QOpenGLExtensions::Sized16Formats);
Laszlo Agocs's avatar
Laszlo Agocs committed
327
    caps.floatFormats = actualFormat.version() >= qMakePair(3, 0);
328
    caps.depthTexture = actualFormat.version() >= qMakePair(3, 0);
Laszlo Agocs's avatar
Laszlo Agocs committed
329

330
    caps.srgbCapableDefaultFramebuffer = f->hasOpenGLExtension(QOpenGLExtensions::SRGBFrameBuffer);
331

332 333
    nativeHandlesStruct.context = ctx;

334
    return true;
335 336 337 338 339 340 341 342 343 344
}

void QRhiGles2::destroy()
{
    if (!f)
        return;

    ensureContext();
    executeDeferredReleases();

Laszlo Agocs's avatar
gl: rsh  
Laszlo Agocs committed
345 346 347 348 349 350
    if (!importedContext) {
        delete ctx;
        ctx = nullptr;
    }

    f = nullptr;
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
}

void QRhiGles2::executeDeferredReleases()
{
    for (int i = releaseQueue.count() - 1; i >= 0; --i) {
        const QRhiGles2::DeferredReleaseEntry &e(releaseQueue[i]);
        switch (e.type) {
        case QRhiGles2::DeferredReleaseEntry::Buffer:
            f->glDeleteBuffers(1, &e.buffer.buffer);
            break;
        case QRhiGles2::DeferredReleaseEntry::Pipeline:
            f->glDeleteProgram(e.pipeline.program);
            break;
        case QRhiGles2::DeferredReleaseEntry::Texture:
            f->glDeleteTextures(1, &e.texture.texture);
            break;
        case QRhiGles2::DeferredReleaseEntry::RenderBuffer:
            f->glDeleteRenderbuffers(1, &e.renderbuffer.renderbuffer);
            break;
        case QRhiGles2::DeferredReleaseEntry::TextureRenderTarget:
            f->glDeleteFramebuffers(1, &e.textureRenderTarget.framebuffer);
            break;
        default:
Laszlo Agocs's avatar
gl: rsh  
Laszlo Agocs committed
374
            Q_UNREACHABLE();
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
            break;
        }
        releaseQueue.removeAt(i);
    }
}

QVector<int> QRhiGles2::supportedSampleCounts() const
{
    return { 1 };
}

QRhiSwapChain *QRhiGles2::createSwapChain()
{
    return new QGles2SwapChain(this);
}

QRhiBuffer *QRhiGles2::createBuffer(QRhiBuffer::Type type, QRhiBuffer::UsageFlags usage, int size)
{
    return new QGles2Buffer(this, type, usage, size);
}

int QRhiGles2::ubufAlignment() const
{
    return 256;
}

bool QRhiGles2::isYUpInFramebuffer() const
{
    return true;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
406 407 408 409 410
bool QRhiGles2::isYUpInNDC() const
{
    return true;
}

411 412 413 414 415
QMatrix4x4 QRhiGles2::clipSpaceCorrMatrix() const
{
    return QMatrix4x4(); // identity
}

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
static inline GLenum toGlCompressedTextureFormat(QRhiTexture::Format format, QRhiTexture::Flags flags)
{
    const bool srgb = flags.testFlag(QRhiTexture::sRGB);
    switch (format) {
    case QRhiTexture::BC1:
        return srgb ? 0x8C4C : 0x83F0;
    case QRhiTexture::BC3:
        return srgb ? 0x8C4E : 0x83F2;
    case QRhiTexture::BC5:
        return srgb ? 0x8C4F : 0x83F3;

    case QRhiTexture::ETC2_RGB8:
        return srgb ? 0x9275 : 0x9274;
    case QRhiTexture::ETC2_RGB8A1:
        return srgb ? 0x9277 : 0x9276;
    case QRhiTexture::ETC2_RGBA8:
        return srgb ? 0x9279 : 0x9278;

    case QRhiTexture::ASTC_4x4:
        return srgb ? 0x93D0 : 0x93B0;
    case QRhiTexture::ASTC_5x4:
        return srgb ? 0x93D1 : 0x93B1;
    case QRhiTexture::ASTC_5x5:
        return srgb ? 0x93D2 : 0x93B2;
    case QRhiTexture::ASTC_6x5:
        return srgb ? 0x93D3 : 0x93B3;
    case QRhiTexture::ASTC_6x6:
        return srgb ? 0x93D4 : 0x93B4;
    case QRhiTexture::ASTC_8x5:
        return srgb ? 0x93D5 : 0x93B5;
    case QRhiTexture::ASTC_8x6:
        return srgb ? 0x93D6 : 0x93B6;
    case QRhiTexture::ASTC_8x8:
        return srgb ? 0x93D7 : 0x93B7;
    case QRhiTexture::ASTC_10x5:
        return srgb ? 0x93D8 : 0x93B8;
    case QRhiTexture::ASTC_10x6:
        return srgb ? 0x93D9 : 0x93B9;
    case QRhiTexture::ASTC_10x8:
        return srgb ? 0x93DA : 0x93BA;
    case QRhiTexture::ASTC_10x10:
        return srgb ? 0x93DB : 0x93BB;
    case QRhiTexture::ASTC_12x10:
        return srgb ? 0x93DC : 0x93BC;
    case QRhiTexture::ASTC_12x12:
        return srgb ? 0x93DD : 0x93BD;

    default:
        return 0; // this is reachable, just return an invalid format
    }
}

468
bool QRhiGles2::isTextureFormatSupported(QRhiTexture::Format format, QRhiTexture::Flags flags) const
469
{
470 471
    if (isCompressedFormat(format))
        return supportedCompressedFormats.contains(toGlCompressedTextureFormat(format, flags));
472

473 474 475 476
    switch (format) {
    case QRhiTexture::D16:
        Q_FALLTHROUGH();
    case QRhiTexture::D32:
477
        return caps.depthTexture;
478 479

    case QRhiTexture::BGRA8:
480 481
        return caps.bgraExternalFormat;

482
    case QRhiTexture::R8:
483
        return caps.r8Format;
484

485
    case QRhiTexture::R16:
486
        return caps.r16Format;
487

Laszlo Agocs's avatar
Laszlo Agocs committed
488 489 490 491 492
    case QRhiTexture::RGBA16F:
        Q_FALLTHROUGH();
    case QRhiTexture::RGBA32F:
        return caps.floatFormats;

493 494 495 496
    default:
        break;
    }

497 498 499
    return true;
}

Laszlo Agocs's avatar
Laszlo Agocs committed
500 501 502 503 504 505 506
bool QRhiGles2::isFeatureSupported(QRhi::Feature feature) const
{
    switch (feature) {
    case QRhi::MultisampleTexture:
        return false;
    case QRhi::MultisampleRenderBuffer:
        return caps.msaaRenderBuffer;
507 508
    case QRhi::DebugMarkers:
        return false;
509 510
    case QRhi::Timestamps:
        return false;
511 512 513 514
    case QRhi::Instancing:
        return false;
    case QRhi::CustomInstanceStepRate:
        return false;
515
    case QRhi::PrimitiveRestart:
516
        return caps.fixedIndexPrimitiveRestart;
517 518 519 520
    case QRhi::GeometryShaders:
        return false;
    case QRhi::TessellationShaders:
        return false;
521 522
    case QRhi::NonDynamicUniformBuffers:
        return true;
523 524
    case QRhi::NonFourAlignedEffectiveIndexBufferOffset:
        return true;
525 526
    case QRhi::NPOTTextureRepeat:
        return caps.npotTextureRepeat;
527 528
    case QRhi::RedOrAlpha8IsRed:
        return false;
Laszlo Agocs's avatar
Laszlo Agocs committed
529 530 531 532 533 534
    default:
        Q_UNREACHABLE();
        return false;
    }
}

535 536 537 538 539 540 541 542 543 544 545 546 547
int QRhiGles2::resourceSizeLimit(QRhi::ResourceSizeLimit limit) const
{
    switch (limit) {
    case QRhi::TextureSizeMin:
        return 1;
    case QRhi::TextureSizeMax:
        return caps.maxTextureSize;
    default:
        Q_UNREACHABLE();
        return 0;
    }
}

548
const QRhiNativeHandles *QRhiGles2::nativeHandles()
549 550 551 552
{
    return &nativeHandlesStruct;
}

553
QRhiRenderBuffer *QRhiGles2::createRenderBuffer(QRhiRenderBuffer::Type type, const QSize &pixelSize,
Laszlo Agocs's avatar
Laszlo Agocs committed
554
                                                int sampleCount, QRhiRenderBuffer::Flags flags)
555
{
Laszlo Agocs's avatar
Laszlo Agocs committed
556
    return new QGles2RenderBuffer(this, type, pixelSize, sampleCount, flags);
557 558
}

Laszlo Agocs's avatar
Laszlo Agocs committed
559 560
QRhiTexture *QRhiGles2::createTexture(QRhiTexture::Format format, const QSize &pixelSize,
                                      int sampleCount, QRhiTexture::Flags flags)
561
{
Laszlo Agocs's avatar
Laszlo Agocs committed
562
    return new QGles2Texture(this, format, pixelSize, sampleCount, flags);
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
}

QRhiSampler *QRhiGles2::createSampler(QRhiSampler::Filter magFilter, QRhiSampler::Filter minFilter,
                                      QRhiSampler::Filter mipmapMode,
                                      QRhiSampler::AddressMode u, QRhiSampler::AddressMode v, QRhiSampler::AddressMode w)
{
    return new QGles2Sampler(this, magFilter, minFilter, mipmapMode, u, v, w);
}

QRhiTextureRenderTarget *QRhiGles2::createTextureRenderTarget(const QRhiTextureRenderTargetDescription &desc,
                                                              QRhiTextureRenderTarget::Flags flags)
{
    return new QGles2TextureRenderTarget(this, desc, flags);
}

QRhiGraphicsPipeline *QRhiGles2::createGraphicsPipeline()
{
    return new QGles2GraphicsPipeline(this);
}

QRhiShaderResourceBindings *QRhiGles2::createShaderResourceBindings()
{
    return new QGles2ShaderResourceBindings(this);
}

588
void QRhiGles2::setGraphicsPipeline(QRhiCommandBuffer *cb, QRhiGraphicsPipeline *ps)
589 590 591
{
    Q_ASSERT(inPass);

592
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
Laszlo Agocs's avatar
Laszlo Agocs committed
593
    QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, ps);
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    const bool pipelineChanged = cbD->currentPipeline != ps || cbD->currentPipelineGeneration != psD->generation;

    if (pipelineChanged) {
        cbD->currentPipeline = ps;
        cbD->currentPipelineGeneration = psD->generation;

        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindGraphicsPipeline;
        cmd.args.bindGraphicsPipeline.ps = ps;
        cbD->commands.append(cmd);
    }
}

void QRhiGles2::setShaderResources(QRhiCommandBuffer *cb, QRhiShaderResourceBindings *srb,
                                   const QVector<QRhiCommandBuffer::DynamicOffset> &dynamicOffsets)
{
    Q_ASSERT(inPass);

    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
    Q_ASSERT(cbD->currentPipeline);

615
    if (!srb)
616
        srb = QRHI_RES(QGles2GraphicsPipeline, cbD->currentPipeline)->m_shaderResourceBindings;
617 618

    QGles2ShaderResourceBindings *srbD = QRHI_RES(QGles2ShaderResourceBindings, srb);
619 620 621 622 623 624 625 626 627 628 629 630
    bool hasDynamicOffsetInSrb = false;
    for (int i = 0, ie = srbD->m_bindings.count(); i != ie; ++i) {
        const QRhiShaderResourceBindingPrivate *b = QRhiShaderResourceBindingPrivate::get(&srbD->m_bindings[i]);
        switch (b->type) {
        case QRhiShaderResourceBinding::UniformBuffer:
            if (b->u.ubuf.hasDynamicOffset)
                hasDynamicOffsetInSrb = true;
            break;
        default:
            break;
        }
    }
631 632 633

    const bool srbChanged = cbD->currentSrb != srb || cbD->currentSrbGeneration != srbD->generation;

634
    if (srbChanged || hasDynamicOffsetInSrb) {
635 636 637 638
        cbD->currentSrb = srb;
        cbD->currentSrbGeneration = srbD->generation;

        QGles2CommandBuffer::Command cmd;
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        cmd.cmd = QGles2CommandBuffer::Command::BindShaderResources;
        cmd.args.bindShaderResources.ps = cbD->currentPipeline;
        cmd.args.bindShaderResources.srb = srb;
        cmd.args.bindShaderResources.dynamicOffsetCount = 0;
        if (hasDynamicOffsetInSrb) {
            const int dynCount = dynamicOffsets.count();
            if (dynCount < QGles2CommandBuffer::Command::MAX_UBUF_BINDINGS) {
                cmd.args.bindShaderResources.dynamicOffsetCount = dynCount;
                uint *p = cmd.args.bindShaderResources.dynamicOffsetPairs;
                for (int i = 0; i < dynCount; ++i) {
                    const QRhiCommandBuffer::DynamicOffset &dynOfs(dynamicOffsets[i]);
                    *p++ = dynOfs.first;
                    *p++ = dynOfs.second;
                }
            } else {
                qWarning("Too many dynamic offsets (%d, max is %d)",
                         dynCount, QGles2CommandBuffer::Command::MAX_UBUF_BINDINGS);
            }
        }
658 659 660 661
        cbD->commands.append(cmd);
    }
}

662 663
void QRhiGles2::setVertexInput(QRhiCommandBuffer *cb, int startBinding, const QVector<QRhiCommandBuffer::VertexInput> &bindings,
                               QRhiBuffer *indexBuf, quint32 indexOffset, QRhiCommandBuffer::IndexFormat indexFormat)
664 665 666 667 668 669 670 671
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    for (int i = 0, ie = bindings.count(); i != ie; ++i) {
        QRhiBuffer *buf = bindings[i].first;
        quint32 ofs = bindings[i].second;
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
672
        Q_ASSERT(bufD->m_usage.testFlag(QRhiBuffer::VertexBuffer));
673 674 675 676 677 678 679 680 681 682 683
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindVertexBuffer;
        cmd.args.bindVertexBuffer.ps = cbD->currentPipeline;
        cmd.args.bindVertexBuffer.buffer = bufD->buffer;
        cmd.args.bindVertexBuffer.offset = ofs;
        cmd.args.bindVertexBuffer.binding = startBinding + i;
        cbD->commands.append(cmd);
    }

    if (indexBuf) {
        QGles2Buffer *ibufD = QRHI_RES(QGles2Buffer, indexBuf);
Laszlo Agocs's avatar
Laszlo Agocs committed
684
        Q_ASSERT(ibufD->m_usage.testFlag(QRhiBuffer::IndexBuffer));
685 686 687 688
        QGles2CommandBuffer::Command cmd;
        cmd.cmd = QGles2CommandBuffer::Command::BindIndexBuffer;
        cmd.args.bindIndexBuffer.buffer = ibufD->buffer;
        cmd.args.bindIndexBuffer.offset = indexOffset;
689
        cmd.args.bindIndexBuffer.type = indexFormat == QRhiCommandBuffer::IndexUInt16 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
690 691 692 693 694 695 696 697 698
        cbD->commands.append(cmd);
    }
}

void QRhiGles2::setViewport(QRhiCommandBuffer *cb, const QRhiViewport &viewport)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Viewport;
Laszlo Agocs's avatar
Laszlo Agocs committed
699 700 701 702 703 704 705
    const QVector4D r = viewport.viewport();
    cmd.args.viewport.x = r.x();
    cmd.args.viewport.y = r.y();
    cmd.args.viewport.w = r.z();
    cmd.args.viewport.h = r.w();
    cmd.args.viewport.d0 = viewport.minDepth();
    cmd.args.viewport.d1 = viewport.maxDepth();
706 707 708 709 710 711 712 713
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setScissor(QRhiCommandBuffer *cb, const QRhiScissor &scissor)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Scissor;
Laszlo Agocs's avatar
Laszlo Agocs committed
714 715 716 717 718
    const QVector4D r = scissor.scissor();
    cmd.args.scissor.x = r.x();
    cmd.args.scissor.y = r.y();
    cmd.args.scissor.w = r.z();
    cmd.args.scissor.h = r.w();
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
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setBlendConstants(QRhiCommandBuffer *cb, const QVector4D &c)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::BlendConstants;
    cmd.args.blendConstants.r = c.x();
    cmd.args.blendConstants.g = c.y();
    cmd.args.blendConstants.b = c.z();
    cmd.args.blendConstants.a = c.w();
    QRHI_RES(QGles2CommandBuffer, cb)->commands.append(cmd);
}

void QRhiGles2::setStencilRef(QRhiCommandBuffer *cb, quint32 refValue)
{
    Q_ASSERT(inPass);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::StencilRef;
    cmd.args.stencilRef.ref = refValue;
    cmd.args.stencilRef.ps = cbD->currentPipeline;
    cbD->commands.append(cmd);
}

void QRhiGles2::draw(QRhiCommandBuffer *cb, quint32 vertexCount,
                     quint32 instanceCount, quint32 firstVertex, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    Q_UNUSED(instanceCount); // no instancing
    Q_UNUSED(firstInstance);
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::Draw;
    cmd.args.draw.ps = cbD->currentPipeline;
    cmd.args.draw.vertexCount = vertexCount;
    cmd.args.draw.firstVertex = firstVertex;
    cbD->commands.append(cmd);
}

void QRhiGles2::drawIndexed(QRhiCommandBuffer *cb, quint32 indexCount,
                            quint32 instanceCount, quint32 firstIndex, qint32 vertexOffset, quint32 firstInstance)
{
    Q_ASSERT(inPass);
    Q_UNUSED(instanceCount); // no instancing
    Q_UNUSED(firstInstance);
    Q_UNUSED(vertexOffset); // no glDrawElementsBaseVertex
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);

    QGles2CommandBuffer::Command cmd;
    cmd.cmd = QGles2CommandBuffer::Command::DrawIndexed;
    cmd.args.drawIndexed.ps = cbD->currentPipeline;
    cmd.args.drawIndexed.indexCount = indexCount;
    cmd.args.drawIndexed.firstIndex = firstIndex;
    cbD->commands.append(cmd);
}

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
void QRhiGles2::debugMarkBegin(QRhiCommandBuffer *cb, const QByteArray &name)
{
    if (!debugMarkers)
        return;

    Q_UNUSED(cb);
    Q_UNUSED(name);
}

void QRhiGles2::debugMarkEnd(QRhiCommandBuffer *cb)
{
    if (!debugMarkers)
        return;

    Q_UNUSED(cb);
}

void QRhiGles2::debugMarkMsg(QRhiCommandBuffer *cb, const QByteArray &msg)
{
    if (!debugMarkers)
        return;

    Q_UNUSED(cb);
    Q_UNUSED(msg);
}

805
QRhi::FrameOpResult QRhiGles2::beginFrame(QRhiSwapChain *swapChain, QRhi::BeginFrameFlags flags)
806
{
807
    Q_UNUSED(flags);
808 809 810
    Q_ASSERT(!inFrame);

    QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
811 812 813
    if (!ensureContext(swapChainD->surface))
        return QRhi::FrameOpError;

814
    inFrame = true;
815
    currentSwapChain = swapChainD;
816

817 818 819
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
    QRHI_PROF_F(beginSwapChainFrame(swapChain));

820 821 822 823 824 825
    executeDeferredReleases();
    QRHI_RES(QGles2CommandBuffer, &swapChainD->cb)->resetState();

    return QRhi::FrameOpSuccess;
}

826
QRhi::FrameOpResult QRhiGles2::endFrame(QRhiSwapChain *swapChain, QRhi::EndFrameFlags flags)
827 828
{
    Q_ASSERT(inFrame);
829
    inFrame = false;
830 831

    QGles2SwapChain *swapChainD = QRHI_RES(QGles2SwapChain, swapChain);
832 833
    Q_ASSERT(currentSwapChain == swapChainD);

834 835 836
    if (!ensureContext(swapChainD->surface))
        return QRhi::FrameOpError;

837 838
    executeCommandBuffer(&swapChainD->cb);

839 840 841 842
    QRhiProfilerPrivate *rhiP = profilerPrivateOrNull();
    // this must be done before the swap
    QRHI_PROF_F(endSwapChainFrame(swapChain, swapChainD->frameCount + 1));

843
    if (swapChainD->surface && !flags.testFlag(QRhi::SkipPresent)) {
844
        ctx->swapBuffers(swapChainD->surface);
845 846 847
        needsMakeCurrent = true;
    } else {
        f->glFlush();
848 849
    }

850 851
    swapChainD->frameCount += 1;
    currentSwapChain = nullptr;
852 853 854
    return QRhi::FrameOpSuccess;
}

855 856
QRhi::FrameOpResult QRhiGles2::beginOffscreenFrame(QRhiCommandBuffer **cb)
{
857 858 859 860 861 862 863 864 865 866 867 868 869
    Q_ASSERT(!inFrame);

    if (!ensureContext())
        return QRhi::FrameOpError;

    inFrame = true;
    ofr.active = true;

    executeDeferredReleases();
    ofr.cbWrapper.resetState();
    *cb = &ofr.cbWrapper;

    return QRhi::FrameOpSuccess;
870 871
}

872
QRhi::FrameOpResult QRhiGles2::endOffscreenFrame()
873
{
874 875 876 877 878 879 880 881 882
    Q_ASSERT(inFrame && ofr.active);
    inFrame = false;
    ofr.active = false;

    if (!ensureContext())
        return QRhi::FrameOpError;

    executeCommandBuffer(&ofr.cbWrapper);

Laszlo Agocs's avatar
Laszlo Agocs committed
883
    return QRhi::FrameOpSuccess;
884 885
}

886 887 888
QRhi::FrameOpResult QRhiGles2::finish()
{
    Q_ASSERT(!inPass);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    if (inFrame) {
        if (ofr.active) {
            Q_ASSERT(!currentSwapChain);
            if (!ensureContext())
                return QRhi::FrameOpError;
            executeCommandBuffer(&ofr.cbWrapper);
            ofr.cbWrapper.resetCommands();
        } else {
            Q_ASSERT(currentSwapChain);
            if (!ensureContext(currentSwapChain->surface))
                return QRhi::FrameOpError;
            executeCommandBuffer(&currentSwapChain->cb);
            currentSwapChain->cb.resetCommands();
        }
    }
904 905 906
    return QRhi::FrameOpSuccess;
}

907
void QRhiGles2::enqueueResourceUpdates(QRhiCommandBuffer *cb, QRhiResourceUpdateBatch *resourceUpdates)
908
{
909
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
910 911 912 913
    QRhiResourceUpdateBatchPrivate *ud = QRhiResourceUpdateBatchPrivate::get(resourceUpdates);

    for (const QRhiResourceUpdateBatchPrivate::DynamicBufferUpdate &u : ud->dynamicBufferUpdates) {
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
914 915
        Q_ASSERT(bufD->m_type == QRhiBuffer::Dynamic);
        if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
916 917
            memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size());
        } else {
918 919 920 921 922 923 924 925
            QGles2CommandBuffer::Command cmd;
            cmd.cmd = QGles2CommandBuffer::Command::BufferSubData;
            cmd.args.bufferSubData.target = bufD->target;
            cmd.args.bufferSubData.buffer = bufD->buffer;
            cmd.args.bufferSubData.offset = u.offset;
            cmd.args.bufferSubData.size = u.data.size();
            cmd.args.bufferSubData.data = cbD->retainData(u.data);
            cbD->commands.append(cmd);
926 927 928 929 930
        }
    }

    for (const QRhiResourceUpdateBatchPrivate::StaticBufferUpload &u : ud->staticBufferUploads) {
        QGles2Buffer *bufD = QRHI_RES(QGles2Buffer, u.buf);
Laszlo Agocs's avatar
Laszlo Agocs committed
931
        Q_ASSERT(bufD->m_type != QRhiBuffer::Dynamic);
932
        Q_ASSERT(u.offset + u.data.size() <= bufD->m_size);
Laszlo Agocs's avatar
Laszlo Agocs committed
933
        if (bufD->m_usage.testFlag(QRhiBuffer::UniformBuffer)) {
Laszlo Agocs's avatar
Laszlo Agocs committed
934
            memcpy(bufD->ubuf.data() + u.offset, u.data.constData(), u.data.size());
935
        } else {
936
            QGles2CommandBuffer::Command cmd;
937 938 939 940 941 942
            cmd.cmd = QGles2CommandBuffer::Command::BufferSubData;
            cmd.args.bufferSubData.target = bufD->target;
            cmd.args.bufferSubData.buffer = bufD->buffer;
            cmd.args.bufferSubData.offset = u.offset;
            cmd.args.bufferSubData.size = u.data.size();
            cmd.args.bufferSubData.data = cbD->retainData(u.data);
943
            cbD->commands.append(cmd);
944 945 946
        }
    }

947 948 949 950
    for (const QRhiResourceUpdateBatchPrivate::TextureOp &u : ud->textureOps) {
        if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::TexUpload) {
            QGles2Texture *texD = QRHI_RES(QGles2Texture, u.upload.tex);
            const bool isCompressed = isCompressedFormat(texD->m_format);
951
            const bool isFloat = isFloatFormat(texD->m_format);
952 953 954 955 956 957 958 959 960
            const bool isCubeMap = texD->m_flags.testFlag(QRhiTexture::CubeMap);
            const GLenum faceTargetBase = isCubeMap ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
            const QVector<QRhiTextureLayer> layers = u.upload.desc.layers();
            for (int layer = 0, layerCount = layers.count(); layer != layerCount; ++layer) {
                const QRhiTextureLayer &layerDesc(layers[layer]);
                const QVector<QRhiTextureMipLevel> mipImages = layerDesc.mipImages();
                for (int level = 0, levelCount = mipImages.count(); level != levelCount; ++level) {
                    const QRhiTextureMipLevel &mipDesc(mipImages[level]);
                    const QPoint dp = mipDesc.destinationTopLeft();
961 962
                    const QByteArray rawData = mipDesc.data();
                    if (isCompressed && !rawData.isEmpty()) {
963 964 965 966 967 968 969 970 971 972 973 974 975 976
                        const QSize size = mipDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
                                                                          : mipDesc.sourceSize();
                        if (texD->specified) {
                            QGles2CommandBuffer::Command cmd;
                            cmd.cmd = QGles2CommandBuffer::Command::CompressedSubImage;
                            cmd.args.compressedSubImage.target = texD->target;
                            cmd.args.compressedSubImage.texture = texD->texture;
                            cmd.args.compressedSubImage.faceTarget = faceTargetBase + layer;
                            cmd.args.compressedSubImage.level = level;
                            cmd.args.compressedSubImage.dx = dp.x();
                            cmd.args.compressedSubImage.dy = dp.y();
                            cmd.args.compressedSubImage.w = size.width();
                            cmd.args.compressedSubImage.h = size.height();
                            cmd.args.compressedSubImage.glintformat = texD->glintformat;
977 978
                            cmd.args.compressedSubImage.size = rawData.size();
                            cmd.args.compressedSubImage.data = cbD->retainData(rawData);
979 980 981 982 983 984 985 986 987 988 989
                            cbD->commands.append(cmd);
                        } else {
                            QGles2CommandBuffer::Command cmd;
                            cmd.cmd = QGles2CommandBuffer::Command::CompressedImage;
                            cmd.args.compressedImage.target = texD->target;
                            cmd.args.compressedImage.texture = texD->texture;
                            cmd.args.compressedImage.faceTarget = faceTargetBase + layer;
                            cmd.args.compressedImage.level = level;
                            cmd.args.compressedImage.glintformat = texD->glintformat;
                            cmd.args.compressedImage.w = size.width();
                            cmd.args.compressedImage.h = size.height();
990 991
                            cmd.args.compressedImage.size = rawData.size();
                            cmd.args.compressedImage.data = cbD->retainData(rawData);
992 993
                            cbD->commands.append(cmd);
                        }
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                    } else if (isFloat && !rawData.isEmpty()) {
                        const QSize size = mipDesc.sourceSize().isEmpty() ? q->sizeForMipLevel(level, texD->m_pixelSize)
                                                                          : mipDesc.sourceSize();
                        QGles2CommandBuffer::Command cmd;
                        cmd.cmd = QGles2CommandBuffer::Command::SubImage;
                        cmd.args.subImage.target = texD->target;
                        cmd.args.subImage.texture = texD->texture;
                        cmd.args.subImage.faceTarget = faceTargetBase + layer;
                        cmd.args.subImage.level = level;
                        cmd.args.subImage.dx = dp.x();
                        cmd.args.subImage.dy = dp.y();
                        cmd.args.subImage.w = size.width();
                        cmd.args.subImage.h = size.height();
                        cmd.args.subImage.glformat = texD->glformat;
                        cmd.args.subImage.gltype = texD->gltype;
                        cmd.args.subImage.data = cbD->retainData(rawData);
                        cbD->commands.append(cmd);
                    } else if (!mipDesc.image().isNull()) {
1012 1013
                        QImage img = mipDesc.image();
                        QSize size = img.size();
1014
                        QGles2CommandBuffer::Command cmd;
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
                        cmd.cmd = QGles2CommandBuffer::Command::SubImage;
                        if (!mipDesc.sourceSize().isEmpty() || !mipDesc.sourceTopLeft().isNull()) {
                            const QPoint sp = mipDesc.sourceTopLeft();
                            if (!mipDesc.sourceSize().isEmpty())
                                size = mipDesc.sourceSize();
                            img = img.copy(sp.x(), sp.y(), size.width(), size.height());
                        }
                        cmd.args.subImage.target = texD->target;
                        cmd.args.subImage.texture = texD->texture;
                        cmd.args.subImage.faceTarget = faceTargetBase + layer;
                        cmd.args.subImage.level = level;
                        cmd.args.subImage.dx = dp.x();
                        cmd.args.subImage.dy = dp.y();
                        cmd.args.subImage.w = size.width();
                        cmd.args.subImage.h = size.height();
                        cmd.args.subImage.glformat = texD->glformat;
                        cmd.args.subImage.gltype = texD->gltype;
                        cmd.args.subImage.data = cbD->retainImage(img);
1033
                        cbD->commands.append(cmd);
1034 1035
                    } else {
                        qWarning("Invalid texture upload for %p layer=%d mip=%d", texD, layer, level);
1036 1037
                    }
                }
1038
            }
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            texD->specified = true;
        } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::TexCopy) {
            Q_ASSERT(u.copy.src && u.copy.dst);
            QGles2Texture *srcD = QRHI_RES(QGles2Texture, u.copy.src);
            QGles2Texture *dstD = QRHI_RES(QGles2Texture, u.copy.dst);

            const QSize size = u.copy.desc.pixelSize().isEmpty() ? srcD->m_pixelSize : u.copy.desc.pixelSize();
            // source offset is bottom-left
            const float sx = u.copy.desc.sourceTopLeft().x();
            const float sy = srcD->m_pixelSize.height() - (u.copy.desc.sourceTopLeft().y() + size.height() - 1);
            // destination offset is top-left
            const float dx = u.copy.desc.destinationTopLeft().x();
            const float dy = u.copy.desc.destinationTopLeft().y();

            const GLenum srcFaceTargetBase = srcD->m_flags.testFlag(QRhiTexture::CubeMap)
                    ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : srcD->target;
            const GLenum dstFaceTargetBase = dstD->m_flags.testFlag(QRhiTexture::CubeMap)
                    ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : dstD->target;
Laszlo Agocs's avatar
Laszlo Agocs committed
1057

1058 1059
            QGles2CommandBuffer::Command cmd;
            cmd.cmd = QGles2CommandBuffer::Command::CopyTex;
1060

1061 1062 1063 1064 1065
            cmd.args.copyTex.srcFaceTarget = srcFaceTargetBase + u.copy.desc.sourceLayer();
            cmd.args.copyTex.srcTexture = srcD->texture;
            cmd.args.copyTex.srcLevel = u.copy.desc.sourceLevel();
            cmd.args.copyTex.srcX = sx;
            cmd.args.copyTex.srcY = sy;
1066

1067 1068 1069 1070 1071 1072
            cmd.args.copyTex.dstTarget = dstD->target;
            cmd.args.copyTex.dstTexture = dstD->texture;
            cmd.args.copyTex.dstFaceTarget = dstFaceTargetBase + u.copy.desc.destinationLayer();
            cmd.args.copyTex.dstLevel = u.copy.desc.destinationLevel();
            cmd.args.copyTex.dstX = dx;
            cmd.args.copyTex.dstY = dy;
1073

1074 1075
            cmd.args.copyTex.w = size.width();
            cmd.args.copyTex.h = size.height();
1076

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
            cbD->commands.append(cmd);
        } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::TexRead) {
            QGles2CommandBuffer::Command cmd;
            cmd.cmd = QGles2CommandBuffer::Command::ReadPixels;
            cmd.args.readPixels.result = u.read.result;
            QGles2Texture *texD = QRHI_RES(QGles2Texture, u.read.rb.texture());
            cmd.args.readPixels.texture = texD ? texD->texture : 0;
            if (texD) {
                cmd.args.readPixels.w = texD->m_pixelSize.width();
                cmd.args.readPixels.h = texD->m_pixelSize.height();
                cmd.args.readPixels.format = texD->m_format;
                const GLenum faceTargetBase = texD->m_flags.testFlag(QRhiTexture::CubeMap)
                        ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : texD->target;
                cmd.args.readPixels.readTarget = faceTargetBase + u.read.rb.layer();
                cmd.args.readPixels.level = u.read.rb.level();
            }
            cbD->commands.append(cmd);
        } else if (u.type == QRhiResourceUpdateBatchPrivate::TextureOp::TexMipGen) {
            QGles2CommandBuffer::Command cmd;
            cmd.cmd = QGles2CommandBuffer::Command::GenMip;
            QGles2Texture *texD = QRHI_RES(QGles2Texture, u.mipgen.tex);
            cmd.args.genMip.target = texD->target;
            cmd.args.genMip.texture = texD->texture;
            cbD->commands.append(cmd);
1101
        }
Laszlo Agocs's avatar
Laszlo Agocs committed
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 1196 1197 1198 1199 1200 1201 1202 1203 1204 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 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    ud->free();
}

static inline GLenum toGlTopology(QRhiGraphicsPipeline::Topology t)
{
    switch (t) {
    case QRhiGraphicsPipeline::Triangles:
        return GL_TRIANGLES;
    case QRhiGraphicsPipeline::TriangleStrip:
        return GL_TRIANGLE_STRIP;
    case QRhiGraphicsPipeline::Lines:
        return GL_LINES;
    case QRhiGraphicsPipeline::LineStrip:
        return GL_LINE_STRIP;
    case QRhiGraphicsPipeline::Points:
        return GL_POINTS;
    default:
        Q_UNREACHABLE();
        return GL_TRIANGLES;
    }
}

static inline GLenum toGlCullMode(QRhiGraphicsPipeline::CullMode c)
{
    switch (c) {
    case QRhiGraphicsPipeline::Front:
        return GL_FRONT;
    case QRhiGraphicsPipeline::Back:
        return GL_BACK;
    default:
        Q_UNREACHABLE();
        return GL_BACK;
    }
}

static inline GLenum toGlFrontFace(QRhiGraphicsPipeline::FrontFace f)
{
    switch (f) {
    case QRhiGraphicsPipeline::CCW:
        return GL_CCW;
    case QRhiGraphicsPipeline::CW:
        return GL_CW;
    default:
        Q_UNREACHABLE();
        return GL_CCW;
    }
}

static inline GLenum toGlBlendFactor(QRhiGraphicsPipeline::BlendFactor f)
{
    switch (f) {
    case QRhiGraphicsPipeline::Zero:
        return GL_ZERO;
    case QRhiGraphicsPipeline::One:
        return GL_ONE;
    case QRhiGraphicsPipeline::SrcColor:
        return GL_SRC_COLOR;
    case QRhiGraphicsPipeline::OneMinusSrcColor:
        return GL_ONE_MINUS_SRC_COLOR;
    case QRhiGraphicsPipeline::DstColor:
        return GL_DST_COLOR;
    case QRhiGraphicsPipeline::OneMinusDstColor:
        return GL_ONE_MINUS_DST_COLOR;
    case QRhiGraphicsPipeline::SrcAlpha:
        return GL_SRC_ALPHA;
    case QRhiGraphicsPipeline::OneMinusSrcAlpha:
        return GL_ONE_MINUS_SRC_ALPHA;
    case QRhiGraphicsPipeline::DstAlpha:
        return GL_DST_ALPHA;
    case QRhiGraphicsPipeline::OneMinusDstAlpha:
        return GL_ONE_MINUS_DST_ALPHA;
    case QRhiGraphicsPipeline::ConstantColor:
        return GL_CONSTANT_COLOR;
    case QRhiGraphicsPipeline::OneMinusConstantColor:
        return GL_ONE_MINUS_CONSTANT_COLOR;
    case QRhiGraphicsPipeline::ConstantAlpha:
        return GL_CONSTANT_ALPHA;
    case QRhiGraphicsPipeline::OneMinusConstantAlpha:
        return GL_ONE_MINUS_CONSTANT_ALPHA;
    case QRhiGraphicsPipeline::SrcAlphaSaturate:
        return GL_SRC_ALPHA_SATURATE;
    case QRhiGraphicsPipeline::Src1Color:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::OneMinusSrc1Color:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::Src1Alpha:
        Q_FALLTHROUGH();
    case QRhiGraphicsPipeline::OneMinusSrc1Alpha:
        qWarning("Unsupported blend factor %d", f);
        return GL_ZERO;
    default:
        Q_UNREACHABLE();
        return GL_ZERO;
    }
}

static inline GLenum toGlBlendOp(QRhiGraphicsPipeline::BlendOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::Add:
        return GL_FUNC_ADD;
    case QRhiGraphicsPipeline::Subtract:
        return GL_FUNC_SUBTRACT;
    case QRhiGraphicsPipeline::ReverseSubtract:
        return GL_FUNC_REVERSE_SUBTRACT;
    case QRhiGraphicsPipeline::Min:
        return GL_MIN;
    case QRhiGraphicsPipeline::Max:
        return GL_MAX;
    default:
        Q_UNREACHABLE();
        return GL_FUNC_ADD;
    }
}

static inline GLenum toGlCompareOp(QRhiGraphicsPipeline::CompareOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::Never:
        return GL_NEVER;
    case QRhiGraphicsPipeline::Less:
        return GL_LESS;
    case QRhiGraphicsPipeline::Equal:
        return GL_EQUAL;
    case QRhiGraphicsPipeline::LessOrEqual:
        return GL_LEQUAL;
    case QRhiGraphicsPipeline::Greater:
        return GL_GREATER;
    case QRhiGraphicsPipeline::NotEqual:
        return GL_NOTEQUAL;
    case QRhiGraphicsPipeline::GreaterOrEqual:
        return GL_GEQUAL;
    case QRhiGraphicsPipeline::Always:
        return GL_ALWAYS;
    default:
        Q_UNREACHABLE();
        return GL_ALWAYS;
    }
}

static inline GLenum toGlStencilOp(QRhiGraphicsPipeline::StencilOp op)
{
    switch (op) {
    case QRhiGraphicsPipeline::StencilZero:
        return GL_ZERO;
    case QRhiGraphicsPipeline::Keep:
        return GL_KEEP;
    case QRhiGraphicsPipeline::Replace:
        return GL_REPLACE;
    case QRhiGraphicsPipeline::IncrementAndClamp:
        return GL_INCR;
    case QRhiGraphicsPipeline::DecrementAndClamp:
        return GL_DECR;
    case QRhiGraphicsPipeline::Invert:
        return GL_INVERT;
    case QRhiGraphicsPipeline::IncrementAndWrap:
        return GL_INCR_WRAP;
    case QRhiGraphicsPipeline::DecrementAndWrap:
        return GL_DECR_WRAP;
    default:
        Q_UNREACHABLE();
        return GL_KEEP;
    }
}

static inline GLenum toGlMinFilter(QRhiSampler::Filter f, QRhiSampler::Filter m)
{
    switch (f) {
    case QRhiSampler::Nearest:
        if (m == QRhiSampler::None)
            return GL_NEAREST;
        else
            return m == QRhiSampler::Nearest ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST_MIPMAP_LINEAR;
    case QRhiSampler::Linear:
        if (m == QRhiSampler::None)
            return GL_LINEAR;
        else
            return m == QRhiSampler::Nearest ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR;
    default:
        Q_UNREACHABLE();
        return GL_LINEAR;
    }
}

static inline GLenum toGlMagFilter(QRhiSampler::Filter f)
{
    switch (f) {
    case QRhiSampler::Nearest:
        return GL_NEAREST;
    case QRhiSampler::Linear:
        return GL_LINEAR;
    default:
        Q_UNREACHABLE();
        return GL_LINEAR;
    }
}

static inline GLenum toGlWrapMode(QRhiSampler::AddressMode m)
{
    switch (m) {
    case QRhiSampler::Repeat:
        return GL_REPEAT;
    case QRhiSampler::ClampToEdge:
        return GL_CLAMP_TO_EDGE;
    case QRhiSampler::Mirror:
        return GL_MIRRORED_REPEAT;
    case QRhiSampler::MirrorOnce:
        Q_FALLTHROUGH();
    case QRhiSampler::Border:
        qWarning("Unsupported wrap mode %d", m);
        return GL_CLAMP_TO_EDGE;
    default:
        Q_UNREACHABLE();
        return GL_CLAMP_TO_EDGE;
    }
}

void QRhiGles2::executeCommandBuffer(QRhiCommandBuffer *cb)
{
    QGles2CommandBuffer *cbD = QRHI_RES(QGles2CommandBuffer, cb);
    GLenum indexType = GL_UNSIGNED_SHORT;
    quint32 indexStride = sizeof(quint16);
    quint32 indexOffset = 0;

    for (const QGles2CommandBuffer::Command &cmd : qAsConst(cbD->commands)) {
        switch (cmd.cmd) {
        case QGles2CommandBuffer::Command::Viewport:
            f->glViewport(cmd.args.viewport.x, cmd.args.viewport.y, cmd.args.viewport.w, cmd.args.viewport.h);
            f->glDepthRangef(cmd.args.viewport.d0, cmd.args.viewport.d1);
            break;
        case QGles2CommandBuffer::Command::Scissor:
            f->glScissor(cmd.args.scissor.x, cmd.args.scissor.y, cmd.args.scissor.w, cmd.args.scissor.h);
            break;
        case QGles2CommandBuffer::Command::BlendConstants:
            f->glBlendColor(cmd.args.blendConstants.r, cmd.args.blendConstants.g, cmd.args.blendConstants.b, cmd.args.blendConstants.a);
            break;
        case QGles2CommandBuffer::Command::StencilRef:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1342 1343 1344 1345
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.stencilRef.ps);
            if (psD) {
                f->glStencilFuncSeparate(GL_FRONT, toGlCompareOp(psD->m_stencilFront.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask);
                f->glStencilFuncSeparate(GL_BACK, toGlCompareOp(psD->m_stencilBack.compareOp), cmd.args.stencilRef.ref, psD->m_stencilReadMask);
1346 1347 1348 1349 1350 1351 1352
            } else {
                qWarning("No graphics pipeline active for setStencilRef; ignored");
            }
        }
            break;
        case QGles2CommandBuffer::Command::BindVertexBuffer:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1353 1354
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.bindVertexBuffer.ps);
            if (psD) {
Laszlo Agocs's avatar
Laszlo Agocs committed
1355 1356 1357 1358
                const QVector<QRhiVertexInputBinding> bindings = psD->m_vertexInputLayout.bindings();
                const QVector<QRhiVertexInputAttribute> attributes = psD->m_vertexInputLayout.attributes();
                for (const QRhiVertexInputAttribute &a : attributes) {
                    if (a.binding() != cmd.args.bindVertexBuffer.binding)
1359 1360 1361 1362 1363
                        continue;

                    // we do not support more than one vertex buffer
                    f->glBindBuffer(GL_ARRAY_BUFFER, cmd.args.bindVertexBuffer.buffer);

Laszlo Agocs's avatar
Laszlo Agocs committed
1364
                    const int stride = bindings[a.binding()].stride();
1365 1366
                    int size = 1;
                    GLenum type = GL_FLOAT;
1367
                    bool normalize = false;
Laszlo Agocs's avatar
Laszlo Agocs committed
1368 1369
                    switch (a.format()) {
                    case QRhiVertexInputAttribute::Float4:
1370 1371 1372
                        type = GL_FLOAT;
                        size = 4;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1373
                    case QRhiVertexInputAttribute::Float3:
1374 1375 1376
                        type = GL_FLOAT;
                        size = 3;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1377
                    case QRhiVertexInputAttribute::Float2:
1378 1379 1380
                        type = GL_FLOAT;
                        size = 2;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1381
                    case QRhiVertexInputAttribute::Float:
1382 1383 1384
                        type = GL_FLOAT;
                        size = 1;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1385
                    case QRhiVertexInputAttribute::UNormByte4:
1386
                        type = GL_UNSIGNED_BYTE;
1387
                        normalize = true;
1388 1389
                        size = 4;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1390
                    case QRhiVertexInputAttribute::UNormByte2:
1391
                        type = GL_UNSIGNED_BYTE;
1392
                        normalize = true;
1393 1394
                        size = 2;
                        break;
Laszlo Agocs's avatar
Laszlo Agocs committed
1395
                    case QRhiVertexInputAttribute::UNormByte:
1396
                        type = GL_UNSIGNED_BYTE;
1397
                        normalize = true;
1398 1399 1400 1401 1402
                        size = 1;
                        break;
                    default:
                        break;
                    }
Laszlo Agocs's avatar
Laszlo Agocs committed
1403 1404
                    quint32 ofs = a.offset() + cmd.args.bindVertexBuffer.offset;
                    f->glVertexAttribPointer(a.location(), size, type, normalize, stride,
1405
                                             reinterpret_cast<const GLvoid *>(quintptr(ofs)));
Laszlo Agocs's avatar
Laszlo Agocs committed
1406
                    f->glEnableVertexAttribArray(a.location());
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
                }
            } else {
                qWarning("No graphics pipeline active for setVertexInput; ignored");
            }
        }
            break;
        case QGles2CommandBuffer::Command::BindIndexBuffer:
            indexType = cmd.args.bindIndexBuffer.type;
            indexStride = indexType == GL_UNSIGNED_SHORT ? sizeof(quint16) : sizeof(quint32);
            indexOffset = cmd.args.bindIndexBuffer.offset;
            f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cmd.args.bindIndexBuffer.buffer);
            break;
        case QGles2CommandBuffer::Command::Draw:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1421 1422 1423
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.draw.ps);
            if (psD)
                f->glDrawArrays(psD->drawMode, cmd.args.draw.firstVertex, cmd.args.draw.vertexCount);
1424 1425 1426 1427 1428 1429
            else
                qWarning("No graphics pipeline active for draw; ignored");
        }
            break;
        case QGles2CommandBuffer::Command::DrawIndexed:
        {
Laszlo Agocs's avatar
Laszlo Agocs committed
1430 1431
            QGles2GraphicsPipeline *psD = QRHI_RES(QGles2GraphicsPipeline, cmd.args.drawIndexed.ps);
            if (psD) {
1432
                quint32 ofs = cmd.args.drawIndexed.firstIndex * indexStride + indexOffset;
Laszlo Agocs's avatar
Laszlo Agocs committed
1433
                f->glDrawElements(psD->drawMode,