summaryrefslogtreecommitdiff
path: root/src/render/backend/renderview.cpp
blob: 55a92d01ab3538aca589d1da7855c80e2e23af7f (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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 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 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "renderview_p.h"
#include <Qt3DRenderer/qmaterial.h>
#include <Qt3DRenderer/qopenglfilter.h>
#include <Qt3DRenderer/renderlogging.h>
#include <Qt3DRenderer/qtexture.h>
#include <Qt3DRenderer/qrendertarget.h>
#include <Qt3DRenderer/sphere.h>

#include <Qt3DRenderer/private/cameraselectornode_p.h>
#include <Qt3DRenderer/private/framegraphnode_p.h>
#include <Qt3DRenderer/private/layerfilternode_p.h>
#include <Qt3DRenderer/private/qmeshdata_p.h>
#include <Qt3DRenderer/private/meshdatamanager_p.h>
#include <Qt3DRenderer/private/qparameter_p.h>
#include <Qt3DRenderer/private/rendercameralens_p.h>
#include <Qt3DRenderer/private/rendercommand_p.h>
#include <Qt3DRenderer/private/rendereffect_p.h>
#include <Qt3DRenderer/private/renderentity_p.h>
#include <Qt3DRenderer/private/renderer_p.h>
#include <Qt3DRenderer/private/renderlayer_p.h>
#include <Qt3DRenderer/private/renderlight_p.h>
#include <Qt3DRenderer/private/renderpassfilternode_p.h>
#include <Qt3DRenderer/private/renderrenderpass_p.h>
#include <Qt3DRenderer/private/techniquefilternode_p.h>
#include <Qt3DRenderer/private/viewportnode_p.h>

#include <Qt3DRenderer/qparametermapping.h>
#include <Qt3DRenderer/qalphatest.h>
#include <Qt3DRenderer/qblendequation.h>
#include <Qt3DRenderer/qblendstate.h>
#include <Qt3DRenderer/qcullface.h>
#include <Qt3DRenderer/qdepthmask.h>
#include <Qt3DRenderer/qdepthtest.h>
#include <Qt3DRenderer/qdithering.h>
#include <Qt3DRenderer/qfrontface.h>
#include <Qt3DRenderer/qscissortest.h>
#include <Qt3DRenderer/qstenciltest.h>
#include <Qt3DRenderer/qalphacoverage.h>
#include <Qt3DRenderer/private/blendstate_p.h>

#include <Qt3DCore/qentity.h>

#include <QtGui/qsurface.h>

#include <algorithm>

#include <QDebug>

QT_BEGIN_NAMESPACE

namespace Qt3D {
namespace Render {

namespace  {

// TODO: Should we treat lack of layer data as implicitly meaning that an
// entity is in all layers?
bool isEntityInLayers(const RenderEntity *entity, const QStringList &layers)
{
    if (layers.isEmpty())
        return true;

    // TODO: find all RenderLayer components associated to node, not just the first one
    RenderLayer *renderLayer = entity->renderComponent<RenderLayer>();
    if (renderLayer) {
        Q_FOREACH (const QString &layerName, renderLayer->layers())
            if (layers.contains(layerName))
                return true;
    }

    return false;
}

} // anonymouse namespace

RenderView::StandardUniformsPFuncsHash RenderView::ms_standardUniformSetters = RenderView::initializeStandardUniformSetters();
QStringList RenderView::ms_standardAttributesNames = RenderView::initializeStandardAttributeNames();

RenderView::StandardUniformsPFuncsHash RenderView::initializeStandardUniformSetters()
{
    RenderView::StandardUniformsPFuncsHash setters;

    setters.insert(QStringLiteral("modelMatrix"), &RenderView::modelMatrix);
    setters.insert(QStringLiteral("viewMatrix"), &RenderView::viewMatrix);
    setters.insert(QStringLiteral("projectionMatrix"), &RenderView::projectionMatrix);
    setters.insert(QStringLiteral("modelView"), &RenderView::modelViewMatrix);
    setters.insert(QStringLiteral("modelViewProjection"), &RenderView::modelViewProjectionMatrix);
    setters.insert(QStringLiteral("mvp"), &RenderView::modelViewProjectionMatrix);
    setters.insert(QStringLiteral("inverseModelMatrix"), &RenderView::inverseModelMatrix);
    setters.insert(QStringLiteral("inverViewMatrix"), &RenderView::inverseViewMatrix);
    setters.insert(QStringLiteral("inverseProjectionMatrix"), &RenderView::inverseProjectionMatrix);
    setters.insert(QStringLiteral("inverseModelView"), &RenderView::inverseModelViewMatrix);
    setters.insert(QStringLiteral("inverseModelViewProjection"), &RenderView::inverseModelViewProjectionMatrix);
    setters.insert(QStringLiteral("modelNormalMatrix"), &RenderView::modelNormalMatrix);
    setters.insert(QStringLiteral("modelViewNormal"), &RenderView::modelViewNormalMatrix);
    setters.insert(QStringLiteral("viewportMatrix"), &RenderView::viewportMatrix);
    setters.insert(QStringLiteral("inverseViewportMatrix"), &RenderView::inverseViewportMatrix);

    return setters;
}

QStringList RenderView::initializeStandardAttributeNames()
{
    QStringList attributesNames;

    attributesNames << QMeshData::defaultPositionAttributeName();
    attributesNames << QMeshData::defaultTextureCoordinateAttributeName();
    attributesNames << QMeshData::defaultNormalAttributeName();
    attributesNames << QMeshData::defaultColorAttributeName();
    attributesNames << QMeshData::defaultTangentAttributeName();

    return attributesNames;
}

QUniformValue *RenderView::modelMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant(model, m_allocator);
}

QUniformValue *RenderView::viewMatrix(const QMatrix4x4 &) const
{
    return QUniformValue::fromVariant(*m_data->m_viewMatrix, m_allocator);
}

QUniformValue *RenderView::projectionMatrix(const QMatrix4x4 &) const
{
    return QUniformValue::fromVariant(m_data->m_renderCamera->projection(), m_allocator);
}

QUniformValue *RenderView::modelViewMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant(*m_data->m_viewMatrix * model, m_allocator);
}

QUniformValue *RenderView::modelViewProjectionMatrix(const QMatrix4x4 &model) const
{
    QMatrix4x4 projection;
    if (m_data->m_renderCamera)
        projection = m_data->m_renderCamera->projection();
    return QUniformValue::fromVariant(projection * *m_data->m_viewMatrix * model, m_allocator);
}

QUniformValue *RenderView::inverseModelMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant(model.inverted(), m_allocator);
}

QUniformValue *RenderView::inverseViewMatrix(const QMatrix4x4 &) const
{
    return QUniformValue::fromVariant(m_data->m_viewMatrix->inverted(), m_allocator);
}

QUniformValue *RenderView::inverseProjectionMatrix(const QMatrix4x4 &) const
{
    QMatrix4x4 projection;
    if (m_data->m_renderCamera)
        projection = m_data->m_renderCamera->projection();
    return QUniformValue::fromVariant(projection.inverted(), m_allocator);
}

QUniformValue *RenderView::inverseModelViewMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant((*m_data->m_viewMatrix * model).inverted(), m_allocator);
}

QUniformValue *RenderView::inverseModelViewProjectionMatrix(const QMatrix4x4 &model) const
{
    QMatrix4x4 projection;
    if (m_data->m_renderCamera)
        projection = m_data->m_renderCamera->projection();
    return QUniformValue::fromVariant((projection * *m_data->m_viewMatrix * model).inverted(0), m_allocator);
}

QUniformValue *RenderView::modelNormalMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant(QVariant::fromValue(model.normalMatrix()), m_allocator);
}

QUniformValue *RenderView::modelViewNormalMatrix(const QMatrix4x4 &model) const
{
    return QUniformValue::fromVariant(QVariant::fromValue((*m_data->m_viewMatrix * model).normalMatrix()), m_allocator);
}

// TODO: Move this somewhere global where QGraphicsContext::setViewport() can use it too
static QRectF 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());
}

QUniformValue *RenderView::viewportMatrix(const QMatrix4x4 &model) const
{
    // TODO: Can we avoid having to pass the model matrix in to these functions?
    Q_UNUSED(model);
    QMatrix4x4 viewportMatrix;
    QSize surfaceSize = m_renderer->surface()->size();
    viewportMatrix.viewport(resolveViewport(*m_viewport, surfaceSize));
    return QUniformValue::fromVariant(QVariant::fromValue(viewportMatrix), m_allocator);

}

QUniformValue *RenderView::inverseViewportMatrix(const QMatrix4x4 &model) const
{
    Q_UNUSED(model);
    QMatrix4x4 viewportMatrix;
    QSize surfaceSize = m_renderer->surface()->size();
    viewportMatrix.viewport(resolveViewport(*m_viewport, surfaceSize));
    QMatrix4x4 inverseViewportMatrix = viewportMatrix.inverted();
    return QUniformValue::fromVariant(QVariant::fromValue(inverseViewportMatrix), m_allocator);

}

RenderView::RenderView()
    : m_renderer(Q_NULLPTR)
    , m_allocator(Q_NULLPTR)
    , m_data(Q_NULLPTR)
    , m_clearColor(Q_NULLPTR)
    , m_viewport(Q_NULLPTR)
    , m_clearBuffer(QClearBuffer::None)
    , m_commands()
{
}

RenderView::~RenderView()
{
    if (m_allocator == Q_NULLPTR) // Mainly needed for unit tests
        return;

    Q_FOREACH (RenderCommand *command, m_commands) {
        // Deallocate all uniform values of the QUniformPack of each RenderCommand
        Q_FOREACH (const QUniformValue *v, command->m_uniforms.uniforms().values())
            m_allocator->deallocate<QUniformValue>(const_cast<QUniformValue *>(v));

        if (command->m_stateSet != Q_NULLPTR) // We do not delete the RenderState as that is stored statically
            m_allocator->deallocate<RenderStateSet>(command->m_stateSet);

        // Deallocate RenderCommand
        m_allocator->deallocate<RenderCommand>(command);
    }

    // Deallocate viewMatrix
    m_allocator->deallocate<QMatrix4x4>(m_data->m_viewMatrix);
    // Deallocate viewport rect
    m_allocator->deallocate<QRectF>(m_viewport);
    // Deallocate clearColor
    m_allocator->deallocate<QColor>(m_clearColor);
    // Deallocate m_data
    m_allocator->deallocate<InnerData>(m_data);
}

// We need to overload the delete operator so that when the Renderer deletes the list of RenderViews, each RenderView
// can clear itself with the frame allocator and deletes its RenderViews
void RenderView::operator delete(void *ptr)
{
    RenderView *rView = static_cast<RenderView *>(ptr);
    if (rView != Q_NULLPTR && rView->m_allocator != Q_NULLPTR)
        rView->m_allocator->deallocateRawMemory<RenderView>(rView);
}

// Since placement new is used we need a matching operator delete, at least MSVC complains otherwise
void RenderView::operator delete(void *ptr, void *)
{
    RenderView *rView = static_cast<RenderView *>(ptr);
    if (rView != Q_NULLPTR && rView->m_allocator != Q_NULLPTR)
        rView->m_allocator->deallocateRawMemory<RenderView>(rView);
}

void RenderView::sort()
{
    // Compares the bitsetKey of the RenderCommands
    // Key[Depth | StateCost | Shader]

    std::sort(m_commands.begin(), m_commands.end());
}

// Tries to order renderCommand by shader so as to minimize shader changes
void RenderView::buildRenderCommands(RenderEntity *node)
{
    // Build renderCommand for current node
    if (isEntityInLayers(node, m_data->m_layers)) {
        RenderMesh *mesh = Q_NULLPTR;
        if (node->componentHandle<RenderMesh, 16>() != HMesh()
                && (mesh = node->renderComponent<RenderMesh>()) != Q_NULLPTR) {
            if (!mesh->meshData().isNull())
            {
                // Perform culling here
                // As shaders may be deforming, transforming the mesh
                // We might want to make that optional or dependent on an explicit bounding box item

                RenderMaterial *material = Q_NULLPTR;
                RenderEffect *effect = Q_NULLPTR;
                if ((material = node->renderComponent<RenderMaterial>()) != Q_NULLPTR)
                    effect = m_renderer->effectManager()->lookupResource(material->effect());
                RenderTechnique *technique = findTechniqueForEffect(effect);
                QList<RenderRenderPass *> passes = findRenderPassesForTechnique(technique);
                if (passes.isEmpty()) {
                    material = m_renderer->materialManager()->data(m_renderer->defaultMaterialHandle());
                    effect = m_renderer->effectManager()->data(m_renderer->defaultEffectHandle());
                    technique = m_renderer->techniqueManager()->data(m_renderer->defaultTechniqueHandle());
                    passes << m_renderer->renderPassManager()->data(m_renderer->defaultRenderPassHandle());
                }
                QHash<QString, QVariant> parameters = parametersFromMaterialEffectTechnique(material, effect, technique);

                // 1 RenderCommand per RenderPass pass on an Entity with a Mesh
                Q_FOREACH (RenderRenderPass *pass, passes) {
                    RenderCommand *command = m_allocator->allocate<RenderCommand>();
                    command->m_depth = m_data->m_eyePos.distanceToPoint(node->worldBoundingVolume()->center());
                    command->m_meshData = mesh->meshData();
                    command->m_instancesCount = 0;
                    command->m_stateSet = buildRenderStateSet(pass);
                    if (command->m_stateSet != Q_NULLPTR)
                        command->m_changeCost = m_renderer->defaultRenderState()->changeCost(command->m_stateSet);
                    setShaderAndUniforms(command, pass, parameters, *(node->worldTransform()));
                    buildSortingKey(command);
                    m_commands.append(command);
                }
            }
        }
    }

    // Traverse children
    Q_FOREACH (RenderEntity *child, node->children())
        buildRenderCommands(child);
}

const AttachmentPack &RenderView::attachmentPack() const
{
    return m_attachmentPack;
}

RenderTechnique *RenderView::findTechniqueForEffect(RenderEffect *effect)
{
    if (effect != Q_NULLPTR) {
        Q_FOREACH (const QNodeUuid &techniqueId, effect->techniques()) {
            RenderTechnique *technique = m_renderer->techniqueManager()->lookupResource(techniqueId);
            if (technique != Q_NULLPTR &&
                    *m_renderer->contextInfo() == *technique->openGLFilter()) {
                // If no techniqueFilter is present, we return the technique as it satisfies OpenGL version
                bool findMatch = (m_data->m_techniqueFilter == Q_NULLPTR || m_data->m_techniqueFilter->filters().size() == 0) ? true : false;
                if (!findMatch && technique->annotations().size() >= m_data->m_techniqueFilter->filters().size()) {
                    Q_FOREACH (const QNodeUuid &refCritId, m_data->m_techniqueFilter->filters()) {
                        RenderAnnotation *refCriterion = m_renderer->criterionManager()->lookupResource(refCritId);
                        findMatch = false;
                        Q_FOREACH (const QNodeUuid &critId, technique->annotations()) {
                            RenderAnnotation *rCrit = m_renderer->criterionManager()->lookupResource(critId);
                            if ((findMatch = (*rCrit == *refCriterion)))
                                break;
                        }
                        if (!findMatch) // No match for TechniqueFilter criterion in any of the technique's criteria
                            break;
                    }
                }
                if (findMatch) // If all criteria matched
                    return technique;
            }
        }
    }
    return Q_NULLPTR;
}

QList<RenderRenderPass *> RenderView::findRenderPassesForTechnique(RenderTechnique *technique)
{
    QList<RenderRenderPass *> passes;
    if (technique != Q_NULLPTR) {
        Q_FOREACH (const QNodeUuid &passId, technique->renderPasses()) {
            RenderRenderPass *renderPass = m_renderer->renderPassManager()->lookupResource(passId);

            if (renderPass != Q_NULLPTR) {
                bool findMatch = (m_data->m_passFilter == Q_NULLPTR || m_data->m_passFilter->filters().size() == 0) ? true : false;
                if (!findMatch && renderPass->annotations().size() >= m_data->m_passFilter->filters().size())
                {
                    Q_FOREACH (const QNodeUuid &refCritId, m_data->m_passFilter->filters()) {
                        RenderAnnotation *refCriterion = m_renderer->criterionManager()->lookupResource(refCritId);
                        findMatch = false;
                        Q_FOREACH (const QNodeUuid &critId, renderPass->annotations()) {
                            RenderAnnotation *rCrit = m_renderer->criterionManager()->lookupResource(critId);
                            if ((findMatch = (*rCrit == *refCriterion)))
                                break;
                        }
                        if (!findMatch) // No match for TechniqueFilter criterion in any of the technique's criteria
                            break;
                    }
                }
                if (findMatch)
                    passes << renderPass;
            }
        }
    }
    return passes;
}

static void addParametersForIds(QHash<QString, QVariant> *params, ParameterManager* manager,
                                const QList<QNodeUuid> &parameterIds)
{
    Q_FOREACH (const QNodeUuid &paramId, parameterIds) {
        RenderParameter *param = manager->lookupResource(paramId);
        if (param != Q_NULLPTR)
            params->insert(param->name(), param->value());
    }
}

QHash<QString, QVariant> RenderView::parametersFromMaterialEffectTechnique(RenderMaterial *material,
                                                                           RenderEffect *effect,
                                                                           RenderTechnique *technique)
{
    QHash<QString, QVariant> params;

    // Material is preferred over Effect
    // Effect is preferred over Technique
    // By filling the hash in reverse preference order, we're ensured that we preserve preference

    if (effect != Q_NULLPTR)
        addParametersForIds(&params, m_renderer->parameterManager(), effect->parameters());

    if (technique != Q_NULLPTR)
        addParametersForIds(&params, m_renderer->parameterManager(), technique->parameters());

    if (material != Q_NULLPTR)
        addParametersForIds(&params, m_renderer->parameterManager(), material->parameters());

    return params;
}

// Build a RenderStateSet from the QRenderState stored in the RenderRenderPass
RenderStateSet *RenderView::buildRenderStateSet(RenderRenderPass *pass)
{
    if (pass != Q_NULLPTR && pass->renderStates().count() > 0) {
        RenderStateSet *stateSet = m_allocator->allocate<RenderStateSet>();

        Q_FOREACH (QRenderState *renderState, pass->renderStates()) {
            if (qobject_cast<QAlphaTest *>(renderState) != Q_NULLPTR) {
                QAlphaTest *alphaTest = qobject_cast<QAlphaTest *>(renderState);
                stateSet->addState(AlphaFunc::getOrCreate(alphaTest->func(), alphaTest->clamp()));
            }
            else if (qobject_cast<QBlendEquation *>(renderState) != Q_NULLPTR) {
                QBlendEquation *blendEquation = qobject_cast<QBlendEquation *>(renderState);
                stateSet->addState(BlendEquation::getOrCreate(blendEquation->mode()));
            }
            else if (qobject_cast<QBlendState *>(renderState) != Q_NULLPTR) {
                QBlendState *blendState = qobject_cast<QBlendState *>(renderState);
                // TO DO : Handle Alpha here as weel
                stateSet->addState(BlendState::getOrCreate(blendState->srcRGB(), blendState->dstRGB()));
            }
            else if (qobject_cast<QCullFace *>(renderState) != Q_NULLPTR) {
                QCullFace *cullFace = qobject_cast<QCullFace *>(renderState);
                stateSet->addState(CullFace::getOrCreate(cullFace->mode()));
            }
            else if (qobject_cast<QDepthMask *>(renderState) != Q_NULLPTR) {
                QDepthMask *depthMask = qobject_cast<QDepthMask *>(renderState);
                stateSet->addState(DepthMask::getOrCreate(depthMask->mask()));
            }
            else if (qobject_cast<QDepthTest *>(renderState) != Q_NULLPTR) {
                QDepthTest *depthTest = qobject_cast<QDepthTest *>(renderState);
                stateSet->addState(DepthTest::getOrCreate(depthTest->func()));
            }
            else if (qobject_cast<QDithering *>(renderState) != Q_NULLPTR) {
                stateSet->addState(Dithering::getOrCreate());
            }
            else if (qobject_cast<QFrontFace *>(renderState) != Q_NULLPTR) {
                QFrontFace *frontFace = qobject_cast<QFrontFace *>(renderState);
                stateSet->addState(FrontFace::getOrCreate(frontFace->direction()));
            }
            else if (qobject_cast<QScissorTest *>(renderState) != Q_NULLPTR) {
                QScissorTest *scissorTest = qobject_cast<QScissorTest *>(renderState);
                stateSet->addState(ScissorTest::getOrCreate(scissorTest->left(),
                                                            scissorTest->bottom(),
                                                            scissorTest->width(),
                                                            scissorTest->height()));
            }
            else if (qobject_cast<QStencilTest *>(renderState) != Q_NULLPTR) {
                QStencilTest *stencilTest = qobject_cast<QStencilTest *>(renderState);
                stateSet->addState(StencilTest::getOrCreate(stencilTest->mask(),
                                                            stencilTest->func(),
                                                            stencilTest->faceMode()));
            }
            else if (qobject_cast<QAlphaCoverage *>(renderState) != Q_NULLPTR) {
                stateSet->addState(AlphaCoverage::getOrCreate());
            }
        }

        return stateSet;
    }
    return Q_NULLPTR;
}

void RenderView::setUniformValue(QUniformPack &uniformPack, const QString &name, const QVariant &value)
{
    QTexture *tex = Q_NULLPTR;
    if ((tex = value.value<Qt3D::QTexture *>()) != Q_NULLPTR) {
        uniformPack.setTexture(name, tex->uuid());
        TextureUniform *texUniform = m_allocator->allocate<TextureUniform>();
        texUniform->setTextureId(tex->uuid());
        uniformPack.setUniform(name, texUniform);
    }
    else {
        uniformPack.setUniform(name, QUniformValue::fromVariant(value, m_allocator));
    }
}

void RenderView::buildSortingKey(RenderCommand *command)
{
    // Build a bitset key depending on the SortingCriterion
    int sortCount = m_data->m_sortingCriteria.count();
    command->m_sortingType.global = 0;

    // Default sorting
    if (sortCount == 0)
        command->m_sortingType.sorts[0] = QSortCriterion::StateChangeCost;

    // Handle at most 4 filters at once
    for (int i = 0; i < sortCount && i < 4; i++) {
        SortCriterion *sC = m_renderer->sortCriterionManager()->lookupResource(m_data->m_sortingCriteria[i]);
        command->m_sortingType.sorts[i] = sC->sortType();
    }
}

void RenderView::setShaderAndUniforms(RenderCommand *command, RenderRenderPass *rPass, QHash<QString, QVariant> &parameters, const QMatrix4x4 &worldTransform)
{
    // The VAO Handle is set directly in the renderer thread so as to avoid having to use a mutex here
    // Set shader, technique, and effect by basically doing :
    // ShaderProgramManager[MaterialManager[frontentEntity->uuid()]->Effect->Techniques[TechniqueFilter->name]->RenderPasses[RenderPassFilter->name]];
    // The Renderer knows that if one of those is null, a default material / technique / effect as to be used

    // Find all RenderPasses (in order) matching values set in the RenderPassFilter
    // Get list of parameters for the Material, Effect, and Technique
    // For each ParameterBinder in the RenderPass -> create a QUniformPack
    // Once that works, improve that to try and minimize QUniformPack updates

    if (rPass != Q_NULLPTR)
    {
        // Index RenderShader by Shader UUID
        command->m_shader = m_renderer->shaderManager()->lookupHandle(rPass->shaderProgram());
        RenderShader *shader = Q_NULLPTR;
        if ((shader = m_renderer->shaderManager()->data(command->m_shader)) != Q_NULLPTR) {

            // Builds the QUniformPack, sets shader standard uniforms and store attributes name / glname bindings
            // If a parameter is defined and not found in the bindings it is assumed to be a binding of Uniform type with the glsl name
            // equals to the parameter name
            QStringList uniformNames = shader->uniformsNames();
            QStringList attributeNames = shader->attributesNames();

            // Set fragData Name and index
            // Later on we might want to relink the shader if attachments have changed
            // But for now we set them once and for all
            QHash<QString, int> fragOutputs;
            if (!m_renderTarget.isNull() && !shader->isLoaded()) {
                Q_FOREACH (const Attachment &att, m_attachmentPack.attachments()) {
                    if (att.m_type <= QRenderAttachment::ColorAttachment15)
                        fragOutputs.insert(att.m_name, att.m_type);
                }
            }

            if (!uniformNames.isEmpty() || !attributeNames.isEmpty()) {

                // Set default standard uniforms without bindings
                Q_FOREACH (const QString &uniformName, uniformNames) {
                    if (ms_standardUniformSetters.contains(uniformName))
                        command->m_uniforms.setUniform(uniformName,
                                                       (this->*ms_standardUniformSetters[uniformName])(worldTransform));
                }

                // Set default attributes
                Q_FOREACH (const QString &attributeName, attributeNames) {
                    if (ms_standardAttributesNames.contains(attributeName))
                        command->m_parameterAttributeToShaderNames[attributeName] = attributeName;
                }

                // Set uniforms and attributes explicitly binded
                Q_FOREACH (QParameterMapping *binding, rPass->bindings()) {
                    if (!parameters.contains(binding->parameterName())) {
                        if (binding->bindingType() == QParameterMapping::Attribute
                            && attributeNames.contains(binding->shaderVariableName())) {
                            command->m_parameterAttributeToShaderNames.insert(binding->parameterName(), binding->shaderVariableName());
                        } else if (binding->bindingType() == QParameterMapping::StandardUniform
                                   && uniformNames.contains(binding->shaderVariableName())
                                   && ms_standardUniformSetters.contains(binding->parameterName())) {
                            command->m_uniforms.setUniform(binding->shaderVariableName(),
                                                           (this->*ms_standardUniformSetters[binding->parameterName()])(worldTransform));
                        } else if (binding->bindingType() == QParameterMapping::FragmentOutput
                                   && fragOutputs.contains(binding->parameterName())) {
                            fragOutputs.insert(binding->shaderVariableName(), fragOutputs.take(binding->parameterName()));
                        } else {
                            qCWarning(Render::Backend) << Q_FUNC_INFO << "Trying to bind a Parameter that hasn't been defined " << binding->parameterName();
                        }
                    } else {
                        setUniformValue(command->m_uniforms, binding->shaderVariableName(), parameters.take(binding->parameterName()));
                    }
                }

                // If there are remaining parameters, those are set as uniforms
                if (!uniformNames.isEmpty() && !parameters.isEmpty()) {
                    QHash<QString, QVariant>::iterator it = parameters.begin();
                    while (it != parameters.end()) {
                        if (uniformNames.contains(it.key())) {
                            setUniformValue(command->m_uniforms, it.key(), it.value());
                            it = parameters.erase(it);
                        } else {
                            // Else param unused by current shader
                            ++it;
                        }
                    }
                }

                // Sets lights in shader
                // Maybe we should provide a flag in the shader to specify if it needs lights
                // that might save a bit of performances
                QHash<QString, int> m_countOfLightTypes;
                Q_FOREACH (const LightPair &lightPair, m_data->m_lights) {
                    RenderLight *light = m_renderer->lightManager()->data(lightPair.first);
                    if (light != Q_NULLPTR) {
                        int lightIdx = m_countOfLightTypes[light->lightBlockName()]++;

                        QHash<QString, QVariant> lightProperties = light->lightProperties();
                        lightProperties[QStringLiteral("position")] = lightPair.second.map(QVector3D());
                        Q_FOREACH (const QString &propertyName, lightProperties.keys()) {
                            QString lightShaderUniform(light->lightUniformName() + QStringLiteral("[") + QString::number(lightIdx) + QStringLiteral("].") + propertyName);
                            if (uniformNames.contains(lightShaderUniform)) {
                                command->m_uniforms.setUniform(lightShaderUniform, QUniformValue::fromVariant(lightProperties[propertyName], m_allocator));
                            }
                        }
                    }
                }
            }
            // Set frag outputs in the shaders if hash not empty
            if (!fragOutputs.empty())
                shader->setFragOutputs(fragOutputs);
        }
    }
    else {
        qCWarning(Render::Backend) << Q_FUNC_INFO << "Using default effect as none was provided";
    }
}

} // namespace Render
} // namespace Qt3D

QT_END_NAMESPACE