summaryrefslogtreecommitdiffstats
path: root/src/Runtime/api/studio3d/q3dspresentation.cpp
blob: 204b2035cc5988d9be84807953c9440eaa8a484a (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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://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 "q3dspresentation_p.h"
#include "q3dssceneelement_p.h"
#include "q3dscommandqueue_p.h"
#include "viewerqmlstreamproxy_p.h"
#include "q3dsdatainput_p.h"
#include "q3dsdataoutput_p.h"
#include "q3dsgeometry_p.h"

#include <QtCore/qdebug.h>
#include <QtCore/qsettings.h>
#include <QtCore/qcoreapplication.h>
#include <QtGui/qevent.h>

QT_BEGIN_NAMESPACE

/*!
    \class Q3DSPresentation
    \inmodule OpenGLRuntime
    \since Qt 3D Studio 2.0

    \brief Represents a Qt 3D Studio presentation.

    This class provides properties and methods for controlling a
    presentation.

    Qt 3D Studio supports multiple presentations in one project. There
    is always a main presentation and zero or more
    subpresentations. The subpresentations are composed into the
    main presentations either as contents of Qt 3D Studio layers or as
    texture maps.

    In the filesystem each presentation corresponds to one \c{.uip}
    presentation file. When present, the \c{.uia} project file ties
    these together by specifying a name for each of the
    (sub-)presentations and specifies which one is the main one.

    The \c{.uia} project also defines \l{DataInput}s and
    \l{DataOutput}s that are exported by the presentations.
    \l{DataInput}s provide a way to provide input to the presentation
    to e.g. control a timeline of a subpresentation from code.
    \c{DataOutput}s provide a way to get notified when an attribute
    is changed in the presentation by animation timeline,
    by behavior scripts or by a \l{DataInput}.

    From the API point of view Q3DSPresentation corresponds to the
    main presentation. The source property can refer either to a
    \c{.uia} or \c{.uip} file. When specifying a file with \c{.uip}
    extension and a \c{.uia} is present with the same name, the
    \c{.uia} is loaded automatically and thus sub-presentation
    information is available regardless.

    \note This class should not be instantiated directly when working with the
    C++ APIs. Q3DSSurfaceViewer and Q3DSWidget create a Q3DSPresentation
    instance implicitly. This can be queried via
    Q3DSSurfaceViewer::presentation() or Q3DSWidget::presentation().
 */

/*!
    Constructs a new Q3DSPresentation with the given \a parent.
 */
Q3DSPresentation::Q3DSPresentation(QObject *parent)
    : QObject(parent)
    , d_ptr(new Q3DSPresentationPrivate(this))
{
}

/*!
    Destructor.
 */
Q3DSPresentation::~Q3DSPresentation()
{
}

/*!
    \qmlproperty string Presentation::source

    Holds the name of the main presentation file (\c{*.uia} or
    \c{*.uip}). This may be either a local file or qrc URL.

    The names of all further assets (image files for texture maps, qml
    behavior scripts, mesh files) will be resolved relative to the
    location of the presentation, unless they use absolute paths. This
    allows bundling all assets next to the presentation in the Qt
    resource system.

    Currently set \c{variantList} property will modify which variant groups
    and tags are loaded from the presentations. See
    Q3DSPresentation::variantList property.
*/

/*!
    \property Q3DSPresentation::source

    Holds the name of the main presentation file (\c{*.uia} or
    \c{*.uip}). This may be either a local file or qrc URL.

    The names of all further assets (image files for texture maps, qml
    behavior scripts, mesh files) will be resolved relative to the
    location of the presentation, unless they use absolute paths. This
    allows bundling all assets next to the presentation in the Qt
    resource system.

    Currently set variantList will modify which variant groups
    and tags are loaded from the presentations. See
    Q3DSPresentation::variantList property.
*/
QUrl Q3DSPresentation::source() const
{
    return d_ptr->m_source;
}

void Q3DSPresentation::setSource(const QUrl &source)
{
    if (d_ptr->m_source != source) {
        d_ptr->setSource(source);
        Q_EMIT sourceChanged(source);
    }
}

/*!
    \qmlproperty variant Presentation::variantList

    Holds a list of (variant group):(variant) tags that are loaded when the
    \c{source} property is set. If this list is left empty (default), no variant
    filtering is applied and all items are loaded regardless of variant tags in
    the presentation. Variant mechanism allows one presentation project to
    contain multiple variants of the presentation and the decision which variant
    set is loaded is determined during runtime based on the \c{variantList}.

    Variants are divided to variant groups, e.g. one variant group could be
    \c{region} and the variants within that group could be e.g. \c{US, EU, CH}.
    Another variant group could be e.g. \c{power} and variants within that could
    be e.g. \c{gas, electric, diesel}. To filter in this example an electric
    variant for the EU region, the variantList needs to contain two strings
    "region:EU" and "power:electric". Also of course the presentation project
    needs to contain these variant groups and tags applied appropriately to the
    presentation content.

    When variant filters are used, the decision what gets loaded and what is not
    loaded is based on checking every item in the presentation:
    \list
    \li If the item has no variant tags, it will be loaded.
    \li If the item has no tags defined for the checked variant group(s),
        it will be loaded.
    \li If the item has tag(s) for the variant group, any of those tags must
        match any of the variants defined in the filter for that group.
    \endlist

    If the item doesn't fulfill the above rules it will not be loaded.
*/

/*!
    \property Q3DSPresentation::variantList

    Holds a list of (variant group):(variant) tags that are loaded when the
    \c{source} property is set. If this list is left empty (default), no variant
    filtering is applied and all items are loaded regardless of variant tags in
    the presentation. Variant mechanism allows one presentation project to
    contain multiple variants of the presentation and the decision which variant
    set is loaded is determined during runtime based on the \c{variantList}.

    Variants are divided to variant groups, e.g. one variant group could be
    \c{region} and the variants within that group could be e.g. \c{US, EU, CH}.
    Another variant group could be e.g. \c{power} and variants within that could
    be e.g. \c{gas, electric, diesel}. To filter in this example an electric
    variant for the EU region, the variantList needs to contain two strings
    "region:EU" and "power:electric". Also of course the presentation project
    needs to contain these variant groups and tags applied appropriately to the
    presentation content.

    When variant filters are used, the decision what gets loaded and what is not
    loaded is based on checking every item in the presentation:
    \list
    \li If the item has no variant tags, it will be loaded.
    \li If the item has no tags defined for the checked variant group(s),
        it will be loaded.
    \li If the item has tag(s) for the variant group, any of those tags must
        match any of the variants defined in the filter for that group.
    \endlist

    If the item doesn't fulfill the above rules it will not be loaded.
*/
QStringList Q3DSPresentation::variantList() const
{
    return d_ptr->m_variantList;
}

void Q3DSPresentation::setVariantList(const QStringList &variantList)
{
    if (d_ptr->m_variantList != variantList) {
        d_ptr->setVariantList(variantList);
        Q_EMIT variantListChanged(variantList);
    }
}

/*!
    \internal
 */
void Q3DSPresentation::registerElement(Q3DSElement *element)
{
    d_ptr->registerElement(element);
}

/*!
    \internal
 */
void Q3DSPresentation::unregisterElement(Q3DSElement *element)
{
    d_ptr->unregisterElement(element);
}

/*!
    \internal
 */
Q3DSElement *Q3DSPresentation::registeredElement(const QString &elementPath) const
{
    return d_ptr->m_elements.value(elementPath, nullptr);
}

/*!
    \internal
 */
void Q3DSPresentation::registerDataInput(Q3DSDataInput *dataInput)
{
    d_ptr->registerDataInput(dataInput);
}

/*!
    \internal
 */
void Q3DSPresentation::unregisterDataInput(Q3DSDataInput *dataInput)
{
    d_ptr->unregisterDataInput(dataInput);
}

/*!
    \internal
 */
Q3DSDataInput *Q3DSPresentation::registeredDataInput(const QString &name) const
{
    return d_ptr->m_dataInputs.value(name, nullptr);
}

/*!
    \internal
 */
void Q3DSPresentation::registerDataOutput(Q3DSDataOutput *dataOutput)
{
    d_ptr->registerDataOutput(dataOutput);
}

/*!
    \internal
 */
void Q3DSPresentation::unregisterDataOutput(Q3DSDataOutput *dataOutput)
{
    d_ptr->unregisterDataOutput(dataOutput);
}

/*!
    \internal
 */
Q3DSDataOutput *Q3DSPresentation::registeredDataOutput(const QString &name) const
{
    return d_ptr->m_dataOutputs.value(name, nullptr);
}

/*!
    Returns a list of datainputs defined for this presentation. Use setDataInputValue()
    interface to set a datainput value using datainput name, or call Q3DSDataInput::setValue
    directly for a specific datainput.

    \sa setDataInputValue
    \sa Q3DSDataInput
 */
QVector<Q3DSDataInput *> Q3DSPresentation::dataInputs() const
{
    QVector<Q3DSDataInput *> ret;
    const auto datainputs = d_ptr->m_dataInputs;
    for (const auto &it : datainputs)
        ret.append(it);

    return ret;
}

/*!
    \qmlmethod variant Presentation::getDataInputs
    Returns a list of datainputs defined for this presentation. Use setDataInputValue()
    interface to set a datainput value using datainput name, or call Q3DSDataInput::setValue
    directly for a specific datainput.

    \sa DataInput
 */

/*!
    Returns a list of datainputs defined for this presentation. Use setDataInputValue()
    interface to set a datainput value using datainput name, or call Q3DSDataInput::setValue
    directly for a specific datainput.

    \sa setDataInputValue
    \sa Q3DSDataInput
 */
QVariantList Q3DSPresentation::getDataInputs() const
{
    QVariantList ret;
    const auto datainputs = dataInputs();

    for (const auto &it : datainputs)
        ret.append(QVariant::fromValue(it));

    return ret;
}

/*!
    Returns a list of dataoutputs defined for this presentation. Use Qt's connect() method
    to connect slots to the valueChanged() signal in the required \l{DataOutput}s to get notified
    when the value tracked by the DataOutput is changed.

    \sa Q3DSDataOutput
 */
QVector<Q3DSDataOutput *> Q3DSPresentation::dataOutputs() const
{
    QVector<Q3DSDataOutput *> ret;
    const auto datainputs = d_ptr->m_dataOutputs;
    for (const auto &it : datainputs)
        ret.append(it);

    return ret;
}

/*!
    \qmlmethod variant Presentation::getDataOutputs

    Returns a list of dataoutputs defined for this presentation. Connect slots to the
    \c{valueChanged()} signal in the required \l{DataOutput}s to get notified
    when the value tracked by the DataOutput is changed.

    \sa SDataOutput
 */
/*!
 * \brief Q3DSPresentation::getDataOutputs Returns \l{DataOutput}s.
    Returns a list of dataoutputs defined for this presentation. Use Qt's connect() method
    to connect slots to the valueChanged() signal in the required \l{DataOutput}s to get notified
    when the value tracked by the DataOutput is changed.

    \sa Q3DSDataOutput
 */
QVariantList Q3DSPresentation::getDataOutputs() const
{
    QVariantList ret;
    const auto dataoutputs = dataOutputs();

    for (const auto &it : dataoutputs)
        ret.append(QVariant::fromValue(it));

    return ret;
}

/*!
    \qmlproperty bool Presentation::delayedLoading

    This property controls whether the presentation resources are loaded while loading
    the presentation(false) or afterwards when they are actually used in the presentation(true).
    The resources are loaded per slide basis so that all resources required by a slide will be
    loaded at once.

    The resources can be images, subpresentations, materials, effects and meshes.

    Default is \c{false}.
  */

/*!
    \property Q3DSPresentation::delayedLoading

    This property controls whether the presentation resources are loaded while loading
    the presentation(false) or afterwards when they are actually used in the presentation(true).
    The resources are loaded per slide basis so that all resources required by a slide will be
    loaded at once.

    The resources can be images, subpresentations, materials, effects and meshes.

    Default is \c{false}.
  */
bool Q3DSPresentation::delayedLoading() const
{
    return d_ptr->m_delayedLoading;
}

void Q3DSPresentation::setDelayedLoading(bool enable)
{
    if (d_ptr->m_delayedLoading != enable) {
        d_ptr->setDelayedLoading(enable);
        Q_EMIT delayedLoadingChanged(enable);
    }
}

/*!
    \qmlmethod Presentation::preloadSlide
    Preloads slide resources to memory. All resources required by the given slide will be
    loaded in the background. This function has effect only when delayed loading is enabled.
    \param elementPath
 */
/*!
    \brief Q3DSPresentation::preloadSlide
    Preloads slide resources to memory. All resources required by the given slide will be
    loaded in the background. This function has effect only when delayed loading is enabled.
    \param elementPath
 */
void Q3DSPresentation::preloadSlide(const QString &elementPath)
{
    if (d_ptr->m_viewerApp)
        d_ptr->m_viewerApp->preloadSlide(elementPath);
    else if (d_ptr->m_commandQueue)
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_PreloadSlide);
}

/*!
    \qmlmethod Presentation::unloadSlide
    Unloads slide resources from memory. If the slide is current, then the resources are unloaded
    when the slide is changed. This function has effect only when delayed loading is enabled.
    \param elementPath
 */

/*!
    \brief Q3DSPresentation::unloadSlide
    Unloads slide resources from memory. If the slide is current, then the resources are unloaded
    when the slide is changed. This function has effect only when delayed loading is enabled.
    \param elementPath
 */
void Q3DSPresentation::unloadSlide(const QString &elementPath)
{
    if (d_ptr->m_viewerApp)
        d_ptr->m_viewerApp->unloadSlide(elementPath);
    else if (d_ptr->m_commandQueue)
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_UnloadSlide);
}

/*!
    This API is for backwards compatibility. We recommend using \l{DataInput}s to control
    slide changes. \l{DataInput} provides stronger contract between the design and
    code as it avoids use of elementPath (a reference to design's internal structure).

    Requests a time context (a Scene or a Component object) to change
    to a specific slide by \a index. If the context is already on that
    slide, playback will start over.

    If \a elementPath points to a time context, that element is
    controlled. For all other element types the time context owning
    that element is controlled instead.  You can target the command to
    a specific sub-presentation by adding "SubPresentationId:" in
    front of the element path, for example \c{"SubPresentationOne:Scene"}.
 */
void Q3DSPresentation::goToSlide(const QString &elementPath, unsigned int index)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        d_ptr->m_viewerApp->GoToSlideByIndex(path, index);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_GoToSlide, int(index));
    }
}

/*!
    This API is for backwards compatibility. We recommend using \l{DataInput}s to control
    slide changes. \l{DataInput} provides stronger contract between the design and
    code as it avoids use of elementPath (a reference to design's internal structure).

    Requests a time context (a Scene or a Component object) to change
    to a specific slide by \a name. If the context is already on that
    slide, playback will start over.

    If \a elementPath points to a time context, that element is
    controlled. For all other element types the time context owning
    that element is controlled instead.  You can target the command to
    a specific sub-presentation by adding "SubPresentationId:" in
    front of the element path, for example \c{"SubPresentationOne:Scene"}.
 */
void Q3DSPresentation::goToSlide(const QString &elementPath, const QString &name)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        const QByteArray byteName(name.toUtf8());
        d_ptr->m_viewerApp->GoToSlideByName(path, byteName);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_GoToSlideByName, name);
    }
}

/*!
    This API is for backwards compatibility. We recommend using \l{DataInput}s to control
    slide changes. \l{DataInput} provides stronger contract between the design and
    code as it avoids use of elementPath (a reference to design's internal structure).

    Requests a time context (a Scene or a Component object) to change to the
    next or previous slide, depending on the value of \a next. If the context
    is already at the last or first slide, \a wrap defines if wrapping over to
    the first or last slide, respectively, occurs.

    If \a elementPath points to a time context, that element is controlled. For
    all other element types the time context owning that element is controlled
    instead. You can target the command to a specific sub-presentation by
    adding "SubPresentationId:" in front of the element path, for example
    \c{"SubPresentationOne:Scene"}.
 */
void Q3DSPresentation::goToSlide(const QString &elementPath, bool next, bool wrap)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        d_ptr->m_viewerApp->GoToSlideRelative(path, next, wrap);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_GoToSlideRelative,
                                            int(next), int(wrap));
    }
}

/*!
    This API is for backwards compatibility. We recommend using \l{DataInput}s to control
    slide changes. \l{DataInput} provides stronger contract between the design and
    code as it avoids use of elementPath (a reference to design's internal structure).

    Moves the timeline for a time context (a Scene or a Component element) to a
    specific position. The position is given in seconds in \a timeSeconds.

    If \a elementPath points to a time context, that element is
    controlled. For all other element types the time context owning
    that element is controlled instead.  You can target the command to
    a specific sub-presentation by adding "SubPresentationId:" in
    front of the element path, for example
    \c{"SubPresentationOne:Scene"}.

    The behavior when specifying a time before 0 or after the end time
    for the current slide depends on the play mode of the slide:

    \list
    \li \c{Stop at End} - values outside the valid time range instead clamp to the boundaries.
    For example, going to time -5 is the same as going to time 0.
    \li \c{Looping} - values outside the valid time range mod into the valid range. For example,
    going to time -4 on a 10 second slide is the same as going to time 6.
    \li \c{Ping Pong} - values outside the valid time range bounce off the ends. For example,
    going to time -4 is the same as going to time 4 (assuming the time context is at least 4 seconds
    long), while going to time 12 on a 10 second slide is the same as going to time 8.
    \li \c{Ping} - values less than 0 are treated as time 0, while values greater than the endtime
    bounce off the end (eventually hitting 0.)
    \endlist
 */
void Q3DSPresentation::goToTime(const QString &elementPath, float time)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        d_ptr->m_viewerApp->GoToTime(path, time);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_GoToTime, time);
    }
}

/*!
    This API is for backwards compatibility. We recommend using \l{DataInput}s to control
    attributes in the presentation. \l{DataInput} provides stronger contract between the
    design and code as it avoids use of elementPath (a reference to design's
    internal structure).

    Sets the \a value of an attribute (property) on the object specified by
    \a elementPath. The \a attributeName is the \l{Attribute Names}{scripting
    name} of the attribute.

    An element path refers to an object in the scene by name, for example,
    \c{Scene.Layer.Camera}. Here the right camera object gets chosen even if
    the scene contains other layers with the default camera names (for instance
    \c{Scene.Layer2.Camera}).

    To reference an object stored in a property of another object, the dot
    syntax can be used. The most typical example of this is changing the source
    of a texture map by changing the \c sourcepath property on the object
    selected by \c{SomeMaterial.diffusemap}.

    To access an object in a sub-presentation, prepend the name of the
    sub-presentation followed by a colon, for example,
    \c{SubPresentationOne:Scene.Layer.Camera}.
 */
void Q3DSPresentation::setAttribute(const QString &elementPath, const QString &attributeName,
                                    const QVariant &value)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        const QByteArray name(attributeName.toUtf8());

        QByteArray valueStr;
        float valueFloat;

        const void *theValue = nullptr;
        switch (static_cast<QMetaType::Type>(value.type())) {
        case QMetaType::Bool:
        case QMetaType::Int:
        case QMetaType::Double:
        case QMetaType::Float:
            valueFloat = value.toFloat();
            theValue = &valueFloat;
            break;
        case QMetaType::QString:
        default: // Try string for other types
            valueStr = value.toString().toUtf8();
            theValue = valueStr.constData();
            break;
        }
        d_ptr->m_viewerApp->SetAttribute(path, name, (char *)theValue);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_SetAttribute,
                                            attributeName, value);
    }
}

// #TODO: QT3DS-3558
/*!
    \brief Q3DSPresentation::setPresentationActive
    \param id
    \param active
 */
void Q3DSPresentation::setPresentationActive(const QString &id, bool active)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray presId(id.toUtf8());
        d_ptr->m_viewerApp->SetPresentationActive(presId, active);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(id, CommandType_SetPresentationActive, active);
    }
}

/*!
    Dispatches a Qt 3D Studio presentation event with \a eventName on
    scene object specified by \a elementPath. These events provide a
    way to communicate with the \c .qml based \c{behavior scripts}
    attached to scene objects since they can register to be notified
    via Behavior::registerForEvent().

    See setAttribute() for a description of \a elementPath.
 */
void Q3DSPresentation::fireEvent(const QString &elementPath, const QString &eventName)
{
    if (d_ptr->m_viewerApp) {
        const QByteArray path(elementPath.toUtf8());
        const QByteArray name(eventName.toUtf8());
        d_ptr->m_viewerApp->FireEvent(path, name);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_FireEvent, eventName);
    }
}

// #TODO: QT3DS-3559
/*!
    \brief Q3DSPresentation::setGlobalAnimationTime
    \param milliseconds
 */
void Q3DSPresentation::setGlobalAnimationTime(qint64 milliseconds)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->SetGlobalAnimationTime(milliseconds);
    } else {
        d_ptr->m_commandQueue->m_globalAnimationTimeChanged = true;
        d_ptr->m_commandQueue->m_globalAnimationTime = milliseconds;
    }
}

/*!
    Sets the \a value of a data input element \a name in the presentation.

    Data input provides a higher level, designer-driven alternative to
    Q3DSElement and setAttribute(). Instead of exposing a large set of
    properties with their internal engine names, data input allows designers to
    decide which properties should be writable by the application, and can
    assign custom names to these data input entries, thus forming a
    well-defined contract between the designer and the developer.

    In addition, data input also allows controlling the time line and the
    current slide for time context objects (Scene or Component). Therefore it
    is also an alternative to the goToSlide() and goToTime() family of APIs and
    to Q3DSSceneElement.

    \sa DataInput
 */
void Q3DSPresentation::setDataInputValue(const QString &name, const QVariant &value,
                                         Q3DSDataInput::ValueRole valueRole)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->SetDataInputValue(name, value,
                                              (qt3ds::runtime::DataInputValueRole)valueRole);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_SetDataInputValue,
                                            name, value, static_cast<int>(valueRole));
    }
}

/*!
 * \brief Q3DSPresentation::createElement Adds a new child element for the specified element.
    Adds a new child element for the element specified by parentElementPath to the slide
    specified with slideName. Only model element creation is currently supported.
    A referenced material element is also created for the new model element. The source material
    name can be specified with custom "material" property in the properties hash.
    The source material must exist in the material container of the presentation.
 */
void Q3DSPresentation::createElement(const QString &parentElementPath, const QString &slideName,
                                     const QHash<QString, QVariant> &properties)
{
    QVector<QHash<QString, QVariant>> theProperties;
    theProperties << properties;
    createElements(parentElementPath, slideName, theProperties);
}

// #TODO: QT3DS-3560
/*!
    \brief Q3DSPresentation::createElements
    \param parentElementPath
    \param slideName
    \param properties
 */
void Q3DSPresentation::createElements(const QString &parentElementPath, const QString &slideName,
                                      const QVector<QHash<QString, QVariant>> &properties)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->createElements(parentElementPath, slideName, properties);
    } else if (d_ptr->m_commandQueue) {
        // We need to copy the properties map as queue takes ownership of it
        QVector<QHash<QString, QVariant>> *theProperties
                = new QVector<QHash<QString, QVariant>>(properties);
        d_ptr->m_commandQueue->queueCommand(parentElementPath, CommandType_CreateElements,
                                            slideName, theProperties);
    }
}

/*!
    \brief Q3DSPresentation::deleteElement
    Removes an element added by createElement and all its child elements.
    \param elementPath
 */
void Q3DSPresentation::deleteElement(const QString &elementPath)
{
    QStringList elementPaths;
    elementPaths << elementPath;
    deleteElements(elementPaths);
}

/*!
    \brief Q3DSPresentation::deleteElements
    Removes the given list of elements added by createElement and all their child elements.
    \param elementPaths QStringList containing the elementPaths of dynamically created objects.
 */
void Q3DSPresentation::deleteElements(const QStringList &elementPaths)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->deleteElements(elementPaths);
    } else if (d_ptr->m_commandQueue) {
        // We need to copy the list as queue takes ownership of it
        QStringList *theElementPaths = new QStringList(elementPaths);
        d_ptr->m_commandQueue->queueCommand(CommandType_DeleteElements, theElementPaths);
    }
}

/*!
    \brief Q3DSPresentation::createMaterial
    Creates a material specified by the materialDefinition parameter into the material
    container of the presentation that owns the element specified by the elementPath parameter.
    After creation, the material can be used for new elements created via createElement.
    The materialDefinition parameter can contain either the file path to a material definition
    file or a material definition in the Qt 3D Studion material data format.
    \param elementPath
    \param materialDefinition
 */
void Q3DSPresentation::createMaterial(const QString &elementPath,
                                      const QString &materialDefinition)
{
    QStringList materialDefinitions;
    materialDefinitions << materialDefinition;
    createMaterials(elementPath, materialDefinitions);
}

/*!
    \brief Q3DSPresentation::createMaterials
    Same as createMaterial, but creates multiple materials.
    \param elementPath
    \param materialDefinitions
 */
void Q3DSPresentation::createMaterials(const QString &elementPath,
                                       const QStringList &materialDefinitions)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->createMaterials(elementPath, materialDefinitions);
    } else if (d_ptr->m_commandQueue) {
        // We need to copy the list as queue takes ownership of it
        QStringList *theMaterialDefinitions = new QStringList(materialDefinitions);
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_CreateMaterials,
                                            theMaterialDefinitions);
    }
}

void Q3DSPresentation::deleteMaterial(const QString &elementPath, const QString &materialName)
{
    QStringList materialNames;
    materialNames << materialName;
    deleteMaterials(elementPath, materialNames);
}

void Q3DSPresentation::deleteMaterials(const QString &elementPath, const QStringList &materialNames)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->deleteMaterials(elementPath, materialNames);
    } else if (d_ptr->m_commandQueue) {
        // We need to copy the list as queue takes ownership of it
        QStringList *theMaterialNames = new QStringList(materialNames);
        d_ptr->m_commandQueue->queueCommand(elementPath, CommandType_DeleteMaterials,
                                            theMaterialNames);
    }
}

/**
    Creates a mesh specified by given geometry. The given meshName can be used as sourcepath
    property value for model elements created with future createElement calls.
*/
void Q3DSPresentation::createMesh(const QString &meshName, const Q3DSGeometry &geometry)
{
    QHash<QString, const Q3DSGeometry *> meshData;
    meshData.insert(meshName, &geometry);
    createMeshes(meshData);
}

// The ownership of supplied geometries stays with the caller
void Q3DSPresentation::createMeshes(const QHash<QString, const Q3DSGeometry *> &meshData)
{
    // We can't refer to API class Q3DSGeometry on the runtime side, so let's grab the meshdata
    // from Q3DSGeometryPrivate that is in runtime approved format and pass that on instead
    auto theMeshData = new QHash<QString, Q3DSViewer::MeshData>;
    QHashIterator<QString, const Q3DSGeometry *> it(meshData);
    while (it.hasNext()) {
        it.next();
        theMeshData->insert(it.key(), it.value()->d_ptr->meshData());
    }

    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->createMeshes(*theMeshData);
        delete theMeshData;
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(CommandType_CreateMeshes, theMeshData);
    }
}

void Q3DSPresentation::deleteMesh(const QString &meshName)
{
    QStringList meshNames;
    meshNames << meshName;
    deleteMeshes(meshNames);
}

void Q3DSPresentation::deleteMeshes(const QStringList &meshNames)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->deleteMeshes(meshNames);
    } else if (d_ptr->m_commandQueue) {
        // We need to copy the list as queue takes ownership of it
        QStringList *theMeshNames = new QStringList(meshNames);
        d_ptr->m_commandQueue->queueCommand(CommandType_DeleteMeshes, theMeshNames);
    }
}

void Q3DSPresentation::mousePressEvent(QMouseEvent *e)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->HandleMousePress(e->x(), e->y(), e->button(), true);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_MousePress,
                                           e->x(), e->y(), int(e->button()));
    }
}

/*!
 * \internal
 */
void Q3DSPresentation::mouseReleaseEvent(QMouseEvent *e)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->HandleMousePress(e->x(), e->y(), e->button(), false);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_MouseRelease,
                                           e->x(), e->y(), int(e->button()));
    }
}

/*!
 * \internal
 */
void Q3DSPresentation::mouseMoveEvent(QMouseEvent *e)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->HandleMouseMove(e->x(), e->y(), true);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_MouseMove,
                                            e->x(), e->y());
    }
}

/*!
 * \internal
 */
void Q3DSPresentation::wheelEvent(QWheelEvent *e)
{
    QPoint pixelData = e->pixelDelta();
    int numSteps = 0;
    if (pixelData.isNull()) {
        if (e->orientation() == Qt::Vertical)
            numSteps = e->angleDelta().y() / 8;
        else
            numSteps = e->angleDelta().x() / 8;
    } else {
        // trackpad, pixel = one step in scroll wheel.
        if (e->orientation() == Qt::Vertical)
            numSteps = pixelData.y();
        else
            numSteps = pixelData.x();
    }
    if (numSteps != 0) {
        if (d_ptr->m_viewerApp) {
            d_ptr->m_viewerApp->HandleMouseWheel(e->x(), e->y(),
                                                 e->orientation() == Qt::Vertical ? 0 : 1,
                                                 numSteps);
        } else if (d_ptr->m_commandQueue) {
            d_ptr->m_commandQueue->queueCommand(QString(), CommandType_MouseWheel,
                                                e->x(), e->y(),
                                                int(e->orientation() == Qt::Vertical), numSteps);
        }
    }
}

/*!
 * \internal
 */
void Q3DSPresentation::keyPressEvent(QKeyEvent *e)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->HandleKeyInput(d_ptr->getScanCode(e), true);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_KeyPress,
                                            d_ptr->getScanCode(e));
    }
}

/*!
 * \internal
 */
void Q3DSPresentation::keyReleaseEvent(QKeyEvent *e)
{
    if (d_ptr->m_viewerApp) {
        d_ptr->m_viewerApp->HandleKeyInput(d_ptr->getScanCode(e), false);
    } else if (d_ptr->m_commandQueue) {
        d_ptr->m_commandQueue->queueCommand(QString(), CommandType_KeyRelease,
                                            d_ptr->getScanCode(e));
    }
}

// #TODO: QT3DS-3562 Most Presentation signals missing documentation
/*!
 * \qmlsignal Presentation::slideEntered
 * Emitted when
 * \param elementPath
 * \param index
 * \param name
 */

/*!
 * \fn Q3DSPresentation::slideEntered
 * Emitted when
 * \param elementPath
 * \param index
 * \param name
 */

/*!
 * \qmlsignal Presentation::slideExited
 * Emitted when
 * \param elementPath
 * \param index
 * \param name
 */

/*!
 * \fn Q3DSPresentation::slideExited
 * Emitted when
 * \param elementPath
 * \param index
 * \param name
 */

/*!
 * \fn Q3DSPresentation::dataInputsReady
 * Emitted when \l{DataInput}s in the Studio project have been parsed and data inputs are available
 * through dataInputs() and getDataInputs() methods.
 */

/*!
 * \fn Q3DSPresentation::dataOutputsReady
 * Emitted when \l{DataOutput}s in the Studio project have been parsed and data outputs are available
 * through dataOutputs() and getDataOutputs() methods.
 */

/*!
 * \qmlsignal Presentation::customSignalEmitted
 * Emitted when
 * \param elementPath
 * \param name
 */

/*!
 * \fn Q3DSPresentation::customSignalEmitted
 * Emitted when
 * \param elementPath
 * \param name
 */

/*!
 * \qmlsignal Presentation::elementsCreated
 * Emitted when
 * \param elementPaths
 * \param error
 */

/*!
 * \fn Q3DSPresentation::elementsCreated
 * Emitted when
 * \param elementPaths
 * \param error
 */

/*!
 * \qmlsignal Presentation::materialsCreated
 * Emitted when
 * \param materialNames
 * \param error
 */

/*!
 * \fn Q3DSPresentation::materialsCreated
 * Emitted when
 * \param materialNames
 * \param error
 */


/*!
 * \internal
 */
Q3DSPresentationPrivate::Q3DSPresentationPrivate(Q3DSPresentation *q)
    : QObject(q)
    , q_ptr(q)
    , m_viewerApp(nullptr)
    , m_commandQueue(nullptr)
    , m_streamProxy(nullptr)
    , m_delayedLoading(false)
{
}

Q3DSPresentationPrivate::~Q3DSPresentationPrivate()
{
    unregisterAllElements();
    unregisterAllDataInputs();
    unregisterAllDataOutputs();
    delete m_streamProxy;
}

void Q3DSPresentationPrivate::setSource(const QUrl &source)
{
    m_source = source;
    if (m_commandQueue) {
        m_commandQueue->m_sourceChanged = true;
        m_commandQueue->m_source = source;
    }
}

void Q3DSPresentationPrivate::setVariantList(const QStringList &variantList)
{
    m_variantList = variantList;
    if (m_commandQueue) {
        m_commandQueue->m_variantListChanged = true;
        m_commandQueue->m_variantList = variantList;
    }
}

void Q3DSPresentationPrivate::setViewerApp(Q3DSViewer::Q3DSViewerApp *app, bool connectApp)
{
    Q3DSViewer::Q3DSViewerApp *oldApp = m_viewerApp;
    m_viewerApp = app;

    const auto elements = m_elements.values();
    for (Q3DSElement *element : elements)
        element->d_ptr->setViewerApp(app);

    if (m_viewerApp) {
        const auto dataInputs = m_viewerApp->dataInputs();
        for (const auto &name : dataInputs) {
            if (!m_dataInputs.contains(name)) {
                // Name is sufficient for C++ side APIs, as other parameters
                // (max/min) are queried synchronously.
                auto *di = new Q3DSDataInput(name, nullptr);
                registerDataInput(di);
            }
        }
        Q_EMIT q_ptr->dataInputsReady();
    }

    if (connectApp) {
        if (app) {
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigSlideEntered,
                    this, &Q3DSPresentationPrivate::handleSlideEntered);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigSlideExited,
                    q_ptr, &Q3DSPresentation::slideExited);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigCustomSignal,
                    q_ptr, &Q3DSPresentation::customSignalEmitted);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigDataOutputValueUpdated,
                    this, &Q3DSPresentationPrivate::handleDataOutputValueUpdate);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigElementsCreated,
                    q_ptr, &Q3DSPresentation::elementsCreated);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigMaterialsCreated,
                    q_ptr, &Q3DSPresentation::materialsCreated);
            connect(app, &Q3DSViewer::Q3DSViewerApp::SigMeshesCreated,
                    q_ptr, &Q3DSPresentation::meshesCreated);
        }
        if (oldApp) {
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigSlideEntered,
                       this, &Q3DSPresentationPrivate::handleSlideEntered);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigSlideExited,
                       q_ptr, &Q3DSPresentation::slideExited);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigCustomSignal,
                       q_ptr, &Q3DSPresentation::customSignalEmitted);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigDataOutputValueUpdated,
                       this, &Q3DSPresentationPrivate::handleDataOutputValueUpdate);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigElementsCreated,
                       q_ptr, &Q3DSPresentation::elementsCreated);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigMaterialsCreated,
                       q_ptr, &Q3DSPresentation::materialsCreated);
            disconnect(oldApp, &Q3DSViewer::Q3DSViewerApp::SigMeshesCreated,
                       q_ptr, &Q3DSPresentation::meshesCreated);
        }
    }
}

void Q3DSPresentationPrivate::setCommandQueue(CommandQueue *queue)
{
    m_commandQueue = queue;

    const auto elements = m_elements.values();
    const auto dataInputs = m_dataInputs.values();
    for (Q3DSElement *element : elements)
        element->d_ptr->setCommandQueue(queue);
    for (Q3DSDataInput *di : dataInputs)
        di->d_ptr->setCommandQueue(queue);

    if (m_commandQueue) {
        setDelayedLoading(m_delayedLoading);
        setVariantList(m_variantList);
        // Queue a request ASAP for datainputs and outputs defined in UIA file so that
        // getDataInputs has up-to-date info at the earliest and that data outputs
        // connect from source to destination
        m_commandQueue->queueCommand({}, CommandType_RequestDataInputs);
        m_commandQueue->queueCommand({}, CommandType_RequestDataOutputs);
        setSource(m_source);
    }
}

void Q3DSPresentationPrivate::setDelayedLoading(bool enable)
{
    m_delayedLoading = enable;
    if (m_commandQueue) {
        m_commandQueue->m_delayedLoading = enable;
        m_commandQueue->m_delayedLoadingChanged = true;
    }
}

void Q3DSPresentationPrivate::requestResponseHandler(CommandType commandType, void *requestData)
{
    switch (commandType) {
    case CommandType_RequestDataInputs: {
        QVariantList *response = reinterpret_cast<QVariantList *>(requestData);

        for (int i = 0; i < response->size(); ++i) {
            // Check and append to QML-side list if the (UIA) presentation has additional datainputs
            // that are not explicitly defined in QML code.
            auto receivedDI = response->at(i).value<Q3DSDataInput *>();
            // For QML behind async command queue, we cache min/max values in addition
            // to name, in order to be able to return values initially set in UIA file (in QML
            // getters).
            if (!m_dataInputs.contains(receivedDI->name())) {
                auto newDI = new Q3DSDataInput(receivedDI->name(), nullptr);
                newDI->d_ptr->m_min = receivedDI->d_ptr->m_min;
                newDI->d_ptr->m_max = receivedDI->d_ptr->m_max;
                registerDataInput(newDI);
            } else {
                m_dataInputs[receivedDI->name()]->d_ptr->m_min = receivedDI->d_ptr->m_min;
                m_dataInputs[receivedDI->name()]->d_ptr->m_max = receivedDI->d_ptr->m_max;
            }
        }
        delete response;
        Q_EMIT q_ptr->dataInputsReady();
        break;
    }
    case CommandType_RequestDataOutputs: {
        QVariantList *response = reinterpret_cast<QVariantList *>(requestData);

        for (int i = 0; i < response->size(); ++i) {
            // Check and append to QML-side list if the (UIA) presentation has additional
            // dataoutputs that are not explicitly defined in QML code.
            if (!m_dataOutputs.contains(response->at(i).value<QString>()))
                registerDataOutput(new Q3DSDataOutput(response->at(i).value<QString>(), nullptr));
        }
        delete response;
        Q_EMIT q_ptr->dataOutputsReady();
        break;
    }
    default:
        Q_ASSERT(false);
        break;
    }
}

// Doc note: The ownership of the registered scenes remains with the caller, who needs to
// ensure that registered scenes are alive as long as the presentation is alive.
void Q3DSPresentationPrivate::registerElement(Q3DSElement *element)
{
    Q_ASSERT(!element->elementPath().isEmpty());

    // Allow only single registration for each element path and scene object
    QMutableHashIterator<QString, Q3DSElement *> i(m_elements);
    while (i.hasNext()) {
        i.next();
        if (i.value() == element) {
            // If the same scene object is already registered with different path,
            // remove it from the map to avoid duplication.
            if (i.key() != element->elementPath())
                i.remove();
        } else if (i.key() == element->elementPath()) {
            // If the same element path is registered by another scene object, the old
            // scene object is unregistered.
            i.value()->d_ptr->setViewerApp(nullptr);
            i.value()->d_ptr->setPresentation(nullptr);
            i.remove();
        }
    }

    element->d_ptr->setViewerApp(m_viewerApp);
    element->d_ptr->setCommandQueue(m_commandQueue);
    element->d_ptr->setPresentation(this);

    m_elements.insert(element->elementPath(), element);
}

void Q3DSPresentationPrivate::unregisterElement(Q3DSElement *element)
{
    Q3DSElement *oldScene = m_elements.value(element->elementPath());
    if (oldScene == element) {
        element->d_ptr->setViewerApp(nullptr);
        element->d_ptr->setCommandQueue(nullptr);
        element->d_ptr->setPresentation(nullptr);
        m_elements.remove(element->elementPath());
    }
}

void Q3DSPresentationPrivate::unregisterAllElements()
{
    for (Q3DSElement *element : m_elements.values()) {
        element->d_ptr->setViewerApp(nullptr);
        element->d_ptr->setCommandQueue(nullptr);
        element->d_ptr->setPresentation(nullptr);
    }
    m_elements.clear();
}

void Q3DSPresentationPrivate::registerDataInput(Q3DSDataInput *dataInput)
{
    Q_ASSERT(!dataInput->name().isEmpty());

    // Allow only single registration for each DataInput
    QMutableHashIterator<QString, Q3DSDataInput *> i(m_dataInputs);
    while (i.hasNext()) {
        i.next();
        if (i.value() == dataInput) {
            // If the same DataInput object is already registered with different name,
            // remove it from the map to avoid duplication.
            if (i.key() != dataInput->name())
                i.remove();
        } else if (i.key() == dataInput->name()) {
            // If the same name is registered by another DataInput object, the old
            // DataInput object is unregistered.
            i.value()->d_ptr->setViewerApp(nullptr);
            i.value()->d_ptr->setPresentation(nullptr);
            i.remove();
        }
    }

    dataInput->d_ptr->setPresentation(q_ptr);
    dataInput->d_ptr->setViewerApp(m_viewerApp);
    dataInput->d_ptr->setCommandQueue(m_commandQueue);

    m_dataInputs.insert(dataInput->name(), dataInput);
}

void Q3DSPresentationPrivate::unregisterDataInput(Q3DSDataInput *dataInput)
{
    Q3DSDataInput *oldDi = m_dataInputs.value(dataInput->name());
    if (oldDi == dataInput) {
        dataInput->d_ptr->setCommandQueue(nullptr);
        dataInput->d_ptr->setViewerApp(nullptr);
        dataInput->d_ptr->setPresentation(nullptr);
        m_dataInputs.remove(dataInput->name());
    }
}

void Q3DSPresentationPrivate::unregisterAllDataInputs()
{
    for (Q3DSDataInput *di : m_dataInputs.values()) {
        di->d_ptr->setViewerApp(nullptr);
        di->d_ptr->setCommandQueue(nullptr);
        di->d_ptr->setPresentation(nullptr);
    }
    m_dataInputs.clear();
}
bool Q3DSPresentationPrivate::isValidDataInput(const Q3DSDataInput *dataInput) const
{
    // For QML instance separated from runtime engine by command queue,
    // check locally cached list for this datainput (initialised at presentation load).
    if (!m_viewerApp) {
        if (m_dataInputs.contains(dataInput->name()))
            return true;
        else
            return false;
    }

    return m_viewerApp->dataInputs().contains(dataInput->name());
}

float Q3DSPresentationPrivate::dataInputMin(const QString &name) const
{
    // For QML instance separated from runtime engine by command queue,
    // return locally cached value (initialised at presentation load).
    if (!m_viewerApp) {
        if (m_dataInputs.contains(name))
            return m_dataInputs[name]->d_ptr->m_min;
        else
            return 0.0f;
    }
    return m_viewerApp->dataInputMin(name);
}

float Q3DSPresentationPrivate::dataInputMax(const QString &name) const
{
    // For QML instance separated from runtime engine by command queue,
    // return locally cached value (initialised at presentation load).
    if (!m_viewerApp) {
        if (m_dataInputs.contains(name))
            return m_dataInputs[name]->d_ptr->m_max;
        else
            return 0.0f;
    }
    return m_viewerApp->dataInputMax(name);
}

void Q3DSPresentationPrivate::registerDataOutput(Q3DSDataOutput *dataOutput)
{
    Q_ASSERT(!dataOutput->name().isEmpty());

    // Allow only single registration for each DataOutput
    QMutableHashIterator<QString, Q3DSDataOutput *> i(m_dataOutputs);
    while (i.hasNext()) {
        i.next();
        if (i.value() == dataOutput) {
            // If the same DataOutput object is already registered with different name,
            // remove it from the map to avoid duplication.
            if (i.key() != dataOutput->name())
                i.remove();
        } else if (i.key() == dataOutput->name()) {
            // If the same name is registered by another DataOutput object, the old
            // DataOutput object is unregistered.
            i.value()->d_ptr->setViewerApp(nullptr);
            i.value()->d_ptr->setPresentation(nullptr);
            i.value()->d_ptr->setCommandQueue(nullptr);
            i.remove();
        }
    }

    dataOutput->d_ptr->setPresentation(q_ptr);
    dataOutput->d_ptr->setViewerApp(m_viewerApp);
    dataOutput->d_ptr->setCommandQueue(m_commandQueue);

    m_dataOutputs.insert(dataOutput->name(), dataOutput);
}

void Q3DSPresentationPrivate::unregisterDataOutput(Q3DSDataOutput *dataOutput)
{
    Q3DSDataOutput *oldDout = m_dataOutputs.value(dataOutput->name());
    if (oldDout == dataOutput) {
        dataOutput->d_ptr->setCommandQueue(nullptr);
        dataOutput->d_ptr->setViewerApp(nullptr);
        dataOutput->d_ptr->setPresentation(nullptr);
        m_dataOutputs.remove(dataOutput->name());
    }
}

void Q3DSPresentationPrivate::unregisterAllDataOutputs()
{
    const auto values = m_dataOutputs.values();
    for (Q3DSDataOutput *dout : values) {
        dout->d_ptr->setViewerApp(nullptr);
        dout->d_ptr->setCommandQueue(nullptr);
        dout->d_ptr->setPresentation(nullptr);
    }
    m_dataOutputs.clear();
}

bool Q3DSPresentationPrivate::isValidDataOutput(const Q3DSDataOutput *dataOutput) const
{
    if (!m_viewerApp)
        return false;

    return m_viewerApp->dataOutputs().contains(dataOutput->name());
}

Q3DStudio::EKeyCode Q3DSPresentationPrivate::getScanCode(QKeyEvent *e)
{
    enum {
        RIGHT_SHIFT = 0x036,
        RIGHT_CTRL = 0x11d,
        RIGHT_ALT = 0x138,
    };

    Qt::Key keyScanCode = static_cast<Qt::Key>(e->key());

    Q3DStudio::EKeyCode newScanCode = Q3DStudio::KEY_NOKEY;
    switch (keyScanCode) {
    case Qt::Key_Down:
        newScanCode = Q3DStudio::KEY_DOWN;
        break;
    case Qt::Key_Up:
        newScanCode = Q3DStudio::KEY_UP;
        break;
    case Qt::Key_Left:
        newScanCode = Q3DStudio::KEY_LEFT;
        break;
    case Qt::Key_Right:
        newScanCode = Q3DStudio::KEY_RIGHT;
        break;
    case Qt::Key_Return:
    case Qt::Key_Enter:
        newScanCode = e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPADENTER
                                                           : Q3DStudio::KEY_RETURN;
        break;
    case Qt::Key_Backspace:
        newScanCode = Q3DStudio::KEY_BACK;
        break;
    case Qt::Key_Tab:
        newScanCode = Q3DStudio::KEY_TAB;
        break;
    case Qt::Key_Escape:
        newScanCode = Q3DStudio::KEY_ESCAPE;
        break;
    case Qt::Key_A:
        newScanCode = Q3DStudio::KEY_A;
        break;
    case Qt::Key_B:
        newScanCode = Q3DStudio::KEY_B;
        break;
    case Qt::Key_C:
        newScanCode = Q3DStudio::KEY_C;
        break;
    case Qt::Key_D:
        newScanCode = Q3DStudio::KEY_D;
        break;
    case Qt::Key_E:
        newScanCode = Q3DStudio::KEY_E;
        break;
    case Qt::Key_F:
        newScanCode = Q3DStudio::KEY_F;
        break;
    case Qt::Key_G:
        newScanCode = Q3DStudio::KEY_G;
        break;
    case Qt::Key_H:
        newScanCode = Q3DStudio::KEY_H;
        break;
    case Qt::Key_I:
        newScanCode = Q3DStudio::KEY_I;
        break;
    case Qt::Key_J:
        newScanCode = Q3DStudio::KEY_J;
        break;
    case Qt::Key_K:
        newScanCode = Q3DStudio::KEY_K;
        break;
    case Qt::Key_L:
        newScanCode = Q3DStudio::KEY_L;
        break;
    case Qt::Key_M:
        newScanCode = Q3DStudio::KEY_M;
        break;
    case Qt::Key_N:
        newScanCode = Q3DStudio::KEY_N;
        break;
    case Qt::Key_O:
        newScanCode = Q3DStudio::KEY_O;
        break;
    case Qt::Key_P:
        newScanCode = Q3DStudio::KEY_P;
        break;
    case Qt::Key_Q:
        newScanCode = Q3DStudio::KEY_Q;
        break;
    case Qt::Key_R:
        newScanCode = Q3DStudio::KEY_R;
        break;
    case Qt::Key_S:
        newScanCode = Q3DStudio::KEY_S;
        break;
    case Qt::Key_T:
        newScanCode = Q3DStudio::KEY_T;
        break;
    case Qt::Key_U:
        newScanCode = Q3DStudio::KEY_U;
        break;
    case Qt::Key_V:
        newScanCode = Q3DStudio::KEY_V;
        break;
    case Qt::Key_W:
        newScanCode = Q3DStudio::KEY_W;
        break;
    case Qt::Key_X:
        newScanCode = Q3DStudio::KEY_X;
        break;
    case Qt::Key_Y:
        newScanCode = Q3DStudio::KEY_Y;
        break;
    case Qt::Key_Z:
        newScanCode = Q3DStudio::KEY_Z;
        break;
    case Qt::Key_0:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD0 : Q3DStudio::KEY_0;
        break;
    case Qt::Key_1:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD1 : Q3DStudio::KEY_1;
        break;
    case Qt::Key_2:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD2 : Q3DStudio::KEY_2;
        break;
    case Qt::Key_3:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD3 : Q3DStudio::KEY_3;
        break;
    case Qt::Key_4:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD4 : Q3DStudio::KEY_4;
        break;
    case Qt::Key_5:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD5 : Q3DStudio::KEY_5;
        break;
    case Qt::Key_6:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD6 : Q3DStudio::KEY_6;
        break;
    case Qt::Key_7:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD7 : Q3DStudio::KEY_7;
        break;
    case Qt::Key_8:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD8 : Q3DStudio::KEY_8;
        break;
    case Qt::Key_9:
        newScanCode =
                e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPAD9 : Q3DStudio::KEY_9;
        break;
    case Qt::Key_Minus:
        newScanCode = e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPADSUBTRACT
                                                           : Q3DStudio::KEY_SUBTRACT;
        break;
    case Qt::Key_Plus:
        newScanCode = e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPADADD
                                                           : Q3DStudio::KEY_EQUALS;
        break;
    case Qt::Key_NumLock:
        newScanCode = Q3DStudio::KEY_NUMLOCK;
        break;
    case Qt::Key_ScrollLock:
        newScanCode = Q3DStudio::KEY_SCROLL;
        break;
    case Qt::Key_CapsLock:
        newScanCode = Q3DStudio::KEY_CAPITAL;
        break;
    case Qt::Key_Pause:
        newScanCode = Q3DStudio::KEY_PAUSE;
        break;
    case Qt::Key_Print:
        newScanCode = Q3DStudio::KEY_PRINTSCREEN;
        break;
    case Qt::Key_Insert:
        newScanCode = Q3DStudio::KEY_INSERT;
        break;
    case Qt::Key_Delete:
        newScanCode = Q3DStudio::KEY_DELETE;
        break;
    case Qt::Key_Home:
        newScanCode = Q3DStudio::KEY_HOME;
        break;
    case Qt::Key_End:
        newScanCode = Q3DStudio::KEY_END;
        break;
    case Qt::Key_PageUp:
        newScanCode = Q3DStudio::KEY_PGUP;
        break;
    case Qt::Key_PageDown:
        newScanCode = Q3DStudio::KEY_PGDN;
        break;
    case Qt::Key_F1:
        newScanCode = Q3DStudio::KEY_F1;
        break;
    case Qt::Key_F2:
        newScanCode = Q3DStudio::KEY_F2;
        break;
    case Qt::Key_F3:
        newScanCode = Q3DStudio::KEY_F3;
        break;
    case Qt::Key_F4:
        newScanCode = Q3DStudio::KEY_F4;
        break;
    case Qt::Key_F5:
        newScanCode = Q3DStudio::KEY_F5;
        break;
    case Qt::Key_F6:
        newScanCode = Q3DStudio::KEY_F6;
        break;
    case Qt::Key_F7:
        newScanCode = Q3DStudio::KEY_F7;
        break;
    case Qt::Key_F8:
        newScanCode = Q3DStudio::KEY_F8;
        break;
    case Qt::Key_F9:
        newScanCode = Q3DStudio::KEY_F9;
        break;
    case Qt::Key_F10:
        newScanCode = Q3DStudio::KEY_F10;
        break;
    case Qt::Key_F11:
        newScanCode = Q3DStudio::KEY_F11;
        break;
    case Qt::Key_F12:
        newScanCode = Q3DStudio::KEY_F12;
        break;
    case Qt::Key_F13:
        newScanCode = Q3DStudio::KEY_F13;
        break;
    case Qt::Key_F14:
        newScanCode = Q3DStudio::KEY_F14;
        break;
    case Qt::Key_QuoteLeft:
        newScanCode = Q3DStudio::KEY_GRAVE;
        break;
    case Qt::Key_Asterisk:
        newScanCode = Q3DStudio::KEY_MULTIPLY;
        break;
    case Qt::Key_BracketRight:
        newScanCode = Q3DStudio::KEY_RBRACKET;
        break;
    case Qt::Key_BracketLeft:
        newScanCode = Q3DStudio::KEY_LBRACKET;
        break;
    case Qt::Key_Semicolon:
        newScanCode = Q3DStudio::KEY_SEMICOLON;
        break;
    case Qt::Key_Comma:
        newScanCode = Q3DStudio::KEY_COMMA;
        break;
    case Qt::Key_Period:
        newScanCode = e->modifiers() == Qt::KeypadModifier ? Q3DStudio::KEY_NUMPADDECIMAL
                                                           : Q3DStudio::KEY_PERIOD;
        break;
    case Qt::Key_Apostrophe:
        newScanCode = Q3DStudio::KEY_APOSTROPHE;
        break;
    case Qt::Key_Slash:
        newScanCode = Q3DStudio::KEY_SLASH;
        break;
    case Qt::Key_Backslash:
        newScanCode = Q3DStudio::KEY_BACKSLASH;
        break;
    case Qt::Key_Equal:
        newScanCode = Q3DStudio::KEY_EQUALS;
        break;
    case Qt::Key_Space:
        newScanCode = Q3DStudio::KEY_SPACE;
        break;
    case Qt::Key_Shift:
        newScanCode =
                e->nativeScanCode() == RIGHT_SHIFT ? Q3DStudio::KEY_RSHIFT : Q3DStudio::KEY_LSHIFT;
        break;
    case Qt::Key_Control:
        newScanCode = e->nativeScanCode() == RIGHT_CTRL ? Q3DStudio::KEY_RCONTROL
                                                        : Q3DStudio::KEY_LCONTROL;
        break;
    case Qt::Key_Alt:
        newScanCode =
                e->nativeScanCode() == RIGHT_ALT ? Q3DStudio::KEY_RALT : Q3DStudio::KEY_LALT;
        break;
    default:
        break;
    }

    return newScanCode;
}

ViewerQmlStreamProxy *Q3DSPresentationPrivate::streamProxy()
{
    if (!m_streamProxy)
        m_streamProxy = new ViewerQmlStreamProxy();
    return m_streamProxy;
}

void Q3DSPresentationPrivate::handleSlideEntered(const QString &elementPath, unsigned int index,
                                                 const QString &name)
{
    Q3DSSceneElement *scene = qobject_cast<Q3DSSceneElement *>(m_elements.value(elementPath));
    if (scene)
        scene->d_func()->handleSlideEntered(index, name);
    Q_EMIT q_ptr->slideEntered(elementPath, index, name);
}

void Q3DSPresentationPrivate::handleDataOutputValueUpdate(const QString &name,
                                                          const QVariant &newValue)
{
    if (!m_dataOutputs.contains(name))
        return;

    Q3DSDataOutput *node = m_dataOutputs[name];
    node->setValue(newValue);
}

QT_END_NAMESPACE