File: runtime.h

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (3198 lines) | stat: -rw-r--r-- 106,602 bytes parent folder | download | duplicates (2)
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
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#ifndef MTROPOLIS_RUNTIME_H
#define MTROPOLIS_RUNTIME_H

#include "common/archive.h"
#include "common/array.h"
#include "common/events.h"
#include "common/language.h"
#include "common/platform.h"
#include "common/ptr.h"
#include "common/stream.h"
#include "common/hashmap.h"
#include "common/hash-str.h"

#include "graphics/pixelformat.h"

#include "mtropolis/actions.h"
#include "mtropolis/core.h"
#include "mtropolis/coroutine_protos.h"
#include "mtropolis/data.h"
#include "mtropolis/debug.h"
#include "mtropolis/hacks.h"
#include "mtropolis/miniscript_protos.h"
#include "mtropolis/subtitles.h"
#include "mtropolis/vthread.h"

class OSystem;

namespace Audio {

class Mixer;

} // End of namespace Audio

namespace Common {

class RandomSource;

} // End of namespace Common

namespace Graphics {

struct WinCursorGroup;
class MacCursor;
class MacFontManager;
class ManagedSurface;
class Cursor;
struct PixelFormat;
struct Surface;

} // End of namespace Graphics

namespace MTropolis {

class Asset;
class AssetManagerInterface;
class CoroutineManager;
class CursorGraphic;
class CursorGraphicCollection;
class Element;
class GraphicModifier;
class KeyboardInputEvent;
class MessageDispatch;
class MiniscriptThread;
class Modifier;
class ObjectLinkingScope;
class PlugInModifier;
class RuntimeObject;
class PlugIn;
class Project;
class Runtime;
class Structural;
class SystemInterface;
class VisualElement;
class Window;
class WorldManagerInterface;
struct DynamicValue;
struct DynamicValueWriteProxy;
struct IBoundaryDetector;
struct ICollider;
struct ILoadUIProvider;
struct IMessageConsumer;
struct IModifierContainer;
struct IPlugInModifierFactory;
struct IPlugInModifierFactoryAndDataFactory;
struct IPostEffect;
struct ISaveUIProvider;
struct ISaveWriter;
struct IStructuralReferenceVisitor;
struct MessageProperties;
struct ModifierLoaderContext;
struct PlugInModifierLoaderContext;
struct SIModifierFactory;
template<typename TElement, typename TElementData> class ElementFactory;

#ifdef MTROPOLIS_DEBUG_ENABLE
class DebugPrimaryTaskList;
#endif

char invariantToLower(char c);
Common::String toCaseInsensitive(const Common::String &str);
bool caseInsensitiveEqual(const Common::String &str1, const Common::String &str2);
size_t caseInsensitiveFind(const Common::String &stringToSearch, const Common::String &stringToFind);

enum ColorDepthMode {
	kColorDepthMode1Bit,
	kColorDepthMode2Bit,
	kColorDepthMode4Bit,
	kColorDepthMode8Bit,
	kColorDepthMode16Bit,
	kColorDepthMode32Bit,

	kColorDepthModeCount,

	kColorDepthModeInvalid,
};

namespace SceneTransitionTypes {

enum SceneTransitionType {
	kNone,
	kPatternDissolve,
	kRandomDissolve, // No steps
	kFade,
	kSlide, // Directional
	kPush,  // Directional
	kZoom,
	kWipe, // Directional
};

bool loadFromData(SceneTransitionType &transType, int32 data);

} // End of namespace SceneTransitionTypes

namespace SceneTransitionDirections {

enum SceneTransitionDirection {
	kUp,
	kDown,
	kLeft,
	kRight,
};

bool loadFromData(SceneTransitionDirection &transDir, int32 data);

} // End of namespace SceneTransitionDirections

enum ConstraintDirection {
	kConstraintDirectionNone,
	kConstraintDirectionHorizontal,
	kConstraintDirectionVertical,
};

enum MouseInteractivityTestType {
	kMouseInteractivityTestAnything,
	kMouseInteractivityTestMouseClick,
};

namespace DynamicValueSourceTypes {
	enum DynamicValueSourceType {
		kInvalid,

		kConstant,
		kVariableReference,
		kIncomingData,
	};
}

namespace DynamicValueTypes {

// These values are stored in the saved game format, so they must be stable
enum DynamicValueType {
	kInvalid = 0,

	kNull = 1,
	kInteger = 2,
	kFloat = 3,
	kPoint = 4,
	kIntegerRange = 5,
	kBoolean = 6,
	kVector = 7,
	kLabel = 8,
	kEvent = 9,

	kString = 12,
	kList = 13,
	kObject = 14,
	kWriteProxy = 15,

	kUnspecified = 16,
};

} // End of namespace DynamicValuesTypes

namespace AttributeIDs {

enum AttributeID {
	kAttribCache = 55,
	kAttribDirect = 56,
	kAttribVisible = 58,
	kAttribLayer = 24,
	kAttribPaused = 25,
	kAttribLoop = 57,
	kAttribPosition = 1,
	kAttribWidth = 2,
	kAttribHeight = 3,
	kAttribRate = 4,
	kAttribRange = 5,
	kAttribCel = 6,
	kAttribLoopBackForth = 59,
	kAttribPlayEveryFrame = 60,
	kAttribTimeValue = 16,
	kAttribTrackDisable = 51,
	kAttribTrackEnable = 50,
	kAttribVolume = 13,
	kAttribBalance = 26,
	kAttribText = 7,
	kAttribMasterVolume = 18,
	kAttribUserTimeout = 19,
};

} // End of namespace AttributeIDs

namespace EventIDs {

enum EventID {
	kNothing = 0,

	kElementEnableEdit = 207,
	kElementDisableEdit = 220,
	kElementSelect = 209,
	kElementDeselect = 210,
	kElementToggleSelect = 213,
	kElementUpdatedCalculated = 219,
	kElementShow = 222,
	kElementHide = 223,

	kElementScrollUp = 1001,
	kElementScrollDown = 1002,
	kElementScrollRight = 1005,
	kElementScrollLeft = 1006,

	kMotionStarted = 501,
	kMotionEnded = 502,

	kTransitionStarted = 503,
	kTransitionEnded = 504,

	kMouseDown = 301,
	kMouseUp = 302,
	kMouseOver = 303,
	kMouseOutside = 304,
	kMouseTrackedInside = 305,
	kMouseTrackedOutside = 306,
	kMouseTracking = 307,
	kMouseUpInside = 309,
	kMouseUpOutside = 310,

	kSceneStarted = 101,
	kSceneEnded = 102,
	kSceneDeactivated = 103,
	kSceneReactivated = 104,
	kSceneTransitionEnded = 506,

	kSharedSceneReturnedToScene = 401,
	kSharedSceneSceneChanged = 402,
	kSharedSceneNoNextScene = 403,
	kSharedSceneNoPrevScene = 404,

	kParentEnabled = 2001,
	kParentDisabled = 2002,
	kParentChanged = 227,

	kPreloadMedia = 1701,
	kFlushMedia = 1703,
	kPrerollMedia = 1704,

	kCloseProject = 1601,

	kUserTimeout = 1801,
	kProjectStarted = 1802,
	kProjectEnded = 1803,
	kFlushAllMedia = 1804,

	kAttribGet = 1300,
	kAttribSet = 1200,

	kClone = 226,
	kKill = 228,

	kPlay = 201,
	kStop = 202,
	kPause = 801,
	kUnpause = 802,
	kTogglePause = 803,
	kAtFirstCel = 804,
	kAtLastCel = 805,


	kAuthorMessage = 900,
};

bool isCommand(EventID eventID);

} // End of namespace EventIDs

MiniscriptInstructionOutcome pointWriteRefAttrib(Common::Point &point, MiniscriptThread *thread, DynamicValueWriteProxy &proxy, const Common::String &attrib);
Common::String pointToString(const Common::Point &point);

struct IntRange {
	IntRange();
	IntRange(int32 pmin, int32 pmax);

	int32 min;
	int32 max;

	bool load(const Data::IntRange &range);

	inline bool operator==(const IntRange &other) const {
		return min == other.min && max == other.max;
	}

	inline bool operator!=(const IntRange &other) const {
		return !((*this) == other);
	}

	MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, const Common::String &attrib);
	Common::String toString() const;
};

struct Label {
	Label();
	Label(int32 psuperGroupID, int32 pid);

	uint32 superGroupID;
	uint32 id;

	bool load(const Data::Label &label);

	inline bool operator==(const Label &other) const {
		return superGroupID == other.superGroupID && id == other.id;
	}

	inline bool operator!=(const Label &other) const {
		return !((*this) == other);
	}
};

struct Event {
	Event();
	Event(EventIDs::EventID peventType, uint32 peventInfo);

	EventIDs::EventID eventType;
	uint32 eventInfo;

	// Returns true if this event, interpreted as a filter, recognizes another event.
	// Handles cases where eventInfo is ignored (hopefully).
	bool respondsTo(const Event &otherEvent) const;

	bool load(const Data::Event &data);

	inline bool operator==(const Event &other) const {
		return eventType == other.eventType && eventInfo == other.eventInfo;
	}

	inline bool operator!=(const Event &other) const {
		return !((*this) == other);
	}
};

struct VarReference {
	VarReference();
	VarReference(uint32 pguid, const Common::String &psource);

	uint32 guid;
	Common::String source;
	Common::WeakPtr<Modifier> resolution;	// NOTE: This may not be a variable

	inline bool operator==(const VarReference &other) const {
		return guid == other.guid && source == other.source;
	}

	inline bool operator!=(const VarReference &other) const {
		return !((*this) == other);
	}

	bool resolve(Structural *structuralScope, Common::WeakPtr<RuntimeObject> &outObject) const;
	bool resolve(Modifier *modifierScope, Common::WeakPtr<RuntimeObject> &outObject) const;

	void linkInternalReferences(ObjectLinkingScope *scope);
	void visitInternalReferences(IStructuralReferenceVisitor *visitor);

private:
	bool resolveContainer(IModifierContainer *modifierContainer, Common::WeakPtr<RuntimeObject> &outObject) const;
	bool resolveSingleModifier(Modifier *modifier, Common::WeakPtr<RuntimeObject> &outObject) const;
};

struct ObjectReference {
	Common::WeakPtr<RuntimeObject> object;

	inline ObjectReference() {
	}

	inline explicit ObjectReference(const Common::WeakPtr<RuntimeObject> &objectPtr) : object(objectPtr) {
	}

	inline bool operator==(const ObjectReference &other) const {
		return !object.owner_before(other.object) && !other.object.owner_before(object);
	}

	inline bool operator!=(const ObjectReference &other) const {
		return !((*this) == other);
	}

	inline void reset() {
		object.reset();
	}
};

struct AngleMagVector {
	AngleMagVector();

	double angleDegrees; // These are stored as radians in the data but scripts treat them as degrees so it's just pointless constantly doing conversion...
	double magnitude;

	inline bool operator==(const AngleMagVector &other) const {
		return angleDegrees == other.angleDegrees && magnitude == other.magnitude;
	}

	inline bool operator!=(const AngleMagVector &other) const {
		return !((*this) == other);
	}

	inline static AngleMagVector createRadians(double angleRadians, double magnitude) {
		return AngleMagVector(angleRadians * (180.0 / M_PI), magnitude);
	}

	inline static AngleMagVector createDegrees(double angleDegrees, double magnitude) {
		return AngleMagVector(angleDegrees, magnitude);
	}

	MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, const Common::String &attrib);
	Common::String toString() const;

private:
	AngleMagVector(double angleDegrees, double magnitude);
};

struct ColorRGB8 {
	ColorRGB8();
	ColorRGB8(uint8 pr, uint8 pg, uint8 pb);

	uint8 r;
	uint8 g;
	uint8 b;

	bool load(const Data::ColorRGB16 &color);

	inline bool operator==(const ColorRGB8 &other) const {
		return r == other.r && g == other.g && b == other.b;
	}

	inline bool operator!=(const ColorRGB8 &other) const {
		return !((*this) == other);
	}
};

struct MessageFlags {
	MessageFlags();

	bool relay : 1;
	bool cascade : 1;
	bool immediate : 1;
};

struct DynamicValue;
struct DynamicList;

// This should be an interface, but since this exists to make global singletons that JUST supply a vtable,
// GCC complains about there being a global destructor, unless we delete the destructor, in which case
// it complains about a class having virtual functions but not having a virtual destructor, so we have to
// do this dispatch table stuff just to make GCC be quiet.
struct DynamicValueWriteInterface {
	typedef MiniscriptInstructionOutcome (*writeFunc_t)(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset);
	typedef MiniscriptInstructionOutcome (*refAttribFunc_t)(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	typedef MiniscriptInstructionOutcome (*refAttribIndexedFunc_t)(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	writeFunc_t write;
	refAttribFunc_t refAttrib;
	refAttribIndexedFunc_t refAttribIndexed;
};

template<class T>
class DynamicValueWriteInterfaceGlue {
public:
	static const DynamicValueWriteInterface *getInstance();

private:
	static DynamicValueWriteInterface _instance;
};

template<class T>
inline const DynamicValueWriteInterface *DynamicValueWriteInterfaceGlue<T>::getInstance() {
	return &_instance;
}

template<class T>
DynamicValueWriteInterface DynamicValueWriteInterfaceGlue<T>::_instance = {
	static_cast<DynamicValueWriteInterface::writeFunc_t>(T::write),
	static_cast<DynamicValueWriteInterface::refAttribFunc_t>(T::refAttrib),
	static_cast<DynamicValueWriteInterface::refAttribIndexedFunc_t>(T::refAttribIndexed),
};



struct DynamicValueWriteProxyPOD {
	uintptr ptrOrOffset;
	void *objectRef;
	const DynamicValueWriteInterface *ifc;

	static DynamicValueWriteProxyPOD createDefault();
};

struct DynamicValueWriteProxy {
	DynamicValueWriteProxy();

	DynamicValueWriteProxyPOD pod;
	Common::SharedPtr<DynamicList> containerList;
};

struct Point16POD {
	int16 x;
	int16 y;

	Common::Point toScummVMPoint() const;
};


class DynamicListContainerBase {
public:
	virtual ~DynamicListContainerBase();
	virtual bool setAtIndex(size_t index, const DynamicValue &dynValue) = 0;
	virtual bool getAtIndex(size_t index, DynamicValue &dynValue) const = 0;
	virtual void truncateToSize(size_t sz) = 0;
	virtual bool expandToMinimumSize(size_t sz) = 0;
	virtual void setFrom(const DynamicListContainerBase &other) = 0; // Only supports setting same type!
	virtual const void *getConstArrayPtr() const = 0;
	virtual void *getArrayPtr() = 0;
	virtual size_t getSize() const = 0;
	virtual bool compareEqual(const DynamicListContainerBase &other) const = 0;
	virtual DynamicListContainerBase *clone() const = 0;
};

struct DynamicListDefaultSetter {
	static void defaultSet(int32 &value);
	static void defaultSet(double &value);
	static void defaultSet(Common::Point &value);
	static void defaultSet(IntRange &value);
	static void defaultSet(bool &value);
	static void defaultSet(AngleMagVector &value);
	static void defaultSet(Label &value);
	static void defaultSet(Event &value);
	static void defaultSet(Common::String &value);
	static void defaultSet(Common::SharedPtr<DynamicList> &value);
	static void defaultSet(ObjectReference &value);
};

template<class T>
struct DynamicListValueConverter {
	typedef T DynamicValuePODType_t;

	static const T &dereference(const T *source) { return *source; }
};

struct DynamicListValueImporter {
	static bool importValue(const DynamicValue &dynValue, const int32 *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const double *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const Common::Point *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const IntRange *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const bool *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const AngleMagVector *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const Label *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const Event *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const Common::String *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const Common::SharedPtr<DynamicList> *&outPtr);
	static bool importValue(const DynamicValue &dynValue, const ObjectReference *&outPtr);
};

struct DynamicListValueExporter {
	static void exportValue(DynamicValue &dynValue, const int32 &value);
	static void exportValue(DynamicValue &dynValue, const double &value);
	static void exportValue(DynamicValue &dynValue, const Common::Point &value);
	static void exportValue(DynamicValue &dynValue, const IntRange &value);
	static void exportValue(DynamicValue &dynValue, const bool &value);
	static void exportValue(DynamicValue &dynValue, const AngleMagVector &value);
	static void exportValue(DynamicValue &dynValue, const Label &value);
	static void exportValue(DynamicValue &dynValue, const Event &value);
	static void exportValue(DynamicValue &dynValue, const Common::String &value);
	static void exportValue(DynamicValue &dynValue, const Common::SharedPtr<DynamicList> &value);
	static void exportValue(DynamicValue &dynValue, const ObjectReference &value);
};

template<class T>
class DynamicListContainer : public DynamicListContainerBase {
public:
	bool setAtIndex(size_t index, const DynamicValue &dynValue) override;
	bool getAtIndex(size_t index, DynamicValue &dynValue) const override;
	void truncateToSize(size_t sz) override;
	bool expandToMinimumSize(size_t sz) override;
	void setFrom(const DynamicListContainerBase &other) override;
	const void *getConstArrayPtr() const override;
	void *getArrayPtr() override;
	size_t getSize() const override;
	bool compareEqual(const DynamicListContainerBase &other) const override;
	DynamicListContainerBase *clone() const override;

private:
	Common::Array<T> _array;
};

template<>
class DynamicListContainer<void> : public DynamicListContainerBase {
public:
	DynamicListContainer();

	bool setAtIndex(size_t index, const DynamicValue &dynValue) override;
	bool getAtIndex(size_t index, DynamicValue &dynValue) const override;
	void truncateToSize(size_t sz) override;
	bool expandToMinimumSize(size_t sz) override;
	void setFrom(const DynamicListContainerBase &other) override;
	const void *getConstArrayPtr() const override;
	void *getArrayPtr() override;
	size_t getSize() const override;
	bool compareEqual(const DynamicListContainerBase &other) const override;
	DynamicListContainerBase *clone() const override;

public:
	size_t _size;
};

template<class T>
bool DynamicListContainer<T>::setAtIndex(size_t index, const DynamicValue &dynValue) {
	const typename DynamicListValueConverter<T>::DynamicValuePODType_t *valuePtr = nullptr;
	if (!DynamicListValueImporter::importValue(dynValue, valuePtr))
		return false;

	_array.reserve(index + 1);
	if (_array.size() <= index) {
		if (_array.size() < index) {
			T defaultValue;
			DynamicListDefaultSetter::defaultSet(defaultValue);
			while (_array.size() < index) {
				_array.push_back(defaultValue);
			}
		}
		_array.push_back(DynamicListValueConverter<T>::dereference(valuePtr));
	} else {
		_array[index] = DynamicListValueConverter<T>::dereference(valuePtr);
	}

	return true;
}

template<class T>
void DynamicListContainer<T>::truncateToSize(size_t sz) {
	if (_array.size() > sz)
		_array.resize(sz);
}

template<class T>
bool DynamicListContainer<T>::expandToMinimumSize(size_t sz) {
	_array.reserve(sz);
	if (_array.size() < sz) {
		T defaultValue;
		DynamicListDefaultSetter::defaultSet(defaultValue);
		while (_array.size() < sz) {
			_array.push_back(defaultValue);
		}
	}

	return true;
}

template<class T>
bool DynamicListContainer<T>::getAtIndex(size_t index, DynamicValue &dynValue) const {
	if (index >= _array.size())
		return false;

	DynamicListValueExporter::exportValue(dynValue, _array[index]);
	return true;
}

template<class T>
void DynamicListContainer<T>::setFrom(const DynamicListContainerBase &other) {
	_array = static_cast<const DynamicListContainer<T> &>(other)._array;
}

template<class T>
const void *DynamicListContainer<T>::getConstArrayPtr() const {
	return &_array;
}

template<class T>
void *DynamicListContainer<T>::getArrayPtr() {
	return &_array;
}

template<class T>
size_t DynamicListContainer<T>::getSize() const {
	return _array.size();
}

template<class T>
bool DynamicListContainer<T>::compareEqual(const DynamicListContainerBase &other) const {
	const DynamicListContainer<T> &otherTyped = static_cast<const DynamicListContainer<T> &>(other);
	return _array == otherTyped._array;
}

template<class T>
DynamicListContainerBase *DynamicListContainer<T>::clone() const {
	return new DynamicListContainer<T>(*this);
}

struct DynamicList {
	DynamicList();
	DynamicList(const DynamicList &other);
	~DynamicList();

	DynamicValueTypes::DynamicValueType getType() const;

	const Common::Array<int32> &getInt() const;
	const Common::Array<double> &getFloat() const;
	const Common::Array<Common::Point> &getPoint() const;
	const Common::Array<IntRange> &getIntRange() const;
	const Common::Array<AngleMagVector> &getVector() const;
	const Common::Array<Label> &getLabel() const;
	const Common::Array<Event> &getEvent() const;
	const Common::Array<Common::String> &getString() const;
	const Common::Array<bool> &getBool() const;
	const Common::Array<Common::SharedPtr<DynamicList> > &getList() const;
	const Common::Array<ObjectReference> &getObjectReference() const;

	Common::Array<int32> &getInt();
	Common::Array<double> &getFloat();
	Common::Array<Common::Point> &getPoint();
	Common::Array<IntRange> &getIntRange();
	Common::Array<AngleMagVector> &getVector();
	Common::Array<Label> &getLabel();
	Common::Array<Event> &getEvent();
	Common::Array<Common::String> &getString();
	Common::Array<bool> &getBool();
	Common::Array<Common::SharedPtr<DynamicList> > &getList();
	Common::Array<ObjectReference> &getObjectReference();

	bool getAtIndex(size_t index, DynamicValue &value) const;
	bool setAtIndex(size_t index, const DynamicValue &value);
	void deleteAtIndex(size_t index);
	void truncateToSize(size_t sz);
	void expandToMinimumSize(size_t sz);
	size_t getSize() const;

	void forceType(DynamicValueTypes::DynamicValueType type);

	static bool dynamicValueToIndex(size_t &outIndex, const DynamicValue &value);

	DynamicList &operator=(const DynamicList &other);

	bool operator==(const DynamicList &other) const;
	inline bool operator!=(const DynamicList &other) const {
		return !((*this) == other);
	}

	void swap(DynamicList &other);

	Common::SharedPtr<DynamicList> clone() const;

	void createWriteProxyForIndex(size_t index, DynamicValueWriteProxy &proxy);

private:
	struct WriteProxyInterface {
		static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset);
		static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
		static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);
	};

	void initFromOther(const DynamicList &other);
	void destroyContainer();
	bool createContainerAndSetType(DynamicValueTypes::DynamicValueType type);

	DynamicValueTypes::DynamicValueType _type;
	DynamicListContainerBase *_container;
};

// Dynamic value container.  Somewhat importantly, lists stored in dynamic values
// are BY REFERENCE and must be cloned as necessary.
struct DynamicValue {
	DynamicValue();
	DynamicValue(const DynamicValue &other);
	~DynamicValue();

	bool loadConstant(const Data::InternalTypeTaggedValue &data, const Common::String &varString);
	bool loadConstant(const Data::PlugInTypeTaggedValue &data);

	DynamicValueTypes::DynamicValueType getType() const;

	const int32 &getInt() const;
	const double &getFloat() const;
	const Common::Point &getPoint() const;
	const IntRange &getIntRange() const;
	const AngleMagVector &getVector() const;
	const Label &getLabel() const;
	const Event &getEvent() const;
	const Common::String &getString() const;
	const bool &getBool() const;
	const Common::SharedPtr<DynamicList> &getList() const;
	const ObjectReference &getObject() const;
	const DynamicValueWriteProxy &getWriteProxy() const;

	void clear();

	void setInt(int32 value);
	void setFloat(double value);
	void setPoint(const Common::Point &value);
	void setIntRange(const IntRange &value);
	void setVector(const AngleMagVector &value);
	void setLabel(const Label &value);
	void setEvent(const Event &value);
	void setString(const Common::String &value);
	void setBool(bool value);
	void setList(const Common::SharedPtr<DynamicList> &value);
	void setObject(const ObjectReference &value);
	void setObject(const Common::WeakPtr<RuntimeObject> &value);
	void setWriteProxy(const DynamicValueWriteProxy &writeProxy);

	bool roundToInt(int32 &outInt) const;

	bool convertToType(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;

	DynamicValue dereference() const;

	DynamicValue &operator=(const DynamicValue &other);

	bool operator==(const DynamicValue &other) const;
	inline bool operator!=(const DynamicValue &other) const {
		return !((*this) == other);
	}

private:
	union ValueUnion {
		ValueUnion();
		~ValueUnion();

		double asFloat;
		int32 asInt;
		IntRange asIntRange;
		AngleMagVector asVector;
		Label asLabel;
		Event asEvent;
		Common::Point asPoint;
		bool asBool;
		DynamicValueWriteProxy asWriteProxy;
		Common::String asString;
		Common::SharedPtr<DynamicList> asList;
		ObjectReference asObj;

		uint64 asUnset;

		template<class T, T(ValueUnion::*TMember)>
		void construct(const T &value);

		template<class T, T(ValueUnion::*TMember)>
		void construct(T &&value);

		template<class T, T(ValueUnion::*TMember)>
		void assign(const T &value);

		template<class T, T(ValueUnion::*TMember)>
		void assign(T &&value);

		template<class T, T(ValueUnion::*TMember)>
		void destruct();
	};

	template<class T>
	void internalSwap(T &a, T &b) {
		T temp = a;
		a = b;
		b = temp;
	}

	bool convertIntToType(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;
	bool convertFloatToType(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;
	bool convertBoolToType(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;
	bool convertStringToType(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;

	bool convertToTypeNoDereference(DynamicValueTypes::DynamicValueType targetType, DynamicValue &result) const;

	void setFromOther(const DynamicValue &other);
	void setFromOther(DynamicValue &&other);

	DynamicValueTypes::DynamicValueType _type;
	ValueUnion _value;
};

struct DynamicValueSource {
	DynamicValueSource();
	DynamicValueSource(const DynamicValueSource &other);
	DynamicValueSource(DynamicValueSource &&other);
	~DynamicValueSource();

	DynamicValueSource &operator=(const DynamicValueSource &other);
	DynamicValueSource &operator=(DynamicValueSource &&other);

	DynamicValueSourceTypes::DynamicValueSourceType getSourceType() const;
	const DynamicValue &getConstant() const;
	const VarReference &getVarReference() const;

	bool load(const Data::InternalTypeTaggedValue &data, const Common::String &varSource, const Common::String &varString);
	bool load(const Data::PlugInTypeTaggedValue &data);

	void linkInternalReferences(ObjectLinkingScope *scope);
	void visitInternalReferences(IStructuralReferenceVisitor *visitor);

	DynamicValue produceValue(const DynamicValue &incomingData) const;

private:
	union ValueUnion {
		ValueUnion();
		~ValueUnion();

		DynamicValue _constValue;
		VarReference _varReference;
	};

	void destructValue();
	void initFromOther(const DynamicValueSource &other);
	void initFromOther(DynamicValueSource &&other);

	DynamicValueSourceTypes::DynamicValueSourceType _sourceType;
	ValueUnion _valueUnion;
};

template<class TFloat>
struct DynamicValueWriteFloatHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset) {
		DynamicValue derefValue = value.dereference();

		TFloat &dest = *static_cast<TFloat *>(objectRef);
		switch (derefValue.getType()) {
		case DynamicValueTypes::kFloat:
			dest = static_cast<TFloat>(derefValue.getFloat());
			return kMiniscriptInstructionOutcomeContinue;
		case DynamicValueTypes::kInteger:
			dest = static_cast<TFloat>(derefValue.getInt());
			return kMiniscriptInstructionOutcomeContinue;
		default:
			return kMiniscriptInstructionOutcomeFailed;
		}
	}
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib) {
		return kMiniscriptInstructionOutcomeFailed;
	}
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index) {
		return kMiniscriptInstructionOutcomeFailed;
	}

	static void create(TFloat *floatValue, DynamicValueWriteProxy &proxy) {
		proxy.pod.ptrOrOffset = 0;
		proxy.pod.objectRef = floatValue;
		proxy.pod.ifc = DynamicValueWriteInterfaceGlue<DynamicValueWriteFloatHelper<TFloat> >::getInstance();
	}
};

template<class TInteger>
struct DynamicValueWriteIntegerHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset) {
		DynamicValue derefValue = value.dereference();

		TInteger &dest = *static_cast<TInteger *>(objectRef);
		switch (derefValue.getType()) {
		case DynamicValueTypes::kFloat:
			dest = static_cast<TInteger>(floor(derefValue.getFloat() + 0.5));
			return kMiniscriptInstructionOutcomeContinue;
		case DynamicValueTypes::kInteger:
			dest = static_cast<TInteger>(derefValue.getInt());
			return kMiniscriptInstructionOutcomeContinue;
		default:
			return kMiniscriptInstructionOutcomeFailed;
		}
	}
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib) {
		return kMiniscriptInstructionOutcomeFailed;
	}
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index) {
		return kMiniscriptInstructionOutcomeFailed;
	}

	static void create(TInteger *intValue, DynamicValueWriteProxy &proxy) {
		proxy.pod.ptrOrOffset = 0;
		proxy.pod.objectRef = intValue;
		proxy.pod.ifc = DynamicValueWriteInterfaceGlue<DynamicValueWriteIntegerHelper<TInteger> >::getInstance();
	}
};

struct DynamicValueWritePointHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset);
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	static void create(Common::Point *pointValue, DynamicValueWriteProxy &proxy);
};

struct DynamicValueWriteBoolHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset);
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	static void create(bool *boolValue, DynamicValueWriteProxy &proxy);
};

struct DynamicValueWriteStringHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset);
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	static void create(Common::String *strValue, DynamicValueWriteProxy &proxy);
};

struct DynamicValueWriteDiscardHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset);
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	static void create(DynamicValueWriteProxy &proxy);
};

template<class TClass, MiniscriptInstructionOutcome (TClass::*TWriteMethod)(MiniscriptThread *thread, const DynamicValue &dest), MiniscriptInstructionOutcome (TClass::*TRefAttribMethod)(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, const Common::String &attrib)>
struct DynamicValueWriteOrRefAttribFuncHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset) {
		DynamicValue derefValue = dest.dereference();

		return (static_cast<TClass *>(objectRef)->*TWriteMethod)(thread, derefValue);
	}
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib) {
		return (static_cast<TClass *>(objectRef)->*TRefAttribMethod)(thread, proxy, attrib);
	}
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index) {
		return kMiniscriptInstructionOutcomeFailed;
	}

	static void create(TClass *obj, DynamicValueWriteProxy &proxy) {
		proxy.pod.ptrOrOffset = 0;
		proxy.pod.objectRef = obj;
		proxy.pod.ifc = DynamicValueWriteInterfaceGlue<DynamicValueWriteOrRefAttribFuncHelper<TClass, TWriteMethod, TRefAttribMethod> >::getInstance();
	}
};

template<class TClass, MiniscriptInstructionOutcome (TClass::*TWriteMethod)(MiniscriptThread *thread, const DynamicValue &dest), bool TDereference>
struct DynamicValueWriteFuncHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset) {
		if (TDereference) {
			return (static_cast<TClass *>(objectRef)->*TWriteMethod)(thread, dest.dereference());
		} else
			return (static_cast<TClass *>(objectRef)->*TWriteMethod)(thread, dest);
	}
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib) {
		return kMiniscriptInstructionOutcomeFailed;
	}
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index) {
		return kMiniscriptInstructionOutcomeFailed;
	}

	static void create(TClass *obj, DynamicValueWriteProxy &proxy) {
		proxy.pod.ptrOrOffset = 0;
		proxy.pod.objectRef = obj;
		proxy.pod.ifc = DynamicValueWriteInterfaceGlue<DynamicValueWriteFuncHelper<TClass, TWriteMethod, TDereference> >::getInstance();
	}
};

struct DynamicValueWriteObjectHelper {
	static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &value, void *objectRef, uintptr ptrOrOffset);
	static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
	static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	static void create(RuntimeObject *obj, DynamicValueWriteProxy &proxy);
};

struct MessengerSendSpec {
	MessengerSendSpec();

	bool load(const Data::Event &dataEvent, uint32 dataMessageFlags, const Data::InternalTypeTaggedValue &dataLocator, const Common::String &dataWithSource, const Common::String &dataWithString, uint32 dataDestination);
	bool load(const Data::PlugInTypeTaggedValue &dataEvent, const MessageFlags &dataMessageFlags, const Data::PlugInTypeTaggedValue &dataWith, uint32 dataDestination);

	void linkInternalReferences(ObjectLinkingScope *outerScope);
	void visitInternalReferences(IStructuralReferenceVisitor *visitor);

	void resolveDestination(Runtime *runtime, Modifier *sender, RuntimeObject *triggerSource, Common::WeakPtr<Structural> &outStructuralDest, Common::WeakPtr<Modifier> &outModifierDest, RuntimeObject *customDestination) const;

	static void resolveVariableObjectType(RuntimeObject *obj, Common::WeakPtr<Structural> &outStructuralDest, Common::WeakPtr<Modifier> &outModifierDest);

	void sendFromMessenger(Runtime *runtime, Modifier *sender, RuntimeObject *triggerSource, const DynamicValue &incomingData, RuntimeObject *customDestination) const;
	void sendFromMessengerWithCustomData(Runtime *runtime, Modifier *sender, RuntimeObject *triggerSource, const DynamicValue &data, RuntimeObject *customDestination) const;

	enum LinkType {
		kLinkTypeNotYetLinked,
		kLinkTypeStructural,
		kLinkTypeModifier,
		kLinkTypeCoded,
		kLinkTypeUnresolved,
	};

	Event send;
	MessageFlags messageFlags;
	DynamicValueSource with;
	uint32 destination; // May be a MessageDestination or GUID

	LinkType _linkType;
	Common::WeakPtr<Structural> _resolvedStructuralDest;
	Common::WeakPtr<Modifier> _resolvedModifierDest;
	Common::WeakPtr<Modifier> _resolvedVarSource;

private:
	void resolveHierarchyStructuralDestination(Runtime *runtime, Modifier *sender, Common::WeakPtr<Structural> &outStructuralDest, Common::WeakPtr<Modifier> &outModifierDest, bool (*compareFunc)(Structural *structural)) const;
	static bool isSceneFilter(Structural *section);
	static bool isSectionFilter(Structural *section);
	static bool isSubsectionFilter(Structural *section);
	static bool isElementFilter(Structural *section);
};

enum MessageDestination {
	kMessageDestNone = 0,

	kMessageDestSharedScene = 0x65,
	kMessageDestScene = 0x66,
	kMessageDestSection = 0x67,
	kMessageDestProject = 0x68,
	kMessageDestActiveScene = 0x69,
	kMessageDestElementsParent = 0x6a,
	kMessageDestChildren = 0x6b,	// Saw this somewhere but can't find it any more?
	kMessageDestModifiersParent = 0x6c,
	kMessageDestSubsection = 0x6d,

	kMessageDestElement = 0xc9,
	kMessageDestSourcesParent = 0xcf,

	kMessageDestBehavior = 0xd4,
	kMessageDestNextElement = 0xd1,
	kMessageDestPrevElement = 0xd2,
	kMessageDestBehaviorsParent = 0xd3,
};

struct SegmentDescription {
	SegmentDescription();

	int volumeID;
	Common::String filePath;
	Common::SeekableReadStream *stream;
};

struct IPlugInModifierRegistrar : public IInterfaceBase {
	virtual void registerPlugInModifier(const char *name, const Data::IPlugInModifierDataFactory *loader, const IPlugInModifierFactory *factory) = 0;
	void registerPlugInModifier(const char *name, const IPlugInModifierFactoryAndDataFactory *loaderFactory);
};

class PlugIn {
public:
	virtual ~PlugIn();

	virtual void registerModifiers(IPlugInModifierRegistrar *registrar) const = 0;
};

class ProjectPersistentResource {
public:
	virtual ~ProjectPersistentResource();
};

struct ProjectResources {
	virtual ~ProjectResources();

	Common::Array<Common::SharedPtr<ProjectPersistentResource> > persistentResources;
};

class CursorGraphic {
public:
	virtual ~CursorGraphic();

	virtual Graphics::Cursor *getCursor() const = 0;
};

class MacCursorGraphic : public CursorGraphic {
public:
	explicit MacCursorGraphic(const Common::SharedPtr<Graphics::MacCursor> &macCursor);

	Graphics::Cursor *getCursor() const override;

private:
	Common::SharedPtr<Graphics::MacCursor> _macCursor;
};

class WinCursorGraphic : public CursorGraphic {
public:
	explicit WinCursorGraphic(const Common::SharedPtr<Graphics::WinCursorGroup> &winCursorGroup, Graphics::Cursor *cursor);

	Graphics::Cursor *getCursor() const override;

private:
	Common::SharedPtr<Graphics::WinCursorGroup> _winCursorGroup;
	Graphics::Cursor *_cursor;
};

class CursorGraphicCollection {
public:
	CursorGraphicCollection();
	~CursorGraphicCollection();

	void addWinCursorGroup(uint32 cursorGroupID, const Common::SharedPtr<Graphics::WinCursorGroup> &cursorGroup);
	void addMacCursor(uint32 cursorID, const Common::SharedPtr<Graphics::MacCursor> &cursor);

	Common::SharedPtr<CursorGraphic> getGraphicByID(uint32 id) const;

private:
	Common::HashMap<uint32, Common::SharedPtr<CursorGraphic> > _cursorGraphics;
};

// The project platform is the platform that the project is running on (not the format of the project)
enum ProjectPlatform {
	kProjectPlatformUnknown,

	kProjectPlatformWindows,
	kProjectPlatformMacintosh,
};

class ProjectDescription {
public:
	ProjectDescription(ProjectPlatform platform, RuntimeVersion runtimeVersion, bool autoDetectVersion, Common::Archive *rootArchive, const Common::Path &projectRootDir);
	~ProjectDescription();

	void addSegment(int volumeID, const char *filePath);
	void addSegment(int volumeID, Common::SeekableReadStream *stream);
	const Common::Array<SegmentDescription> &getSegments() const;

	void addPlugIn(const Common::SharedPtr<PlugIn> &plugIn);
	const Common::Array<Common::SharedPtr<PlugIn> > &getPlugIns() const;

	void setResources(const Common::SharedPtr<ProjectResources> &resources);
	const Common::SharedPtr<ProjectResources> &getResources() const;

	void setCursorGraphics(const Common::SharedPtr<CursorGraphicCollection> &cursorGraphics);
	const Common::SharedPtr<CursorGraphicCollection> &getCursorGraphics() const;

	void setLanguage(const Common::Language &language);
	const Common::Language &getLanguage() const;

	ProjectPlatform getPlatform() const;
	RuntimeVersion getRuntimeVersion() const;
	bool isRuntimeVersionAuto() const;

	Common::Archive *getRootArchive() const;
	const Common::Path &getProjectRootDir() const;

	const SubtitleTables &getSubtitles() const;
	void setSubtitles(const SubtitleTables &subs);

private:
	Common::Array<SegmentDescription> _segments;
	Common::Array<Common::SharedPtr<PlugIn> > _plugIns;
	Common::SharedPtr<ProjectResources> _resources;
	Common::SharedPtr<CursorGraphicCollection> _cursorGraphics;
	Common::Language _language;
	SubtitleTables _subtitles;
	ProjectPlatform _platform;
	RuntimeVersion _runtimeVersion;
	bool _isRuntimeVersionAuto;

	Common::Archive *_rootArchive;
	Common::Path _projectRootDir;
};

struct VolumeState {
	VolumeState();

	Common::String name;
	int volumeID;
	bool isMounted;
};

class ObjectLinkingScope {
public:
	ObjectLinkingScope();
	~ObjectLinkingScope();

	void setParent(ObjectLinkingScope *parent);
	void addObject(uint32 guid, const Common::String &name, const Common::WeakPtr<RuntimeObject> &object);
	Common::WeakPtr<RuntimeObject> resolve(uint32 staticGUID) const;
	Common::WeakPtr<RuntimeObject> resolve(const Common::String &name, bool isNameAlreadyInsensitive) const;
	Common::WeakPtr<RuntimeObject> resolve(uint32 staticGUID, const Common::String &name, bool isNameAlreadyInsensitive) const;

	void reset();

private:
	Common::HashMap<uint32, Common::WeakPtr<RuntimeObject> > _guidToObject;
	Common::HashMap<Common::String, Common::WeakPtr<RuntimeObject> > _nameToObject;
	ObjectLinkingScope *_parent;
};

struct LowLevelSceneStateTransitionAction {
	enum ActionType {
		kLoad,
		kUnload,
		kSendMessage,
		kAutoResetCursor,
		kHideAllElements,
		kShowDefaultVisibleElements,
	};

	explicit LowLevelSceneStateTransitionAction(const Common::SharedPtr<MessageDispatch> &msg);
	explicit LowLevelSceneStateTransitionAction(ActionType actionType);
	LowLevelSceneStateTransitionAction(const LowLevelSceneStateTransitionAction &other);
	LowLevelSceneStateTransitionAction(const Common::SharedPtr<Structural> &scene, ActionType actionType);

	ActionType getActionType() const;
	const Common::SharedPtr<Structural> &getScene() const;
	const Common::SharedPtr<MessageDispatch> &getMessage() const;

	LowLevelSceneStateTransitionAction &operator=(const LowLevelSceneStateTransitionAction &other);

private:
	ActionType _actionType;
	Common::SharedPtr<Structural> _scene;
	Common::SharedPtr<MessageDispatch> _msg;
};

struct ObjectParentChange {
	explicit ObjectParentChange(const Common::WeakPtr<RuntimeObject> &object, const Common::WeakPtr<RuntimeObject> &newParent);

	Common::WeakPtr<RuntimeObject> _object;
	Common::WeakPtr<RuntimeObject> _newParent;
};

struct HighLevelSceneTransition {
	enum Type {
		kTypeChangeToScene,
		kTypeChangeSharedScene,
		kTypeForceLoadScene,
		kTypeRequestUnloadScene,
	};

	HighLevelSceneTransition(const Common::SharedPtr<Structural> &hlst_scene, Type hlst_type, bool hlst_addToDestinationScene, bool hlst_addToReturnList);

	Common::SharedPtr<Structural> scene;
	Type type;
	bool addToDestinationScene;
	bool addToReturnList;
};

struct SceneTransitionEffect {
	SceneTransitionEffect();

	uint32 _duration; // 6000000 is maximum
	uint16 _steps;
	SceneTransitionTypes::SceneTransitionType _transitionType;
	SceneTransitionDirections::SceneTransitionDirection _transitionDirection;
};

class MessageDispatch {
public:
	enum class RootType {
		Invalid,

		Command,
		Structural,
		Modifier,
	};

	MessageDispatch(const Common::SharedPtr<MessageProperties> &msgProps, Structural *root, bool cascade, bool relay, bool couldBeCommand);
	MessageDispatch(const Common::SharedPtr<MessageProperties> &msgProps, Modifier *root, bool cascade, bool relay, bool couldBeCommand);

	const Common::SharedPtr<MessageProperties> &getMsg() const;
	RuntimeObject *getRootPropagator() const;

	bool isCascade() const;
	bool isRelay() const;

	RootType getRootType() const;
	const Common::WeakPtr<RuntimeObject> &getRootWeakPtr() const;

private:
	Common::SharedPtr<MessageProperties> _msg;

	Common::WeakPtr<RuntimeObject> _root;

	bool _cascade; // Traverses structure tree
	bool _relay;   // Fire on multiple modifiers
	bool _isCommand;

	RootType _rootType;
};

class KeyEventDispatch {
public:
	explicit KeyEventDispatch(const Common::SharedPtr<KeyboardInputEvent> &evt);

	Common::Array<Common::WeakPtr<RuntimeObject> > &getKeyboardMessengerArray();
	static bool keyboardMessengerFilterFunc(void *userData, RuntimeObject *object);

	bool isTerminated() const;
	VThreadState continuePropagating(Runtime *runtime);

private:
	Common::Array<Common::WeakPtr<RuntimeObject> > _keyboardMessengers;
	size_t _dispatchIndex;
	const Common::SharedPtr<KeyboardInputEvent> _evt;
};

class Scheduler;

class ScheduledEvent : Common::NonCopyable {
	friend class Scheduler;

public:
	void cancel();
	uint64 getScheduledTime() const;
	void activate(Runtime *runtime) const;

private:
	ScheduledEvent(void *obj, void (*activateFunc)(void *, Runtime *), uint64 scheduledTime, Scheduler *scheduler);

	void *_obj;
	void (*_activateFunc)(void *obj, Runtime *runtime);

	uint64 _scheduledTime;
	Scheduler *_scheduler;
};

class Scheduler {
	friend class ScheduledEvent;

public:
	Scheduler();
	~Scheduler();

	template<class T, void (T::*TMethodPtr)(Runtime *)>
	Common::SharedPtr<ScheduledEvent> scheduleMethod(uint64 scheduledTime, T* obj) {
		Common::SharedPtr<ScheduledEvent> evt(new ScheduledEvent(obj, Scheduler::methodActivateHelper<T, TMethodPtr>, scheduledTime, this));
		insertEvent(evt);
		return evt;
	}

	Common::SharedPtr<ScheduledEvent> getFirstEvent() const;
	void descheduleFirstEvent();

private:
	template<class T, void (T::*TMethodPtr)(Runtime *)>
	static void methodActivateHelper(void *obj, Runtime *runtime) {
		(static_cast<T *>(obj)->*TMethodPtr)(runtime);
	}

	void insertEvent(const Common::SharedPtr<ScheduledEvent> &evt);
	void removeEvent(const ScheduledEvent *evt);

	Common::Array<Common::SharedPtr<ScheduledEvent>> _events;
};

enum OSEventType {
	kOSEventTypeMouseDown,
	kOSEventTypeMouseUp,
	kOSEventTypeMouseMove,

	kOSEventTypeKeyboard,

	kOSEventTypeAction,
};

class OSEvent {
public:
	explicit OSEvent(OSEventType eventType);
	virtual ~OSEvent();

	OSEventType getEventType() const;

private:
	OSEventType _eventType;
};

class MouseInputEvent : public OSEvent {
public:
	explicit MouseInputEvent(OSEventType eventType, int32 x, int32 y, Actions::MouseButton button);

	int32 getX() const;
	int32 getY() const;
	Actions::MouseButton getButton() const;

private:
	int32 _x;
	int32 _y;
	Actions::MouseButton _button;
};

class KeyboardInputEvent : public OSEvent {
public:
	explicit KeyboardInputEvent(OSEventType osEventType, Common::EventType keyEventType, bool repeat, const Common::KeyState &keyEvt);

	Common::EventType getKeyEventType() const;
	bool isRepeat() const;
	const Common::KeyState &getKeyState() const;

private:
	Common::EventType _keyEventType;
	bool _repeat;
	const Common::KeyState _keyEvt;
};

class ActionEvent : public OSEvent {
public:
	explicit ActionEvent(OSEventType osEventType, Actions::Action action);

	Actions::Action getAction() const;

private:
	Actions::Action _action;
};

struct DragMotionProperties {
	DragMotionProperties();

	ConstraintDirection constraintDirection;
	Common::Rect constraintMargin;
	bool constrainToParent;
};

class SceneTransitionHooks {
public:
	virtual ~SceneTransitionHooks();

	virtual void onSceneTransitionSetup(Runtime *runtime, const Common::WeakPtr<Structural> &oldScene, const Common::WeakPtr<Structural> &newScene);
	virtual void onSceneTransitionEnded(Runtime *runtime, const Common::WeakPtr<Structural> &newScene);
	virtual void onProjectStarted(Runtime *runtime);
};

class Palette {
public:
	Palette();
	explicit Palette(const ColorRGB8 *colors);

	void initDefaultPalette(int version);

	const byte *getPalette() const;

	static const uint kNumColors = 256;

private:
	byte _colors[kNumColors * 3];
};

class Runtime {
public:
	explicit Runtime(OSystem *system, Audio::Mixer *mixer, ISaveUIProvider *saveProvider, ILoadUIProvider *loadProvider, const Common::SharedPtr<SubtitleRenderer> &subRenderer);
	~Runtime();

	bool runFrame();
	void drawFrame();

	void queueProject(const Common::SharedPtr<ProjectDescription> &desc);
	void closeProject();

	void addVolume(int volumeID, const char *name, bool isMounted);
	bool getVolumeState(const Common::String &name, int &outVolumeID, bool &outIsMounted) const;

	void addSceneReturn();
	void addSceneStateTransition(const HighLevelSceneTransition &transition);

	void setSceneTransitionEffect(bool isInDestinationScene, SceneTransitionEffect *effect);

	Project *getProject() const;

	void postConsumeMessageTask(IMessageConsumer *msgConsumer, const Common::SharedPtr<MessageProperties> &msg);
	void postConsumeCommandTask(Structural *structural, const Common::SharedPtr<MessageProperties> &msg);

	uint32 allocateRuntimeGUID();

	void addWindow(const Common::SharedPtr<Window> &window);
	void removeWindow(Window *window);

	// Sets up a supported display mode
	void setupDisplayMode(ColorDepthMode displayMode, const Graphics::PixelFormat &pixelFormat);

	bool isDisplayModeSupported(ColorDepthMode displayMode) const;

	// Switches to a specified display mode.  Returns true if the mode was actually changed.  If so, all windows will need
	// to be recreated.
	bool switchDisplayMode(ColorDepthMode realDisplayMode, ColorDepthMode fakeDisplayMode);

	void setDisplayResolution(uint16 width, uint16 height);
	void getDisplayResolution(uint16 &outWidth, uint16 &outHeight) const;

	ColorDepthMode getRealColorDepth() const;
	ColorDepthMode getFakeColorDepth() const;	// Fake color depth that will be reported to scripts

	const Graphics::PixelFormat &getRenderPixelFormat() const;

	const Common::SharedPtr<Graphics::MacFontManager> &getMacFontManager() const;

	const Common::SharedPtr<Structural> &getActiveMainScene() const;
	const Common::SharedPtr<Structural> &getActiveSharedScene() const;
	void getSceneStack(Common::Array<Common::SharedPtr<Structural> > &sceneStack) const;

	bool mustDraw() const;

	uint64 getRealTime() const;
	uint64 getPlayTime() const;

	VThread &getVThread() const;

	// Sending a message on the VThread means "immediately"
	void sendMessageOnVThread(const Common::SharedPtr<MessageDispatch> &dispatch);

	struct SendMessageOnVThreadCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_2(Runtime *, runtime, Common::SharedPtr<MessageDispatch>, dispatch);
	};

	void queueMessage(const Common::SharedPtr<MessageDispatch> &dispatch);

	void queueOSEvent(const Common::SharedPtr<OSEvent> &osEvent);

	Scheduler &getScheduler();

	void getScenesInRenderOrder(Common::Array<Structural *> &scenes) const;

	void instantiateIfAlias(Common::SharedPtr<Modifier> &modifier, const Common::WeakPtr<RuntimeObject> &relinkParent);

	Common::SharedPtr<Window> findTopWindow(int32 x, int32 y) const;

	void setVolume(double volume);

	void onMouseDown(int32 x, int32 y, Actions::MouseButton mButton);
	void onMouseMove(int32 x, int32 y);
	void onMouseUp(int32 x, int32 y, Actions::MouseButton mButton);
	void onKeyboardEvent(const Common::EventType evtType, bool repeat, const Common::KeyState &keyEvt);
	void onAction(MTropolis::Actions::Action action);

	const Common::Point &getCachedMousePosition() const;
	void setModifierCursorOverride(uint32 cursorID);
	void clearModifierCursorOverride();
	void forceCursorRefreshOnce();
	void setAutoResetCursor(bool enabled);

	uint getMultiClickCount() const;

	bool isAwaitingSceneTransition() const;

	Common::RandomSource *getRandom() const;
	WorldManagerInterface *getWorldManagerInterface() const;
	AssetManagerInterface *getAssetManagerInterface() const;
	SystemInterface *getSystemInterface() const;

	ISaveUIProvider *getSaveProvider() const;
	ILoadUIProvider *getLoadProvider() const;

	Audio::Mixer *getAudioMixer() const;

	Hacks &getHacks();
	const Hacks &getHacks() const;

	void setSceneGraphDirty();
	void clearSceneGraphDirty();
	bool isSceneGraphDirty() const;

	void addCollider(ICollider *collider);
	void removeCollider(ICollider *collider);
	void checkCollisions(ICollider *optRestrictToCollider);

	void setCursorElement(const Common::WeakPtr<VisualElement> &element);
	void updateCursorElementPosition();

	void addBoundaryDetector(IBoundaryDetector *boundaryDetector);
	void removeBoundaryDetector(IBoundaryDetector *boundaryDetector);
	void checkBoundaries();

	void addPostEffect(IPostEffect *postEffect);
	void removePostEffect(IPostEffect *postEffect);
	const Common::Array<IPostEffect *> &getPostEffects() const;

	const Palette &getGlobalPalette() const;
	void setGlobalPalette(const Palette &palette);

	void addMouseBlocker();
	void removeMouseBlocker();

	const Common::String *resolveAttributeIDName(uint32 attribID) const;

	const Common::WeakPtr<Window> &getMainWindow() const;

	const Common::SharedPtr<Graphics::ManagedSurface> &getSaveScreenshotOverride() const;
	void setSaveScreenshotOverride(const Common::SharedPtr<Graphics::ManagedSurface> &screenshot);

	bool isIdle() const;

	const Common::SharedPtr<SubtitleRenderer> &getSubtitleRenderer() const;

	void queueCloneObject(const Common::WeakPtr<RuntimeObject> &obj);
	void queueKillObject(const Common::WeakPtr<RuntimeObject> &obj);
	void queueChangeObjectParent(const Common::WeakPtr<RuntimeObject> &obj, const Common::WeakPtr<RuntimeObject> &newParent);

	void hotLoadScene(Structural *structural);

#ifdef MTROPOLIS_DEBUG_ENABLE
	void debugSetEnabled(bool enabled);
	void debugBreak();
	Debugger *debugGetDebugger() const;

	void debugGetPrimaryTaskList(Common::Array<Common::SharedPtr<DebugPrimaryTaskList> > &primaryTaskLists);
#endif

private:
	enum SceneTransitionState {
		kSceneTransitionStateNotTransitioning,
		kSceneTransitionStateWaitingForDraw,
		kSceneTransitionStateTransitioning,
	};

	struct SceneStackEntry {
		SceneStackEntry();

		Common::SharedPtr<Structural> scene;
	};

	struct Teardown {
		Teardown();

		Common::WeakPtr<Structural> structural;
		Common::WeakPtr<Modifier> modifier;
		bool onlyRemoveChildren;
	};

	struct SceneReturnListEntry {
		SceneReturnListEntry();

		Common::SharedPtr<Structural> scene;
		bool isAddToDestinationSceneTransition;
	};

	struct DispatchMethodTaskData {
		Common::SharedPtr<MessageDispatch> dispatch;
	};

	struct DispatchKeyTaskData {
		Common::SharedPtr<KeyEventDispatch> dispatch;
	};

	struct DispatchActionTaskData {
		DispatchActionTaskData();

		Actions::Action action;
	};

	struct ConsumeMessageTaskData {
		ConsumeMessageTaskData();

		IMessageConsumer *consumer;
		Common::SharedPtr<MessageProperties> message;
	};

	struct ConsumeCommandTaskData {
		ConsumeCommandTaskData();

		Structural *structural;
		Common::SharedPtr<MessageProperties> message;
	};

	struct ApplyDefaultVisibilityTaskData {
		ApplyDefaultVisibilityTaskData();

		VisualElement *element;
		bool targetVisibility;
	};

	struct UpdateMouseStateTaskData {
		UpdateMouseStateTaskData();

		bool mouseDown;
	};

	struct UpdateMousePositionTaskData {
		UpdateMousePositionTaskData();

		int32 x;
		int32 y;
	};

	struct CollisionCheckState {
		CollisionCheckState();

		Common::Array<Common::WeakPtr<VisualElement> > activeElements;
		ICollider *collider;
	};

	struct BoundaryCheckState {
		BoundaryCheckState();

		IBoundaryDetector *detector;
		uint currentContacts;
		Common::Point position;
		bool positionResolved;
	};

	struct ColliderInfo {
		ColliderInfo();

		size_t sceneStackDepth;
		uint16 layer;
		VisualElement *element;
		Common::Rect absRect;
	};

	static Common::SharedPtr<Structural> findDefaultSharedSceneForScene(Structural *scene);
	void executeTeardown(const Teardown &teardown);
	void executeLowLevelSceneStateTransition(const LowLevelSceneStateTransitionAction &transitionAction);
	void executeHighLevelSceneReturn();
	void executeHighLevelSceneTransition(const HighLevelSceneTransition &transition);
	void executeCompleteTransitionToScene(const Common::SharedPtr<Structural> &scene);
	void executeSharedScenePostSceneChangeActions();
	void executeSceneChangeRecursiveVisibilityChange(Structural *structural, bool showing);
	void executeChangeObjectParent(RuntimeObject *object, RuntimeObject *newParent);
	void executeCloneObject(RuntimeObject *object);
	void executeKillObject(RuntimeObject *object);

	void recursiveAutoPlayMedia(Structural *structural);
	void recursiveDeactivateStructural(Structural *structural);
	void recursiveActivateStructural(Structural *structural);

	static bool isStructuralMouseInteractive(Structural *structural, MouseInteractivityTestType testType);
	static bool isModifierMouseInteractive(Modifier *modifier, MouseInteractivityTestType testType);
	static void recursiveFindMouseCollision(Structural *&bestResult, int32 &bestLayer, int32 &bestStackHeight, bool &bestDirect, Structural *candidate, int32 stackHeight, int32 relativeX, int32 relativeY, MouseInteractivityTestType testType);

	void queueEventAsLowLevelSceneStateTransitionAction(const Event &evt, Structural *root, bool cascade, bool relay);

	void loadScene(const Common::SharedPtr<Structural> &scene);

	void ensureMainWindowExists();

	void unloadProject();
	void refreshPlayTime();	// Updates play time to be in sync with the system clock.  Used so that events occurring after storage access don't skip.

	struct DispatchMessageCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_2(Runtime *, runtime, Common::SharedPtr<MessageDispatch>, dispatch);
	};

	struct SendMessageToStructuralCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_4(Runtime *, runtime, bool *, isTerminatedPtr, Structural *, structural, MessageDispatch *, dispatch);
	};

	struct SendMessageToModifierContainerCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_4(Runtime *, runtime, bool *, isTerminatedPtr, IModifierContainer *, modifierContainer, MessageDispatch *, dispatch);
	};

	struct SendMessageToModifierCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_4(Runtime *, runtime, bool *, isTerminatedPtr, Modifier *, modifier, MessageDispatch *, dispatch);
	};

	VThreadState dispatchKeyTask(const DispatchKeyTaskData &data);
	VThreadState dispatchActionTask(const DispatchActionTaskData &data);
	VThreadState consumeMessageTask(const ConsumeMessageTaskData &data);
	VThreadState consumeCommandTask(const ConsumeCommandTaskData &data);
	VThreadState updateMouseStateTask(const UpdateMouseStateTaskData &data);
	VThreadState updateMousePositionTask(const UpdateMousePositionTaskData &data);
	VThreadState applyDefaultVisibility(const ApplyDefaultVisibilityTaskData &data);

	void updateMainWindowCursor();

	static void recursiveFindColliders(Structural *structural, size_t sceneStackDepth, Common::Array<ColliderInfo> &colliders, int32 parentOriginX, int32 parentOriginY, bool isRoot);
	static bool sortColliderPredicate(const ColliderInfo &a, const ColliderInfo &b);

	Common::ScopedPtr<ICoroutineManager> _coroManager;

	Common::Array<VolumeState> _volumes;
	Common::SharedPtr<ProjectDescription> _queuedProjectDesc;
	Common::SharedPtr<Project> _project;
	Common::ScopedPtr<VThread> _vthread;
	Common::Array<Common::SharedPtr<MessageDispatch> > _messageQueue;
	Common::Array<Common::SharedPtr<OSEvent> > _osEventQueue;
	ObjectLinkingScope _rootLinkingScope;

	Common::Array<Teardown> _pendingTeardowns;
	Common::Array<LowLevelSceneStateTransitionAction> _pendingLowLevelTransitions;
	Common::Array<Common::WeakPtr<RuntimeObject> > _pendingKills;
	Common::Array<Common::WeakPtr<RuntimeObject> > _pendingClones;
	Common::Array<Common::WeakPtr<Structural> > _pendingPostCloneShowChecks;
	Common::Array<Common::WeakPtr<Structural> > _pendingShowClonedObject;
	Common::Array<ObjectParentChange> _pendingParentChanges;
	uint _pendingSceneReturnCount;
	Common::Array<HighLevelSceneTransition> _pendingSceneTransitions;
	Common::Array<SceneStackEntry> _sceneStack;
	Common::SharedPtr<Structural> _activeMainScene;
	Common::SharedPtr<Structural> _activeSharedScene;
	Common::Array<SceneReturnListEntry> _sceneReturnList;

	SceneTransitionState _sceneTransitionState;
	SceneTransitionEffect _sourceSceneTransitionEffect;
	SceneTransitionEffect _destinationSceneTransitionEffect;
	SceneTransitionEffect *_activeSceneTransitionEffect;
	Common::SharedPtr<Graphics::ManagedSurface> _sceneTransitionOldFrame;
	Common::SharedPtr<Graphics::ManagedSurface> _sceneTransitionNewFrame;
	uint32 _sceneTransitionStartTime;
	uint32 _sceneTransitionEndTime;
	bool _sharedSceneWasSetExplicitly;

	Common::WeakPtr<Window> _mainWindow;
	Common::Array<Common::SharedPtr<Window> > _windows;

	Common::SharedPtr<Graphics::MacFontManager> _macFontMan;

	Common::SharedPtr<Common::RandomSource> _random;

	uint32 _nextRuntimeGUID;

	bool _displayModeSupported[kColorDepthModeCount];
	Graphics::PixelFormat _displayModePixelFormats[kColorDepthModeCount];
	ColorDepthMode _realDisplayMode;
	ColorDepthMode _fakeDisplayMode;
	uint16 _displayWidth;
	uint16 _displayHeight;

	uint64 _realTimeBase;
	uint64 _playTimeBase;

	uint32 _realTime;
	uint32 _playTime;

	Scheduler _scheduler;
	OSystem *_system;
	Audio::Mixer *_mixer;

	ISaveUIProvider *_saveProvider;
	ILoadUIProvider *_loadProvider;
	Common::SharedPtr<Graphics::ManagedSurface> _saveScreenshotOverride;

	Common::SharedPtr<CursorGraphic> _lastFrameCursor;
	Common::SharedPtr<CursorGraphic> _defaultCursor;
	bool _lastFrameMouseVisible;

	Common::WeakPtr<Window> _mouseFocusWindow;
	bool _mouseFocusFlags[Actions::kMouseButtonCount];

	Common::WeakPtr<Window> _keyFocusWindow;

	Common::SharedPtr<SystemInterface> _systemInterface;
	Common::SharedPtr<WorldManagerInterface> _worldManagerInterface;
	Common::SharedPtr<AssetManagerInterface> _assetManagerInterface;

	// The cached mouse position is updated at frame end
	Common::Point _cachedMousePosition;

	// The real mouse position is updated all the time (even when suspended)
	Common::Point _realMousePosition;

	// Mouse control is tracked in two ways: Mouse over is detected with mouse movement AND when
	// "refreshCursor" is set on the world manager, it indicates the frontmost object that
	// responds to any mouse event.  The mouse tracking object is the object that was clicked.
	// These can differ if the user holds down the mouse and moves it to a spot where the tracked
	// object is either not clickable, or is behind another object with mouse collision.
	// Note that mouseOverObject is also NOT necessarily what will receive mouse down events.
	Common::WeakPtr<Structural> _mouseOverObject;
	Common::WeakPtr<Structural> _mouseTrackingObject;
	Common::Point _mouseTrackingDragStart;
	Common::Point _mouseTrackingObjectInitialOrigin;
	bool _trackedMouseOutside;
	bool _forceCursorRefreshOnce;
	bool _autoResetCursor;

	uint32 _modifierOverrideCursorID;
	bool _haveModifierOverrideCursor;
	bool _haveCursorElement;

	uint32 _multiClickStartTime;
	uint32 _multiClickInterval;
	uint _multiClickCount;

	uint _numMouseBlockers;

	bool _defaultVolumeState;

	// True if any elements were added to the scene, removed from the scene, or reparented since last draw
	bool _sceneGraphChanged;

	bool _isQuitting;

	Common::Array<Common::SharedPtr<CollisionCheckState> > _colliders;
	Common::Array<BoundaryCheckState> _boundaryChecks;
	uint32 _collisionCheckTime;

	Common::WeakPtr<VisualElement> _elementTrackedToCursor;
	//uint32 _elementCursorUpdateTime;

	Common::Array<IPostEffect *> _postEffects;

	Palette _globalPalette;

	Common::SharedPtr<SubtitleRenderer> _subtitleRenderer;

	Hacks _hacks;

	Common::HashMap<uint32, Common::String> _getSetAttribIDsToAttribName;

#ifdef MTROPOLIS_DEBUG_ENABLE
	Common::SharedPtr<Debugger> _debugger;
#endif
};

struct IModifierContainer : public IInterfaceBase {
	virtual const Common::Array<Common::SharedPtr<Modifier> > &getModifiers() const = 0;
	virtual void appendModifier(const Common::SharedPtr<Modifier> &modifier) = 0;
	virtual void removeModifier(const Modifier *modifier) = 0;
};

class SimpleModifierContainer : public IModifierContainer {
public:
	const Common::Array<Common::SharedPtr<Modifier> > &getModifiers() const override;
	void appendModifier(const Common::SharedPtr<Modifier> &modifier) override;
	void removeModifier(const Modifier *modifier) override;

	void clear();

private:
	Common::Array<Common::SharedPtr<Modifier> > _modifiers;
};

class RuntimeObject {
	template<typename TElement, typename TElementData>
	friend class ElementFactory;

public:
	RuntimeObject();
	virtual ~RuntimeObject();

	uint32 getStaticGUID() const;
	uint32 getRuntimeGUID() const;

	void setRuntimeGUID(uint32 runtimeGUID);

	void setSelfReference(const Common::WeakPtr<RuntimeObject> &selfReference);
	const Common::WeakPtr<RuntimeObject> &getSelfReference() const;

	virtual bool isStructural() const;
	virtual bool isProject() const;
	virtual bool isSection() const;
	virtual bool isSubsection() const;
	virtual bool isModifier() const;
	virtual bool isElement() const;

	virtual bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib);
	virtual bool readAttributeIndexed(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib, const DynamicValue &index);
	virtual MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib);
	virtual MiniscriptInstructionOutcome writeRefAttributeIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib, const DynamicValue &index);

protected:
	MiniscriptInstructionOutcome scriptSetClone(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome scriptSetKill(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome scriptSetParent(MiniscriptThread *thread, const DynamicValue &value);

	// This is the static GUID stored in the data, it is not guaranteed
	// to be globally unique at runtime.  In particular, cloning an object
	// and using aliased modifiers will cause multiple objects with the same
	// static GUID to exist with separate runtime GUIDs.
	uint32 _guid;
	uint32 _runtimeGUID;
	Common::WeakPtr<RuntimeObject> _selfReference;

	struct ParentWriteProxyInterface {
		static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset);
		static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
		static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);

	private:
		static RuntimeObject *resolveObjectParent(RuntimeObject *obj);
	};
};

struct MessageProperties {
	MessageProperties(const Event &evt, const DynamicValue &value, const Common::WeakPtr<RuntimeObject> &source);

	const Event &getEvent() const;
	const DynamicValue &getValue() const;
	const Common::WeakPtr<RuntimeObject> &getSource() const;

	void setValue(const DynamicValue &value);

private:
	Event _evt;
	DynamicValue _value;
	Common::WeakPtr<RuntimeObject> _source;
};

struct IStructuralReferenceVisitor : public IInterfaceBase {
	virtual void visitChildStructuralRef(Common::SharedPtr<Structural> &structural) = 0;
	virtual void visitChildModifierRef(Common::SharedPtr<Modifier> &modifier) = 0;
	virtual void visitWeakStructuralRef(Common::WeakPtr<Structural> &structural) = 0;
	virtual void visitWeakModifierRef(Common::WeakPtr<Modifier> &modifier) = 0;
};

struct IMessageConsumer : public IInterfaceBase {
	// These should only be implemented as direct responses - child traversal is handled by the message propagation process
	virtual bool respondsToEvent(const Event &evt) const = 0;
	virtual VThreadState consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) = 0;
};

class WorldManagerInterface : public RuntimeObject {
public:
	WorldManagerInterface();

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) override;

private:
	MiniscriptInstructionOutcome setCurrentScene(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setRefreshCursor(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setAutoResetCursor(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setWinSndBufferSize(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setCursor(MiniscriptThread *thread, const DynamicValue &value);

	int32 _opInt;
	bool _gameMode;
	bool _combineRedraws;
	bool _postponeRedraws;
};

class AssetManagerInterface : public RuntimeObject {
public:
	AssetManagerInterface();

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) override;

private:
	Common::String _opString;
};

class SystemInterface : public RuntimeObject {
public:
	const int kFullVolume = 7;

	SystemInterface();

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	bool readAttributeIndexed(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib, const DynamicValue &index) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) override;

private:
	MiniscriptInstructionOutcome setEjectCD(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setGameMode(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setMasterVolume(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setMonitorBitDepth(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome setVolumeName(MiniscriptThread *thread, const DynamicValue &value);

	Common::String _volumeName;
	Common::String _opString;
	int _masterVolume;
};

class StructuralHooks {
public:
	virtual ~StructuralHooks();

	virtual void onCreate(Structural *structural);
	virtual void onPostActivate(Structural *structural);
	virtual void onSetPosition(Runtime *runtime, Structural *structural, const Common::Point &oldPt, Common::Point &pt);
	virtual void onStopPlayingMToon(Structural *structural, bool &visible, bool &stopped, Graphics::ManagedSurface *lastSurf);
	virtual void onHidden(Structural *structural, bool &visible);
};

class Structural : public RuntimeObject, public IModifierContainer, public IMessageConsumer, public Debuggable {
public:
	enum class SceneLoadState {
		kNotAScene,
		kSceneNotLoaded,
		kSceneLoaded,
	};

	Structural();
	explicit Structural(Runtime *runtime);
	virtual ~Structural();

	bool isStructural() const override;
	SceneLoadState getSceneLoadState() const;
	void setSceneLoadState(SceneLoadState sceneLoadState);

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	bool readAttributeIndexed(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib, const DynamicValue &index) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) override;

	const Common::Array<Common::SharedPtr<Structural> > &getChildren() const;
	void addChild(const Common::SharedPtr<Structural> &child);
	void removeAllChildren();
	void removeAllModifiers();
	void removeChild(Structural *child);
	void removeAllAssets();

	void holdAssets(const Common::Array<Common::SharedPtr<Asset> > &assets);

	Structural *getParent() const;
	Structural *findNextSibling() const;
	Structural *findPrevSibling() const;
	void setParent(Structural *parent);

	// Helper that finds the scene containing the structural object, or itself if it is the scene
	VisualElement *findScene();

	const Common::String &getName() const;

	const Common::Array<Common::SharedPtr<Modifier> > &getModifiers() const override;
	void appendModifier(const Common::SharedPtr<Modifier> &modifier) override;
	void removeModifier(const Modifier *modifier) override;

	bool respondsToEvent(const Event &evt) const override;
	VThreadState consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) override;

	void materializeSelfAndDescendents(Runtime *runtime, ObjectLinkingScope *outerScope);
	void materializeDescendents(Runtime *runtime, ObjectLinkingScope *outerScope);

	struct StructuralConsumeCommandCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_3(Structural *, self, Runtime *, runtime, Common::SharedPtr<MessageProperties>, msg);
	};

	virtual VThreadState asyncConsumeCommand(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg);

	virtual void activate();
	virtual void deactivate();

	void recursiveCollectObjectsMatchingCriteria(Common::Array<Common::WeakPtr<RuntimeObject> > &results, bool (*evalFunc)(void *userData, RuntimeObject *object), void *userData, bool onlyEnabled);

	void setHooks(const Common::SharedPtr<StructuralHooks> &hooks);
	const Common::SharedPtr<StructuralHooks> &getHooks() const;

	// Shallow clones only need to copy the object.  Descendent copies are done using visitInternalReferences.
	virtual Common::SharedPtr<Structural> shallowClone() const = 0;

	virtual void visitInternalReferences(IStructuralReferenceVisitor *visitor);

#ifdef MTROPOLIS_DEBUG_ENABLE
	SupportStatus debugGetSupportStatus() const override;
	const Common::String &debugGetName() const override;
	void debugInspect(IDebugInspectionReport *report) const override;

	virtual void debugSkipMovies();
#endif

protected:
	explicit Structural(const Structural &other);

	virtual ObjectLinkingScope *getPersistentStructuralScope();
	virtual ObjectLinkingScope *getPersistentModifierScope();

	MiniscriptInstructionOutcome scriptSetPaused(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome scriptSetLoop(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome scriptSetDebug(MiniscriptThread *thread, const DynamicValue &value);
	MiniscriptInstructionOutcome scriptSetUnload(MiniscriptThread *thread, const DynamicValue &value);

	// If you override this, you must override visitInternalReferences too.
	virtual void linkInternalReferences(ObjectLinkingScope *outerScope);

	virtual void onPauseStateChanged();

	Runtime *getRuntime() const;

	Structural *_parent;
	Common::Array<Common::SharedPtr<Structural> > _children;
	Common::Array<Common::SharedPtr<Modifier> > _modifiers;
	Common::String _name;

	Common::Array<Common::SharedPtr<Asset> > _assets;

	// "paused" attrib is available for ALL structural types, even when it doesn't do anything.
	// Changing it does not affect modifiers on the object that play media, but does fire
	// "Paused"/"Unpaused" events.
	bool _paused;

	// "loop" appears to have been made available on everything in 1.2.  Obsidian depends on it
	// being available for sound indexes to be properly set up.
	bool _loop;

	int32 _flushPriority;
	SceneLoadState _sceneLoadState;

	Common::SharedPtr<StructuralHooks> _hooks;

private:
	Runtime *_runtime;
};

struct ProjectPresentationSettings {
	ProjectPresentationSettings();

	uint16 width;
	uint16 height;
	uint32 bitsPerPixel;
};

struct AssetDefLoaderContext {
	Common::Array<Common::SharedPtr<Asset> > assets;
};

struct ChildLoaderContext {
	enum Type {
		kTypeUnknown,
		kTypeCountedModifierList,
		kTypeFlagTerminatedModifierList,
		kTypeProject,
		kTypeSection,
		kTypeFilteredElements,
	};

	struct FilteredElements {
		Structural *structural;
		bool (*filterFunc)(Data::DataObjectTypes::DataObjectType dataObjectType);
	};

	union ContainerUnion {
		IModifierContainer *modifierContainer;
		Structural *structural;
		FilteredElements filteredElements;
	};

	ChildLoaderContext();

	uint remainingCount;
	Type type;
	ContainerUnion containerUnion;
};

struct ChildLoaderStack {
	Common::Array<ChildLoaderContext> contexts;
};

class ProjectPlugInRegistry : public IPlugInModifierRegistrar  {
public:
	ProjectPlugInRegistry();

	void registerPlugInModifier(const char *name, const Data::IPlugInModifierDataFactory *dataFactory, const IPlugInModifierFactory *factory) override;

	const Data::PlugInModifierRegistry &getDataLoaderRegistry() const;
	const IPlugInModifierFactory *findPlugInModifierFactory(const char *name) const;

private:
	Data::PlugInModifierRegistry _dataLoaderRegistry;
	Common::HashMap<Common::String, const IPlugInModifierFactory *> _factoryRegistry;
};

struct IPlayMediaSignalReceiver : public IInterfaceBase {
	virtual void playMedia(Runtime *runtime, Project *project) = 0;
};

class PlayMediaSignaller {
public:
	PlayMediaSignaller();
	~PlayMediaSignaller();

	void playMedia(Runtime *runtime, Project *project);
	void addReceiver(IPlayMediaSignalReceiver *receiver);
	void removeReceiver(IPlayMediaSignalReceiver *receiver);

private:
	Common::Array<IPlayMediaSignalReceiver *> _receivers;
};

struct ISegmentUnloadSignalReceiver : public IInterfaceBase {
	virtual void onSegmentUnloaded(int segmentIndex) = 0;
};

class SegmentUnloadSignaller {
public:
	explicit SegmentUnloadSignaller(Project *project, int segmentIndex);
	~SegmentUnloadSignaller();

	void onSegmentUnloaded();
	void addReceiver(ISegmentUnloadSignalReceiver *receiver);
	void removeReceiver(ISegmentUnloadSignalReceiver *receiver);

private:
	Project *_project;
	int _segmentIndex;
	Common::Array<ISegmentUnloadSignalReceiver *> _receivers;
};

struct IKeyboardEventReceiver : public IInterfaceBase {
	virtual void onKeyboardEvent(Runtime *runtime, const KeyboardInputEvent &keyEvt) = 0;
};

class KeyboardEventSignaller {
public:
	KeyboardEventSignaller();
	~KeyboardEventSignaller();

	void onKeyboardEvent(Runtime *runtime, const KeyboardInputEvent &keyEvt);
	void addReceiver(IKeyboardEventReceiver *receiver);
	void removeReceiver(IKeyboardEventReceiver *receiver);

private:
	Common::Array<IKeyboardEventReceiver *> _receivers;
	Common::SharedPtr<KeyboardEventSignaller> _signaller;
};

struct ICollider : public IInterfaceBase {
	virtual void getCollisionProperties(Modifier *&modifier, bool &collideInFront, bool &collideBehind, bool &excludeParents) const = 0;
	virtual void triggerCollision(Runtime *runtime, Structural *collidingElement, bool wasInContact, bool isInContact, bool &outShouldStop) = 0;
};

struct IBoundaryDetector : public IInterfaceBase {
	enum EdgeFlags {
		kEdgeTop = 0x1,
		kEdgeBottom = 0x2,
		kEdgeLeft = 0x4,
		kEdgeRight = 0x8,
	};

	virtual void getCollisionProperties(Modifier *&modifier, uint &edgeFlags, bool &mustBeCompletelyOutside, bool &continuous) const = 0;
	virtual void triggerCollision(Runtime *runtime) = 0;
};

struct IPostEffect : public IInterfaceBase {
	virtual void renderPostEffect(Graphics::ManagedSurface &surface) const = 0;
};

struct IMediaCueModifier : public IInterfaceBase {
	virtual Modifier *getMediaCueModifier() = 0;
	virtual Common::WeakPtr<Modifier> getMediaCueTriggerSource() const = 0;
};

struct MediaCueState {
	enum TriggerTiming {
		kTriggerTimingStart = 0,
		kTriggerTimingDuring = 1,
		kTriggerTimingEnd = 2,
	};

	int32 minTime;
	int32 maxTime;

	IMediaCueModifier *sourceModifier;
	TriggerTiming triggerTiming;
	MessengerSendSpec send;
	DynamicValue incomingData;

	MediaCueState();
	void checkTimestampChange(Runtime *runtime, uint32 oldTS, uint32 newTS, bool continuousTimestamps, bool canTriggerDuring);
};

class Project : public Structural {
public:
	explicit Project(Runtime *runtime);
	~Project();

	VThreadState asyncConsumeCommand(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) override;

	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) override;

	void loadFromDescription(const ProjectDescription &desc, const Hacks &hacks);
	void loadSceneFromStream(const Common::SharedPtr<Structural> &structural, uint32 streamID, const Hacks &hacks);

	Common::SharedPtr<Modifier> resolveAlias(uint32 aliasID) const;
	Common::SharedPtr<Modifier> findGlobalVarWithName(const Common::String &name) const;
	void materializeGlobalVariables(Runtime *runtime, ObjectLinkingScope *scope);

	const ProjectPresentationSettings &getPresentationSettings() const;

	bool isProject() const override;

	Common::String getAssetNameByID(uint32 assetID) const;
	Common::WeakPtr<Asset> getAssetByID(uint32 assetID) const;
	bool getAssetIDByName(const Common::String &assetName, uint32 &outAssetID) const;
	void forceLoadAsset(uint32 assetID, Common::Array<Common::SharedPtr<Asset> > &outHoldAssets);

	size_t getSegmentForStreamIndex(size_t streamIndex) const;
	void openSegmentStream(int segmentIndex);
	void closeSegmentStream(int segmentIndex);
	Common::SeekableReadStream *getStreamForSegment(int segmentIndex);

	const Common::String *findNameOfLabel(const Label &label) const;

	void onPostRender();
	void onKeyboardEvent(Runtime *runtime, const KeyboardInputEvent &keyEvt);

	Common::SharedPtr<SegmentUnloadSignaller> notifyOnSegmentUnload(int segmentIndex, ISegmentUnloadSignalReceiver *receiver);
	Common::SharedPtr<KeyboardEventSignaller> notifyOnKeyboardEvent(IKeyboardEventReceiver *receiver);
	Common::SharedPtr<PlayMediaSignaller> notifyOnPlayMedia(IPlayMediaSignalReceiver *receiver);

	const char *findAuthorMessageName(uint32 id) const;

	const Common::SharedPtr<CursorGraphicCollection> &getCursorGraphics() const;

	const SubtitleTables &getSubtitles() const;

	RuntimeVersion getRuntimeVersion() const;
	ProjectPlatform getPlatform() const;

	void visitInternalReferences(IStructuralReferenceVisitor *visitor) override;
	Common::SharedPtr<Structural> shallowClone() const override;

#ifdef MTROPOLIS_DEBUG_ENABLE
	const char *debugGetTypeName() const override { return "Project"; }
#endif

private:
	struct LabelSuperGroup {
		LabelSuperGroup();

		size_t firstRootNodeIndex;
		size_t numRootNodes;
		size_t numTotalNodes;

		uint32 superGroupID;
		Common::String name;
	};

	struct LabelTree {
		LabelTree();

		size_t firstChildIndex;
		size_t numChildren;

		uint32 id;
		Common::String name;
	};

	struct Segment {
		Segment();

		SegmentDescription desc;
		Common::SharedPtr<Common::SeekableReadStream> rcStream;

		Common::SeekableReadStream *weakStream;
		Common::SharedPtr<SegmentUnloadSignaller> unloadSignaller;
	};

	enum StreamType {
		kStreamTypeUnknown,

		kStreamTypeAsset,
		kStreamTypeBoot,
		kStreamTypeScene,
	};

	struct StreamDesc {
		StreamDesc();

		StreamType streamType;
		uint16 segmentIndex;
		uint32 size;
		uint32 pos;
	};

	struct AssetDesc {
		AssetDesc();

		uint32 typeCode;
		uint32 streamID;
		uint32 filePosition;
		size_t id;
		Common::String name;

		// If the asset is live, this will be its asset info
		Common::WeakPtr<Asset> asset;
	};

	void loadBootStream(size_t streamIndex, const Hacks &hacks);

	void loadPresentationSettings(const Data::PresentationSettings &presentationSettings);
	void loadAssetCatalog(const Data::AssetCatalog &assetCatalog);
	void loadGlobalObjectInfo(ChildLoaderStack &loaderStack, const Data::GlobalObjectInfo &globalObjectInfo);
	void loadAssetDef(size_t streamIndex, AssetDefLoaderContext &context, const Data::DataObject &dataObject);
	void loadContextualObject(size_t streamIndex, ChildLoaderStack &stack, const Data::DataObject &dataObject);
	Common::SharedPtr<Modifier> loadModifierObject(ModifierLoaderContext &loaderContext, const Data::DataObject &dataObject);
	void loadLabelMap(const Data::ProjectLabelMap &projectLabelMap);
	static size_t recursiveCountLabels(const Data::ProjectLabelMap::LabelTree &tree);

	ObjectLinkingScope *getPersistentStructuralScope() override;
	ObjectLinkingScope *getPersistentModifierScope() override;

	void assignAssets(const Common::Array<Common::SharedPtr<Asset> > &assets, const Hacks &hacks);

	void initAdditionalSegments(const Common::String &projectName);

	Common::Array<Segment> _segments;
	Common::Array<StreamDesc> _streams;
	Common::Array<LabelTree> _labelTree;
	Common::Array<LabelSuperGroup> _labelSuperGroups;
	Data::ProjectFormat _projectFormat;

	Common::Array<AssetDesc *> _assetsByID;
	Common::Array<AssetDesc> _realAssets;

	Common::HashMap<Common::String, size_t> _assetNameToID;

	ProjectPresentationSettings _presentationSettings;

	bool _haveGlobalObjectInfo;
	bool _haveProjectStructuralDef;
	SimpleModifierContainer _globalModifiers;

	ProjectPlugInRegistry _plugInRegistry;

	Common::Array<Common::SharedPtr<PlugIn> > _plugIns;
	Common::SharedPtr<ProjectResources> _resources;
	Common::SharedPtr<CursorGraphicCollection> _cursorGraphics;

	ObjectLinkingScope _structuralScope;
	ObjectLinkingScope _modifierScope;

	Common::SharedPtr<PlayMediaSignaller> _playMediaSignaller;
	Common::SharedPtr<KeyboardEventSignaller> _keyboardEventSignaller;

	SubtitleTables _subtitles;

	ProjectPlatform _platform;

	Common::Archive *_rootArchive;
	Common::Path _projectRootDir;

	RuntimeVersion _runtimeVersion;
	bool _isRuntimeVersionAutoDetect;
};

class Section : public Structural {
public:
	bool load(const Data::SectionStructuralDef &data);

	bool isSection() const override;

	Common::SharedPtr<Structural> shallowClone() const override;
	void visitInternalReferences(IStructuralReferenceVisitor *visitor) override;

#ifdef MTROPOLIS_DEBUG_ENABLE
	const char *debugGetTypeName() const override { return "Section"; }
#endif

private:
	ObjectLinkingScope *getPersistentStructuralScope() override;
	ObjectLinkingScope *getPersistentModifierScope() override;

	ObjectLinkingScope _structuralScope;
	ObjectLinkingScope _modifierScope;
};

class Subsection : public Structural {
public:
	bool load(const Data::SubsectionStructuralDef &data);

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;

	ObjectLinkingScope *getSceneLoadMaterializeScope();

	bool isSubsection() const override;

	Common::SharedPtr<Structural> shallowClone() const override;
	void visitInternalReferences(IStructuralReferenceVisitor *visitor) override;

#ifdef MTROPOLIS_DEBUG_ENABLE
	const char *debugGetTypeName() const override { return "Subsection"; }
#endif

private:
	ObjectLinkingScope *getPersistentStructuralScope() override;
	ObjectLinkingScope *getPersistentModifierScope() override;

	ObjectLinkingScope _structuralScope;
	ObjectLinkingScope _modifierScope;
};

class Element : public Structural {
public:
	Element();

	virtual bool isVisual() const = 0;
	virtual bool canAutoPlay() const;
	virtual void queueAutoPlayEvents(Runtime *runtime, bool isAutoPlaying);

	bool isElement() const override;

	uint32 getStreamLocator() const;

	void addMediaCue(MediaCueState *mediaCue);
	void removeMediaCue(const MediaCueState *mediaCue);

	void triggerAutoPlay(Runtime *runtime);
	virtual void tryAutoSetName(Runtime *runtime, Project *project);

	virtual bool resolveMediaMarkerLabel(const Label &label, int32 &outResolution) const;

	void visitInternalReferences(IStructuralReferenceVisitor *visitor) override;

	typedef StructuralConsumeCommandCoroutine ElementConsumeCommandCoroutine;

protected:
	Element(const Element &other);

	uint32 _streamLocator;
	uint16 _sectionID;

	Common::Array<MediaCueState *> _mediaCues;

	bool _haveCheckedAutoPlay;
};

class VisualElementTransitionProperties {
public:
	VisualElementTransitionProperties();

	uint8 getAlpha() const;
	void setAlpha(uint8 alpha);

	bool isDirty() const;
	void clearDirty();

private:
	uint8 _alpha;
	bool _isDirty;
};

class VisualElementRenderProperties {
public:
	VisualElementRenderProperties();
	VisualElementRenderProperties(const VisualElementRenderProperties &) = default;

	enum InkMode {
		kInkModeCopy = 0x0,
		kInkModeTransparent = 0x1,				// src*dest
		kInkModeGhost = 0x3,					// (1-src)+dest
		kInkModeReverseCopy = 0x4,				// 1-src
		kInkModeReverseGhost = 0x7,				// src+dest
		kInkModeReverseTransparent = 0x9,		// (1-src)*dest
		kInkModeBlend = 0x20,					// (src*bgcolor)+(dest*(1-bgcolor)
		kInkModeBackgroundTransparent = 0x24,	// BG color is transparent
		kInkModeChameleonDark = 0x25,			// src+dest
		kInkModeChameleonLight = 0x27,			// src*dest
		kInkModeBackgroundMatte = 0x224,		// BG color is transparent and non-interactive
		kInkModeInvisible = 0xffff,				// Not drawn, but interactive

		kInkModeXor = 0x7ffffff0,				// Fake ink mode for Obsidian canvas puzzle, not a valid value from data
		kInkModeDefault = 0x7fffffff,			// Not a valid value from data
	};

	enum Shape {
		kShapeRect = 0x1,
		kShapeRoundedRect = 0x2,
		kShapeOval = 0x3,
		kShapePolygon = 0x9,
		kShapeStar = 0xb, // 5-point star, horizontal arms are at (top+bottom*2)/3

		// Fake shapes for Obsidian canvas puzzle, not a valid from data
		kShapeObsidianCanvasPuzzleTri1 = 0x7ffffff1,
		kShapeObsidianCanvasPuzzleTri2 = 0x7ffffff2,
		kShapeObsidianCanvasPuzzleTri3 = 0x7ffffff3,
		kShapeObsidianCanvasPuzzleTri4 = 0x7ffffff4,
	};

	InkMode getInkMode() const;
	void setInkMode(InkMode inkMode);

	Shape getShape() const;
	void setShape(Shape shape);

	const ColorRGB8 &getForeColor() const;
	void setForeColor(const ColorRGB8 &color);

	const ColorRGB8 &getBackColor() const;
	void setBackColor(const ColorRGB8 &color);

	const ColorRGB8 &getBorderColor() const;
	void setBorderColor(const ColorRGB8 &color);

	const ColorRGB8 &getShadowColor() const;
	void setShadowColor(const ColorRGB8 &color);

	uint16 getBorderSize() const;
	void setBorderSize(uint16 size);

	uint16 getShadowSize() const;
	void setShadowSize(uint16 size);

	const Common::Array<Common::Point> &getPolyPoints() const;
	Common::Array<Common::Point> &modifyPolyPoints();

	bool isDirty() const;
	void clearDirty();

	VisualElementRenderProperties &operator=(const VisualElementRenderProperties &other);

private:
	InkMode _inkMode;
	Shape _shape;
	ColorRGB8 _foreColor;
	ColorRGB8 _backColor;
	uint16 _borderSize;
	ColorRGB8 _borderColor;
	uint16 _shadowSize;
	ColorRGB8 _shadowColor;

	Common::Array<Common::Point> _polyPoints;

	bool _isDirty;
};

class VisualElement : public Element {
public:
	VisualElement();

	bool isVisual() const override;
	virtual bool isTextLabel() const;

	struct VisualElementConsumeCommandCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_3(VisualElement *, self, Runtime *, runtime, Common::SharedPtr<MessageProperties>, msg);
	};

	VThreadState asyncConsumeCommand(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) override;

	bool respondsToEvent(const Event &evt) const override;
	VThreadState consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) override;

	bool isVisible() const;
	bool isVisibleByDefault() const;
	void setVisible(Runtime *runtime, bool visible);

	bool isDirectToScreen() const;
	void setDirectToScreen(bool directToScreen);

	uint16 getLayer() const;
	void setLayer(uint16 layer);

	bool isMouseInsideDrawableArea(int32 relativeX, int32 relativeY) const;

	// Returns true if there is mouse collision at a specified point, assuming it has already passed isMouseInsideBox
	virtual bool isMouseCollisionAtPoint(int32 relativeX, int32 relativeY) const;

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib) override;

	Common::Point getParentOrigin() const;
	Common::Point getGlobalPosition() const;
	const Common::Rect &getRelativeRect() const;
	virtual Common::Rect getRelativeCollisionRect() const;

	void setRelativeRect(const Common::Rect &rect);

	// The cached absolute origin is from the last time the element was rendered.
	// Do not rely on it mid-frame.
	const Common::Point &getCachedAbsoluteOrigin() const;
	void setCachedAbsoluteOrigin(const Common::Point &absOrigin);

	void setDragMotionProperties(const Common::SharedPtr<DragMotionProperties> &dragProps);
	const Common::SharedPtr<DragMotionProperties> &getDragMotionProperties() const;

	void handleDragMotion(Runtime *runtime, const Common::Point &initialOrigin, const Common::Point &targetOrigin);

	struct OffsetTranslateTaskData {
		OffsetTranslateTaskData() : dx(0), dy(0) {}

		int32 dx;
		int32 dy;
	};

	VThreadState offsetTranslateTask(const OffsetTranslateTaskData &data);

	void setRenderProperties(const VisualElementRenderProperties &props, const Common::WeakPtr<GraphicModifier> &primaryGraphicModifier);
	const VisualElementRenderProperties &getRenderProperties() const;
	const Common::WeakPtr<GraphicModifier> &getPrimaryGraphicModifier() const;

	void setShading(int16 topLeftBevelShading, int16 bottomRightBevelShading, int16 interiorShading, uint32 bevelSize);

	void setTransitionProperties(const VisualElementTransitionProperties &props);
	const VisualElementTransitionProperties &getTransitionProperties() const;

	bool needsRender() const;
	virtual void render(Window *window) = 0;
	void finalizeRender();

	void setPalette(const Common::SharedPtr<Palette> &palette);
	const Common::SharedPtr<Palette> &getPalette() const;

	void visitInternalReferences(IStructuralReferenceVisitor *visitor) override;

	void pushVisibilityChangeTask(Runtime *runtime, bool desiredVisibility);

#ifdef MTROPOLIS_DEBUG_ENABLE
	void debugInspect(IDebugInspectionReport *report) const override;
#endif

protected:
	VisualElement(const VisualElement &other);

	bool loadCommon(const Common::String &name, uint32 guid, const Data::Rect &rect, uint32 elementFlags, uint16 layer, uint32 streamLocator, uint16 sectionID);

	MiniscriptInstructionOutcome scriptSetDirect(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetPosition(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetPositionX(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetPositionY(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetCenterPosition(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetCenterPositionX(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetCenterPositionY(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetVisibility(MiniscriptThread *thread, const DynamicValue &result);
	MiniscriptInstructionOutcome scriptSetSize(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetWidth(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetHeight(MiniscriptThread *thread, const DynamicValue &dest);
	MiniscriptInstructionOutcome scriptSetLayer(MiniscriptThread *thread, const DynamicValue &dest);

	MiniscriptInstructionOutcome scriptWriteRefPositionAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib);
	MiniscriptInstructionOutcome scriptWriteRefSizeAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib);
	MiniscriptInstructionOutcome scriptWriteRefCenterPositionAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib);

	void offsetTranslate(int32 xDelta, int32 yDelta, bool cachedOriginOnly);
	void resize(int32 width, int32 height);

	Common::Point getCenterPosition() const;

	struct ChangeVisibilityCoroutine {
		CORO_DEFINE_RETURN_TYPE(void);
		CORO_DEFINE_PARAMS_3(VisualElement *, self, Runtime *, runtime, bool, desiredFlag);
	};

	struct ChangeFlagTaskData {
		ChangeFlagTaskData() : desiredFlag(false), runtime(nullptr) {}

		bool desiredFlag;
		Runtime *runtime;
	};

	VThreadState changeVisibilityTask(const ChangeFlagTaskData &taskData);

	static VisualElement *recursiveFindItemWithLayer(VisualElement *element, int32 layer);

	void renderShading(Graphics::Surface &surf) const;

	static uint32 quantizeShading(uint32 mask, int16 shading);

	static void renderShadingScanlineDynamic(void *data, size_t numElements, uint32 rMask, uint32 rAdd, uint32 gMask, uint32 gAdd, uint32 bMask, uint32 bAdd, bool isBrighten, byte bytesPerPixel);

	template<class TElement>
	static void renderBrightenScanline(TElement *element, size_t numElements, TElement rMask, TElement rAdd, TElement gMask, TElement gAdd, TElement bMask, TElement bAdd);

	template<class TElement>
	static void renderDarkenScanline(TElement *element, size_t numElements, TElement rMask, TElement rSub, TElement gMask, TElement gSub, TElement bMask, TElement bSub);

	bool _directToScreen;
	bool _visible;
	bool _visibleByDefault;
	Common::Rect _rect;
	Common::Point _cachedAbsoluteOrigin;
	uint16 _layer;

	int16 _topLeftBevelShading;
	int16 _bottomRightBevelShading;
	int16 _interiorShading;
	uint32 _bevelSize;

	Common::SharedPtr<DragMotionProperties> _dragProps;

	// Quirk: When a graphic modifier is applied, it becomes the primary graphic modifier, and disabling it
	// will only take effect if it's the primary graphic modifier.
	VisualElementRenderProperties _renderProps;
	Common::WeakPtr<GraphicModifier> _primaryGraphicModifier;

	VisualElementTransitionProperties _transitionProps;

	Common::SharedPtr<Palette> _palette;

	Common::Rect _prevRect;
	bool _contentsDirty;
};

class NonVisualElement : public Element {
public:
	bool isVisual() const override;

	bool loadCommon(const Common::String &name, uint32 guid, uint32 elementFlags);

	typedef ElementConsumeCommandCoroutine NonVisualElementConsumeCommandCoroutine;
};

struct ModifierFlags {
	ModifierFlags();
	bool load(const uint32 dataModifierFlags);

	bool isLastModifier : 1;
	bool flagsWereLoaded : 1;
};

class ModifierSaveLoad {
public:
	virtual ~ModifierSaveLoad();

	void save(Modifier *modifier, Common::WriteStream *stream);
	bool load(Modifier *modifier, Common::ReadStream *stream, uint32 saveFileVersion);
	virtual void commitLoad() const = 0;

protected:
	// Saves the modifier state to a stream
	virtual void saveInternal(Common::WriteStream *stream) const = 0;

	// Loads the modifier state from a stream into the save/load state and returns true
	// if successful.  This will not trigger any actual changes until "commit" is called.
	virtual bool loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) = 0;
};

class ModifierHooks {
public:
	virtual ~ModifierHooks();

	virtual void onCreate(Modifier *modifier);
};

class Modifier : public RuntimeObject, public IMessageConsumer, public Debuggable {
public:
	Modifier();
	virtual ~Modifier();

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;
	MiniscriptInstructionOutcome writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib) override;

	void materialize(Runtime *runtime, ObjectLinkingScope *outerScope);

	virtual bool isAlias() const;
	virtual bool isVariable() const;
	virtual bool isBehavior() const;
	virtual bool isCompoundVariable() const;
	virtual bool isKeyboardMessenger() const;
	virtual Common::SharedPtr<ModifierSaveLoad> getSaveLoad(Runtime *runtime);

	bool isModifier() const override;

	// This should only return a propagation container if messages should actually be propagated (i.e. NOT switched-off behaviors!)
	virtual IModifierContainer *getMessagePropagationContainer();
	virtual IModifierContainer *getChildContainer();

	const Common::WeakPtr<RuntimeObject> &getParent() const;
	void setParent(const Common::WeakPtr<RuntimeObject> &parent);

	Modifier *findNextSibling() const;
	Modifier *findPrevSibling() const;

	bool respondsToEvent(const Event &evt) const override;
	VThreadState consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) override;

	void setName(const Common::String &name);
	const Common::String &getName() const;

	const ModifierFlags &getModifierFlags() const;

	// Shallow clones only need to copy the object.  Descendent copies are done using visitInternalReferences.
	virtual Common::SharedPtr<Modifier> shallowClone() const = 0;

	// Returns the default name of the modifier.  This isn't optional: It can cause behavioral changes, e.g.
	// Obsidian depends on this working properly to resolve the TextWork modifier in the Piazza.
	virtual const char *getDefaultName() const = 0;

	// Visits any internal references in the object.
	// Any references to other elements owned by the object MUST be SharedPtr, any references to non-owned objects
	// MUST be WeakPtr, in order for the cloning and materialization logic to work correctly.
	virtual void visitInternalReferences(IStructuralReferenceVisitor *visitor);

	bool loadPlugInHeader(const PlugInModifierLoaderContext &plugInContext);

	void recursiveCollectObjectsMatchingCriteria(Common::Array<Common::WeakPtr<RuntimeObject> > &results, bool (*evalFunc)(void *userData, RuntimeObject *object), void *userData, bool onlyEnabled);

	Structural *findStructuralOwner() const;

	void setHooks(const Common::SharedPtr<ModifierHooks> &hooks);
	const Common::SharedPtr<ModifierHooks> &getHooks() const;

	// Recursively disable due to containing behavior being disabled
	virtual void disable(Runtime *runtime) = 0;

#ifdef MTROPOLIS_DEBUG_ENABLE
	SupportStatus debugGetSupportStatus() const override;
	const Common::String &debugGetName() const override;
	void debugInspect(IDebugInspectionReport *report) const override;
#endif

protected:
	bool loadTypicalHeader(const Data::TypicalModifierHeader &typicalHeader);

	// Links any references contained in the object, resolving static GUIDs to runtime object references.
	// If you override this, you should override visitInternalReferences too
	virtual void linkInternalReferences(ObjectLinkingScope *scope);

	Common::String _name;
	ModifierFlags _modifierFlags;
	Common::WeakPtr<RuntimeObject> _parent;

	Common::SharedPtr<ModifierHooks> _hooks;
};

class VariableStorage {
public:
	virtual ~VariableStorage();
	virtual Common::SharedPtr<ModifierSaveLoad> getSaveLoad(Runtime *runtime) = 0;

	virtual Common::SharedPtr<VariableStorage> clone() const = 0;
};

class VariableModifier : public Modifier {
public:
	explicit VariableModifier(const Common::SharedPtr<VariableStorage> &storage);
	VariableModifier(const VariableModifier &other);

	virtual bool isVariable() const override;
	virtual bool isListVariable() const;

	virtual Common::SharedPtr<ModifierSaveLoad> getSaveLoad(Runtime *runtime) override final;

	const Common::SharedPtr<VariableStorage> &getStorage() const;
	void setStorage(const Common::SharedPtr<VariableStorage> &storage);

	virtual bool varSetValue(MiniscriptThread *thread, const DynamicValue &value) = 0;
	virtual void varGetValue(DynamicValue &dest) const = 0;

	bool readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) override;

	void disable(Runtime *runtime) override;

	virtual DynamicValueWriteProxy createWriteProxy();

#ifdef MTROPOLIS_DEBUG_ENABLE
	void debugInspect(IDebugInspectionReport *report) const override;
#endif

private:
	VariableModifier() = delete;

	struct WriteProxyInterface {
		static MiniscriptInstructionOutcome write(MiniscriptThread *thread, const DynamicValue &dest, void *objectRef, uintptr ptrOrOffset);
		static MiniscriptInstructionOutcome refAttrib(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib);
		static MiniscriptInstructionOutcome refAttribIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &proxy, void *objectRef, uintptr ptrOrOffset, const Common::String &attrib, const DynamicValue &index);
	};

protected:
	Common::SharedPtr<VariableStorage> _storage;
};

enum AssetType {
	kAssetTypeNone,

	kAssetTypeMovie,
	kAssetTypeAudio,
	kAssetTypeColorTable,
	kAssetTypeImage,
	kAssetTypeText,
	kAssetTypeMToon,
	kAssetTypeAVIMovie,
};

class AssetHooks {
public:
	virtual ~AssetHooks();

	virtual void onLoaded(Asset *asset, const Common::String &name);
};

class Asset {
public:
	Asset();
	virtual ~Asset();

	uint32 getAssetID() const;

	virtual AssetType getAssetType() const = 0;

protected:
	uint32 _assetID;
};


} // End of namespace MTropolis

#endif