File: modifiers.cpp

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 (3781 lines) | stat: -rw-r--r-- 127,747 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
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
/* 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/>.
 *
 */

#include "common/memstream.h"
#include "common/random.h"

#include "graphics/managed_surface.h"

#include "mtropolis/assets.h"
#include "mtropolis/audio_player.h"
#include "mtropolis/coroutines.h"
#include "mtropolis/miniscript.h"
#include "mtropolis/modifiers.h"
#include "mtropolis/modifier_factory.h"
#include "mtropolis/saveload.h"

#include "mtropolis/elements.h"

namespace MTropolis {

class CompoundVarLoader : public ISaveReader {
public:
	CompoundVarLoader(Runtime *runtime, RuntimeObject *object);

	bool readSave(Common::ReadStream *stream, uint32 saveFileVersion) override;

private:
	Runtime *_runtime;
	RuntimeObject *_object;
};

CompoundVarLoader::CompoundVarLoader(Runtime *runtime, RuntimeObject *object) : _runtime(runtime), _object(object) {
}

bool CompoundVarLoader::readSave(Common::ReadStream *stream, uint32 saveFileVersion) {
	if (_object == nullptr || !_object->isModifier())
		return false;

	Modifier *modifier = static_cast<Modifier *>(_object);
	Common::SharedPtr<ModifierSaveLoad> saveLoad = modifier->getSaveLoad(_runtime);
	if (!saveLoad)
		return false;

	if (!saveLoad->load(modifier, stream, saveFileVersion))
		return false;

	if (stream->err())
		return false;

	saveLoad->commitLoad();

	return true;
}

BehaviorModifier::BehaviorModifier() : _switchable(false), _isEnabled(false) {
}

bool BehaviorModifier::load(ModifierLoaderContext &context, const Data::BehaviorModifier &data) {
	if (data.numChildren > 0) {
		ChildLoaderContext loaderContext;
		loaderContext.containerUnion.modifierContainer = this;
		loaderContext.type = ChildLoaderContext::kTypeCountedModifierList;
		loaderContext.remainingCount = data.numChildren;

		context.childLoaderStack->contexts.push_back(loaderContext);
	}

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen))
		return false;

	_guid = data.guid;
	_name = data.name;
	_modifierFlags.load(data.modifierFlags);
	_switchable = ((data.behaviorFlags & Data::BehaviorModifier::kBehaviorFlagSwitchable) != 0);
	_isEnabled = !_switchable;

	return true;
}

const Common::Array<Common::SharedPtr<Modifier> > &BehaviorModifier::getModifiers() const {
	return _children;
}

void BehaviorModifier::appendModifier(const Common::SharedPtr<Modifier> &modifier) {
	_children.push_back(modifier);
	modifier->setParent(getSelfReference());
}

void BehaviorModifier::removeModifier(const Modifier *modifier) {
	for (Common::Array<Common::SharedPtr<Modifier> >::iterator it = _children.begin(), itEnd = _children.end(); it != itEnd; ++it) {
		if (it->get() == modifier) {
			_children.erase(it);
			return;
		}
	}
}

IModifierContainer *BehaviorModifier::getMessagePropagationContainer() {
	if (_isEnabled)
		return this;
	else
		return nullptr;
}

IModifierContainer* BehaviorModifier::getChildContainer() {
	return this;
}

bool BehaviorModifier::respondsToEvent(const Event &evt) const {
	if (_switchable) {
		if (_enableWhen.respondsTo(evt))
			return true;
		if (_disableWhen.respondsTo(evt))
			return true;
	}
	return false;
}

VThreadState BehaviorModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_switchable) {
		if (_disableWhen.respondsTo(msg->getEvent())) {
			// These are executed in reverse order.  The disable event is propagated to children, then the disable task
			// runs to forcibly disable any children.
			//
			// This works a bit weirdly in practice with child behaviors since ultimately we want them to be disabled and
			// fire their Parent Disabled task but we don't actually do it on disable.  We instead rely on it being kind of
			// the logical outcome of how this works:
			//
			// If the behavior is enabled, then Parent Disabled will propagate through the behavior, followed by the children
			// actually being disabled.
			DisableTaskData *disableTask = runtime->getVThread().pushTask("BehaviorModifier::disableTask", this, &BehaviorModifier::disableTask);
			disableTask->runtime = runtime;

			SwitchTaskData *switchTask = runtime->getVThread().pushTask("BehaviorModifier::switchTask", this, &BehaviorModifier::switchTask);
			switchTask->targetState = false;
			switchTask->eventID = EventIDs::kParentDisabled;
			switchTask->runtime = runtime;
		}
		if (_enableWhen.respondsTo(msg->getEvent())) {
			SwitchTaskData *taskData = runtime->getVThread().pushTask("BehaviorModifier::switchTask", this, &BehaviorModifier::switchTask);
			taskData->targetState = true;
			taskData->eventID = EventIDs::kParentEnabled;
			taskData->runtime = runtime;
		}
	}

	return kVThreadReturn;
}

void BehaviorModifier::disable(Runtime *runtime) {
	if (_switchable && _isEnabled)
		_isEnabled = false;

	for (const Common::SharedPtr<Modifier> &child : _children)
		child->disable(runtime);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void BehaviorModifier::debugInspect(IDebugInspectionReport *report) const {
	Modifier::debugInspect(report);

	report->declareDynamic("switchable", _switchable ? "true" : "false");
	report->declareDynamic("enabled", _isEnabled ? "true" : "false");
}
#endif

VThreadState BehaviorModifier::switchTask(const SwitchTaskData &taskData) {
	if (_isEnabled != taskData.targetState) {
		_isEnabled = taskData.targetState;

		if (_children.size() > 0) {
			PropagateTaskData *propagateData = taskData.runtime->getVThread().pushTask("BehaviorModifier::propagateTask", this, &BehaviorModifier::propagateTask);
			propagateData->eventID = taskData.eventID;
			propagateData->index = 0;
			propagateData->runtime = taskData.runtime;
		}
	}

	return kVThreadReturn;
}

VThreadState BehaviorModifier::propagateTask(const PropagateTaskData &taskData) {
	if (taskData.index + 1 < _children.size()) {
		PropagateTaskData *propagateData = taskData.runtime->getVThread().pushTask("BehaviorModifier::propagateTask", this, &BehaviorModifier::propagateTask);
		propagateData->eventID = taskData.eventID;
		propagateData->index = taskData.index + 1;
		propagateData->runtime = taskData.runtime;
	}

	Common::SharedPtr<MessageProperties> msgProps(new MessageProperties(Event(taskData.eventID, 0), DynamicValue(), this->getSelfReference()));
	Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(msgProps, _children[taskData.index].get(), true, true, false));
	taskData.runtime->sendMessageOnVThread(dispatch);

	return kVThreadReturn;
}

VThreadState BehaviorModifier::disableTask(const DisableTaskData &taskData) {
	disable(taskData.runtime);
	return kVThreadReturn;
}

Common::SharedPtr<Modifier> BehaviorModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new BehaviorModifier(*this));
}

const char *BehaviorModifier::getDefaultName() const {
	return "Behavior";
}

void BehaviorModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	Modifier::linkInternalReferences(scope);
}

void BehaviorModifier::visitInternalReferences(IStructuralReferenceVisitor* visitor) {
	for (Common::Array<Common::SharedPtr<Modifier> >::iterator it = _children.begin(), itEnd = _children.end(); it != itEnd; ++it) {
		visitor->visitChildModifierRef(*it);
	}
}

// Miniscript modifier
bool MiniscriptModifier::load(ModifierLoaderContext &context, const Data::MiniscriptModifier &data) {
	if (!this->loadTypicalHeader(data.modHeader) || !_enableWhen.load(data.enableWhen))
		return false;

	if (!MiniscriptParser::parse(data.program, _program, _references))
		return false;

	return true;
}

bool MiniscriptModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt);
}

VThreadState MiniscriptModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_enableWhen.respondsTo(msg->getEvent())) {
		Common::SharedPtr<MiniscriptThread> thread(new MiniscriptThread(runtime, msg, _program, _references, this));
		runtime->getVThread().pushCoroutine<MiniscriptThread::ResumeThreadCoroutine>(thread);
	}

	return kVThreadReturn;
}

Common::SharedPtr<Modifier> MiniscriptModifier::shallowClone() const {
	MiniscriptModifier *clonePtr = new MiniscriptModifier(*this);
	Common::SharedPtr<Modifier> clone(clonePtr);

	// Keep the Miniscript program (which is static), but clone the references
	clonePtr->_references.reset(new MiniscriptReferences(*_references));

	return clone;
}

const char *MiniscriptModifier::getDefaultName() const {
	return "Miniscript Modifier";
}

void MiniscriptModifier::linkInternalReferences(ObjectLinkingScope* scope) {
	_references->linkInternalReferences(scope);
}

void MiniscriptModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_references->visitInternalReferences(visitor);
}

ColorTableModifier::ColorTableModifier() : _assetID(0xffffffff) {
}

bool ColorTableModifier::load(ModifierLoaderContext &context, const Data::ColorTableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_applyWhen.load(data.applyWhen))
		return false;

	_assetID = data.assetID;

	return true;
}

bool ColorTableModifier::respondsToEvent(const Event &evt) const {
	return _applyWhen.respondsTo(evt);
}

VThreadState ColorTableModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_applyWhen.respondsTo(msg->getEvent())) {
		Common::SharedPtr<Asset> ctabAsset = runtime->getProject()->getAssetByID(_assetID).lock();
		if (ctabAsset) {
			if (ctabAsset->getAssetType() == kAssetTypeColorTable) {
				const ColorRGB8 *colors = static_cast<ColorTableAsset *>(ctabAsset.get())->getColors();

				Palette palette(colors);

				if (runtime->getFakeColorDepth() <= kColorDepthMode8Bit) {
					runtime->setGlobalPalette(palette);
				} else {
					Structural *structural = this->findStructuralOwner();
					if (structural != nullptr && structural->isElement() && static_cast<Element *>(structural)->isVisual()) {
						static_cast<VisualElement *>(structural)->setPalette(Common::SharedPtr<Palette>(new Palette(palette)));
					} else {
						warning("Attempted to apply a color table to a non-element");
					}
				}
			} else {
				error("Color table modifier applied an asset that wasn't a color table");
			}
		} else {
			warning("Failed to apply color table, asset %u wasn't found", _assetID);
		}

		return kVThreadReturn;
	}

	return kVThreadReturn;
}

Common::SharedPtr<Modifier> ColorTableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new ColorTableModifier(*this));
}

const char *ColorTableModifier::getDefaultName() const {
	return "Color Table Modifier";
}

bool SaveAndRestoreModifier::load(ModifierLoaderContext &context, const Data::SaveAndRestoreModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_saveWhen.load(data.saveWhen) || !_restoreWhen.load(data.restoreWhen))
		return false;

	if (!_saveOrRestoreValue.load(data.saveOrRestoreValue, data.varName, data.varString))
		return false;

	_filePath = data.filePath;
	_fileName = data.fileName;

	return true;
}


SoundFadeModifier::SoundFadeModifier() : _fadeToVolume(0), _durationMSec(0) {
}

bool SoundFadeModifier::load(ModifierLoaderContext &context, const Data::SoundFadeModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen))
		return false;

	_fadeToVolume = data.fadeToVolume;
	_durationMSec = ((((data.codedDuration[0] * 60) + data.codedDuration[1]) * 60 + data.codedDuration[2]) * 100 + data.codedDuration[3]) * 10;

	return true;
}

bool SoundFadeModifier::respondsToEvent(const Event &evt) const {
	return evt.respondsTo(_enableWhen) || evt.respondsTo(_disableWhen);
}

VThreadState SoundFadeModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	warning("Sound fade modifier is not implemented");
	return kVThreadReturn;
}

Common::SharedPtr<Modifier> SoundFadeModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SoundFadeModifier(*this));
}

const char *SoundFadeModifier::getDefaultName() const {
	return "Sound Fade Modifier";
}

bool SaveAndRestoreModifier::respondsToEvent(const Event &evt) const {
	if (_saveWhen.respondsTo(evt) || _restoreWhen.respondsTo(evt))
		return true;

	return false;
}

VThreadState SaveAndRestoreModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_saveOrRestoreValue.getSourceType() != DynamicValueSourceTypes::kVariableReference) {
		warning("Save/restore failed, don't know how to use something that isn't a var reference");
		return kVThreadError;
	}

	const VarReference &var = _saveOrRestoreValue.getVarReference();

	Common::WeakPtr<RuntimeObject> objWeak;
	var.resolve(this, objWeak);

	if (objWeak.expired()) {
		warning("Save/load failed, couldn't resolve compound var");
		return kVThreadError;
	}

	RuntimeObject *obj = objWeak.lock().get();
	if (!obj->isModifier()) {
		warning("Save/load failed, source wasn't a modifier");
		return kVThreadError;
	}

	// There doesn't appear to be any flag for this, it just uses the file path field
	bool isPrompt = (_filePath == "Ask User");

	if (_saveWhen.respondsTo(msg->getEvent())) {
		CompoundVarSaver saver(runtime, obj);

		const Graphics::ManagedSurface *screenshotOverrideManaged = runtime->getSaveScreenshotOverride().get();
		const Graphics::Surface *screenshotOverride = nullptr;

		if (screenshotOverrideManaged)
			screenshotOverride = &screenshotOverrideManaged->rawSurface();

		bool succeeded = false;
		if (isPrompt)
			succeeded = runtime->getSaveProvider()->promptSave(&saver, screenshotOverride);
		else
			succeeded = runtime->getSaveProvider()->namedSave(&saver, screenshotOverride, _fileName);

		if (succeeded) {
			for (const Common::SharedPtr<SaveLoadHooks> &hooks : runtime->getHacks().saveLoadHooks)
				hooks->onSave(runtime, this, static_cast<Modifier *>(obj));
		}
		return kVThreadReturn;
	} else if (_restoreWhen.respondsTo(msg->getEvent())) {
		CompoundVarLoader loader(runtime, obj);

		bool succeeded = false;
		if (isPrompt)
			succeeded = runtime->getLoadProvider()->promptLoad(&loader);
		else
			succeeded = runtime->getLoadProvider()->namedLoad(&loader, _fileName);

		if (succeeded) {
			for (const Common::SharedPtr<SaveLoadHooks> &hooks : runtime->getHacks().saveLoadHooks)
				hooks->onLoad(runtime, this, static_cast<Modifier *>(obj));
		}
		return kVThreadReturn;
	}

	return kVThreadError;
}

void SaveAndRestoreModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	Modifier::linkInternalReferences(scope);

	_saveOrRestoreValue.linkInternalReferences(scope);
}

void SaveAndRestoreModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	Modifier::visitInternalReferences(visitor);

	_saveOrRestoreValue.visitInternalReferences(visitor);
}

Common::SharedPtr<Modifier> SaveAndRestoreModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SaveAndRestoreModifier(*this));
}

const char *SaveAndRestoreModifier::getDefaultName() const {
	return "Save And Restore Modifier";
}

bool MessengerModifier::load(ModifierLoaderContext &context, const Data::MessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_when.load(data.when) || !_sendSpec.load(data.send, data.messageFlags, data.with, data.withSource, data.withString, data.destination))
		return false;

	return true;
}

bool MessengerModifier::respondsToEvent(const Event &evt) const {
	return _when.respondsTo(evt);
}

VThreadState MessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_when.respondsTo(msg->getEvent())) {
		_sendSpec.sendFromMessenger(runtime, this, msg->getSource().lock().get(), msg->getValue(), nullptr);
	}

	return kVThreadReturn;
}

void MessengerModifier::linkInternalReferences(ObjectLinkingScope *outerScope) {
	_sendSpec.linkInternalReferences(outerScope);
}

void MessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_sendSpec.visitInternalReferences(visitor);
}

Common::SharedPtr<Modifier> MessengerModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new MessengerModifier(*this));
}

const char *MessengerModifier::getDefaultName() const {
	return "Messenger";
}

bool SetModifier::load(ModifierLoaderContext &context, const Data::SetModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen) || !_source.load(data.source, data.sourceName, data.sourceString) || !_target.load(data.target, data.targetName, data.targetString))
		return false;

	return true;
}

bool SetModifier::respondsToEvent(const Event &evt) const {
	if (_executeWhen.respondsTo(evt))
		return true;

	return false;
}

VThreadState SetModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_executeWhen.respondsTo(msg->getEvent())) {
		if (_target.getSourceType() != DynamicValueSourceTypes::kVariableReference) {
#ifdef MTROPOLIS_DEBUG_ENABLE
			if (Debugger *debugger = runtime->debugGetDebugger())
				debugger->notifyFmt(kDebugSeverityError, "Set modifier target isn't a variable reference");
#endif
			return kVThreadError;
		} else {
			Common::SharedPtr<Modifier> targetModifier = _target.getVarReference().resolution.lock();
			if (!targetModifier) {
#ifdef MTROPOLIS_DEBUG_ENABLE
				if (Debugger *debugger = runtime->debugGetDebugger())
					debugger->notifyFmt(kDebugSeverityError, "Set modifier target was invalid");
#endif
				return kVThreadError;
			} else if (!targetModifier->isVariable()) {
#ifdef MTROPOLIS_DEBUG_ENABLE
				if (Debugger *debugger = runtime->debugGetDebugger())
					debugger->notifyFmt(kDebugSeverityError, "Set modifier target was invalid");
#endif
				return kVThreadError;
			} else {
				DynamicValue srcValue = _source.produceValue(msg->getValue());
				VariableModifier *targetVar = static_cast<VariableModifier *>(targetModifier.get());
				if (!targetVar->varSetValue(nullptr, srcValue)) {
#ifdef MTROPOLIS_DEBUG_ENABLE
					if (Debugger *debugger = runtime->debugGetDebugger())
						debugger->notifyFmt(kDebugSeverityError, "Set modifier failed to set target value");
#endif
					return kVThreadError;
				}
			}
		}
	}
	return kVThreadReturn;
}

void SetModifier::linkInternalReferences(ObjectLinkingScope *outerScope) {
	_source.linkInternalReferences(outerScope);
	_target.linkInternalReferences(outerScope);
}

void SetModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_source.visitInternalReferences(visitor);
	_target.visitInternalReferences(visitor);
}

Common::SharedPtr<Modifier> SetModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SetModifier(*this));
}

const char *SetModifier::getDefaultName() const {
	return "Set Modifier";
}

AliasModifier::AliasModifier() : _aliasID(0) {
}

bool AliasModifier::load(ModifierLoaderContext &context, const Data::AliasModifier &data) {
	_guid = data.guid;
	if (!_modifierFlags.load(data.modifierFlags))
		return false;
	_name = data.name;

	_aliasID = data.aliasIndexPlusOne;

	return true;
}

Common::SharedPtr<Modifier> AliasModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new AliasModifier(*this));
}

const char *AliasModifier::getDefaultName() const {
	return "";
}

uint32 AliasModifier::getAliasID() const {
	return _aliasID;
}

bool AliasModifier::isAlias() const {
	return true;
}

bool ChangeSceneModifier::load(ModifierLoaderContext& context, const Data::ChangeSceneModifier& data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen))
		return false;

	if ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagNextScene) != 0)
		_sceneSelectionType = kSceneSelectionTypeNext;
	else if ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagPrevScene) != 0)
		_sceneSelectionType = kSceneSelectionTypePrevious;
	else if ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagSpecificScene) != 0)
		_sceneSelectionType = kSceneSelectionTypeSpecific;
	else
		return false;

	_targetSectionGUID = data.targetSectionGUID;
	_targetSubsectionGUID = data.targetSubsectionGUID;
	_targetSceneGUID = data.targetSceneGUID;

	_addToReturnList = ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagAddToReturnList) != 0);
	_addToDestList = ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagAddToDestList) != 0);
	_wrapAround = ((data.changeSceneFlags & Data::ChangeSceneModifier::kChangeSceneFlagWrapAround) != 0);

	return true;
}

bool ChangeSceneModifier::respondsToEvent(const Event &evt) const {
	if (_executeWhen.respondsTo(evt))
		return true;

	return false;
}

VThreadState ChangeSceneModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties>& msg) {
	if (_executeWhen.respondsTo(msg->getEvent())) {
		Common::SharedPtr<Structural> targetScene;
		if (_sceneSelectionType == kSceneSelectionTypeSpecific) {
			Structural *project = runtime->getProject();
			Structural *section = nullptr;

			if (_targetSectionGUID == 0xfffffffeu) {
				// For some reason, some scene change modifiers have a garbled section ID.  In that case, look in the current section.
				Structural *sectionSearch = findStructuralOwner();
				while (sectionSearch && !sectionSearch->isSection())
					sectionSearch = sectionSearch->getParent();

				section = sectionSearch;
			} else {
				for (Common::Array<Common::SharedPtr<Structural> >::const_iterator it = project->getChildren().begin(), itEnd = project->getChildren().end(); it != itEnd; ++it) {
					Structural *candidate = it->get();
					assert(candidate->isSection());
					if (candidate->getStaticGUID() == _targetSectionGUID) {
						section = candidate;
						break;
					}
				}
			}

			if (section) {
				Structural *subsection = nullptr;
				for (Common::Array<Common::SharedPtr<Structural> >::const_iterator it = section->getChildren().begin(), itEnd = section->getChildren().end(); it != itEnd; ++it) {
					Structural *candidate = it->get();
					assert(candidate->isSubsection());
					if (candidate->getStaticGUID() == _targetSubsectionGUID) {
						subsection = candidate;
						break;
					}
				}

				if (subsection) {
					for (Common::Array<Common::SharedPtr<Structural> >::const_iterator it = subsection->getChildren().begin(), itEnd = subsection->getChildren().end(); it != itEnd; ++it) {
						const Common::SharedPtr<Structural> &candidate = *it;
						assert(candidate->isElement() && static_cast<const Element *>(candidate.get())->isVisual());
						if (candidate->getStaticGUID() == _targetSceneGUID) {
							targetScene = candidate;
							break;
						}
					}
				} else {
					warning("Change Scene Modifier failed, subsection could not be resolved");
				}
			} else {
				warning("Change Scene Modifier failed, section could not be resolved");
			}
		} else {
			Structural *mainScene = runtime->getActiveMainScene().get();
			if (mainScene) {
				Structural *subsection = mainScene->getParent();

				const Common::Array<Common::SharedPtr<Structural> > &scenes = subsection->getChildren();
				if (scenes.size() == 1)
					error("Scene list is invalid");

				size_t sceneIndex = 0;
				for (size_t i = 1; i < scenes.size(); i++) {
					if (scenes[i].get() == mainScene) {
						sceneIndex = i;
						break;
					}
				}

				if (sceneIndex == 0) {
					warning("Change Scene Modifier failed, couldn't identify current scene's cyclical position");
				} else {
					if (_sceneSelectionType == kSceneSelectionTypePrevious) {
						if (sceneIndex == 1) {
							if (!_wrapAround)
								return kVThreadReturn;
							targetScene = scenes.back();
						} else {
							targetScene = scenes[sceneIndex - 1];
						}
					} else if (_sceneSelectionType == kSceneSelectionTypeNext) {

						if (sceneIndex == scenes.size() - 1) {
							if (!_wrapAround)
								return kVThreadReturn;
							targetScene = scenes[1];
						} else {
							targetScene = scenes[sceneIndex + 1];
						}
					}
				}
			}
		}

		if (targetScene) {
			runtime->addSceneStateTransition(HighLevelSceneTransition(targetScene, HighLevelSceneTransition::kTypeChangeToScene, _addToDestList, _addToReturnList));
		} else {
			warning("Change Scene Modifier failed, scene could not be resolved");
		}
	}

	return kVThreadReturn;
}

Common::SharedPtr<Modifier> ChangeSceneModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new ChangeSceneModifier(*this));
}

const char *ChangeSceneModifier::getDefaultName() const {
	return "Change Scene Modifier";
}

SoundEffectModifier::SoundEffectModifier() : _soundType(kSoundTypeBeep), _assetID(0) {
}

bool SoundEffectModifier::load(ModifierLoaderContext &context, const Data::SoundEffectModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen) || !_terminateWhen.load(data.terminateWhen))
		return false;

	if (data.assetID == Data::SoundEffectModifier::kSpecialAssetIDSystemBeep) {
		_soundType = kSoundTypeBeep;
		_assetID = 0;
	} else {
		_soundType = kSoundTypeAudioAsset;
		_assetID = data.assetID;
	}

	return true;
}

bool SoundEffectModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt) || _terminateWhen.respondsTo(evt);
}

VThreadState SoundEffectModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_terminateWhen.respondsTo(msg->getEvent())) {
		if (_player) {
			_player->stop();
			_player.reset();
		}
	} else if (_executeWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
	}

	return kVThreadReturn;
}

void SoundEffectModifier::disable(Runtime *runtime) {
	if (_soundType == kSoundTypeAudioAsset) {
		if (!_cachedAudio)
			loadAndCacheAudio(runtime);

		if (_cachedAudio) {
			if (_player) {
				_player->stop();
				_player.reset();
			}

			size_t numSamples = _cachedAudio->getNumSamples(*_metadata);
			_player.reset(new AudioPlayer(runtime->getAudioMixer(), 255, 0, _metadata, _cachedAudio, false, 0, 0, numSamples));
		}
	}
}

void SoundEffectModifier::loadAndCacheAudio(Runtime *runtime) {
	if (_cachedAudio)
		return;

	Project *project = runtime->getProject();
	Common::SharedPtr<Asset> asset = project->getAssetByID(_assetID).lock();

	if (!asset) {
		warning("Sound effect modifier references asset %i but the asset isn't loaded!", _assetID);
		return;
	}

	if (asset->getAssetType() != kAssetTypeAudio) {
		warning("Sound element assigned an asset that isn't audio");
		return;
	}

	_cachedAudio = static_cast<AudioAsset *>(asset.get())->loadAndCacheAudio(runtime);
	_metadata = static_cast<AudioAsset *>(asset.get())->getMetadata();
}

Common::SharedPtr<Modifier> SoundEffectModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SoundEffectModifier(*this));
}

const char *SoundEffectModifier::getDefaultName() const {
	return "Sound Effect Modifier";
}

PathMotionModifier::PointDef::PointDef() : frame(0), useFrame(false) {
}

PathMotionModifier::PathMotionModifier()
	: _reverse(false), _loop(false), _alternate(false),
	  _startAtBeginning(false), _frameDurationDUSec(1), _isAlternatingDirection(false), _lastPointTimeDUSec(0), _currentPointIndex(0) {
}

PathMotionModifier::~PathMotionModifier() {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

bool PathMotionModifier::load(ModifierLoaderContext &context, const Data::PathMotionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen) || !_terminateWhen.load(data.terminateWhen))
		return false;

	_reverse = ((data.flags & Data::PathMotionModifier::kFlagReverse) != 0);
	_loop = ((data.flags & Data::PathMotionModifier::kFlagLoop) != 0);
	_alternate = ((data.flags & Data::PathMotionModifier::kFlagAlternate) != 0);
	_startAtBeginning = ((data.flags & Data::PathMotionModifier::kFlagStartAtBeginning) != 0);

	_frameDurationDUSec = data.frameDurationTimes10Million;

	if (_frameDurationDUSec == 0)
		_frameDurationDUSec = 1; // Maybe set this to 1/60?  It seems like subframe movement is possible though.

	_points.resize(data.numPoints);

	for (size_t i = 0; i < _points.size(); i++) {
		const Data::PathMotionModifier::PointDef &inPoint = data.points[i];
		PointDef &outPoint = _points[i];

		outPoint.frame = inPoint.frame;
		outPoint.useFrame = ((inPoint.frameFlags & Data::PathMotionModifier::PointDef::kFrameFlagPlaySequentially) == 0);
		if (!inPoint.point.toScummVMPoint(outPoint.point))
			return false;

		if (data.havePointDefMessageSpecs) {
			const Data::PathMotionModifier::PointDefMessageSpec &messageSpec = inPoint.messageSpec;
			if (!outPoint.sendSpec.load(messageSpec.send, messageSpec.messageFlags, messageSpec.with, messageSpec.withSource, messageSpec.withString, messageSpec.destination))
				return false;
		} else {
			outPoint.sendSpec.destination = kMessageDestNone;
		}
	}

	return true;
}

bool PathMotionModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt) || _terminateWhen.respondsTo(evt);
}

VThreadState PathMotionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_terminateWhen.respondsTo(msg->getEvent())) {
		TerminateTaskData *terminateTask = runtime->getVThread().pushTask("PathMotionModifier::terminateTask", this, &PathMotionModifier::terminateTask);
		terminateTask->runtime = runtime;

		return kVThreadReturn;
	}
	if (_executeWhen.respondsTo(msg->getEvent())) {
		ExecuteTaskData *executeTask = runtime->getVThread().pushTask("PathMotionModifier::executeTask", this, &PathMotionModifier::executeTask);
		executeTask->runtime = runtime;

		_incomingData = msg->getValue();
		_triggerSource = msg->getSource();

		return kVThreadReturn;
	}

	return kVThreadReturn;
}

void PathMotionModifier::disable(Runtime *runtime) {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

void PathMotionModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	for (PointDef &point : _points)
		point.sendSpec.linkInternalReferences(scope);
}

void PathMotionModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	for (PointDef &point : _points)
		point.sendSpec.visitInternalReferences(visitor);
}

VThreadState PathMotionModifier::executeTask(const ExecuteTaskData &taskData) {
	if (_points.size() == 0)
		return kVThreadError;

	Runtime *runtime = taskData.runtime;

	uint64 timeMSec = runtime->getPlayTime();

	uint prevPointIndex = _currentPointIndex;
	uint newPointIndex = _reverse ? _points.size() - 1 : 0;

	_lastPointTimeDUSec = timeMSec * 10000u;
	_isAlternatingDirection = false;

	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}

	scheduleNextAdvance(runtime, _lastPointTimeDUSec);

	ChangePointsTaskData *changePointsTask = runtime->getVThread().pushTask("PathMotionModifier::changePoints", this, &PathMotionModifier::changePointsTask);
	changePointsTask->runtime = runtime;
	changePointsTask->prevPoint = (_startAtBeginning ? prevPointIndex : newPointIndex);
	changePointsTask->newPoint = newPointIndex;
	changePointsTask->isTerminal = (_loop == false && _points.size() == 1);

	SendMessageToParentTaskData *sendMessageToParentTask = runtime->getVThread().pushTask("PathMotionModifier::sendMessageToParent", this, &PathMotionModifier::sendMessageToParentTask);
	sendMessageToParentTask->runtime = runtime;
	sendMessageToParentTask->eventID = EventIDs::kMotionStarted;

	return kVThreadReturn;
}

VThreadState PathMotionModifier::changePointsTask(const ChangePointsTaskData &taskData) {
	Runtime *runtime = taskData.runtime;

	_currentPointIndex = taskData.newPoint;

	// TODO: Figure out if this is the correct order.  These are pushed tasks so order is reversed: We set position first,
	// then set cel, then fire the message if any.  I don't think the cel or position change have side effects.
	if (_points[_currentPointIndex].sendSpec.destination != kMessageDestNone) {
		TriggerMessageTaskData *triggerMessageTask = runtime->getVThread().pushTask("PathMotionModifier::triggerMessage", this, &PathMotionModifier::triggerMessageTask);
		triggerMessageTask->runtime = runtime;
		triggerMessageTask->pointIndex = _currentPointIndex;
	}

	// However, we DO need to fire Motion Ended events BEFORE we fire the last point's message.
	if (taskData.isTerminal) {
		SendMessageToParentTaskData *sendToParentTask = runtime->getVThread().pushTask("PathMotionModifier::sendMessageToParent", this, &PathMotionModifier::sendMessageToParentTask);
		sendToParentTask->runtime = runtime;
		sendToParentTask->eventID = EventIDs::kMotionEnded;
	}

	if (_points[_currentPointIndex].useFrame) {
		ChangeCelTaskData *changeCelTask = runtime->getVThread().pushTask("PathMotionModifier::changeCel", this, &PathMotionModifier::changeCelTask);
		changeCelTask->runtime = runtime;
		changeCelTask->pointIndex = _currentPointIndex;
	}

	Common::Point positionDelta = _points[taskData.newPoint].point - _points[taskData.prevPoint].point;
	if (positionDelta != Common::Point(0, 0)) {
		ChangePositionTaskData *changePositionTask = runtime->getVThread().pushTask("PathMotionModifier::changePosition", this, &PathMotionModifier::changePositionTask);
		changePositionTask->runtime = runtime;
		changePositionTask->positionDelta = positionDelta;
	}

	return kVThreadReturn;
}

VThreadState PathMotionModifier::triggerMessageTask(const TriggerMessageTaskData &taskData) {
	_points[taskData.pointIndex].sendSpec.sendFromMessenger(taskData.runtime, this, _triggerSource.lock().get(), _incomingData, nullptr);

	return kVThreadReturn;
}

VThreadState PathMotionModifier::sendMessageToParentTask(const SendMessageToParentTaskData &taskData) {
	Structural *owner = this->findStructuralOwner();

	if (owner) {
		Common::SharedPtr<MessageProperties> props(new MessageProperties(Event(taskData.eventID, 0), DynamicValue(), this->getSelfReference()));
		Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(props, owner, true, true, false));

		// Send immediately
		taskData.runtime->sendMessageOnVThread(dispatch);
	}

	return kVThreadReturn;
}

VThreadState PathMotionModifier::changeCelTask(const ChangeCelTaskData &taskData) {
	if (_points[taskData.pointIndex].useFrame) {
		Structural *structural = findStructuralOwner();

		if (structural) {
			MiniscriptThread thread(taskData.runtime, nullptr, nullptr, nullptr, this);
			DynamicValueWriteProxy proxy;

			MiniscriptInstructionOutcome writeRefOutcome = structural->writeRefAttribute(&thread, proxy, "cel");
			if (writeRefOutcome == kMiniscriptInstructionOutcomeContinue) {
				DynamicValue cel;
				cel.setInt(_points[taskData.pointIndex].frame + 1);
				(void) proxy.pod.ifc->write(&thread, cel, proxy.pod.objectRef, proxy.pod.ptrOrOffset);
			}
		}
	}

	return kVThreadReturn;
}

VThreadState PathMotionModifier::changePositionTask(const ChangePositionTaskData &taskData) {
	Structural *structural = findStructuralOwner();

	if (structural && structural->isElement() && static_cast<Element *>(structural)->isVisual()) {
		VisualElement *visual = static_cast<VisualElement *>(structural);
		VisualElement::OffsetTranslateTaskData *offsetTranslateTask = taskData.runtime->getVThread().pushTask("VisualElement::offsetTranslate", visual, &VisualElement::offsetTranslateTask);
		offsetTranslateTask->dx = taskData.positionDelta.x;
		offsetTranslateTask->dy = taskData.positionDelta.y;
	}

	return kVThreadReturn;
}

VThreadState PathMotionModifier::advanceFrameTask(const AdvanceFrameTaskData &taskData) {
	// Check what the new time will be and if it's in the future.  This also handles the case where the current time was changed
	// due to a triggered message re-executing the modifier: In that case, this will prevent any subframe advances that would have happened.
	uint64 newTime = _lastPointTimeDUSec + _frameDurationDUSec;
	if (newTime >= taskData.terminationTimeDUSec)
		return kVThreadReturn;

	_lastPointTimeDUSec = newTime;

	bool isPlayingForward = (_reverse == _isAlternatingDirection);
	bool isAtLastPoint = isPlayingForward ? (_currentPointIndex == _points.size() - 1) : (_currentPointIndex == 0);

	if (isAtLastPoint) {
		// If this isn't looping, we're done
		if (_loop == false) {
			if (_scheduledEvent) {
				_scheduledEvent->cancel();
				_scheduledEvent.reset();
			}
			return kVThreadReturn;
		}

		// Otherwise, check for alternation and trigger it
		if (_alternate) {
			isPlayingForward = !isPlayingForward;
			_isAlternatingDirection = !_isAlternatingDirection;
		}
	}

	uint prevPointIndex = _currentPointIndex;

	// If the path only has one point, we still act like it's advancing, messages
	uint nextPointIndex = 0;
	if (isPlayingForward) {
		nextPointIndex = _currentPointIndex + 1;
		if (nextPointIndex > _points.size())
			nextPointIndex = 0;
	} else {
		if (_currentPointIndex == 0)
			nextPointIndex = _points.size() - 1;
		else
			nextPointIndex = _currentPointIndex - 1;
	}

	bool isTerminal = false;
	if (!_loop) {
		isTerminal = isPlayingForward ? (nextPointIndex == _points.size() - 1) : (nextPointIndex == 0);
		if (isTerminal && _scheduledEvent) {
			_scheduledEvent->cancel();
			_scheduledEvent.reset();
		}
	}

	// Push the next frame advance for this advancement
	AdvanceFrameTaskData *advanceFrameTask = taskData.runtime->getVThread().pushTask("PathMotionModifier::advanceFrame", this, &PathMotionModifier::advanceFrameTask);
	advanceFrameTask->runtime = taskData.runtime;
	advanceFrameTask->terminationTimeDUSec = taskData.terminationTimeDUSec;

	// Push this frame advance
	ChangePointsTaskData *changePointsTask = taskData.runtime->getVThread().pushTask("PathMotionModifier::changePoints", this, &PathMotionModifier::changePointsTask);
	changePointsTask->runtime = taskData.runtime;
	changePointsTask->prevPoint = prevPointIndex;
	changePointsTask->newPoint = nextPointIndex;
	changePointsTask->isTerminal = isTerminal;

	return kVThreadReturn;
}

void PathMotionModifier::scheduleNextAdvance(Runtime *runtime, uint64 startingFromTimeDUSec) {
	assert(_scheduledEvent.get() == nullptr);

	uint64 nextFrameTimeMSec = (startingFromTimeDUSec + _frameDurationDUSec + 9999u) / 10000u;
	_scheduledEvent = runtime->getScheduler().scheduleMethod<PathMotionModifier, &PathMotionModifier::advance>(nextFrameTimeMSec, this);
}

void PathMotionModifier::advance(Runtime *runtime) {
	_scheduledEvent.reset();

	uint64 currentTimeDUSec = runtime->getPlayTime() * 10000u;

	uint64 framesToAdvance = (currentTimeDUSec - _lastPointTimeDUSec) / _frameDurationDUSec;
	uint64 nextFrameDUSec = _lastPointTimeDUSec + framesToAdvance * _frameDurationDUSec;

	// Schedule the next advance now, since the advance may be cancelled by a message triggered by one of the advances
	scheduleNextAdvance(runtime, nextFrameDUSec);

	AdvanceFrameTaskData *advanceFrameTask = runtime->getVThread().pushTask("PathMotionModifier::advanceFrame", this, &PathMotionModifier::advanceFrameTask);
	advanceFrameTask->runtime = runtime;
	advanceFrameTask->terminationTimeDUSec = currentTimeDUSec;
}

VThreadState PathMotionModifier::terminateTask(const TerminateTaskData &taskData) {
	if (_scheduledEvent) {
		SendMessageToParentTaskData *sendToParentTask = taskData.runtime->getVThread().pushTask("PathMotionModifier::endMotion", this, &PathMotionModifier::sendMessageToParentTask);
		sendToParentTask->runtime = taskData.runtime;
		sendToParentTask->eventID = EventIDs::kMotionEnded;
	}

	disable(taskData.runtime);

	return kVThreadReturn;
}

Common::SharedPtr<Modifier> PathMotionModifier::shallowClone() const {
	Common::SharedPtr<PathMotionModifier> clone(new PathMotionModifier(*this));
	clone->_incomingData = DynamicValue();
	clone->_scheduledEvent.reset();
	return clone;
}

const char *PathMotionModifier::getDefaultName() const {
	return "Path Motion Modifier";
}

SimpleMotionModifier::SimpleMotionModifier() : _motionType(kMotionTypeIntoScene), _directionFlags(0), _steps(0), _delayMSecTimes4800(0), _lastTickTime(0) {
}

SimpleMotionModifier::~SimpleMotionModifier() {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

bool SimpleMotionModifier::load(ModifierLoaderContext &context, const Data::SimpleMotionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen) || !_terminateWhen.load(data.terminateWhen))
		return false;

	_directionFlags = data.directionFlags;
	_steps = data.steps;
	_motionType = static_cast<MotionType>(data.motionType);
	_delayMSecTimes4800 = data.delayMSecTimes4800;

	return true;
}

bool SimpleMotionModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt) || _terminateWhen.respondsTo(evt);
}

VThreadState SimpleMotionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_executeWhen.respondsTo(msg->getEvent())) {
		if (!_scheduledEvent) {
			if (_motionType == kMotionTypeRandomBounce)
				startRandomBounce(runtime);
			else {
#ifdef MTROPOLIS_DEBUG_ENABLE
				if (Debugger *debugger = runtime->debugGetDebugger())
					debugger->notifyFmt(kDebugSeverityError, "Simple motion modifier was activated with an unsupported motion type");
#endif
			}
		}
		return kVThreadReturn;
	}
	if (_terminateWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}
	return kVThreadReturn;
}

void SimpleMotionModifier::disable(Runtime *runtime) {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

void SimpleMotionModifier::startRandomBounce(Runtime *runtime) {
	_velocity = Common::Point(24, 24);	// Seems to be static
	_lastTickTime = runtime->getPlayTime();

	_scheduledEvent = runtime->getScheduler().scheduleMethod<SimpleMotionModifier, &SimpleMotionModifier::runRandomBounce>(_lastTickTime + 1, this);
}

void SimpleMotionModifier::runRandomBounce(Runtime *runtime) {
	uint numTicks = 100;

	uint64 currentTime = runtime->getPlayTime();

 	if (_delayMSecTimes4800 > 0) {
		uint64 ticksToExecute = (currentTime - _lastTickTime) * 4800u / _delayMSecTimes4800;

		if (ticksToExecute < 100) {
			numTicks = static_cast<uint>(ticksToExecute);
			_lastTickTime += (static_cast<uint64>(numTicks) * _delayMSecTimes4800 / 4800u);
		} else {
			_lastTickTime = currentTime;
		}
	}

	if (numTicks > 0) {
		Structural *structural = this->findStructuralOwner();
		if (structural && structural->isElement() && static_cast<Element *>(structural)->isVisual()) {
			VisualElement *visual = static_cast<VisualElement *>(structural);

			const Common::Point initialPosition = visual->getGlobalPosition();
			Common::Point newPosition = initialPosition;

			Common::Rect relRect = visual->getRelativeRect();

			int32 w = relRect.width();
			int32 h = relRect.height();

			Window *mainWindow = runtime->getMainWindow().lock().get();
			if (mainWindow) {
				int32 windowWidth = mainWindow->getWidth();
				int32 windowHeight = mainWindow->getHeight();

				for (uint tick = 0; tick < numTicks; tick++) {
					Common::Rect newRect(newPosition.x + _velocity.x, newPosition.y + _velocity.y, newPosition.x + _velocity.x + w, newPosition.y + _velocity.y + h);

					if (newRect.left < 0) {
						newRect.translate(-newRect.left, 0);
						_velocity.x = runtime->getRandom()->getRandomNumber(31) + 1;
					} else if (newRect.right > windowWidth) {
						newRect.translate(windowWidth - newRect.right, 0);
						_velocity.x = -1 - static_cast<int32>(runtime->getRandom()->getRandomNumber(31));
					}

					if (newRect.top < 0) {
						newRect.translate(0, -newRect.top);
						_velocity.y = runtime->getRandom()->getRandomNumber(31) + 1;
					} else if (newRect.bottom > windowHeight) {
						newRect.translate(windowHeight - newRect.bottom, 0);
						_velocity.y = -1 - static_cast<int32>(runtime->getRandom()->getRandomNumber(31));
					}

					newPosition = Common::Point(newRect.left, newRect.top);
					_velocity.y++;
				}
			}

			if (visual->getHooks())
				visual->getHooks()->onSetPosition(runtime, visual, initialPosition, newPosition);

			if (newPosition != initialPosition) {
				VisualElement::OffsetTranslateTaskData *taskData = runtime->getVThread().pushTask("VisualElement::offsetTranslateTask", visual, &VisualElement::offsetTranslateTask);
				taskData->dx = newPosition.x - initialPosition.x;
				taskData->dy = newPosition.y - initialPosition.y;
			}
		}
	}

	_scheduledEvent = runtime->getScheduler().scheduleMethod<SimpleMotionModifier, &SimpleMotionModifier::runRandomBounce>(currentTime + 1, this);
}

Common::SharedPtr<Modifier> SimpleMotionModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SimpleMotionModifier(*this));
}

const char *SimpleMotionModifier::getDefaultName() const {
	return "Simple Motion Modifier";
}

bool DragMotionModifier::load(ModifierLoaderContext &context, const Data::DragMotionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	_dragProps.reset(new DragMotionProperties());

	// constraint margin is unchecked here because it's a margin, not a real rectangle, but it's stored as if it's a rect
	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen) || !data.constraintMargin.toScummVMRectUnchecked(_dragProps->constraintMargin))
		return false;

	bool constrainVertical = false;
	bool constrainHorizontal = false;
	if (data.haveMacPart) {
		_dragProps->constrainToParent = ((data.platform.mac.flags & Data::DragMotionModifier::MacPart::kConstrainToParent) != 0);
		constrainHorizontal = ((data.platform.mac.flags & Data::DragMotionModifier::MacPart::kConstrainHorizontal) != 0);
		constrainVertical = ((data.platform.mac.flags & Data::DragMotionModifier::MacPart::kConstrainVertical) != 0);
	} else if (data.haveWinPart) {
		_dragProps->constrainToParent = (data.platform.win.constrainToParent != 0);
		constrainVertical = (data.platform.win.constrainVertical != 0);
		constrainHorizontal = (data.platform.win.constrainHorizontal != 0);
	} else {
		return false;
	}

	if (constrainVertical) {
		if (constrainHorizontal)
			return false;	// ???
		else
			_dragProps->constraintDirection = kConstraintDirectionVertical;
	} else {
		if (constrainHorizontal)
			_dragProps->constraintDirection = kConstraintDirectionHorizontal;
		else
			_dragProps->constraintDirection = kConstraintDirectionNone;
	}

	return true;
}

Common::SharedPtr<Modifier> DragMotionModifier::shallowClone() const {
	Common::SharedPtr<DragMotionModifier> clone = Common::SharedPtr<DragMotionModifier>(new DragMotionModifier(*this));
	clone->_dragProps.reset(new DragMotionProperties(*_dragProps));
	return clone;
}

const char *DragMotionModifier::getDefaultName() const {
	return "Drag Motion Modifier";
}

bool DragMotionModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState DragMotionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_enableWhen.respondsTo(msg->getEvent())) {
		Structural *owner = this->findStructuralOwner();
		if (owner->isElement() && static_cast<Element *>(owner)->isVisual())
			static_cast<VisualElement *>(owner)->setDragMotionProperties(_dragProps);
		return kVThreadReturn;
	}
	if (_disableWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}

	return kVThreadReturn;
}

void DragMotionModifier::disable(Runtime *runtime) {
	Structural *owner = this->findStructuralOwner();
	if (owner->isElement() && static_cast<Element *>(owner)->isVisual())
		static_cast<VisualElement *>(owner)->setDragMotionProperties(nullptr);
}

VectorMotionModifier::~VectorMotionModifier() {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

bool VectorMotionModifier::load(ModifierLoaderContext &context, const Data::VectorMotionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen) || !_vec.load(data.vec, data.vecSource, data.vecString))
		return false;

	return true;
}

bool VectorMotionModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState VectorMotionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_enableWhen.respondsTo(msg->getEvent())) {
		DynamicValue vec = _vec.produceValue(msg->getValue());

		if (!vec.convertToType(DynamicValueTypes::kVector, vec)) {
#ifdef MTROPOLIS_DEBUG_ENABLE
			if (Debugger *debugger = runtime->debugGetDebugger())
				debugger->notify(kDebugSeverityError, "Vector value was not actually a vector");
#endif
			return kVThreadError;
		}

		_resolvedVector = vec.getVector();

		if (!_scheduledEvent) {
			_lastTickTime = runtime->getPlayTime();
			_subpixelX = 0;
			_subpixelY = 0;
			_scheduledEvent = runtime->getScheduler().scheduleMethod<VectorMotionModifier, &VectorMotionModifier::trigger>(_lastTickTime + 1, this);
			return kVThreadReturn;
		}
	}
	if (_disableWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}

	return kVThreadReturn;
}

void VectorMotionModifier::disable(Runtime *runtime) {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

void VectorMotionModifier::trigger(Runtime *runtime) {
	uint64 currentTime = runtime->getPlayTime();
	_scheduledEvent = runtime->getScheduler().scheduleMethod<VectorMotionModifier, &VectorMotionModifier::trigger>(currentTime + 1, this);

	// Variable-sourced motion is continuously updated and doesn't need to be re-triggered.
	// The Pong minigame in Obsidian's Bureau chapter depends on this.
	if (_vec.getSourceType() == DynamicValueSourceTypes::kVariableReference) {
		DynamicValue vec = _vec.produceValue(DynamicValue());

		if (vec.convertToType(DynamicValueTypes::kVector, vec))
			_resolvedVector = vec.getVector();
	}

	double radians = _resolvedVector.angleDegrees * (M_PI / 180.0);

	// Distance is per-tick, which is 1/60 of a sec, so the multiplier is 60.0/1000.0 or 0.06
	// We then scale the entire thing up by 2^64, so the result is 60*65536/1000
	double distance = static_cast<double>(currentTime - _lastTickTime) * _resolvedVector.magnitude * 3932.16;

	int32 dx = static_cast<int32>(cos(radians) * distance) + static_cast<int32>(_subpixelX);
	int32 dy = static_cast<int32>(-sin(radians) * distance) + static_cast<int32>(_subpixelY);
	_subpixelX = (dx & 0xffff);
	_subpixelY = (dy & 0xffff);

	dx -= _subpixelX;
	dy -= _subpixelY;

	dx /= 65536;
	dy /= 65536;

	Structural *structural = findStructuralOwner();
	if (structural->isElement()) {
		Element *element = static_cast<Element *>(structural);
		if (element->isVisual()) {
			VisualElement *visual = static_cast<VisualElement *>(element);

			VisualElement::OffsetTranslateTaskData *taskData = runtime->getVThread().pushTask("VisualElement::offsetTranslateTask", visual, &VisualElement::offsetTranslateTask);
			taskData->dx = dx;
			taskData->dy = dy;
		}
	}

	_lastTickTime = currentTime;
}

Common::SharedPtr<Modifier> VectorMotionModifier::shallowClone() const {
	Common::SharedPtr<VectorMotionModifier> clone(new VectorMotionModifier(*this));
	clone->_scheduledEvent.reset();
	return clone;
}

const char *VectorMotionModifier::getDefaultName() const {
	return "Vector Motion Modifier";
}

void VectorMotionModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	_vec.linkInternalReferences(scope);
}

void VectorMotionModifier::visitInternalReferences(IStructuralReferenceVisitor* visitor) {
	_vec.visitInternalReferences(visitor);
}

bool SceneTransitionModifier::load(ModifierLoaderContext &context, const Data::SceneTransitionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen))
		return false;

	_duration = data.duration;
	_steps = data.steps;
	if (!SceneTransitionTypes::loadFromData(_transitionType, data.transitionType))
		return false;
	if (!SceneTransitionDirections::loadFromData(_transitionDirection, data.direction))
		return false;

	return true;
}

bool SceneTransitionModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState SceneTransitionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_enableWhen.respondsTo(msg->getEvent())) {
		SceneTransitionEffect effect;

		// For some reason, these vary
		uint32 timeDivisor = 100;
		switch (effect._transitionType) {
		case SceneTransitionTypes::kRandomDissolve:
			timeDivisor = 50;
			break;
		case SceneTransitionTypes::kFade:
			timeDivisor = 25;
			break;
		default:
			break;
		}

		effect._duration = _duration / timeDivisor;
		effect._steps = _steps;
		effect._transitionDirection = _transitionDirection;
		effect._transitionType = _transitionType;
		runtime->setSceneTransitionEffect(true, &effect);
	}
	if (_disableWhen.respondsTo(msg->getEvent()))
		disable(runtime);

	return kVThreadReturn;
}

void SceneTransitionModifier::disable(Runtime *runtime) {
	runtime->setSceneTransitionEffect(true, nullptr);
}

Common::SharedPtr<Modifier> SceneTransitionModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SceneTransitionModifier(*this));
}

const char *SceneTransitionModifier::getDefaultName() const {
	return "Scene Transition Modifier";
}

ElementTransitionModifier::ElementTransitionModifier() : _rate(0), _steps(0),
	_transitionType(kTransitionTypeFade), _revealType(kRevealTypeReveal), _transitionStartTime(0), _currentStep(0) {
}

ElementTransitionModifier::~ElementTransitionModifier() {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

bool ElementTransitionModifier::load(ModifierLoaderContext &context, const Data::ElementTransitionModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen))
		return false;

	_rate = data.rate;
	_steps = data.steps;

	switch (data.transitionType) {
	case Data::ElementTransitionModifier::kTransitionTypeFade:
		_transitionType = kTransitionTypeFade;
		break;
	case Data::ElementTransitionModifier::kTransitionTypeOvalIris:
		_transitionType = kTransitionTypeOvalIris;
		break;
	case Data::ElementTransitionModifier::kTransitionTypeRectangularIris:
		_transitionType = kTransitionTypeRectangularIris;
		break;
	case Data::ElementTransitionModifier::kTransitionTypeZoom:
		_transitionType = kTransitionTypeZoom;
		break;
	default:
		return false;
	}

	switch (data.revealType) {
	case Data::ElementTransitionModifier::kRevealTypeConceal:
		_revealType = kRevealTypeConceal;
		break;
	case Data::ElementTransitionModifier::kRevealTypeReveal:
		_revealType = kRevealTypeReveal;
		break;
	default:
		return false;
	}

	return true;
}

bool ElementTransitionModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState ElementTransitionModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	// How element transition modifiers work:
	// - When activated, if Reveal, then Show is sent (regardless of whether element is visible or not).
	// - Then, for both reveal and conceal, Transition Started is sent by the modifier.
	// - When a conceal transition completes, Hide is sent to the element.
	// - Then, for both reveal and conceal, Transition Ended is sent by the modifier.
	// - If a transition is active and the Disable signal is called, then the transition completes immediately.
	//
	// Q. Does that mean if an element has a Revealer followed by a Concealer and they take opposing messages,
	//    that the element will be hidden if a reveal interrupts the concealer due to its hide message happening
	//    second, but that won't happen if they're in Concealer-Revealer order?
	// A. Yes.
	if (_enableWhen.respondsTo(msg->getEvent())) {
		if (_scheduledEvent) {
			_scheduledEvent->cancel();
			_scheduledEvent.reset();
		}

		_scheduledEvent = runtime->getScheduler().scheduleMethod<ElementTransitionModifier, &ElementTransitionModifier::continueTransition>(runtime->getPlayTime() + 1, this);
		_transitionStartTime = runtime->getPlayTime();
		_currentStep = 0;
		setTransitionProgress(0, _steps);

		// Pushed tasks, so these are executed in reverse order (Show -> Transition Started)
		{
			Common::SharedPtr<MessageProperties> msgProps(new MessageProperties(Event(EventIDs::kTransitionStarted, 0), DynamicValue(), getSelfReference()));
			Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(msgProps, findStructuralOwner(), false, true, false));
			runtime->sendMessageOnVThread(dispatch);
		}

		if (_revealType == kRevealTypeReveal)
		{
			Common::SharedPtr<MessageProperties> msgProps(new MessageProperties(Event(EventIDs::kElementShow, 0), DynamicValue(), getSelfReference()));
			Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(msgProps, findStructuralOwner(), false, false, true));
			runtime->sendMessageOnVThread(dispatch);
		}

		return kVThreadReturn;
	}

	if (_disableWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}

	return Modifier::consumeMessage(runtime, msg);
}

void ElementTransitionModifier::disable(Runtime *runtime) {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();

		completeTransition(runtime);
	}
}

Common::SharedPtr<Modifier> ElementTransitionModifier::shallowClone() const {
	Common::SharedPtr<ElementTransitionModifier> clone(new ElementTransitionModifier(*this));
	clone->_scheduledEvent.reset();

	return clone;
}

const char *ElementTransitionModifier::getDefaultName() const {
	return "Element Transition Modifier";
}

void ElementTransitionModifier::continueTransition(Runtime *runtime) {
	_scheduledEvent.reset();

	const uint64 playTime = runtime->getPlayTime();
	const uint64 timeSinceStart = playTime - _transitionStartTime;

	uint32 step = static_cast<uint32>(timeSinceStart * _rate / 1000);

	if (step >= _steps || _rate == 0) {
		completeTransition(runtime);
		return;
	}

	if (step != _currentStep) {
		setTransitionProgress(step, _steps);
		_currentStep = step;
	}

	runtime->setSceneGraphDirty();
	_scheduledEvent = runtime->getScheduler().scheduleMethod<ElementTransitionModifier, &ElementTransitionModifier::continueTransition>(playTime + 1, this);
}

void ElementTransitionModifier::completeTransition(Runtime *runtime) {
	// Pushed tasks, so these are executed in reverse order (Hide -> Transition Ended)
	{
		Common::SharedPtr<MessageProperties> msgProps(new MessageProperties(Event(EventIDs::kTransitionEnded, 0), DynamicValue(), getSelfReference()));
		Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(msgProps, findStructuralOwner(), false, true, false));
		runtime->sendMessageOnVThread(dispatch);
	}

	if (_revealType == kRevealTypeConceal) {
		Common::SharedPtr<MessageProperties> msgProps(new MessageProperties(Event(EventIDs::kElementHide, 0), DynamicValue(), getSelfReference()));
		Common::SharedPtr<MessageDispatch> dispatch(new MessageDispatch(msgProps, findStructuralOwner(), false, false, true));
		runtime->sendMessageOnVThread(dispatch);
	}

	setTransitionProgress(( _revealType == kRevealTypeReveal) ? 1 : 0, 1);
	runtime->setSceneGraphDirty();
}

void ElementTransitionModifier::setTransitionProgress(uint32 step, uint32 maxSteps) {
	Structural *structural = findStructuralOwner();
	if (structural && structural->isElement() && static_cast<Element *>(structural)->isVisual()) {
		VisualElement *visual = static_cast<VisualElement *>(structural);
		VisualElementTransitionProperties props = visual->getTransitionProperties();

		if (_transitionType == kTransitionTypeFade) {
			if (step > maxSteps)
				step = maxSteps;

			uint32 alpha = step * 255 / maxSteps;
			if (_revealType == kRevealTypeConceal)
				alpha = 255 - alpha;

			props.setAlpha(alpha);
			visual->setTransitionProperties(props);
		} else {
			warning("Unsupported transition type");
		}
	}
}


SharedSceneModifier::SharedSceneModifier() : _targetSectionGUID(0), _targetSubsectionGUID(0), _targetSceneGUID(0) {
}

SharedSceneModifier::~SharedSceneModifier() {
}

bool SharedSceneModifier::load(ModifierLoaderContext &context, const Data::SharedSceneModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen))
		return false;

	_targetSectionGUID = data.sectionGUID;
	_targetSubsectionGUID = data.subsectionGUID;
	_targetSceneGUID = data.sceneGUID;

	return true;
}

bool SharedSceneModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt);
}

VThreadState SharedSceneModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_executeWhen.respondsTo(msg->getEvent())) {
		Project *project = runtime->getProject();
		bool found = false;
		for (const Common::SharedPtr<Structural> &section : project->getChildren()) {
			if (section->getStaticGUID() == _targetSectionGUID) {
				for (const Common::SharedPtr<Structural> &subsection : section->getChildren()) {
					if (subsection->getStaticGUID() == _targetSubsectionGUID) {
						for (const Common::SharedPtr<Structural> &scene : subsection->getChildren()) {
							if (scene->getStaticGUID() == _targetSceneGUID) {
								runtime->addSceneStateTransition(HighLevelSceneTransition(scene, HighLevelSceneTransition::kTypeChangeSharedScene, false, false));
								found = true;
								break;
							}
						}
						break;
					}
				}
				break;
			}
		}

		if (!found) {
#ifdef MTROPOLIS_DEBUG_ENABLE
			if (Debugger *debugger = runtime->debugGetDebugger())
				debugger->notifyFmt(kDebugSeverityError, "Failed to resolve shared scene modifier target scene");
#endif
			return kVThreadError;
		}
	}
	return kVThreadReturn;
}

void SharedSceneModifier::disable(Runtime *runtime) {
}

Common::SharedPtr<Modifier> SharedSceneModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new SharedSceneModifier(*this));
}

const char *SharedSceneModifier::getDefaultName() const {
	return "Shared Scene Modifier";
}

bool IfMessengerModifier::load(ModifierLoaderContext &context, const Data::IfMessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_when.load(data.when) || !_sendSpec.load(data.send, data.messageFlags, data.with, data.withSource, data.withString, data.destination))
		return false;

	if (!MiniscriptParser::parse(data.program, _program, _references))
		return false;

	return true;
}

bool IfMessengerModifier::respondsToEvent(const Event &evt) const {
	return _when.respondsTo(evt);
}

CORO_BEGIN_DEFINITION(IfMessengerModifier::RunEvaluateAndSendCoroutine)
	struct Locals {
		Common::WeakPtr<RuntimeObject> triggerSource;
		DynamicValue incomingData;
		bool isTrue = false;
		Common::SharedPtr<MiniscriptThread> thread;
	};

	CORO_BEGIN_FUNCTION
		// Is this the right place for this?  Not sure if Miniscript can change incomingData
		locals->triggerSource = params->msg->getSource();
		locals->incomingData = params->msg->getValue();

		locals->thread.reset(new MiniscriptThread(params->runtime, params->msg, params->self->_program, params->self->_references, params->self));

		CORO_CALL(MiniscriptThread::ResumeThreadCoroutine, locals->thread);

		CORO_IF (!locals->thread->evaluateTruthOfResult(locals->isTrue))
			CORO_ERROR;
		CORO_END_IF

		CORO_IF(locals->isTrue)
			CORO_AWAIT(params->self->_sendSpec.sendFromMessenger(params->runtime, params->self, locals->triggerSource.lock().get(), locals->incomingData, nullptr));
		CORO_END_IF
	CORO_END_FUNCTION
CORO_END_DEFINITION

VThreadState IfMessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_when.respondsTo(msg->getEvent()))
		runtime->getVThread().pushCoroutine<IfMessengerModifier::RunEvaluateAndSendCoroutine>(this, runtime, msg);

	return kVThreadReturn;
}

Common::SharedPtr<Modifier> IfMessengerModifier::shallowClone() const {
	IfMessengerModifier *clonePtr = new IfMessengerModifier(*this);
	Common::SharedPtr<Modifier> clone(clonePtr);

	// Keep the Miniscript program (which is static), but clone the references
	clonePtr->_references.reset(new MiniscriptReferences(*_references));

	return clone;
}

const char *IfMessengerModifier::getDefaultName() const {
	return "If Messenger";
}

void IfMessengerModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	_sendSpec.linkInternalReferences(scope);
	_references->linkInternalReferences(scope);
}

void IfMessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_sendSpec.visitInternalReferences(visitor);
	_references->visitInternalReferences(visitor);
}

TimerMessengerModifier::TimerMessengerModifier() : _milliseconds(0), _looping(false) {
}

TimerMessengerModifier::~TimerMessengerModifier() {
	if (_scheduledEvent)
		_scheduledEvent->cancel();
}

bool TimerMessengerModifier::load(ModifierLoaderContext &context, const Data::TimerMessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_executeWhen.load(data.executeWhen) || !this->_terminateWhen.load(data.terminateWhen))
		return false;

	if (!_sendSpec.load(data.send, data.messageAndTimerFlags, data.with, data.withSource, data.withString, data.destination))
		return false;

	_milliseconds = data.minutes * (60 * 1000) + data.seconds * (1000) + data.hundredthsOfSeconds * 10;
	_looping = ((data.messageAndTimerFlags & Data::TimerMessengerModifier::kTimerFlagLooping) != 0);

	return true;
}

bool TimerMessengerModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt) || _terminateWhen.respondsTo(evt);
}

VThreadState TimerMessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	// If this terminates AND starts then just cancel out and terminate
	if (_terminateWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}
	if (_executeWhen.respondsTo(msg->getEvent())) {
		// 0-time events are not allowed
		uint32 realMilliseconds = _milliseconds;
		if (realMilliseconds == 0)
			realMilliseconds = 1;

		_triggerSource = msg->getSource();

		debug(3, "Timer %x '%s' scheduled to execute in %i milliseconds", getStaticGUID(), getName().c_str(), realMilliseconds);

		if (_scheduledEvent) {
			_scheduledEvent->cancel();
			_scheduledEvent.reset();
		}

		_scheduledEvent = runtime->getScheduler().scheduleMethod<TimerMessengerModifier, &TimerMessengerModifier::trigger>(runtime->getPlayTime() + realMilliseconds, this);
		_incomingData = msg->getValue();
		if (_incomingData.getType() == DynamicValueTypes::kList)
			_incomingData.setList(_incomingData.getList()->clone());

		return kVThreadReturn;
	}

	return kVThreadReturn;
}

void TimerMessengerModifier::disable(Runtime *runtime) {
	if (_scheduledEvent) {
		_scheduledEvent->cancel();
		_scheduledEvent.reset();
	}
}

void TimerMessengerModifier::linkInternalReferences(ObjectLinkingScope *outerScope) {
	_sendSpec.linkInternalReferences(outerScope);
}

void TimerMessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_sendSpec.visitInternalReferences(visitor);
}

Common::SharedPtr<Modifier> TimerMessengerModifier::shallowClone() const {
	TimerMessengerModifier *clone = new TimerMessengerModifier(*this);
	clone->_scheduledEvent.reset();

	return Common::SharedPtr<Modifier>(clone);
}

const char *TimerMessengerModifier::getDefaultName() const {
	return "Timer Messenger";
}

void TimerMessengerModifier::trigger(Runtime *runtime) {
	debug(3, "Timer %x '%s' triggered", getStaticGUID(), getName().c_str());
	if (_looping) {
		uint32 realMilliseconds = _milliseconds;
		if (realMilliseconds == 0)
			realMilliseconds = 1;
		_scheduledEvent = runtime->getScheduler().scheduleMethod<TimerMessengerModifier, &TimerMessengerModifier::trigger>(runtime->getPlayTime() + realMilliseconds, this);
	} else
		_scheduledEvent.reset();

	_sendSpec.sendFromMessenger(runtime, this, _triggerSource.lock().get(), _incomingData, nullptr);
}

BoundaryDetectionMessengerModifier::BoundaryDetectionMessengerModifier()
	: _exitTriggerMode(kExitTriggerExiting), _detectTopEdge(false), _detectBottomEdge(false),
	  _detectLeftEdge(false), _detectRightEdge(false), _detectionMode(kContinuous),
	  _runtime(nullptr), _isActive(false) {
}

BoundaryDetectionMessengerModifier::~BoundaryDetectionMessengerModifier() {
	if (_isActive)
		_runtime->removeBoundaryDetector(this);
}


bool BoundaryDetectionMessengerModifier::load(ModifierLoaderContext &context, const Data::BoundaryDetectionMessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !this->_disableWhen.load(data.disableWhen))
		return false;

	_exitTriggerMode = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kDetectExiting) != 0) ? kExitTriggerExiting : kExitTriggerOnceExited;
	_detectionMode = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kWhileDetected) != 0) ? kContinuous : kOnFirstDetection;

	_detectTopEdge = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kDetectTopEdge) != 0);
	_detectBottomEdge = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kDetectBottomEdge) != 0);
	_detectLeftEdge = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kDetectLeftEdge) != 0);
	_detectRightEdge = ((data.messageFlagsHigh & Data::BoundaryDetectionMessengerModifier::kDetectRightEdge) != 0);

	if (!_send.load(data.send, data.messageFlagsHigh << 16, data.with, data.withSource, data.withString, data.destination))
		return false;

	return true;
}

bool BoundaryDetectionMessengerModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState BoundaryDetectionMessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_enableWhen.respondsTo(msg->getEvent()) && !_isActive) {
		_runtime = runtime;
		_runtime->addBoundaryDetector(this);
		_isActive = true;

		_incomingData = msg->getValue();
		if (_incomingData.getType() == DynamicValueTypes::kList)
			_incomingData.setList(_incomingData.getList()->clone());
		_triggerSource = msg->getSource();
	}
	if (_disableWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
	}

	return kVThreadReturn;
}

void BoundaryDetectionMessengerModifier::disable(Runtime *runtime) {
	if (_isActive) {
		_runtime->removeBoundaryDetector(this);
		_isActive = false;
		_runtime = nullptr;
	}
}

void BoundaryDetectionMessengerModifier::linkInternalReferences(ObjectLinkingScope *outerScope) {
	_send.linkInternalReferences(outerScope);
}

void BoundaryDetectionMessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_send.visitInternalReferences(visitor);
}

void BoundaryDetectionMessengerModifier::getCollisionProperties(Modifier *&modifier, uint &edgeFlags, bool &mustBeCompletelyOutside, bool &continuous) const {
	modifier = const_cast<BoundaryDetectionMessengerModifier *>(this);

	uint flags = 0;
	if (_detectBottomEdge)
		flags |= kEdgeBottom;
	if (_detectTopEdge)
		flags |= kEdgeTop;
	if (_detectRightEdge)
		flags |= kEdgeRight;
	if (_detectLeftEdge)
		flags |= kEdgeLeft;

	edgeFlags = flags;
	mustBeCompletelyOutside = (_exitTriggerMode == kExitTriggerOnceExited);
	continuous = (_detectionMode == kContinuous);
}

void BoundaryDetectionMessengerModifier::triggerCollision(Runtime *runtime) {
	_send.sendFromMessenger(runtime, this, _triggerSource.lock().get(), _incomingData, nullptr);
}

Common::SharedPtr<Modifier> BoundaryDetectionMessengerModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new BoundaryDetectionMessengerModifier(*this));
}

const char *BoundaryDetectionMessengerModifier::getDefaultName() const {
	return "Boundary Detection Messenger";
}

CollisionDetectionMessengerModifier::CollisionDetectionMessengerModifier()
	: _detectionMode(kDetectionModeFirstContact), _detectInFront(true), _detectBehind(true),
	  _ignoreParent(true), _sendToCollidingElement(false), _sendToOnlyFirstCollidingElement(false),
	  _runtime(nullptr), _isActive(false) {
}

CollisionDetectionMessengerModifier::~CollisionDetectionMessengerModifier() {
	if (_isActive)
		_runtime->removeCollider(this);
}

bool CollisionDetectionMessengerModifier::load(ModifierLoaderContext &context, const Data::CollisionDetectionMessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_enableWhen.load(data.enableWhen) || !_disableWhen.load(data.disableWhen))
		return false;

	if (!_sendSpec.load(data.send, data.messageAndModifierFlags, data.with, data.withSource, data.withString, data.destination))
		return false;

	_detectInFront = ((data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kDetectLayerInFront) != 0);
	_detectBehind = ((data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kDetectLayerBehind) != 0);
	_ignoreParent = ((data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kNoCollideWithParent) != 0);
	_sendToCollidingElement = ((data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kSendToCollidingElement) != 0);
	_sendToOnlyFirstCollidingElement = ((data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kSendToOnlyFirstCollidingElement) != 0);

	switch (data.messageAndModifierFlags & Data::CollisionDetectionMessengerModifier::kDetectionModeMask) {
	case Data::CollisionDetectionMessengerModifier::kDetectionModeFirstContact:
		_detectionMode = kDetectionModeFirstContact;
		break;
	case Data::CollisionDetectionMessengerModifier::kDetectionModeWhileInContact:
		_detectionMode = kDetectionModeWhileInContact;
		break;
	case Data::CollisionDetectionMessengerModifier::kDetectionModeExiting:
		_detectionMode = kDetectionModeExiting;
		break;
	default:
		return false;	// Unknown flag combination
	}

	return true;
}

bool CollisionDetectionMessengerModifier::respondsToEvent(const Event &evt) const {
	return _enableWhen.respondsTo(evt) || _disableWhen.respondsTo(evt);
}

VThreadState CollisionDetectionMessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	// If we get a message that enables AND disables this at the same time, then we need to detect collisions and fire them,
	// then disable this element.
	// MTI depends on this behavior for the save game menu.

	if (_disableWhen.respondsTo(msg->getEvent())) {
		runtime->getVThread().pushTask("CollisionDetectionModifier::disableTask", this, &CollisionDetectionMessengerModifier::disableTask);
	}
	if (_enableWhen.respondsTo(msg->getEvent())) {
		runtime->getVThread().pushTask("CollisionDetectionModifier::enableTask", this, &CollisionDetectionMessengerModifier::enableTask);

		_incomingData = msg->getValue();
		if (_incomingData.getType() == DynamicValueTypes::kList)
			_incomingData.setList(_incomingData.getList()->clone());
		_triggerSource = msg->getSource();
		_runtime = runtime;
	}

	return kVThreadReturn;
}

VThreadState CollisionDetectionMessengerModifier::enableTask(const EnableTaskData &taskData) {
	if (!_isActive) {
		_isActive = true;
		_runtime->addCollider(this);
		_runtime->checkCollisions(this);
	}
	return kVThreadReturn;
}

VThreadState CollisionDetectionMessengerModifier::disableTask(const DisableTaskData &taskData) {
	disable(_runtime);
	return kVThreadReturn;
}

void CollisionDetectionMessengerModifier::disable(Runtime *runtime) {
	if (_isActive) {
		_isActive = false;
		_runtime->removeCollider(this);
		_incomingData = DynamicValue();
	}
}

void CollisionDetectionMessengerModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	_sendSpec.linkInternalReferences(scope);
}

void CollisionDetectionMessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_sendSpec.visitInternalReferences(visitor);
}

Common::SharedPtr<Modifier> CollisionDetectionMessengerModifier::shallowClone() const {
	Common::SharedPtr<CollisionDetectionMessengerModifier> clone(new CollisionDetectionMessengerModifier(*this));
	clone->_isActive = false;
	clone->_incomingData = DynamicValue();
	return clone;
}

const char *CollisionDetectionMessengerModifier::getDefaultName() const {
	return "Collision Messenger";
}

void CollisionDetectionMessengerModifier::getCollisionProperties(Modifier *&modifier, bool &collideInFront, bool &collideBehind, bool &excludeParents) const {
	collideBehind = _detectBehind;
	collideInFront = _detectInFront;
	excludeParents = _ignoreParent;
	modifier = const_cast<CollisionDetectionMessengerModifier *>(this);
}

void CollisionDetectionMessengerModifier::triggerCollision(Runtime *runtime, Structural *collidingElement, bool wasInContact, bool isInContact, bool &shouldStop) {
	switch (_detectionMode) {
	case kDetectionModeExiting:
		if (isInContact || !wasInContact)
			return;
		break;
	case kDetectionModeFirstContact:
		if (!isInContact || wasInContact)
			return;
		break;
	case kDetectionModeWhileInContact:
		if (!isInContact)
			return;
		break;
	default:
		error("Unknown collision detection mode");
		return;
	}

	RuntimeObject *customDestination = nullptr;
	if (_sendToCollidingElement) {
		if (_sendToOnlyFirstCollidingElement)
			shouldStop = true;

		customDestination = collidingElement;
	}

	_sendSpec.sendFromMessenger(runtime, this, _triggerSource.lock().get(), _incomingData, customDestination);
}

KeyboardMessengerModifier::~KeyboardMessengerModifier() {
}

KeyboardMessengerModifier::KeyboardMessengerModifier()
	: _onDown(false), _onUp(false), _onRepeat(false), _keyModControl(false), _keyModCommand(false), _keyModOption(false),
	  _isEnabled(false), _keyCodeType(kAny), _macRomanChar(0) {
}

bool KeyboardMessengerModifier::isKeyboardMessenger() const {
	return true;
}

bool KeyboardMessengerModifier::load(ModifierLoaderContext &context, const Data::KeyboardMessengerModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	_onDown = ((data.messageFlagsAndKeyStates & Data::KeyboardMessengerModifier::kOnDown) != 0);
	_onUp = ((data.messageFlagsAndKeyStates & Data::KeyboardMessengerModifier::kOnUp) != 0);
	_onRepeat = ((data.messageFlagsAndKeyStates & Data::KeyboardMessengerModifier::kOnRepeat) != 0);
	_keyModControl = ((data.keyModifiers & Data::KeyboardMessengerModifier::kControl) != 0);
	_keyModCommand = ((data.keyModifiers & Data::KeyboardMessengerModifier::kCommand) != 0);
	_keyModOption = ((data.keyModifiers & Data::KeyboardMessengerModifier::kOption) != 0);

	switch (data.keycode) {
	case KeyCodeType::kAny:
	case KeyCodeType::kHome:
	case KeyCodeType::kEnter:
	case KeyCodeType::kEnd:
	case KeyCodeType::kHelp:
	case KeyCodeType::kBackspace:
	case KeyCodeType::kTab:
	case KeyCodeType::kPageUp:
	case KeyCodeType::kPageDown:
	case KeyCodeType::kReturn:
	case KeyCodeType::kEscape:
	case KeyCodeType::kArrowLeft:
	case KeyCodeType::kArrowRight:
	case KeyCodeType::kArrowUp:
	case KeyCodeType::kArrowDown:
	case KeyCodeType::kDelete:
		_keyCodeType = static_cast<KeyCodeType>(data.keycode);
		_macRomanChar = 0;
		break;
	default:
		_keyCodeType = kMacRomanChar;
		memcpy(&_macRomanChar, &data.keycode, 1);
		break;
	}

	if (!_sendSpec.load(data.message, data.messageFlagsAndKeyStates, data.with, data.withSource, data.withString, data.destination))
		return false;

	return true;
}

bool KeyboardMessengerModifier::respondsToEvent(const Event &evt) const {
	if (Event(EventIDs::kParentEnabled, 0).respondsTo(evt) || Event(EventIDs::kParentDisabled, 0).respondsTo(evt))
		return true;

	return false;
}

VThreadState KeyboardMessengerModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
 	if (Event(EventIDs::kParentEnabled, 0).respondsTo(msg->getEvent())) {
		_isEnabled = true;
	} else if (Event(EventIDs::kParentDisabled, 0).respondsTo(msg->getEvent())) {
		disable(runtime);
	}

	return kVThreadReturn;
}

void KeyboardMessengerModifier::disable(Runtime *runtime) {
	_isEnabled = false;
}

Common::SharedPtr<Modifier> KeyboardMessengerModifier::shallowClone() const {
	Common::SharedPtr<KeyboardMessengerModifier> cloned(new KeyboardMessengerModifier(*this));
	cloned->_isEnabled = false;
	return cloned;
}

const char *KeyboardMessengerModifier::getDefaultName() const {
	return "Keyboard Messenger";
}

bool KeyboardMessengerModifier::checkKeyEventTrigger(Runtime *runtime, Common::EventType evtType, bool repeat, const Common::KeyState &keyEvt, Common::String &outCharStr) const {
	if (!_isEnabled)
		return false;

	bool responds = false;
	if (evtType == Common::EVENT_KEYDOWN) {
		if (repeat)
			responds = _onRepeat;
		else
			responds = _onDown;
	} else if (evtType == Common::EVENT_KEYUP)
		responds = _onUp;

	if (!responds)
		return false;

	if (_keyModCommand) {
		if (runtime->getProject()->getPlatform() == kProjectPlatformWindows) {
			// Windows projects check "alt"
			if ((keyEvt.flags & Common::KBD_ALT) == 0)
				return false;
		} else if (runtime->getProject()->getPlatform() == kProjectPlatformMacintosh) {
			if ((keyEvt.flags & Common::KBD_META) == 0)
				return false;
		}
	}

	if (_keyModControl) {
		if ((keyEvt.flags & Common::KBD_CTRL) == 0)
			return false;
	}

	if (_keyModOption) {
		if ((keyEvt.flags & Common::KBD_ALT) == 0)
			return false;
	}

	outCharStr.clear();

	KeyCodeType resolvedType = kAny;
	switch (keyEvt.keycode) {
	case Common::KEYCODE_HOME:
		resolvedType = kHome;
		break;
	case Common::KEYCODE_KP_ENTER:
		resolvedType = kEnter;
		break;
	case Common::KEYCODE_END:
		resolvedType = kEnd;
		break;
	case Common::KEYCODE_HELP:
		resolvedType = kHelp;
		break;
	case Common::KEYCODE_F1:
		// Windows projects map F1 to "help"
		if (runtime->getProject()->getPlatform() == kProjectPlatformWindows)
			resolvedType = kHelp;
		break;
	case Common::KEYCODE_BACKSPACE:
		resolvedType = kBackspace;
		break;
	case Common::KEYCODE_TAB:
		resolvedType = kTab;
		break;
	case Common::KEYCODE_PAGEUP:
		resolvedType = kPageUp;
		break;
	case Common::KEYCODE_PAGEDOWN:
		resolvedType = kPageDown;
		break;
	case Common::KEYCODE_RETURN:
		resolvedType = kReturn;
		break;
	case Common::KEYCODE_ESCAPE:
		resolvedType = kEscape;
		break;
	case Common::KEYCODE_LEFT:
		resolvedType = kArrowLeft;
		break;
	case Common::KEYCODE_RIGHT:
		resolvedType = kArrowRight;
		break;
	case Common::KEYCODE_UP:
		resolvedType = kArrowUp;
		break;
	case Common::KEYCODE_DOWN:
		resolvedType = kDelete;
		break;
	default:
		if (keyEvt.ascii != 0) {
			bool isQuestion = (keyEvt.ascii == '?');
			uint32 uchar = keyEvt.ascii;
			Common::U32String u(&uchar, 1);
			outCharStr = u.encode(Common::kMacRoman);

			// STUPID HACK PLEASE FIX ME: ScummVM has no way of just telling us that the character mapping failed,
			// so we have to check if it encoded "?"
			if (outCharStr.size() < 1 || (outCharStr[0] == '?' && !isQuestion))
				return false;

			resolvedType = kMacRomanChar;
		}
		break;
	}

	if (_keyCodeType != kAny && resolvedType != _keyCodeType)
		return false;

	if (_keyCodeType == kMacRomanChar && (outCharStr.size() == 0 || outCharStr[0] != _macRomanChar))
		return false;

	return true;
}

void KeyboardMessengerModifier::dispatchMessage(Runtime *runtime, const Common::String &charStr) {
	Common::SharedPtr<MessageProperties> msgProps;

	if (charStr.size() != 1)
		warning("Keyboard messenger is supposed to send the character code, but they key was a special key and we haven't implemented conversion of those keycodes");

	DynamicValue charStrValue;
	charStrValue.setString(charStr);
	_sendSpec.sendFromMessenger(runtime, this, nullptr, charStrValue, nullptr);
}

void KeyboardMessengerModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	_sendSpec.visitInternalReferences(visitor);
}

void KeyboardMessengerModifier::linkInternalReferences(ObjectLinkingScope *scope) {
	_sendSpec.linkInternalReferences(scope);
}

bool TextStyleModifier::load(ModifierLoaderContext &context, const Data::TextStyleModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_textColor.load(data.textColor) || !_backgroundColor.load(data.backgroundColor) || !_applyWhen.load(data.applyWhen) || !_removeWhen.load(data.removeWhen))
		return false;

	_macFontID = data.macFontID;
	_size = data.size;
	_fontFamilyName = data.fontFamilyName;

	if (!_styleFlags.load(data.flags))
		return false;

	switch (data.alignment) {
	case 0:
		_alignment = kTextAlignmentLeft;
		break;
	case 1:
		_alignment = kTextAlignmentCenter;
		break;
	case 0xffff:
		_alignment = kTextAlignmentRight;
		break;
	default:
		warning("Unrecognized text alignment");
		return false;
	}

	return true;
}

bool TextStyleModifier::respondsToEvent(const Event &evt) const {
	if (_applyWhen.respondsTo(evt) || _removeWhen.respondsTo(evt))
		return true;

	return Modifier::respondsToEvent(evt);
}

VThreadState TextStyleModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_applyWhen.respondsTo(msg->getEvent())) {
		Structural *owner = findStructuralOwner();
		if (owner && owner->isElement()) {
			Element *element = static_cast<Element *>(owner);
			if (element->isVisual()) {
				VisualElement *visualElement = static_cast<VisualElement *>(element);
				if (visualElement->isTextLabel()) {
					static_cast<TextLabelElement *>(visualElement)->setTextStyle(_macFontID, _fontFamilyName, _size, _alignment, _styleFlags);
				}
			}
		}

		return kVThreadReturn;
	} else if (_removeWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
		return kVThreadReturn;
	}

	return Modifier::consumeMessage(runtime, msg);
}

void TextStyleModifier::disable(Runtime *runtime) {
	// Doesn't actually do anything
}

Common::SharedPtr<Modifier> TextStyleModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new TextStyleModifier(*this));
}

const char *TextStyleModifier::getDefaultName() const {
	return "Text Style Messenger";
}

bool GraphicModifier::load(ModifierLoaderContext &context, const Data::GraphicModifier &data) {
	ColorRGB8 foreColor;
	ColorRGB8 backColor;
	ColorRGB8 borderColor;
	ColorRGB8 shadowColor;

	if (!loadTypicalHeader(data.modHeader) || !_applyWhen.load(data.applyWhen) || !_removeWhen.load(data.removeWhen)
		|| !foreColor.load(data.foreColor) || !backColor.load(data.backColor)
		|| !borderColor.load(data.borderColor) || !shadowColor.load(data.shadowColor))
		return false;

	// We need the poly points even if this isn't a poly shape since I think it's possible to change the shape type at runtime
	Common::Array<Common::Point> &polyPoints = _renderProps.modifyPolyPoints();
	polyPoints.resize(data.polyPoints.size());
	for (size_t i = 0; i < data.polyPoints.size(); i++) {
		polyPoints[i].x = data.polyPoints[i].x;
		polyPoints[i].y = data.polyPoints[i].y;
	}

	_renderProps.setInkMode(static_cast<VisualElementRenderProperties::InkMode>(data.inkMode));
	_renderProps.setShape(static_cast<VisualElementRenderProperties::Shape>(data.shape));
	_renderProps.setBorderSize(data.borderSize);
	_renderProps.setShadowSize(data.shadowSize);
	_renderProps.setForeColor(foreColor);
	_renderProps.setBackColor(backColor);
	_renderProps.setBorderColor(borderColor);
	_renderProps.setShadowColor(shadowColor);

	return true;
}

bool GraphicModifier::respondsToEvent(const Event &evt) const {
	return _applyWhen.respondsTo(evt) || _removeWhen.respondsTo(evt);
}

VThreadState GraphicModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	Structural *owner = findStructuralOwner();
	if (!owner)
		return kVThreadError;

	if (!owner->isElement())
		return kVThreadReturn;

	Element *element = static_cast<Element *>(owner);
	if (!element->isVisual())
		return kVThreadReturn;

	VisualElement *visual = static_cast<VisualElement *>(element);

	// If a graphic modifier is the active graphic modifier, then it may be removed, but removing it resets to default, not to
	// any other graphic modifier.  If it is not the active graphic modifier, then removing it has no effect.
	// This is required for correct rendering of the beaker when freeing Max in Obsidian.
	if (_applyWhen.respondsTo(msg->getEvent())) {
		visual->setRenderProperties(_renderProps, this->getSelfReference().staticCast<GraphicModifier>());
	}
	if (_removeWhen.respondsTo(msg->getEvent())) {
		disable(runtime);
	}

	return kVThreadReturn;
}

void GraphicModifier::disable(Runtime *runtime) {
	Structural *owner = findStructuralOwner();
	if (!owner)
		return;

	if (!owner->isElement())
		return;

	Element *element = static_cast<Element *>(owner);
	if (!element->isVisual())
		return;

	VisualElement *visual = static_cast<VisualElement *>(element);

	if (visual->getPrimaryGraphicModifier().lock().get() == this)
		static_cast<VisualElement *>(element)->setRenderProperties(VisualElementRenderProperties(), Common::WeakPtr<GraphicModifier>());
}

Common::SharedPtr<Modifier> GraphicModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new GraphicModifier(*this));
}

const char *GraphicModifier::getDefaultName() const {
	return "Graphic Modifier";
}

ImageEffectModifier::ImageEffectModifier() : _type(kTypeUnknown), _bevelWidth(0), _toneAmount(0), _includeBorders(false) {
}

bool ImageEffectModifier::load(ModifierLoaderContext &context, const Data::ImageEffectModifier &data) {
	if (!loadTypicalHeader(data.modHeader) || !_applyWhen.load(data.applyWhen) || !_removeWhen.load(data.removeWhen))
		return false;

	_includeBorders = ((data.flags & 0x40000000) != 0);
	_type = static_cast<Type>(data.type);
	_bevelWidth = data.bevelWidth;
	_toneAmount = data.toneAmount;

	return true;
}

bool ImageEffectModifier::respondsToEvent(const Event &evt) const {
	return _applyWhen.respondsTo(evt) || _removeWhen.respondsTo(evt);
}

VThreadState ImageEffectModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_removeWhen.respondsTo(msg->getEvent())) {
		RemoveTaskData *removeTask = runtime->getVThread().pushTask("ImageEffectModifier::removeTask", this, &ImageEffectModifier::removeTask);
		removeTask->runtime = runtime;
	}
	if (_applyWhen.respondsTo(msg->getEvent())) {
		ApplyTaskData *applyTask = runtime->getVThread().pushTask("ImageEffectModifier::applyTask", this, &ImageEffectModifier::applyTask);
		applyTask->runtime = runtime;
	}

	return kVThreadReturn;
}

void ImageEffectModifier::disable(Runtime *runtime) {
	Structural *structural = findStructuralOwner();
	if (!structural || !structural->isElement() || !static_cast<Element *>(structural)->isVisual())
		return;

	VisualElement *visual = static_cast<VisualElement *>(structural);
	visual->setShading(0, 0, 0, 0);
}

Common::SharedPtr<Modifier> ImageEffectModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new ImageEffectModifier(*this));
}

const char *ImageEffectModifier::getDefaultName() const {
	return "Image Effect Modifier";
}

VThreadState ImageEffectModifier::applyTask(const ApplyTaskData &taskData) {
	Structural *structural = findStructuralOwner();
	if (!structural || !structural->isElement() || !static_cast<Element *>(structural)->isVisual())
		return kVThreadReturn;

	VisualElement *visual = static_cast<VisualElement *>(structural);

	int16 shadingLevel = static_cast<int16>(_toneAmount) * 256 / 100;

	switch (_type) {
	case kTypeDeselectedBevels:
		visual->setShading(-shadingLevel, shadingLevel, 0, _bevelWidth);
		break;
	case kTypeSelectedBevels:
		visual->setShading(shadingLevel, -shadingLevel, 0, _bevelWidth);
		break;
	case kTypeToneUp:
		visual->setShading(0, 0, shadingLevel, 0);
		break;
	case kTypeToneDown:
		visual->setShading(0, 0, -shadingLevel, 0);
		break;
	default:
		break;
	}

	return kVThreadReturn;
}

VThreadState ImageEffectModifier::removeTask(const RemoveTaskData &taskData) {
	this->disable(taskData.runtime);

	return kVThreadReturn;
}

ReturnModifier::ReturnModifier() {
}

bool ReturnModifier::load(ModifierLoaderContext &context, const Data::ReturnModifier &data) {
	if (!loadTypicalHeader(data.modHeader) || !_executeWhen.load(data.executeWhen))
		return false;

	return true;
}

bool ReturnModifier::respondsToEvent(const Event &evt) const {
	return _executeWhen.respondsTo(evt);
}

VThreadState ReturnModifier::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	runtime->addSceneReturn();
	return kVThreadReturn;
}

void ReturnModifier::disable(Runtime *runtime) {
}

Common::SharedPtr<Modifier> ReturnModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new ReturnModifier(*this));
}

const char *ReturnModifier::getDefaultName() const {
	return "Return Modifier";
}


CursorModifierV1::CursorModifierV1() : _cursorIndex(kCursor_Interact) {
}

bool CursorModifierV1::load(ModifierLoaderContext &context, const Data::CursorModifierV1 &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (data.hasMacOnlyPart)
		_cursorIndex = data.macOnlyPart.cursorIndex;

	return true;
}

bool CursorModifierV1::respondsToEvent(const Event &evt) const {
	return _applyWhen.respondsTo(evt);
}

VThreadState CursorModifierV1::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (_applyWhen.respondsTo(msg->getEvent())) {
		warning("Cursor modifier V1 should be applied, but is not implemented");
		return kVThreadReturn;
	}
	return kVThreadReturn;
}

void CursorModifierV1::disable(Runtime *runtime) {
	warning("Cursor modifier V1 should probably dismiss when disabled?");
}

Common::SharedPtr<Modifier> CursorModifierV1::shallowClone() const {
	return Common::SharedPtr<Modifier>(new CursorModifierV1(*this));
}

const char *CursorModifierV1::getDefaultName() const {
	return "Cursor Modifier";
}

bool CompoundVariableModifier::load(ModifierLoaderContext &context, const Data::CompoundVariableModifier &data) {
	if (data.numChildren > 0) {
		ChildLoaderContext loaderContext;
		loaderContext.containerUnion.modifierContainer = this;
		loaderContext.type = ChildLoaderContext::kTypeCountedModifierList;
		loaderContext.remainingCount = data.numChildren;

		context.childLoaderStack->contexts.push_back(loaderContext);
	}

	if (!_modifierFlags.load(data.modifierFlags))
		return false;
	_guid = data.guid;
	_name = data.name;

	return true;
}

void CompoundVariableModifier::disable(Runtime *runtime) {
	// Do nothing I guess, no variables can be disabled
}

Common::SharedPtr<ModifierSaveLoad> CompoundVariableModifier::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(runtime, this));
}

IModifierContainer *CompoundVariableModifier::getChildContainer() {
	return this;
}

const Common::Array<Common::SharedPtr<Modifier> > &CompoundVariableModifier::getModifiers() const {
	return _children;
}

void CompoundVariableModifier::appendModifier(const Common::SharedPtr<Modifier> &modifier) {
	_children.push_back(modifier);
	modifier->setParent(getSelfReference());
}

void CompoundVariableModifier::removeModifier(const Modifier *modifier) {
	for (Common::Array<Common::SharedPtr<Modifier> >::iterator it = _children.begin(), itEnd = _children.end(); it != itEnd; ++it) {
		if (it->get() == modifier) {
			_children.erase(it);
			return;
		}
	}
}

void CompoundVariableModifier::visitInternalReferences(IStructuralReferenceVisitor *visitor) {
	for (Common::Array<Common::SharedPtr<Modifier> >::iterator it = _children.begin(), itEnd = _children.end(); it != itEnd; ++it) {
		visitor->visitChildModifierRef(*it);
	}
}

bool CompoundVariableModifier::readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) {
	Modifier *var = findChildByName(thread->getRuntime(), attrib);
	if (var) {
		// Shouldn't dereference the value here, some scripts (e.g. "<go dest> on MUI" in Obsidian) depend on it not being dereferenced
		result.setObject(var->getSelfReference());
		return true;
	}
	return Modifier::readAttribute(thread, result, attrib);
}

bool CompoundVariableModifier::readAttributeIndexed(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib, const DynamicValue &index) {
	Modifier *var = findChildByName(thread->getRuntime(), attrib);
	if (!var || !var->isVariable())
		return false;

	return var->readAttributeIndexed(thread, result, "value", index);
}

MiniscriptInstructionOutcome CompoundVariableModifier::writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib) {
	Modifier *var = findChildByName(thread->getRuntime(), attrib);
	if (!var)
		return kMiniscriptInstructionOutcomeFailed;

	if (var->isVariable())
		writeProxy = static_cast<VariableModifier *>(var)->createWriteProxy();
	else if (var->isModifier())
		DynamicValueWriteObjectHelper::create(var, writeProxy);
	else
		return kMiniscriptInstructionOutcomeFailed;

	return kMiniscriptInstructionOutcomeContinue;
}

MiniscriptInstructionOutcome CompoundVariableModifier::writeRefAttributeIndexed(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib, const DynamicValue &index) {
	Modifier *var = findChildByName(thread->getRuntime(), attrib);
	if (!var || !var->isModifier())
		return kMiniscriptInstructionOutcomeFailed;

	return var->writeRefAttributeIndexed(thread, writeProxy, "value", index);
}

Modifier *CompoundVariableModifier::findChildByName(Runtime *runtime, const Common::String &name) const {
	if (runtime->getHacks().mtiVariableReferencesHack) {
		const Common::String &myName = getName();

		if (myName.size() == 1 && (myName == "a" || myName == "b" || myName == "c" || myName == "d")) {
			Project *project = runtime->getProject();
			Modifier *modifier = project->findGlobalVarWithName(MTropolis::toCaseInsensitive(name)).get();

			if (modifier)
				return modifier;
		}

		if (myName.size() == 1 && myName == "g") {
			if (caseInsensitiveEqual(name, "choresdone") || caseInsensitiveEqual(name, "donechore")) {
				Project *project = runtime->getProject();
				Modifier *modifier = project->findGlobalVarWithName(MTropolis::toCaseInsensitive(name)).get();

				if (modifier)
					return modifier;
			}
		}
	}

	for (Common::Array<Common::SharedPtr<Modifier> >::const_iterator it = _children.begin(), itEnd = _children.end(); it != itEnd; ++it) {
		Modifier *modifier = it->get();
		if (caseInsensitiveEqual(name, modifier->getName()))
			return modifier;
	}

	return nullptr;
}

CompoundVariableModifier::SaveLoad::ChildSaveLoad::ChildSaveLoad() : modifier(nullptr) {
}

CompoundVariableModifier::SaveLoad::SaveLoad(Runtime *runtime, CompoundVariableModifier *modifier) /* : _modifier(modifier) */ {
	// Gross hacks for MTI save games.
	//
	// This looks like it's due to some kind of divergence between mTropolis 1.1 and whatever
	// MTI shipped with.  MTI's saves are done using a compound variable named "MTI" in the Load/Save scene
	// which contains aliases to compound vars a, b, c, d, and g.  While these are aliases to the same globals
	// as are used elsewhere (unlike the "billyState" hack), mTropolis 1.1 will DUPLICATE compound variables children
	// unless the children themselves are aliases, which is not the case in MTI.
	//
	// Consequently, the default behavior here is that the compounds in the Load/Save menu will not reference the
	// children of the aliases compound.  So, we need to patch those references here.
	bool isMTIHackG = false;
	bool isMTIHackGlobalContainer = false;
	if (runtime->getHacks().mtiVariableReferencesHack) {
		const Common::String &name = modifier->getName();
		if (name == "g") {
			isMTIHackG = true;
		} else if (name == "a" || name == "b" || name == "c" || name == "d") {
			isMTIHackGlobalContainer = true;
		}
	}

	if (isMTIHackG) {
		// For "g" use the "g" in the project instead
		for (const Common::SharedPtr<Modifier> &projChild : runtime->getProject()->getModifiers()) {
			if (projChild->getName() == "g" && projChild->isCompoundVariable()) {
				modifier = static_cast<CompoundVariableModifier *>(projChild.get());
				break;
			}
		}
	}

	for (const Common::SharedPtr<Modifier> &child : modifier->_children) {
		bool loadFromGlobal = false;

		if (isMTIHackGlobalContainer)
			loadFromGlobal = true;
		else if (isMTIHackG) {
			// Hack to fix Hispaniola not transitioning to night
			loadFromGlobal = caseInsensitiveEqual(child->getName(), "choresdone") || caseInsensitiveEqual(child->getName(), "donechore");
		}

		if (loadFromGlobal) {
			Common::SharedPtr<Modifier> globalVarModifier = runtime->getProject()->findGlobalVarWithName(child->getName());

			if (globalVarModifier) {
				Common::SharedPtr<ModifierSaveLoad> childSL = globalVarModifier->getSaveLoad(runtime);

				ChildSaveLoad childSaveLoad;
				childSaveLoad.saveLoad = childSL;
				childSaveLoad.modifier = globalVarModifier.get();
				_childrenSaveLoad.push_back(childSaveLoad);

				continue;
			}
		}

		Common::SharedPtr<ModifierSaveLoad> childSL = child->getSaveLoad(runtime);
		if (childSL) {
			ChildSaveLoad childSaveLoad;
			childSaveLoad.saveLoad = childSL;
			childSaveLoad.modifier = child.get();
			_childrenSaveLoad.push_back(childSaveLoad);
		}
	}
}

void CompoundVariableModifier::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeUint32BE(_childrenSaveLoad.size());
	for (const ChildSaveLoad &childSL : _childrenSaveLoad)
		childSL.saveLoad->save(childSL.modifier, stream);
}

bool CompoundVariableModifier::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	const uint32 numChildren = stream->readUint32BE();
	if (stream->err())
		return false;

	if (numChildren != _childrenSaveLoad.size())
		return false;

	for (const ChildSaveLoad &childSL : _childrenSaveLoad) {
		if (!childSL.saveLoad->load(childSL.modifier, stream, saveFileVersion))
			return false;
	}

	return true;
}

void CompoundVariableModifier::SaveLoad::commitLoad() const {
	for (const ChildSaveLoad &childSL : _childrenSaveLoad)
		childSL.saveLoad->commitLoad();
}

Common::SharedPtr<Modifier> CompoundVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new CompoundVariableModifier(*this));
}

const char *CompoundVariableModifier::getDefaultName() const {
	return "Compound Variable";
}

BooleanVariableModifier::BooleanVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new BooleanVariableStorage())) {
}

bool BooleanVariableModifier::load(ModifierLoaderContext &context, const Data::BooleanVariableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	static_cast<BooleanVariableStorage *>(_storage.get())->_value = (data.value != 0);

	return true;
}

bool BooleanVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue boolValue;
	if (!value.convertToType(DynamicValueTypes::kBoolean, boolValue))
		return false;

	static_cast<BooleanVariableStorage *>(_storage.get())->_value = boolValue.getBool();

	return true;
}

void BooleanVariableModifier::varGetValue(DynamicValue &dest) const {
	dest.setBool(static_cast<BooleanVariableStorage *>(_storage.get())->_value);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void BooleanVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	report->declareDynamic("value", static_cast<BooleanVariableStorage *>(_storage.get())->_value ? "true" : "false");
}
#endif

Common::SharedPtr<Modifier> BooleanVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new BooleanVariableModifier(*this));
}

const char *BooleanVariableModifier::getDefaultName() const {
	return "Boolean Variable";
}

BooleanVariableStorage::BooleanVariableStorage() : _value(false) {
}

Common::SharedPtr<ModifierSaveLoad> BooleanVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> BooleanVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new BooleanVariableStorage(*this));
}

BooleanVariableStorage::SaveLoad::SaveLoad(BooleanVariableStorage *storage) : _storage(storage) {
	_value = _storage->_value;
}

void BooleanVariableStorage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void BooleanVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeByte(_value ? 1 : 0);
}

bool BooleanVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	byte b = stream->readByte();
	if (stream->err())
		return false;

	_value = (b != 0);
	return true;
}

IntegerVariableModifier::IntegerVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new IntegerVariableStorage())) {
}

bool IntegerVariableModifier::load(ModifierLoaderContext& context, const Data::IntegerVariableModifier& data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	static_cast<IntegerVariableStorage *>(_storage.get())->_value = data.value;

	return true;
}

IntegerVariableStorage::IntegerVariableStorage() : _value(0) {
}

Common::SharedPtr<ModifierSaveLoad> IntegerVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> IntegerVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new IntegerVariableStorage(*this));
}

bool IntegerVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue intValue;
	if (!value.convertToType(DynamicValueTypes::kInteger, intValue))
		return false;

	static_cast<IntegerVariableStorage *>(_storage.get())->_value = intValue.getInt();

	return true;
}

void IntegerVariableModifier::varGetValue(DynamicValue &dest) const {
	dest.setInt(static_cast<IntegerVariableStorage *>(_storage.get())->_value);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void IntegerVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	report->declareDynamic("value", Common::String::format("%i", static_cast<IntegerVariableStorage *>(_storage.get())->_value));
}
#endif

Common::SharedPtr<Modifier> IntegerVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new IntegerVariableModifier(*this));
}

const char *IntegerVariableModifier::getDefaultName() const {
	return "Integer Variable";
}

IntegerVariableStorage::SaveLoad::SaveLoad(IntegerVariableStorage *storage) : _storage(storage) {
	_value = _storage->_value;
}

void IntegerVariableStorage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void IntegerVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeSint32BE(_value);
}

bool IntegerVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	_value = stream->readSint32BE();

	if (stream->err())
		return false;

	return true;
}


IntegerRangeVariableModifier::IntegerRangeVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new IntegerRangeVariableStorage())) {
}

bool IntegerRangeVariableModifier::load(ModifierLoaderContext& context, const Data::IntegerRangeVariableModifier& data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!static_cast<IntegerRangeVariableStorage *>(_storage.get())->_range.load(data.range))
		return false;

	return true;
}

bool IntegerRangeVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue intRangeValue;
	if (!value.convertToType(DynamicValueTypes::kIntegerRange, intRangeValue))
		return false;

	static_cast<IntegerRangeVariableStorage *>(_storage.get())->_range = intRangeValue.getIntRange();

	return true;
}

void IntegerRangeVariableModifier::varGetValue(DynamicValue &dest) const {
	dest.setIntRange(static_cast<IntegerRangeVariableStorage *>(_storage.get())->_range);
}

bool IntegerRangeVariableModifier::readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) {
	IntegerRangeVariableStorage *storage = static_cast<IntegerRangeVariableStorage *>(_storage.get());

	if (attrib == "start") {
		result.setInt(storage->_range.min);
		return true;
	}
	if (attrib == "end") {
		result.setInt(storage->_range.max);
		return true;
	}
	return Modifier::readAttribute(thread, result, attrib);
}

MiniscriptInstructionOutcome IntegerRangeVariableModifier::writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) {
	IntegerRangeVariableStorage *storage = static_cast<IntegerRangeVariableStorage *>(_storage.get());

	if (attrib == "start") {
		DynamicValueWriteIntegerHelper<int32>::create(&storage->_range.min, result);
		return kMiniscriptInstructionOutcomeContinue;
	}
	if (attrib == "end") {
		DynamicValueWriteIntegerHelper<int32>::create(&storage->_range.max, result);
		return kMiniscriptInstructionOutcomeContinue;
	}
	return Modifier::writeRefAttribute(thread, result, attrib);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void IntegerRangeVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	IntegerRangeVariableStorage *storage = static_cast<IntegerRangeVariableStorage *>(_storage.get());

	VariableModifier::debugInspect(report);

	report->declareDynamic("value", storage->_range.toString());
}
#endif

Common::SharedPtr<Modifier> IntegerRangeVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new IntegerRangeVariableModifier(*this));
}

const char *IntegerRangeVariableModifier::getDefaultName() const {
	return "Integer Range Variable";
}

IntegerRangeVariableStorage::IntegerRangeVariableStorage() {
}

Common::SharedPtr<ModifierSaveLoad> IntegerRangeVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> IntegerRangeVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new IntegerRangeVariableStorage(*this));
}

IntegerRangeVariableStorage::SaveLoad::SaveLoad(IntegerRangeVariableStorage *storage) : _storage(storage) {
	_range = _storage->_range;
}

void IntegerRangeVariableStorage::SaveLoad::commitLoad() const {
	_storage->_range = _range;
}

void IntegerRangeVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeSint32BE(_storage->_range.min);
	stream->writeSint32BE(_storage->_range.max);
}

bool IntegerRangeVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	_storage->_range.min = stream->readSint32BE();
	_storage->_range.max = stream->readSint32BE();

	if (stream->err())
		return false;

	return true;
}

VectorVariableModifier::VectorVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new VectorVariableStorage())) {
}

bool VectorVariableModifier::load(ModifierLoaderContext &context, const Data::VectorVariableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	storage->_vector.angleDegrees = data.vector.angleRadians.toDouble() * (180 / M_PI);
	storage->_vector.magnitude = data.vector.magnitude.toDouble();

	return true;
}

bool VectorVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue vectorValue;
	if (!value.convertToType(DynamicValueTypes::kVector, vectorValue))
		return false;

	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	storage->_vector = vectorValue.getVector();

	return true;
}

void VectorVariableModifier::varGetValue(DynamicValue &dest) const {
	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	dest.setVector(storage->_vector);
}

bool VectorVariableModifier::readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) {
	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	if (attrib == "magnitude") {
		result.setFloat(storage->_vector.magnitude);
		return true;
	} else if (attrib == "angle") {
		result.setFloat(storage->_vector.angleDegrees);
		return true;
	}

	return VariableModifier::readAttribute(thread, result, attrib);
}

MiniscriptInstructionOutcome VectorVariableModifier::writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &result, const Common::String &attrib) {
	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	if (attrib == "magnitude") {
		DynamicValueWriteFloatHelper<double>::create(&storage->_vector.magnitude, result);
		return kMiniscriptInstructionOutcomeContinue;
	} else if (attrib == "angle") {
		DynamicValueWriteFloatHelper<double>::create(&storage->_vector.angleDegrees, result);
		return kMiniscriptInstructionOutcomeContinue;
	}

	return writeRefAttribute(thread, result, attrib);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void VectorVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	VectorVariableStorage *storage = static_cast<VectorVariableStorage *>(_storage.get());

	report->declareDynamic("value", storage->_vector.toString());
}
#endif

Common::SharedPtr<Modifier> VectorVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new VectorVariableModifier(*this));
}

const char *VectorVariableModifier::getDefaultName() const {
	return "Vector Variable";
}

VectorVariableStorage::VectorVariableStorage() {
}

Common::SharedPtr<ModifierSaveLoad> VectorVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> VectorVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new VectorVariableStorage(*this));
}

VectorVariableStorage::SaveLoad::SaveLoad(VectorVariableStorage *storage) : _storage(storage) {
	_vector = _storage->_vector;
}

void VectorVariableStorage::SaveLoad::commitLoad() const {
	_storage->_vector = _vector;
}

void VectorVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeDoubleBE(_vector.angleDegrees);
	stream->writeDoubleBE(_vector.magnitude);
}

bool VectorVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	_vector.angleDegrees = stream->readDoubleBE();
	_vector.magnitude = stream->readDoubleBE();

	if (stream->err())
		return false;

	return true;
}

PointVariableModifier::PointVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new PointVariableStorage())) {
}

bool PointVariableModifier::load(ModifierLoaderContext &context, const Data::PointVariableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	if (!data.value.toScummVMPoint(storage->_value))
		return false;

	return true;
}

bool PointVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue pointValue;
	if (!value.convertToType(DynamicValueTypes::kPoint, pointValue))
		return false;

	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	storage->_value = pointValue.getPoint();

	return true;
}

void PointVariableModifier::varGetValue(DynamicValue &dest) const {
	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	dest.setPoint(storage->_value);
}

bool PointVariableModifier::readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) {
	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	if (attrib == "x") {
		result.setInt(storage->_value.x);
		return true;
	}
	if (attrib == "y") {
		result.setInt(storage->_value.y);
		return true;
	}

	return VariableModifier::readAttribute(thread, result, attrib);
}

MiniscriptInstructionOutcome PointVariableModifier::writeRefAttribute(MiniscriptThread *thread, DynamicValueWriteProxy &writeProxy, const Common::String &attrib) {
	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	if (attrib == "x") {
		DynamicValueWriteIntegerHelper<int16>::create(&storage->_value.x, writeProxy);
		return kMiniscriptInstructionOutcomeContinue;
	}
	if (attrib == "y") {
		DynamicValueWriteIntegerHelper<int16>::create(&storage->_value.y, writeProxy);
		return kMiniscriptInstructionOutcomeContinue;
	}

	return writeRefAttribute(thread, writeProxy, attrib);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void PointVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	PointVariableStorage *storage = static_cast<PointVariableStorage *>(_storage.get());

	report->declareDynamic("value", pointToString(storage->_value));
}
#endif

Common::SharedPtr<Modifier> PointVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new PointVariableModifier(*this));
}

const char *PointVariableModifier::getDefaultName() const {
	return "Point Variable";
}

PointVariableStorage::PointVariableStorage() {
}

Common::SharedPtr<ModifierSaveLoad> PointVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> PointVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new PointVariableStorage(*this));
}

PointVariableStorage::SaveLoad::SaveLoad(PointVariableStorage *storage) : _storage(storage) {
	_value = storage->_value;
}

void PointVariableStorage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void PointVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeSint16BE(_value.x);
	stream->writeSint16BE(_value.y);
}

bool PointVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	_value.x = stream->readSint16BE();
	_value.y = stream->readSint16BE();

	if (stream->err())
		return false;

	return true;
}

FloatingPointVariableModifier::FloatingPointVariableModifier() : VariableModifier(Common::SharedPtr<FloatingPointVariableStorage>(new FloatingPointVariableStorage())) {
}

bool FloatingPointVariableModifier::load(ModifierLoaderContext &context, const Data::FloatingPointVariableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	FloatingPointVariableStorage *storage = static_cast<FloatingPointVariableStorage *>(_storage.get());

	storage->_value = data.value.toDouble();

	return true;
}

bool FloatingPointVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue floatValue;
	if (!value.convertToType(DynamicValueTypes::kFloat, floatValue))
		return false;

	FloatingPointVariableStorage *storage = static_cast<FloatingPointVariableStorage *>(_storage.get());

	storage->_value = floatValue.getFloat();

	return true;
}

void FloatingPointVariableModifier::varGetValue(DynamicValue &dest) const {
	FloatingPointVariableStorage *storage = static_cast<FloatingPointVariableStorage *>(_storage.get());

	dest.setFloat(storage->_value);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void FloatingPointVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	FloatingPointVariableStorage *storage = static_cast<FloatingPointVariableStorage *>(_storage.get());

	report->declareDynamic("value", Common::String::format("%g", storage->_value));
}
#endif

Common::SharedPtr<Modifier> FloatingPointVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new FloatingPointVariableModifier(*this));
}

const char *FloatingPointVariableModifier::getDefaultName() const {
	return "Floating Point Variable";
}

FloatingPointVariableStorage::FloatingPointVariableStorage() : _value(0.0) {
}

Common::SharedPtr<ModifierSaveLoad> FloatingPointVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> FloatingPointVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new FloatingPointVariableStorage(*this));
}

FloatingPointVariableStorage::SaveLoad::SaveLoad(FloatingPointVariableStorage *storage) : _storage(storage) {
	_value = _storage->_value;
}

void FloatingPointVariableStorage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void FloatingPointVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeDoubleBE(_storage->_value);
}

bool FloatingPointVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	_storage->_value = stream->readDoubleBE();

	if (stream->err())
		return false;

	return true;
}

StringVariableModifier::StringVariableModifier() : VariableModifier(Common::SharedPtr<VariableStorage>(new StringVariableStorage())) {
}

bool StringVariableModifier::load(ModifierLoaderContext &context, const Data::StringVariableModifier &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	StringVariableStorage *storage = static_cast<StringVariableStorage *>(_storage.get());

	storage->_value = data.value;

	return true;
}

bool StringVariableModifier::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	DynamicValue stringValue;
	if (!value.convertToType(DynamicValueTypes::kString, stringValue))
		return false;

	StringVariableStorage *storage = static_cast<StringVariableStorage *>(_storage.get());

	storage->_value = stringValue.getString();

	return true;
}

void StringVariableModifier::varGetValue(DynamicValue &dest) const {
	StringVariableStorage *storage = static_cast<StringVariableStorage *>(_storage.get());

	dest.setString(storage->_value);
}

#ifdef MTROPOLIS_DEBUG_ENABLE
void StringVariableModifier::debugInspect(IDebugInspectionReport *report) const {
	VariableModifier::debugInspect(report);

	StringVariableStorage *storage = static_cast<StringVariableStorage *>(_storage.get());

	report->declareDynamic("value", storage->_value);
}
#endif

Common::SharedPtr<Modifier> StringVariableModifier::shallowClone() const {
	return Common::SharedPtr<Modifier>(new StringVariableModifier(*this));
}

const char *StringVariableModifier::getDefaultName() const {
	return "String Variable";
}

StringVariableStorage::StringVariableStorage() {
}

Common::SharedPtr<ModifierSaveLoad> StringVariableStorage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> StringVariableStorage::clone() const {
	return Common::SharedPtr<VariableStorage>(new StringVariableStorage(*this));
}

StringVariableStorage::SaveLoad::SaveLoad(StringVariableStorage *storage) : _storage(storage) {
	_value = _storage->_value;
}

void StringVariableStorage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void StringVariableStorage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	stream->writeUint32BE(_value.size());
	stream->writeString(_value);
}

bool StringVariableStorage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	uint32 size = stream->readUint32BE();

	if (stream->err())
		return false;

	_value.clear();

	if (size > 0) {
		Common::Array<char> chars;
		chars.resize(size);
		stream->read(&chars[0], size);
		if (stream->err())
			return false;

		_value = Common::String(&chars[0], size);
	}

	return true;
}

ObjectReferenceVariableModifierV1::ObjectReferenceVariableModifierV1() : VariableModifier(Common::SharedPtr<VariableStorage>(new ObjectReferenceVariableV1Storage())) {
}

bool ObjectReferenceVariableModifierV1::load(ModifierLoaderContext &context, const Data::ObjectReferenceVariableModifierV1 &data) {
	if (!loadTypicalHeader(data.modHeader))
		return false;

	if (!_setToSourcesParentWhen.load(data.setToSourcesParentWhen))
		return false;

	return true;
}

bool ObjectReferenceVariableModifierV1::respondsToEvent(const Event &evt) const {
	return _setToSourcesParentWhen.respondsTo(evt);
}

VThreadState ObjectReferenceVariableModifierV1::consumeMessage(Runtime *runtime, const Common::SharedPtr<MessageProperties> &msg) {
	if (msg->getEvent().respondsTo(_setToSourcesParentWhen)) {
		warning("Set to source's parent is not implemented");
	}
	return kVThreadError;
}


bool ObjectReferenceVariableModifierV1::readAttribute(MiniscriptThread *thread, DynamicValue &result, const Common::String &attrib) {
	if (attrib == "object") {
		ObjectReferenceVariableV1Storage *storage = static_cast<ObjectReferenceVariableV1Storage *>(_storage.get());

		if (storage->_value.expired())
			result.clear();
		else
			result.setObject(storage->_value);
		return true;
	}

	return VariableModifier::readAttribute(thread, result, attrib);
}

bool ObjectReferenceVariableModifierV1::varSetValue(MiniscriptThread *thread, const DynamicValue &value) {
	ObjectReferenceVariableV1Storage *storage = static_cast<ObjectReferenceVariableV1Storage *>(_storage.get());

	// Somewhat tricky aspect: If this is set to another object reference variable modifier, then this will reference
	// the other object variable modifier, it will NOT copy it.
	if (value.getType() == DynamicValueTypes::kNull)
		storage->_value.reset();
	else if (value.getType() == DynamicValueTypes::kObject)
		storage->_value = value.getObject().object;
	else
		return false;

	return true;
}

void ObjectReferenceVariableModifierV1::varGetValue(DynamicValue &dest) const {
	dest.setObject(getSelfReference());
}

Common::SharedPtr<Modifier> ObjectReferenceVariableModifierV1::shallowClone() const {
	return Common::SharedPtr<Modifier>(new ObjectReferenceVariableModifierV1(*this));
}

const char *ObjectReferenceVariableModifierV1::getDefaultName() const {
	return "Object Reference Variable";
}

ObjectReferenceVariableV1Storage::ObjectReferenceVariableV1Storage() {
}

Common::SharedPtr<ModifierSaveLoad> ObjectReferenceVariableV1Storage::getSaveLoad(Runtime *runtime) {
	return Common::SharedPtr<ModifierSaveLoad>(new SaveLoad(this));
}

Common::SharedPtr<VariableStorage> ObjectReferenceVariableV1Storage::clone() const {
	return Common::SharedPtr<VariableStorage>(new ObjectReferenceVariableV1Storage(*this));
}

ObjectReferenceVariableV1Storage::SaveLoad::SaveLoad(ObjectReferenceVariableV1Storage *storage) : _storage(storage) {
}

void ObjectReferenceVariableV1Storage::SaveLoad::commitLoad() const {
	_storage->_value = _value;
}

void ObjectReferenceVariableV1Storage::SaveLoad::saveInternal(Common::WriteStream *stream) const {
	error("Saving version 1 object reference variables is not currently supported");
}

bool ObjectReferenceVariableV1Storage::SaveLoad::loadInternal(Common::ReadStream *stream, uint32 saveFileVersion) {
	return true;
}

} // End of namespace MTropolis