summaryrefslogtreecommitdiffstats
path: root/src/runtime/dragon/renderer/dragondraw.cpp
blob: 983f89289b17748113e9e4f71ecbfb72bd8ee3cd (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
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
406
407
408
409
410
411
412
413
414
415
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/****************************************************************************
**
** Copyright (C) 2015 Klaralvdalens Datakonsult AB (KDAB).
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** 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 https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "dragondraw_p.h"

#include <private/dragonattribute_p.h>
#include <private/dragoncameralens_p.h>
#include <private/dragongeometry_p.h>
#include <private/dragongeometryrenderer_p.h>
#include <private/dragonparameter_p.h>
#include <private/dragonrenderview_p.h>
#include <private/dragontexture_p.h>

#include <private/dragonglbuffer_p.h>
#include <private/dragonglshader_p.h>
#include <private/dragongltypehelpers_p.h>
#include <private/dragonopenglvertexarrayobject_p.h>

#include <private/dragonactivatedsurface_p.h>
#include <private/dragongltexture_p.h>
#include <private/dragonrenderviewjobs_p.h>

// glBufferTypes
#ifndef GL_ARRAY_BUFFER
# define GL_ARRAY_BUFFER            0x8892
#endif
#ifndef GL_UNIFORM_BUFFER
# define GL_UNIFORM_BUFFER          0x8A11
#endif
#ifndef GL_ELEMENT_ARRAY_BUFFER
# define GL_ELEMENT_ARRAY_BUFFER    0x8893
#endif
#ifndef GL_SHADER_STORAGE_BUFFER
# define GL_SHADER_STORAGE_BUFFER   0x90D2
#endif
#ifndef GL_PIXEL_PACK_BUFFER
# define GL_PIXEL_PACK_BUFFER       0x88EB
#endif
#ifndef GL_PIXEL_UNPACK_BUFFER
# define GL_PIXEL_UNPACK_BUFFER     0x88EC
#endif
#ifndef GL_DRAW_INDIRECT_BUFFER
# define GL_DRAW_INDIRECT_BUFFER    0x8F3F
#endif

QT_BEGIN_NAMESPACE

using namespace Qt3DCore;

namespace Qt3DRender {
namespace Dragon {

namespace Commands {

namespace {

template<UniformType>
void applyUniformHelper(GraphicsHelperInterface *, const ShaderUniform &, const UniformValue &)
{
    Q_ASSERT_X(false, Q_FUNC_INFO, "Uniform: Didn't provide specialized apply() implementation");
}

// TODO consider a template-only (macro-free) implementation
#define QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformTypeEnum, BaseType, Func) \
    template<> \
    void applyUniformHelper<UniformTypeEnum>(GraphicsHelperInterface * m_glHelper, \
                                             const ShaderUniform &description, \
                                             const UniformValue &value) \
    { \
        const int count = qMin(description.m_size, \
                               int(value.byteSize() / description.m_rawByteSize)); \
        m_glHelper->Func(description.m_location, count, value.constData<BaseType>()); \
    }

QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Float, float, glUniform1fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Vec2, float, glUniform2fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Vec3, float, glUniform3fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Vec4, float, glUniform4fv)

// OpenGL expects int* as values for booleans
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Bool, int, glUniform1iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::BVec2, int, glUniform2iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::BVec3, int, glUniform3iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::BVec4, int, glUniform4iv)

QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Int, int, glUniform1iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::IVec2, int, glUniform2iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::IVec3, int, glUniform3iv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::IVec4, int, glUniform4iv)

QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::UInt, uint, glUniform1uiv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::UIVec2, uint, glUniform2uiv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::UIVec3, uint, glUniform3uiv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::UIVec4, uint, glUniform4uiv)

QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat2, float, glUniformMatrix2fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat3, float, glUniformMatrix3fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat4, float, glUniformMatrix4fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat2x3, float, glUniformMatrix2x3fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat3x2, float, glUniformMatrix3x2fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat2x4, float, glUniformMatrix2x4fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat4x2, float, glUniformMatrix4x2fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat3x4, float, glUniformMatrix3x4fv)
QT3D_DRAGON_UNIFORM_TYPE_IMPL(UniformType::Mat4x3, float, glUniformMatrix4x3fv)

UniformValue standardUniformValue(StandardUniform standardUniformType,
                                  const Immutable<RenderView> &renderView,
                                  const Immutable<CameraMatrices> &cameraMatrices,
                                  const Matrix4x4 &model)
{
    auto getProjectionMatrix = [](const Immutable<CameraLens> lens) { return lens->projection(); };

    auto resolveViewport = [](const QRectF &fractionalViewport, const QSize &surfaceSize) {
        return QRectF(fractionalViewport.x() * surfaceSize.width(),
                      (1.0 - fractionalViewport.y() - fractionalViewport.height())
                          * surfaceSize.height(),
                      fractionalViewport.width() * surfaceSize.width(),
                      fractionalViewport.height() * surfaceSize.height());
    };

    switch (standardUniformType) {
    case ModelMatrix:
        return UniformValue(model);
    case ViewMatrix:
        return UniformValue(cameraMatrices->viewMatrix);
    case ProjectionMatrix:
        return UniformValue(getProjectionMatrix(renderView->cameraLens));
    case ModelViewMatrix:
        return UniformValue(cameraMatrices->viewMatrix * model);
    case ViewProjectionMatrix:
        return UniformValue(getProjectionMatrix(renderView->cameraLens) * cameraMatrices->viewMatrix);
    case ModelViewProjectionMatrix:
        return UniformValue(cameraMatrices->viewProjectionMatrix * model);
    case InverseModelMatrix:
        return UniformValue(model.inverted());
    case InverseViewMatrix:
        return UniformValue(cameraMatrices->viewMatrix.inverted());
    case InverseProjectionMatrix: {
        return UniformValue(getProjectionMatrix(renderView->cameraLens).inverted());
    }
    case InverseModelViewMatrix:
        return UniformValue((cameraMatrices->viewMatrix * model).inverted());
    case InverseViewProjectionMatrix: {
        const Matrix4x4 viewProjectionMatrix = getProjectionMatrix(renderView->cameraLens)
                                               * cameraMatrices->viewMatrix;
        return UniformValue(viewProjectionMatrix.inverted());
    }
    case InverseModelViewProjectionMatrix:
        return UniformValue((cameraMatrices->viewProjectionMatrix * model).inverted());
    case ModelNormalMatrix:
        return UniformValue(convertToQMatrix4x4(model).normalMatrix());
    case ModelViewNormalMatrix:
        return UniformValue(convertToQMatrix4x4(cameraMatrices->viewMatrix * model).normalMatrix());
    case ViewportMatrix: {
        QMatrix4x4 viewportMatrix;
        // TO DO: Implement on Matrix4x4
        viewportMatrix.viewport(resolveViewport(renderView->viewport, renderView->surfaceSize));
        return UniformValue(Matrix4x4(viewportMatrix));
    }
    case InverseViewportMatrix: {
        QMatrix4x4 viewportMatrix;
        // TO DO: Implement on Matrix4x4
        viewportMatrix.viewport(resolveViewport(renderView->viewport, renderView->surfaceSize));
        return UniformValue(Matrix4x4(viewportMatrix.inverted()));
    }
    case AspectRatio:
        return float(renderView->surfaceSize.width()) / float(renderView->surfaceSize.height());
    case Exposure:
        return UniformValue(renderView->cameraLens->exposure());
    case Gamma:
        return UniformValue(renderView->gamma);
    case Time:
        // TODO add back time
        //        return UniformValue(float(m_renderer->time() / 1000000000.0f));
        return UniformValue(0.0f);
    case EyePosition:
        return UniformValue(cameraMatrices->eyePosition);
    case SkinningPalette: {
        //        const Armature *armature = entity->renderComponent<Armature>();
        //        if (!armature) {
        //            qCWarning(Jobs, "Requesting skinningPalette uniform but no armature set on entity");
        //            return UniformValue();
        //        }
        //        return armature->skinningPaletteUniform();
        qWarning() << "WARNING: Armatures not supported in Dragon renderer";
        return UniformValue();
    }
    default:
        Q_UNREACHABLE();
        return UniformValue();
    }
}

void applyUniform(GraphicsHelperInterface *m_glHelper, const ShaderUniform &description, const UniformValue &v)
{
    const UniformType type = m_glHelper->uniformTypeFromGLType(description.m_type);

    switch (type) {
    case UniformType::Float:
        // See QTBUG-57510 and uniform_p.h
        if (v.storedType() == UniformType::Int) {
            float value = float(*v.constData<int>());
            UniformValue floatV(value);
            applyUniformHelper<UniformType::Float>(m_glHelper, description, floatV);
        } else {
            applyUniformHelper<UniformType::Float>(m_glHelper, description, v);
        }
        break;
    case UniformType::Vec2:
        applyUniformHelper<UniformType::Vec2>(m_glHelper, description, v);
        break;
    case UniformType::Vec3:
        applyUniformHelper<UniformType::Vec3>(m_glHelper, description, v);
        break;
    case UniformType::Vec4:
        applyUniformHelper<UniformType::Vec4>(m_glHelper, description, v);
        break;

    case UniformType::Double:
        applyUniformHelper<UniformType::Double>(m_glHelper, description, v);
        break;
    case UniformType::DVec2:
        applyUniformHelper<UniformType::DVec2>(m_glHelper, description, v);
        break;
    case UniformType::DVec3:
        applyUniformHelper<UniformType::DVec3>(m_glHelper, description, v);
        break;
    case UniformType::DVec4:
        applyUniformHelper<UniformType::DVec4>(m_glHelper, description, v);
        break;

    case UniformType::Sampler:
    case UniformType::Int:
        applyUniformHelper<UniformType::Int>(m_glHelper, description, v);
        break;
    case UniformType::IVec2:
        applyUniformHelper<UniformType::IVec2>(m_glHelper, description, v);
        break;
    case UniformType::IVec3:
        applyUniformHelper<UniformType::IVec3>(m_glHelper, description, v);
        break;
    case UniformType::IVec4:
        applyUniformHelper<UniformType::IVec4>(m_glHelper, description, v);
        break;

    case UniformType::UInt:
        applyUniformHelper<UniformType::UInt>(m_glHelper, description, v);
        break;
    case UniformType::UIVec2:
        applyUniformHelper<UniformType::UIVec2>(m_glHelper, description, v);
        break;
    case UniformType::UIVec3:
        applyUniformHelper<UniformType::UIVec3>(m_glHelper, description, v);
        break;
    case UniformType::UIVec4:
        applyUniformHelper<UniformType::UIVec4>(m_glHelper, description, v);
        break;

    case UniformType::Bool:
        applyUniformHelper<UniformType::Bool>(m_glHelper, description, v);
        break;
    case UniformType::BVec2:
        applyUniformHelper<UniformType::BVec2>(m_glHelper, description, v);
        break;
    case UniformType::BVec3:
        applyUniformHelper<UniformType::BVec3>(m_glHelper, description, v);
        break;
    case UniformType::BVec4:
        applyUniformHelper<UniformType::BVec4>(m_glHelper, description, v);
        break;

    case UniformType::Mat2:
        applyUniformHelper<UniformType::Mat2>(m_glHelper, description, v);
        break;
    case UniformType::Mat3:
        applyUniformHelper<UniformType::Mat3>(m_glHelper, description, v);
        break;
    case UniformType::Mat4:
        applyUniformHelper<UniformType::Mat4>(m_glHelper, description, v);
        break;
    case UniformType::Mat2x3:
        applyUniformHelper<UniformType::Mat2x3>(m_glHelper, description, v);
        break;
    case UniformType::Mat3x2:
        applyUniformHelper<UniformType::Mat3x2>(m_glHelper, description, v);
        break;
    case UniformType::Mat2x4:
        applyUniformHelper<UniformType::Mat2x4>(m_glHelper, description, v);
        break;
    case UniformType::Mat4x2:
        applyUniformHelper<UniformType::Mat4x2>(m_glHelper, description, v);
        break;
    case UniformType::Mat3x4:
        applyUniformHelper<UniformType::Mat3x4>(m_glHelper, description, v);
        break;
    case UniformType::Mat4x3:
        applyUniformHelper<UniformType::Mat4x3>(m_glHelper, description, v);
        break;

    default:
        break;
    }
}

GLenum glBufferTypes[] = {GL_ARRAY_BUFFER,
                          GL_UNIFORM_BUFFER,
                          GL_ELEMENT_ARRAY_BUFFER,
                          GL_SHADER_STORAGE_BUFFER,
                          GL_PIXEL_PACK_BUFFER,
                          GL_PIXEL_UNPACK_BUFFER,
                          GL_DRAW_INDIRECT_BUFFER};

bool bindParameters(QOpenGLContext *openGLContext,
                    GraphicsHelperInterface *graphicsHelper,
                    const Immutable<RenderView> &renderView,
                    const Immutable<CameraMatrices> &cameraMatrices,
                    const MutableContainer<GLBuffer> &glBuffers,
                    const MutableContainer<GLTexture> &glTextures,
                    int maxTextureImageUnits,
                    const Mutable<GLShader> &glShader,
                    const ValueContainer<Parameter> &parameters,
                    const Immutable<Matrix4x4> &worldTransform,
                    const ParameterNameToIdMap &parameterIds)
{
    // ParameterMap = nameId -> parameter for current command

    // Set standard uniforms
    // TODO Once we have shader graphs, we should put standard uniforms in a uniform buffer object
    // and emulate UBOs on hardware that doesn't support it, including unrolling them in the
    // shaders
    for (const auto &standardShaderUniform : glShader->standardUniforms) {
        const auto &shaderUniform = standardShaderUniform.shaderUniform;
        const auto &setter = standardShaderUniform.standardUniform;
        UniformValue uniformValue = standardUniformValue(setter, renderView, cameraMatrices, *worldTransform);
        applyUniform(graphicsHelper, shaderUniform, uniformValue);
    }

    // Keep track of the currently bound texture unit
    int unit = 0;
    // TODO: In OpenGL 4.4+, there is bindTextures(), which we could add to our graphics helpers:
    // https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTextures.xhtml
    for (const auto &shaderUniform : glShader->uniforms) { // scalars and textures
        // TODO consider returning the result of this in cases where the parameters have not changed,
        // so that we can reuse the same parameter and avoid looking it up every frame. The returned
        // result can be stored in a map in the Frame
        const auto &parameterIt = parameterIds.constFind(shaderUniform.m_nameId);
        if (parameterIt == parameterIds.cend())
            continue;

        const auto &parameterId = parameterIt.value();
        const auto &parameter = parameters[parameterId];
        const auto &uniformValue = parameter->uniformValue();

        if (uniformValue.valueType() != UniformValue::NodeId) {
            applyUniform(graphicsHelper, shaderUniform, uniformValue);
            continue;
        }

        // At this point a uniform value can only be a scalar type
        // or a Qt3DCore::QNodeId corresponding to a Texture
        // ShaderData/Buffers would be handled as UBO/SSBO and would therefore
        // not be in the default uniform block

        const QNodeId *nodeIds = uniformValue.constData<QNodeId>();
        const int uniformArraySize = uint(uniformValue.byteSize()) / sizeof(QNodeId);
        for (int i = 0; i < uniformArraySize; ++i) {
            const QNodeId texId = nodeIds[i];
            if (texId.isNull()) {
                // TODO this entire implementation is a bit fragile. Consider making UniformValue
                // store data in a more type-safe way for QNodeIds
                continue;
            }

            Q_ASSERT(glTextures.contains(texId));
            const auto &texture = glTextures[texId];
            //            Q_ASSERT(texture->openGLTexture != nullptr);

            if (texture->openGLTexture == nullptr) {
                // TODO current valid case for this is when the format is automatic, however,
                // we need to investigate where this is used and why we should skip at this point
                continue;
            }

            ShaderParameterPack::NamedTexture namedTex(shaderUniform.m_nameId, texId, i);

            UniformValue textureValue(uniformArraySize * sizeof(int), UniformValue::TextureValue);
            std::fill(textureValue.data<int>(), textureValue.data<int>() + uniformArraySize, -1);

            if (unit >= maxTextureImageUnits) {
                // TODO: Check this earlier and skip rendering completely if this is the case.
                qWarning() << "WARNING: Max number of texture units exhausted,"
                           << "GL_MAX_TEXTURE_IMAGE_UNITS:" << maxTextureImageUnits
                           << "Texture cannot be bound.";
                continue;
            }
            // NOTE: Qt3D used to have some logic to keep track of bound textures to avoid
            // re-binding. However, this introduced additional complexity and caused performance
            // problems on the CPU side. We should consider adding back some of this logic
            // if it turns out to be beneficial for performance. However, considering that
            // glBindTextures no longer uses glActiveTexture, it seems likely that there is
            // no need for this.
            texture->openGLTexture->bind(GLuint(unit));

            textureValue.data<int>()[namedTex.uniformArrayIndex] = unit;
            applyUniform(graphicsHelper, shaderUniform, textureValue);

            unit += 1;
        }
    }

    GLuint uboIndex = 0;
    for (const auto &shaderUniformBlock : glShader->uniformBlocks) {
        const auto &parameterIt = parameterIds.constFind(shaderUniformBlock.m_nameId);
        if (parameterIt == parameterIds.cend())
            continue;

        const auto &parameterId = parameterIt.value();
        const auto &parameter = parameters[parameterId];
        const auto &uniformValue = parameter->uniformValue();
        if (uniformValue.valueType() != UniformValue::NodeId) {
            // TODO might be a bit spammy to send this to the output
            qWarning()
                << "WARNING: Found UniformBlock with corresponding parameter that was not of UniformValue::NodeId type. This is not supported";
        }

        const auto &bufferId = *uniformValue.constData<QNodeId>();
        Q_ASSERT(glBuffers.contains(bufferId));
        const auto &glBuffer = glBuffers[bufferId];

        // TODO always zero, consider using other locations...
        // TODO Make sure that there's enough binding points
        const GLuint blockIndex = GLuint(shaderUniformBlock.m_index);
        const GLuint programId = glShader->shaderProgram->programId();
        graphicsHelper->bindUniformBlock(programId, blockIndex, uboIndex);
        // Needed to avoid conflict where the buffer would already be bound as a VertexArray
        const auto glType = glBufferTypes[GLBuffer::UniformBuffer];
        openGLContext->functions()->glBindBuffer(glType,
                                                                          glBuffer->bufferId());
        graphicsHelper->bindBufferBase(glType, uboIndex++, glBuffer->bufferId());
        // Buffer update to GL buffer will be done at render time
    }

    for (const auto &shaderStorageBlock : glShader->storageBlocks) {
        // TODO add support for shader storage blocks
        Q_UNUSED(shaderStorageBlock)
        qWarning() << "WARNING: Shader storage blocks are not yet supported";
    }

    // if not all data is valid, the next frame will be rendered immediately
    return true;
}

} // namespace

bool draw(const ActivatedSurface &activatedSurface,
          const Immutable<RenderView> &renderView,
          const Immutable<CameraMatrices> &cameraMatrices,
          const MutableContainer<GLBuffer> &uploadedBuffers,
          const MutableContainer<GLTexture> &uploadedTextures,
          int maxTextureImageUnits,
          const Immutable<RenderCommand> &cmd,
          const Mutable<GLShader> &glShader,
          const ValueContainer<Attribute> &attributes,
          const ValueContainer<Parameter> &parameters,
          const ValueContainer<Matrix4x4> &worldTransforms,
          const Immutable<GLVertexArrayObject> &vao)
{
    QOpenGLContext *openGLContext = activatedSurface.openGLContext();
    GraphicsHelperInterface *graphicsHelper = activatedSurface.glHelper();
    RenderCommand command = *cmd;
    // TODO consider "global state" from executeCommandSubmission
    //    bindVertexArrayObject(vao);

    // TODO consider emulated VAO
    vao->m_vao->bind();

    Q_ASSERT(glShader->shaderProgram != nullptr);
    glShader->shaderProgram->bind();

    const auto &worldTransform = worldTransforms[command.m_entity->peerId()];

    // TODO move this out and split draw into something like bindVaoAndShader, bindParameters, draw
    bindParameters(openGLContext,
                   graphicsHelper,
                   renderView,
                   cameraMatrices,
                   uploadedBuffers,
                   uploadedTextures,
                   maxTextureImageUnits,
                   glShader,
                   parameters,
                   worldTransform,
                   command.m_parameterIds);

    const auto &geometryRenderer = command.m_geometryRenderer;
    const auto &geometry = command.m_geometry;

    bool drawIndexed = false;

    // Update the draw command with what's going to be needed for the drawing
    int primitiveCount = geometryRenderer->vertexCount();
    uint estimatedCount = 0;
    uint indexAttributeCount = 0;
    GLint indexAttributeDataType = 0;
    uint indexAttributeByteOffset = 0;

    const QVector<Qt3DCore::QNodeId> attributeIds = geometry->attributes();
    for (Qt3DCore::QNodeId attributeId : attributeIds) {
        const auto &attribute = attributes[attributeId];
        switch (attribute->attributeType()) {
        case QAttribute::IndexAttribute:
            drawIndexed = true;
            indexAttributeDataType = GLTypes::glDataTypeFromAttributeDataType(
                attribute->vertexBaseType());
            indexAttributeByteOffset = attribute->byteOffset();
            indexAttributeCount = attribute->count();
            break;
        case QAttribute::DrawIndirectAttribute:
            qDebug() << "WARNING: Indirect attributes are not yet implemented.";
            break;
        case QAttribute::VertexAttribute: {
            // TODO not the nicest loop and not necessary to do this again here, consider moving
            for (const auto &shaderAttribute : glShader->attributes) {
                if (shaderAttribute.m_nameId == attribute->nameId()) {
                    estimatedCount = qMax(attribute->count(), estimatedCount);
                }
            }
            break;
        }
        default:
            Q_UNREACHABLE();
            break;
        }
    }

    if (!drawIndexed) {
        // TODO implement regular drawing again
        qDebug() << "WARNING: Only indexed drawing is currently supported in Dragon";
        return false;
    }

    if (primitiveCount == 0) {
        if (drawIndexed)
            primitiveCount = indexAttributeCount;
        else
            primitiveCount = estimatedCount;
    }

    auto primitiveType = geometryRenderer->primitiveType();
    auto primitiveRestartEnabled = geometryRenderer->primitiveRestartEnabled();
    auto restartIndexValue = geometryRenderer->restartIndexValue();
//    auto firstInstance = geometryRenderer->firstInstance();
    auto instanceCount = geometryRenderer->instanceCount();
    auto firstVertex = geometryRenderer->firstVertex();
    auto indexOffset = geometryRenderer->indexOffset();
    auto verticesPerPatch = geometryRenderer->verticesPerPatch();

    // TO DO: Add glMulti Draw variants
    if (primitiveType == QGeometryRenderer::Patches)
        graphicsHelper->setVerticesPerPatch(verticesPerPatch);

    if (primitiveRestartEnabled) {
        if (graphicsHelper->supportsFeature(GraphicsHelperInterface::PrimitiveRestart))
            graphicsHelper->enablePrimitiveRestart(restartIndexValue);
    }

    // TO DO: Add glMulti Draw variants
    if (drawIndexed) {
        graphicsHelper
            ->drawElementsInstancedBaseVertexBaseInstance(primitiveType,
                                                          primitiveCount,
                                                          indexAttributeDataType,
                                                          reinterpret_cast<void *>(quintptr(
                                                              indexAttributeByteOffset)),
                                                          instanceCount,
                                                          indexOffset,
                                                          firstVertex);
    }
    // TODO add back draw array
    //    } else {
    //        Profiling::GLTimeRecorder recorder(Profiling::DrawArray);
    //        m_submissionContext->drawArraysInstancedBaseInstance(primitiveType,
    //                                                             firstInstance,
    //                                                             primitiveCount,
    //                                                             instanceCount,
    //                                                             firstVertex);
    //    }

    vao->m_vao->release();
    glShader->shaderProgram->release();

    return true;
}

} // namespace Commands
} // namespace Dragon
} // namespace Qt3DRender

QT_END_NAMESPACE