aboutsummaryrefslogtreecommitdiff
path: root/engines/tsage/core.cpp
blob: 424df164b234a5e0f5ea74e87e10ca3c26dce395 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
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
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
/* 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 2
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "common/system.h"
#include "common/config-manager.h"
#include "common/util.h"
#include "engines/engine.h"
#include "graphics/palette.h"
#include "tsage/tsage.h"
#include "tsage/core.h"
#include "tsage/dialogs.h"
#include "tsage/events.h"
#include "tsage/scenes.h"
#include "tsage/staticres.h"
#include "tsage/globals.h"
#include "tsage/sound.h"
#include "tsage/blue_force/blueforce_logic.h"
#include "tsage/ringworld2/ringworld2_logic.h"

namespace TsAGE {

// The engine uses ScumMVM screen buffering, so all logic is hardcoded to use pane buffer 0
#define CURRENT_PANENUM 0

/*--------------------------------------------------------------------------*/

InvObject::InvObject(int sceneNumber, int rlbNum, int cursorNum, CursorType cursorId, const Common::String description) :
		_sceneNumber(sceneNumber), _rlbNum(rlbNum), _cursorNum(cursorNum), _cursorId(cursorId),
		_description(description) {
	_displayResNum = 3;
	_iconResNum = 5;

	// Decode the image for the inventory item to get it's display bounds
	uint size;
	byte *imgData = g_resourceManager->getSubResource(_displayResNum, _rlbNum, _cursorNum, &size);
	GfxSurface s = surfaceFromRes(imgData);
	_bounds = s.getBounds();

	DEALLOCATE(imgData);
}

InvObject::InvObject(int visage, int strip, int frame) {
	assert(g_vm->getGameID() == GType_BlueForce);
	_visage = visage;
	_strip = strip;
	_frame = frame;
	_sceneNumber = 0;
	_iconResNum = 10;

	_displayResNum = 0;
	_rlbNum = 0;
	_cursorNum = 0;
	_cursorId = INV_NONE;
}

InvObject::InvObject(int strip, int frame) {
	assert(g_vm->getGameID() == GType_Ringworld2);
	_strip = strip;
	_frame = frame;

	_visage = 7;
	_sceneNumber = 0;
	_iconResNum = 10;

	_displayResNum = 0;
	_rlbNum = 0;
	_cursorNum = 0;
	_cursorId = INV_NONE;
}

void InvObject::setCursor() {
	if (g_vm->getGameID() != GType_Ringworld) {
		// All other games
		_cursorId = (CursorType)BF_GLOBALS._inventory->indexOf(this);
		g_globals->_events.setCursor(_cursorId);
	} else {
		// Ringworld cursor handling
		g_globals->_events._currentCursor = _cursorId;

		if (_iconResNum != -1) {
			GfxSurface s = surfaceFromRes(_iconResNum, _rlbNum, _cursorNum);

			Graphics::Surface src = s.lockSurface();
			g_globals->_events.setCursor(src, s._transColor, s._centroid, _cursorId);
		}
	}
}

bool InvObject::inInventory() const {
	return _sceneNumber == ((g_vm->getGameID() != GType_Ringworld2) ? 1 : g_globals->_player._characterIndex);
}

/*--------------------------------------------------------------------------*/

InvObjectList::InvObjectList() {
	_selectedItem = NULL;
}

void InvObjectList::synchronize(Serializer &s) {
	SavedObject::synchronize(s);
	SYNC_POINTER(_selectedItem);
}

int InvObjectList::indexOf(InvObject *obj) const {
	int idx = 0;
	SynchronizedList<InvObject *>::const_iterator i;

	for (i = _itemList.begin(); i != _itemList.end(); ++i, ++idx) {
		if ((*i) == obj)
			return idx;
	}

	return -1;
}

InvObject *InvObjectList::getItem(int objectNum) {
	SynchronizedList<InvObject *>::const_iterator i = _itemList.begin();
	while (objectNum-- > 0)
		++i;

	return *i;
}

int InvObjectList::getObjectScene(int objectNum) {
	InvObject *obj = getItem(objectNum);
	return obj->_sceneNumber;
}

/*--------------------------------------------------------------------------*/

void EventHandler::dispatch() {
	if (_action) _action->dispatch();
}

void EventHandler::setAction(Action *action, EventHandler *endHandler, ...) {
	if (_action) {
		_action->_endHandler = NULL;
		_action->remove();
	}

	_action = action;
	if (action) {
		va_list va;
		va_start(va, endHandler);
		_action->attached(this, endHandler, va);
		va_end(va);
	}
}

/*--------------------------------------------------------------------------*/

Action::Action() {
	_actionIndex = 0;
	_owner = NULL;
	_endHandler = NULL;
	_attached = false;
	_delayFrames = 0;
	_startFrame = 0;
}

void Action::synchronize(Serializer &s) {
	EventHandler::synchronize(s);
	if (s.getVersion() == 1)
		remove();

	SYNC_POINTER(_owner);
	s.syncAsSint32LE(_actionIndex);
	s.syncAsSint32LE(_delayFrames);
	s.syncAsUint32LE(_startFrame);
	s.syncAsByte(_attached);
	SYNC_POINTER(_endHandler);
}

void Action::remove() {
	if (_action)
		_action->remove();

	if (_owner) {
		_owner->_action = NULL;
		_owner = NULL;
	} else {
		g_globals->_sceneManager.removeAction(this);
	}

	_attached = false;
	if (_endHandler)
		_endHandler->signal();
}

void Action::process(Event &event) {
	if (_action)
		_action->process(event);
}

void Action::dispatch() {
	if (_action)
		_action->dispatch();

	if (_delayFrames) {
		uint32 frameNumber = g_globals->_events.getFrameNumber();

		if (frameNumber >= _startFrame) {
			_delayFrames -= frameNumber - _startFrame;
			_startFrame = frameNumber;
			if (_delayFrames <= 0) {
				_delayFrames = 0;
				signal();
			}
		}
	}
}

void Action::attached(EventHandler *newOwner, EventHandler *endHandler, va_list va) {
	_actionIndex = 0;
	_delayFrames = 0;
	_startFrame = g_globals->_events.getFrameNumber();
	_owner = newOwner;
	_endHandler = endHandler;
	_attached = true;
	signal();
}

void Action::setDelay(int numFrames) {
	_delayFrames = numFrames;
	_startFrame = g_globals->_events.getFrameNumber();
}

/*--------------------------------------------------------------------------*/

ObjectMover::~ObjectMover() {
	if (_sceneObject->_mover == this)
		_sceneObject->_mover = NULL;
}

void ObjectMover::synchronize(Serializer &s) {
	EventHandler::synchronize(s);

	s.syncAsSint16LE(_destPosition.x); s.syncAsSint16LE(_destPosition.y);
	s.syncAsSint16LE(_moveDelta.x); s.syncAsSint16LE(_moveDelta.y);
	s.syncAsSint16LE(_moveSign.x); s.syncAsSint16LE(_moveSign.y);
	s.syncAsSint32LE(_minorDiff);
	s.syncAsSint32LE(_majorDiff);
	s.syncAsSint32LE(_changeCtr);
	SYNC_POINTER(_action);
	SYNC_POINTER(_sceneObject);
}

void ObjectMover::remove() {
	if (_sceneObject->_mover == this)
		_sceneObject->_mover = NULL;

	delete this;
}

void ObjectMover::dispatch() {
	Common::Point currPos = _sceneObject->_position;
	int yDiff = _sceneObject->_yDiff;

	if (dontMove())
		return;

	_sceneObject->_regionIndex = 0;
	if (_moveDelta.x >= _moveDelta.y) {
		int xAmount = _moveSign.x * _sceneObject->_moveDiff.x * _sceneObject->_percent / 100;
		if (!xAmount)
			xAmount = _moveSign.x;
		currPos.x += xAmount;

		int yAmount = ABS(_destPosition.y - currPos.y);
		int yChange = _majorDiff / ABS(xAmount);
		int ySign;

		if (!yChange)
			ySign = _moveSign.y;
		else {
			int v = yAmount / yChange;
			_changeCtr += yAmount % yChange;
			if (_changeCtr >= yChange) {
				++v;
				_changeCtr -= yChange;
			}

			ySign = _moveSign.y * v;
		}

		currPos.y += ySign;
		_majorDiff -= ABS(xAmount);

	} else {
		int yAmount = _moveSign.y * _sceneObject->_moveDiff.y * _sceneObject->_percent / 100;
		if (!yAmount)
			yAmount = _moveSign.y;
		currPos.y += yAmount;

		int xAmount = ABS(_destPosition.x - currPos.x);
		int xChange = _majorDiff / ABS(yAmount);
		int xSign;

		if (!xChange)
			xSign = _moveSign.x;
		else {
			int v = xAmount / xChange;
			_changeCtr += xAmount % xChange;
			if (_changeCtr >= xChange) {
				++v;
				_changeCtr -= xChange;
			}

			xSign = _moveSign.x * v;
		}

		currPos.x += xSign;
		_majorDiff -= ABS(yAmount);
	}

	_sceneObject->_regionIndex = _sceneObject->checkRegion(currPos);
	if (!_sceneObject->_regionIndex) {
		_sceneObject->setPosition(currPos, yDiff);
		_sceneObject->getHorizBounds();

		if (dontMove()) {
			_sceneObject->_position = _destPosition;
			endMove();
		}
	} else {
		endMove();
	}
}

void ObjectMover::setup(const Common::Point &destPos) {
	_sceneObject->calcAngle(destPos);

	if ((_sceneObject->_objectWrapper) && !(_sceneObject->_flags & OBJFLAG_SUPPRESS_DISPATCH)) {
		if (g_vm->getGameID() == GType_Ringworld)
			_sceneObject->_objectWrapper->dispatch();
		else
			_sceneObject->updateAngle(destPos);
	}

	// Get the difference
	int diffX = destPos.x - _sceneObject->_position.x;
	int diffY = destPos.y - _sceneObject->_position.y;
	int xSign = (diffX < 0) ? -1 : (diffX > 0 ? 1 : 0);
	int ySign = (diffY < 0) ? -1 : (diffY > 0 ? 1 : 0);
	diffX = ABS(diffX);
	diffY = ABS(diffY);

	if (diffX < diffY) {
		_minorDiff = diffX / 2;
		_majorDiff = diffY;
	} else {
		_minorDiff = diffY / 2;
		_majorDiff = diffX;
	}

	// Set the destination position
	_destPosition = destPos;
	_moveDelta = Common::Point(diffX, diffY);
	_moveSign = Common::Point(xSign, ySign);
	_changeCtr = 0;

	if (!diffX && !diffY)
		// Object is already at the correct destination
		endMove();
}

bool ObjectMover::dontMove() const {
	return (_majorDiff <= 0);
}

void ObjectMover::endMove() {
	EventHandler *actionP = _action;
	remove();

	if (actionP)
		actionP->signal();
}

/*--------------------------------------------------------------------------*/

ObjectMover2::ObjectMover2() : ObjectMover() {
	_destObject = NULL;
	_minArea = 0;
	_maxArea = 0;
}

void ObjectMover2::synchronize(Serializer &s) {
	ObjectMover::synchronize(s);

	SYNC_POINTER(_destObject);
	s.syncAsSint32LE(_minArea);
	s.syncAsSint32LE(_maxArea);
}

void ObjectMover2::dispatch() {
	int area = _sceneObject->getSpliceArea(_destObject);
	if (area > _maxArea) {
		// Setup again for the new destination
		setup(_destObject->_position);
		ObjectMover::dispatch();
	} else if (area >= _minArea) {
		// Keep dispatching
		ObjectMover::dispatch();
	} else {
		// Within minimum, so end move
		endMove();
	}
}

void ObjectMover2::startMove(SceneObject *sceneObj, va_list va) {
	// Set up fields
	_sceneObject = sceneObj;

	_minArea = va_arg(va, int);
	_maxArea = va_arg(va, int);
	_destObject = va_arg(va, SceneObject *);

	setup(_destObject->_position);
}

void ObjectMover2::endMove() {
	_sceneObject->_regionIndex = 0x40;
}

/*--------------------------------------------------------------------------*/

void ObjectMover3::dispatch() {
	int area = _sceneObject->getSpliceArea(_destObject);
	if (area <= _minArea) {
		endMove();
	} else {
		setup(_destObject->_position);
		ObjectMover::dispatch();
	}
}

void ObjectMover3::startMove(SceneObject *sceneObj, va_list va) {
	_sceneObject = sceneObj;
	_destObject = va_arg(va, SceneObject *);
	_minArea = va_arg(va, int);
	_action = va_arg(va, Action *);

	setup(_destObject->_position);
}

void ObjectMover3::endMove() {
	ObjectMover::endMove();
}

/*--------------------------------------------------------------------------*/

void NpcMover::startMove(SceneObject *sceneObj, va_list va) {
	_sceneObject = sceneObj;

	Common::Point *destPos = va_arg(va, Common::Point *);
	_action = va_arg(va, Action *);

	setup(*destPos);
}

/*--------------------------------------------------------------------------*/

void PlayerMover::synchronize(Serializer &s) {
	NpcMover::synchronize(s);

	s.syncAsSint16LE(_finalDest.x); s.syncAsSint16LE(_finalDest.y);
	s.syncAsSint32LE(_routeIndex);

	for (int i = 0; i < MAX_ROUTE_SIZE; ++i) {
		s.syncAsSint16LE(_routeList[i].x); s.syncAsSint16LE(_routeList[i].y);
	}
}

void PlayerMover::startMove(SceneObject *sceneObj, va_list va) {
	_sceneObject = sceneObj;
	Common::Point *pt = va_arg(va, Common::Point *);
	_finalDest = *pt;
	_action = va_arg(va, Action *);

	setDest(_finalDest);
}

void PlayerMover::endMove() {
	while (++_routeIndex != 0) {
		if ((_routeList[_routeIndex].x == ROUTE_END_VAL) ||
			(_routeList[_routeIndex].y == ROUTE_END_VAL) ||
			(_sceneObject->_regionIndex)) {
			// Movement route is completely finished
			ObjectMover::endMove();
			return;
		}

		if ((_routeList[_routeIndex].x != _sceneObject->_position.x) ||
			(_routeList[_routeIndex].y != _sceneObject->_position.y))
			break;
	}

	// Set up the new interim destination along the route
	g_globals->_walkRegions._routeEnds.moveSrc = g_globals->_walkRegions._routeEnds.moveDest;
	g_globals->_walkRegions._routeEnds.moveDest = _routeList[_routeIndex];
	setup(_routeList[_routeIndex]);
	dispatch();
}

void PlayerMover::setDest(const Common::Point &destPos) {
	_routeList[0] = _sceneObject->_position;

	if (g_globals->_walkRegions._resNum == -1) {
		// Scene has no walk regions defined, so player can walk anywhere directly
		_routeList[0] = destPos;
		_routeList[1] = Common::Point(ROUTE_END_VAL, ROUTE_END_VAL);
	} else {
		// Figure out a path to the destination (or as close as possible to it)
		pathfind(_routeList, _sceneObject->_position, destPos, g_globals->_walkRegions._routeEnds);
	}

	_routeIndex = 0;
	g_globals->_walkRegions._routeEnds.moveSrc = _sceneObject->_position;
	g_globals->_walkRegions._routeEnds.moveDest = _routeList[0];
	setup(_routeList[0]);
}

#define REGION_LIST_SIZE 20

void PlayerMover::pathfind(Common::Point *routeList, Common::Point srcPos, Common::Point destPos, RouteEnds routeEnds) {
	Common::List<int> regionIndexes;
	RouteEnds tempRouteEnds;
	int routeRegions[REGION_LIST_SIZE];
	Common::Point objPos;

	// Get the region the source is in
	int srcRegion = g_globals->_walkRegions.indexOf(srcPos);
	if (srcRegion == -1) {
		srcRegion = findClosestRegion(srcPos, regionIndexes);
	}

	// Main loop for building up the path
	routeRegions[0] = 0;
	while (!routeRegions[0]) {
		// Check the destination region
		int destRegion = g_globals->_walkRegions.indexOf(destPos, &regionIndexes);

		if ((srcRegion == -1) && (destRegion == -1)) {
			// Both source and destination are outside walkable areas
		} else if (srcRegion == -1) {
			// Source is outside walkable areas
			tempRouteEnds = routeEnds;
			objPos = _sceneObject->_position;

			Common::Point newPos;
			findLinePoint(&tempRouteEnds, &objPos, 1, &newPos);
			int srcId = g_globals->_walkRegions.indexOf(newPos);

			if (srcId == -1) {
				tempRouteEnds.moveDest = tempRouteEnds.moveSrc;
				tempRouteEnds.moveSrc = routeEnds.moveDest;

				findLinePoint(&tempRouteEnds, &objPos, 1, &newPos);
				srcRegion = g_globals->_walkRegions.indexOf(newPos);

				if (srcRegion == -1)
					srcRegion = checkMover(srcPos, destPos);
			}

		} else if (destRegion == -1) {
			// Destination is outside walkable areas
			destRegion = findClosestRegion(destPos, regionIndexes);
			if (destRegion == -1) {
				// No further route found, so end it
				*routeList++ = srcPos;
				break;
			} else {
				_finalDest = destPos;
			}
		}

		if (srcRegion == destRegion) {
			*routeList++ = (srcRegion == -1) ? srcPos : destPos;
			break;
		}

		bool tempVar; // This is used only as internal state for the function.
		calculateRestOfRoute(routeRegions, srcRegion, destRegion, tempVar);

		// Empty route?
		if (!routeRegions[0]) {
			regionIndexes.push_back(destRegion);
			continue;
		}

		// field 0 holds the start, and field 1 holds the destination
		WRField18 &currSrcField = g_globals->_walkRegions._field18[0];
		WRField18 &currDestField = g_globals->_walkRegions._field18[1];

		currSrcField._pt1 = srcPos;
		currSrcField._pt2 = srcPos;
		currDestField._pt1 = destPos;
		currDestField._pt2 = destPos;

		int tempList[REGION_LIST_SIZE];
		tempList[0] = 0;
		int endIndex = 0;
		int idx = 1;

		// Find the indexes for each entry in the found route.
		do {
			int breakEntry = routeRegions[idx];
			int breakEntry2 = routeRegions[idx + 1];

			int listIndex = 0;
			while (g_globals->_walkRegions._idxList[g_globals->_walkRegions[breakEntry]._idxListIndex + listIndex] !=
					breakEntry2)
				++listIndex;

			tempList[idx] = g_globals->_walkRegions._idxList2[g_globals->_walkRegions[breakEntry]._idxList2Index
				+ listIndex];

			++endIndex;
		} while (routeRegions[++idx] != destRegion);

		tempList[idx] = 1;
		for (int listIndex = 1; listIndex <= endIndex; ++listIndex) {
			int thisIdx = tempList[listIndex];
			int nextIdx = tempList[listIndex + 1];

			WRField18 &thisField = g_globals->_walkRegions._field18[thisIdx];
			WRField18 &nextField = g_globals->_walkRegions._field18[nextIdx];

			if (sub_F8E5_calculatePoint(currSrcField._pt1, nextField._pt1,
					thisField._pt1, thisField._pt2) &&
				sub_F8E5_calculatePoint(currSrcField._pt1, nextField._pt2,
					thisField._pt1, thisField._pt2))
				continue;

			Common::Point tempPt;
			if (sub_F8E5_calculatePoint(currSrcField._pt1, currDestField._pt1,
					thisField._pt1, thisField._pt2, &tempPt)) {
				// Add point to the route list
				currSrcField._pt1 = tempPt;
				*routeList++ = tempPt;
			} else {
				int dist1 =
					(findDistance(currSrcField._pt1, thisField._pt1) << 1) +
					(findDistance(thisField._pt1, currDestField._pt1) << 1) +
					findDistance(thisField._pt1, nextField._pt1) +
					findDistance(thisField._pt1, nextField._pt2);

				int dist2 =
					(findDistance(currSrcField._pt1, thisField._pt2) << 1) +
					(findDistance(thisField._pt2, currDestField._pt2) << 1) +
					findDistance(thisField._pt2, nextField._pt1) +
					findDistance(thisField._pt2, nextField._pt2);

				// Do 1 step of movement, storing the new position in objPos.
				if (dist1 < dist2) {
					doStepsOfNpcMovement(thisField._pt1, thisField._pt2, 1, objPos);
				} else {
					doStepsOfNpcMovement(thisField._pt2, thisField._pt1, 1, objPos);
				}

				// Update the current position.
				currSrcField._pt1 = objPos;
				*routeList++ = objPos;
			}
		}

		// Add in the route entry
		*routeList++ = currDestField._pt1;
	}

	// Mark the end of the path
	*routeList = Common::Point(ROUTE_END_VAL, ROUTE_END_VAL);
}

int PlayerMover::regionIndexOf(const Common::Point &pt) {
	for (uint idx = 0; idx < g_globals->_walkRegions._regionList.size(); ++idx) {
		if (g_globals->_walkRegions._regionList[idx].contains(pt))
			return idx + 1;
	}

	return 0;
}

int PlayerMover::findClosestRegion(Common::Point &pt, const Common::List<int> &indexList) {
	int newY = pt.y;
	int result = 0;

	for (int idx = 1; idx < SCREEN_WIDTH; ++idx, newY += idx) {
		int newX = pt.x + idx;
		result = regionIndexOf(newX, pt.y);

		if ((result == 0) || contains(indexList, result)) {
			newY = pt.y + idx;
			result = regionIndexOf(newX, newY);

			if ((result == 0) || contains(indexList, result)) {
				newX -= idx;
				result = regionIndexOf(newX, newY);

				if ((result == 0) || contains(indexList, result)) {
					newX -= idx;
					result = regionIndexOf(newX, newY);

					if ((result == 0) || contains(indexList, result)) {
						newY -= idx;
						result = regionIndexOf(newX, newY);

						if ((result == 0) || contains(indexList, result)) {
							newY -= idx;
							result = regionIndexOf(newX, newY);

							if ((result == 0) || contains(indexList, result)) {
								newX += idx;
								result = regionIndexOf(newX, newY);

								if ((result == 0) || contains(indexList, result)) {
									newX += idx;
									result = regionIndexOf(newX, newY);

									if ((result == 0) || contains(indexList, result)) {
										continue;
									}
								}
							}
						}
					}
				}
			}
		}

		// Found an index
		pt.x = newX;
		pt.y = newY;
		return result;
	}

	return (result == 0) ? -1 : result;
}

Common::Point *PlayerMover::findLinePoint(RouteEnds *routeEnds, Common::Point *objPos, int length, Common::Point *outPos) {
	int xp = objPos->x + (((routeEnds->moveDest.y - routeEnds->moveSrc.y) * 9) / 8);
	int yp = objPos->y - (((routeEnds->moveDest.x - routeEnds->moveSrc.x) * 8) / 9);

	int xDiff = xp - objPos->x;
	int yDiff = yp - objPos->y;
	int xDirection = (xDiff == 0) ? 0 : ((xDiff < 0) ? 1 : -1);
	int yDirection = (yDiff == 0) ? 0 : ((yDiff < 0) ? 1 : -1);
	xDiff = ABS(xDiff);
	yDiff = ABS(yDiff);
	int majorChange = MAX(xDiff, yDiff) / 2;

	int outX = objPos->x;
	int outY = objPos->y;

	while (length-- > 0) {
		if (xDiff < yDiff) {
			outY += yDirection;
			majorChange += xDiff;
			if (majorChange > yDiff) {
				majorChange -= yDiff;
				outX += xDirection;
			}
		} else {
			outX += xDirection;
			majorChange += yDiff;
			if (majorChange > xDiff) {
				majorChange -= xDiff;
				outY += yDirection;
			}
		}
	}

	outPos->x = outX;
	outPos->y = outY;
	return outPos;
}

int PlayerMover::checkMover(Common::Point &srcPos, const Common::Point &destPos) {
	int regionIndex = 0;
	Common::Point objPos = _sceneObject->_position;
	uint32 regionBitList = _sceneObject->_regionBitList;
	_sceneObject->_regionBitList = 0;

	_sceneObject->_position.x = srcPos.x;
	_sceneObject->_position.y = srcPos.y;
	_sceneObject->_mover = NULL;

	NpcMover *mover = new NpcMover();
	_sceneObject->addMover(mover, &destPos, NULL);

	// Handle automatic movement of the player until a walkable region is reached,
	// or the end point of the movement is
	do {
		_sceneObject->_mover->dispatch();

		// Scan walk regions for point
		for (uint idx = 0; idx < g_globals->_walkRegions._regionList.size(); ++idx) {
			if (g_globals->_walkRegions[idx].contains(_sceneObject->_position)) {
				regionIndex = idx + 1;
				srcPos = _sceneObject->_position;
				break;
			}
		}
	} while ((regionIndex == 0) && (_sceneObject->_mover) && !g_vm->shouldQuit());

	_sceneObject->_position = objPos;
	_sceneObject->_regionBitList = regionBitList;

	if (_sceneObject->_mover)
		_sceneObject->_mover->remove();

	_sceneObject->_mover = this;
	return regionIndex;
}

void PlayerMover::doStepsOfNpcMovement(const Common::Point &srcPos, const Common::Point &destPos, int numSteps, Common::Point &ptOut) {
	Common::Point objPos = _sceneObject->_position;
	_sceneObject->_position = srcPos;
	uint32 regionBitList = _sceneObject->_regionBitList;
	_sceneObject->_position = srcPos;
	_sceneObject->_mover = NULL;

	NpcMover *mover = new NpcMover();
	_sceneObject->addMover(mover, &destPos, NULL);

	while ((numSteps > 0) && ((_sceneObject->_position.x != destPos.x) || (_sceneObject->_position.y != destPos.y))) {
		_sceneObject->_mover->dispatch();
		--numSteps;
	}

	ptOut = _sceneObject->_position;
	_sceneObject->_position = objPos;
	_sceneObject->_regionBitList = regionBitList;

	if (_sceneObject->_mover)
		_sceneObject->_mover->remove();

	_sceneObject->_mover = this;
}

int PlayerMover::calculateRestOfRoute(int *routeList, int srcRegion, int destRegion, bool &foundRoute) {
	// Make a copy of the provided route. The first entry is the size.
	int tempList[REGION_LIST_SIZE + 1];
	memset(tempList, 0, REGION_LIST_SIZE + 1);

	foundRoute = false;
	for (int idx = 0; idx <= *routeList; ++idx)
		tempList[idx] = routeList[idx];

	if (*routeList == REGION_LIST_SIZE)
		// Sequence too long
		return 32000;

	int regionIndex;
	for (regionIndex = 1; regionIndex <= *tempList; ++regionIndex) {
		if (routeList[regionIndex] == srcRegion)
			// Current path returns to original source region, so don't allow it
			return 32000;
	}

	WalkRegion &srcWalkRegion = g_globals->_walkRegions[srcRegion];
	int distance;
	if (!routeList[0]) {
		// The route is empty (new route).
		distance = 0;
	} else {
		// Find the distance from the last region in the route.
		WalkRegion &region = g_globals->_walkRegions[routeList[*routeList]];
		distance = findDistance(srcWalkRegion._pt, region._pt);
	}

	// Add the srcRegion to the end of the route.
	tempList[++*tempList] = srcRegion;
	int ourListSize = *tempList;

	if (srcRegion == destRegion) {
		// We made a route to the destination; copy that route and return.
		foundRoute = true;
		for (int idx = ourListSize; idx <= *tempList; ++idx) {
			routeList[idx] = tempList[idx];
			++*routeList;
		}
		return distance;
	} else {
		// Find the first connected region leading to our destination.
		int foundIndex = 0;
		int idx = 0;
		int currDest;
		while ((currDest = g_globals->_walkRegions._idxList[srcWalkRegion._idxListIndex + idx]) != 0) {
			if (currDest == destRegion) {
				foundIndex = idx;
				break;
			}

			++idx;
		}

		// Check every connected region until we find a route to the destination (or we have no more to check).
		int bestDistance = 31990;
		while (((currDest = g_globals->_walkRegions._idxList[srcWalkRegion._idxListIndex + foundIndex]) != 0) && (!foundRoute)) {
			// Only check the region if it isn't in the list of explicitly disabled regions
			if (!contains(g_globals->_walkRegions._disabledRegions, (int)currDest)) {
				int newDistance = calculateRestOfRoute(tempList, currDest, destRegion, foundRoute);

				if ((newDistance <= bestDistance) || foundRoute) {
					// We found a shorter possible route, or one leading to the destination.

					// Overwrite the route with this new one.
					routeList[0] = ourListSize - 1;

					for (int i = ourListSize; i <= tempList[0]; ++i) {
						routeList[i] = tempList[i];
						++routeList[0];
					}

					bestDistance = newDistance;
				}

				// Truncate our local list to the size it was before the call.
				tempList[0] = ourListSize;
			}

			++foundIndex;
		}

		foundRoute = false;
		return bestDistance + distance;
	}
}

int PlayerMover::findDistance(const Common::Point &pt1, const Common::Point &pt2) {
	int diff = ABS(pt1.x - pt2.x);
	double xx = diff * diff;
	diff = ABS(pt1.y - pt2.y);
	double yy = diff * 8.0 / 7.0;
	yy *= yy;

	return (int)sqrt(xx + yy);
}

// Calculate intersection of the line segments pt1-pt2 and pt3-pt4.
// Return true if they intersect, and return the intersection in ptOut.
bool PlayerMover::sub_F8E5_calculatePoint(const Common::Point &pt1, const Common::Point &pt2, const Common::Point &pt3,
						  const Common::Point &pt4, Common::Point *ptOut) {
	double diffX1 = pt2.x - pt1.x;
	double diffY1 = pt2.y - pt1.y;
	double diffX2 = pt4.x - pt3.x;
	double diffY2 = pt4.y - pt3.y;
	double ratio1 = 0.0, ratio2 = 0.0;
	double adjustedY1 = 0.0, adjustedY2 = 0.0;

	// Calculate the ratios between the X and Y points.
	if (diffX1 != 0.0) {
		ratio1 = diffY1 / diffX1;
		adjustedY1 = pt1.y - (pt1.x * ratio1);
	}
	if (diffX2 != 0.0) {
		ratio2 = diffY2 / diffX2;
		adjustedY2 = pt3.y - (pt3.x * ratio2);
	}

	if (ratio1 == ratio2)
		return false;

	double xPos, yPos;
	if (diffX1 == 0) {
		if (diffX2 == 0)
			return false;

		xPos = pt1.x;
		yPos = ratio2 * xPos + adjustedY2;
	} else {
		xPos = (diffX2 == 0) ? pt3.x : (adjustedY2 - adjustedY1) / (ratio1 - ratio2);
		yPos = ratio1 * xPos + adjustedY1;
	}

	// This is our candidate point, which we must check for validity.
	Common::Point tempPt((int)(xPos + 0.5), (int)(yPos + 0.5));

	// Is tempPt inside the second bounds?
	if (!((tempPt.x >= pt3.x) && (tempPt.x <= pt4.x)))
		if (!((tempPt.x >= pt4.x) && (tempPt.x <= pt3.x)))
			return false;
	if (!((tempPt.y >= pt3.y) && (tempPt.y <= pt4.y)))
		if (!((tempPt.y >= pt4.y) && (tempPt.y <= pt3.y)))
			return false;

	// Is tempPt inside the first bounds?
	if (!((tempPt.x >= pt1.x) && (tempPt.x <= pt2.x)))
		if (!((tempPt.x >= pt2.x) && (tempPt.x <= pt1.x)))
			return false;
	if (!((tempPt.y >= pt1.y) && (tempPt.y <= pt2.y)))
		if (!((tempPt.y >= pt2.y) && (tempPt.y <= pt1.y)))
			return false;

	if (ptOut)
		*ptOut = tempPt;
	return true;
}

/*--------------------------------------------------------------------------*/

void PlayerMover2::synchronize(Serializer &s) {
	if (s.getVersion() >= 2)
		PlayerMover::synchronize(s);
	SYNC_POINTER(_destObject);
	s.syncAsSint16LE(_maxArea);
	s.syncAsSint16LE(_minArea);
}

void PlayerMover2::dispatch() {
	int total = _sceneObject->getSpliceArea(_destObject);

	if (total <= _minArea)
		endMove();
	else {
		setDest(_destObject->_position);
		ObjectMover::dispatch();
	}
}

void PlayerMover2::startMove(SceneObject *sceneObj, va_list va) {
	_sceneObject = sceneObj;
	_maxArea = va_arg(va, int);
	_minArea = va_arg(va, int);
	_destObject = va_arg(va, SceneObject *);

	PlayerMover::setDest(_destObject->_position);
}

void PlayerMover2::endMove() {
	_sceneObject->_regionIndex = 0x40;
}

/*--------------------------------------------------------------------------*/

PaletteModifier::PaletteModifier() {
	_scenePalette = NULL;
	_action = NULL;
}

/*--------------------------------------------------------------------------*/

PaletteModifierCached::PaletteModifierCached(): PaletteModifier() {
	_step = 0;
	_percent = 0;
	for (int i = 0; i < 768; i++)
		_palette[i] = 0;
}

void PaletteModifierCached::setPalette(ScenePalette *palette, int step) {
	_scenePalette = palette;
	_step = step;
	_percent = 100;
}

void PaletteModifierCached::synchronize(Serializer &s) {
	PaletteModifier::synchronize(s);

	s.syncAsByte(_step);
	s.syncAsSint32LE(_percent);
}

/*--------------------------------------------------------------------------*/

PaletteRotation::PaletteRotation() : PaletteModifierCached() {
	_percent = 0;
	_delayCtr = 0;
	_frameNumber = g_globals->_events.getFrameNumber();
	_idxChange = 1;
	_countdown = 0;
	_currIndex = 0;
	_start = _end = 0;
	_rotationMode = 0;
	_duration = 0;
}

void PaletteRotation::synchronize(Serializer &s) {
	PaletteModifierCached::synchronize(s);

	s.syncAsSint32LE(_delayCtr);
	s.syncAsUint32LE(_frameNumber);
	s.syncAsSint32LE(_currIndex);
	s.syncAsSint32LE(_start);
	s.syncAsSint32LE(_end);
	s.syncAsSint32LE(_rotationMode);
	s.syncAsSint32LE(_duration);
	s.syncBytes(&_palette[0], 256 * 3);

	if (g_vm->getGameID() == GType_Ringworld2) {
		s.syncAsSint16LE(_idxChange);
		s.syncAsSint16LE(_countdown);
	}
}

void PaletteRotation::signal() {
	if (_countdown > 0) {
		--_countdown;
		return;
	}

	if (_delayCtr) {
		uint32 frameNumber = g_globals->_events.getFrameNumber();

		if (frameNumber >= _frameNumber) {
			_delayCtr -= frameNumber - _frameNumber;
			_frameNumber = frameNumber;

			if (_delayCtr < 0)
				_delayCtr = 0;
		}
	}

	if (_delayCtr)
		return;
	_delayCtr = _percent;
	if (_step)
		return;

	bool flag = true;
	switch (_rotationMode) {
	case -1:
		_currIndex -= _idxChange;
		if (_currIndex < _start) {
			flag = decDuration();
			if (flag)
				_currIndex = _end - 1;
		}
		break;
	case 1:
		_currIndex += _idxChange;
		if (_currIndex >= _end) {
			flag = decDuration();
			if (flag)
				_currIndex = _start;
		}
		break;
	case 2:
		_currIndex += _idxChange;
		if (_currIndex >= _end) {
			flag = decDuration();
			if (flag) {
				_currIndex = _end - 2;
				_rotationMode = 3;
			}
		}
		break;
	case 3:
		_currIndex -= _idxChange;
		if (_currIndex < _start) {
			flag = decDuration();
			if (flag) {
				_currIndex = _start + 1;
				_rotationMode = 2;
			}
		}
		break;
	}

	if (flag) {
		int count2 = _currIndex - _start;
		int count = _end - _currIndex;
		g_system->getPaletteManager()->setPalette((const byte *)&_palette[_currIndex * 3], _start, count);

		if (count2 > 0) {
			g_system->getPaletteManager()->setPalette((const byte *)&_palette[_start * 3], _start + count, count2);
		}
	}
}

void PaletteRotation::remove() {
	Action *action = _action;

	if (_idxChange)
		g_system->getPaletteManager()->setPalette((const byte *)&_palette[_start * 3], _start, _end - _start);

	_scenePalette->_listeners.remove(this);

	delete this;
	if (action)
		action->signal();
}

void PaletteRotation::set(ScenePalette *palette, int start, int end, int rotationMode, int duration, Action *action) {
	_duration = duration;
	_step = false;
	_action = action;
	_scenePalette = palette;

	Common::copy(&palette->_palette[0], &palette->_palette[256 * 3], &_palette[0]);

	_start = start;
	_end = end + 1;
	_rotationMode = rotationMode;

	switch (_rotationMode) {
	case -1:
	case 3:
		_currIndex = _end;
		break;
	default:
		_currIndex = _start;
		break;
	}
}

bool PaletteRotation::decDuration() {
	if (_duration) {
		if (--_duration == 0) {
			remove();
			return false;
		}
	}
	return true;
}

void PaletteRotation::setDelay(int amount) {
	_percent = _delayCtr = amount;
}

/*--------------------------------------------------------------------------*/

void PaletteFader::synchronize(Serializer &s) {
	PaletteModifierCached::synchronize(s);

	s.syncAsSint16LE(_step);
	s.syncAsSint16LE(_percent);
	s.syncBytes(&_palette[0], 256 * 3);
}

void PaletteFader::signal() {
	_percent -= _step;
	if (_percent > 0) {
		_scenePalette->fade((byte *)_palette, true /* 256 */, _percent);
	} else {
		remove();
	}
}

void PaletteFader::remove() {
	// Save of a copy of the object's action, since it will be used after the object is destroyed
	Action *action = _action;

	Common::copy(&_palette[0], &_palette[256 * 3], &_scenePalette->_palette[0]);
	_scenePalette->refresh();
	_scenePalette->_listeners.remove(this);
	delete this;

	if (action)
		action->signal();
}

void PaletteFader::setPalette(ScenePalette *palette, int step) {
	if (step < 0) {
		// Reverse step means moving from dest palette to source, so swap the two palettes
		byte tempPal[256 * 3];
		Common::copy(&palette->_palette[0], &palette->_palette[256 * 3], &tempPal[0]);
		Common::copy(&this->_palette[0], &this->_palette[256 * 3], &palette->_palette[0]);
		Common::copy(&tempPal[0], &tempPal[256 * 3], &this->_palette[0]);

		step = -step;
	}

	PaletteModifierCached::setPalette(palette, step);
}

/*--------------------------------------------------------------------------*/

ScenePalette::ScenePalette() {
	// Set a default gradiant range
	byte *palData = &_palette[0];
	for (int idx = 0; idx < 256; ++idx) {
		*palData++ = idx;
		*palData++ = idx;
		*palData++ = idx;
	}

	_field412 = 0;
	_redColor = _greenColor = _blueColor = 0;
	_aquaColor = 0;
	_purpleColor = 0;
	_limeColor = 0;
}

ScenePalette::~ScenePalette() {
	clearListeners();
}

ScenePalette::ScenePalette(int paletteNum) {
	_field412 = 0;
	_redColor = _greenColor = _blueColor = 0;
	_aquaColor = 0;
	_purpleColor = 0;
	_limeColor = 0;

	loadPalette(paletteNum);
}

bool ScenePalette::loadPalette(int paletteNum) {
	byte *palData = g_resourceManager->getResource(RES_PALETTE, paletteNum, 0, true);
	if (!palData)
		return false;

	int palStart = READ_LE_UINT16(palData);
	int palSize = READ_LE_UINT16(palData + 2);
	assert(palSize <= 256);

	byte *destP = &_palette[palStart * 3];
	byte *srcP = palData + 6;

	Common::copy(&srcP[0], &srcP[palSize * 3], destP);

	DEALLOCATE(palData);
	return true;
}

/**
 * Loads a palette from the passed raw data block
 */
void ScenePalette::loadPalette(const byte *pSrc, int start, int count) {
	Common::copy(pSrc, pSrc + count * 3, &_palette[start * 3]);
}

void ScenePalette::refresh() {
	// Set indexes for standard colors to closest color in the palette
	_colors.background = indexOf(255, 255, 255);	// White background
	_colors.foreground = indexOf(0, 0, 0);			// Black foreground
	_redColor = indexOf(180, 0, 0);				// Red-ish
	_greenColor = indexOf(0, 180, 0);				// Green-ish
	_blueColor = indexOf(0, 0, 180);				// Blue-ish
	_aquaColor = indexOf(0, 180, 180);				// Aqua
	_purpleColor = indexOf(180, 0, 180);			// Purple
	_limeColor = indexOf(180, 180, 0);				// Lime

	// Refresh the palette
	g_system->getPaletteManager()->setPalette((const byte *)&_palette[0], 0, 256);
}

/**
 * Loads a section of the palette into the game palette
 */
void ScenePalette::setPalette(int index, int count) {
	g_system->getPaletteManager()->setPalette((const byte *)&_palette[index * 3], index, count);
}

/**
 * Get a palette entry
 */
void ScenePalette::getEntry(int index, uint *r, uint *g, uint *b) {
	*r = _palette[index * 3];
	*g = _palette[index * 3 + 1];
	*b = _palette[index * 3 + 2];
}

/**
 * Set a palette entry
 */
void ScenePalette::setEntry(int index, uint r, uint g, uint b) {
	_palette[index * 3] = r;
	_palette[index * 3 + 1] = g;
	_palette[index * 3 + 2] = b;
}

/**
 * Returns the palette index with the closest matching color to that specified
 * @param r			R component
 * @param g			G component
 * @param b			B component
 * @param threshold	Closeness threshold.
 * @param start		Starting index
 * @param count		Number of indexes to scan
 * @remarks	A threshold may be provided to specify how close the matching color must be
 */
uint8 ScenePalette::indexOf(uint r, uint g, uint b, int threshold, int start, int count) {
	int palIndex = -1;
	byte *palData = &_palette[0];

	for (int i = start; i < (start + count); ++i) {
		byte ir = *palData++;
		byte ig = *palData++;
		byte ib = *palData++;
		int rDiff = abs(ir - (int)r);
		int gDiff = abs(ig - (int)g);
		int bDiff = abs(ib - (int)b);

		int idxThreshold = rDiff * rDiff + gDiff * gDiff + bDiff * bDiff;
		if (idxThreshold < threshold) {
			threshold = idxThreshold;
			palIndex = i;
		}
	}

	return palIndex;
}

/**
 * Loads the specified range of the palette with the current system palette
 * @param start		Start index
 * @param count		Number of palette entries
 */
void ScenePalette::getPalette(int start, int count) {
	g_system->getPaletteManager()->grabPalette((byte *)&_palette[start], start, count);
}

void ScenePalette::signalListeners() {
	SynchronizedList<PaletteModifier *>::iterator i = _listeners.begin();
	while (i != _listeners.end()) {
		PaletteModifier *obj = *i;
		++i;
		obj->signal();
	}
}

void ScenePalette::clearListeners() {
	SynchronizedList<PaletteModifier *>::iterator i = _listeners.begin();
	while (i != _listeners.end()) {
		PaletteModifier *obj = *i;
		++i;
		obj->remove();
	}
}

void ScenePalette::fade(const byte *adjustData, bool fullAdjust, int percent) {
	byte tempPalette[256 * 3];

	// Ensure the percent adjustment is within 0 - 100%
	percent = CLIP(percent, 0, 100);

	for (int palIndex = 0; palIndex < 256; ++palIndex) {
		const byte *srcP = (const byte *)&_palette[palIndex * 3];
		byte *destP = &tempPalette[palIndex * 3];

		for (int rgbIndex = 0; rgbIndex < 3; ++rgbIndex, ++srcP, ++destP) {
			*destP = *srcP - ((*srcP - adjustData[rgbIndex]) * (100 - percent)) / 100;
		}

		if (fullAdjust)
			adjustData += 3;
	}

	// Set the altered pale4tte
	g_system->getPaletteManager()->setPalette((const byte *)&tempPalette[0], 0, 256);
	GLOBALS._screenSurface.updateScreen();
}

PaletteRotation *ScenePalette::addRotation(int start, int end, int rotationMode, int duration, Action *action) {
	PaletteRotation *obj = new PaletteRotation();

	if ((rotationMode == 2) || (rotationMode == 3))
		duration <<= 1;

	obj->set(this, start, end, rotationMode, duration, action);
	_listeners.push_back(obj);
	return obj;
}

PaletteFader *ScenePalette::addFader(const byte *arrBufferRGB, int palSize, int step, Action *action) {
	PaletteFader *fader = new PaletteFader();
	fader->_action = action;
	for (int i = 0; i < 256 * 3; i += 3) {
		fader->_palette[i] = *(arrBufferRGB + 0);
		fader->_palette[i + 1] = *(arrBufferRGB + 1);
		fader->_palette[i + 2] = *(arrBufferRGB + 2);

		if (palSize > 1)
			arrBufferRGB += 3;
	}

	fader->setPalette(this, step);
	g_globals->_scenePalette._listeners.push_back(fader);
	return fader;
}


void ScenePalette::changeBackground(const Rect &bounds, FadeMode fadeMode) {
	ScenePalette tempPalette;

	if (g_globals->_sceneManager._hasPalette) {
		if ((fadeMode == FADEMODE_GRADUAL) || (fadeMode == FADEMODE_IMMEDIATE)) {
			// Fade out any active palette
			tempPalette.getPalette();
			uint32 adjustData = 0;

			for (int percent = 100; percent >= 0; percent -= 5) {
				if (fadeMode == FADEMODE_IMMEDIATE)
					percent = 0;
				tempPalette.fade((byte *)&adjustData, false, percent);
				g_system->delayMillis(10);
			}
		} else {
			g_globals->_scenePalette.refresh();
			g_globals->_sceneManager._hasPalette = false;
		}
	}

	Rect tempRect = bounds;
	if (g_vm->getGameID() != GType_Ringworld)
		tempRect.setHeight(T2_GLOBALS._interfaceY);

	g_globals->_screenSurface.copyFrom(g_globals->_sceneManager._scene->_backSurface,
		tempRect, Rect(0, 0, tempRect.width(), tempRect.height()), NULL);
	if (g_vm->getGameID() == GType_Ringworld2 && !GLOBALS._player._uiEnabled
			&& T2_GLOBALS._interfaceY == UI_INTERFACE_Y) {
		g_globals->_screenSurface.fillRect(Rect(0, UI_INTERFACE_Y, SCREEN_WIDTH, SCREEN_HEIGHT - 1), 0);
	}

	for (SynchronizedList<PaletteModifier *>::iterator i = tempPalette._listeners.begin(); i != tempPalette._listeners.end(); ++i)
		delete *i;
	tempPalette._listeners.clear();
}

void ScenePalette::synchronize(Serializer &s) {
	if (s.getVersion() >= 2)
		SavedObject::synchronize(s);
	if (s.getVersion() >= 5)
		_listeners.synchronize(s);

	s.syncBytes(_palette, 256 * 3);
	s.syncAsSint32LE(_colors.foreground);
	s.syncAsSint32LE(_colors.background);

	s.syncAsSint32LE(_field412);
	s.syncAsByte(_redColor);
	s.syncAsByte(_greenColor);
	s.syncAsByte(_blueColor);
	s.syncAsByte(_aquaColor);
	s.syncAsByte(_purpleColor);
	s.syncAsByte(_limeColor);
}

/*--------------------------------------------------------------------------*/

void SceneItem::synchronize(Serializer &s) {
	EventHandler::synchronize(s);

	_bounds.synchronize(s);
	s.syncString(_msg);
	s.syncAsSint32LE(_fieldE);
	s.syncAsSint32LE(_field10);
	s.syncAsSint16LE(_position.x); s.syncAsSint32LE(_position.y);
	s.syncAsSint16LE(_yDiff);
	s.syncAsSint32LE(_sceneRegionId);
}

void SceneItem::remove() {
	g_globals->_sceneItems.remove(this);
}

bool SceneItem::startAction(CursorType action, Event &event) {
	if (g_vm->getGameID() == GType_Ringworld) {
		doAction(action);
		return true;
	} else if ((action == CURSOR_LOOK) || (action == CURSOR_USE) || (action == CURSOR_TALK) ||
			(action < CURSOR_LOOK)) {
		doAction(action);
		return true;
	} else {
		return false;
	}
}

void SceneItem::doAction(int action) {
	const char *msg = NULL;

	if (g_vm->getGameID() == GType_Ringworld2) {
		Event dummyEvent;
		((Ringworld2::SceneExt *)GLOBALS._sceneManager._scene)->display((CursorType)action, dummyEvent);
	} else {
		switch ((int)action) {
		case CURSOR_LOOK:
			msg = LOOK_SCENE_HOTSPOT;
			break;
		case CURSOR_USE:
			msg = USE_SCENE_HOTSPOT;
			break;
		case CURSOR_TALK:
			msg = TALK_SCENE_HOTSPOT;
			break;
		case 0x1000:
			msg = SPECIAL_SCENE_HOTSPOT;
			break;
		default:
			msg = DEFAULT_SCENE_HOTSPOT;
			break;
		}

		GUIErrorMessage(msg);
	}
}

bool SceneItem::contains(const Common::Point &pt) {
	const Rect &sceneBounds = g_globals->_sceneManager._scene->_sceneBounds;

	if (_sceneRegionId == 0)
		return _bounds.contains(pt.x + sceneBounds.left, pt.y + sceneBounds.top);
	else
		return g_globals->_sceneRegions.indexOf(Common::Point(pt.x + sceneBounds.left,
			pt.y + sceneBounds.top)) == _sceneRegionId;
}

void SceneItem::display(int resNum, int lineNum, ...) {
	Common::String msg = (!resNum || (resNum == -1)) ? Common::String() :
		g_resourceManager->getMessage(resNum, lineNum);

	if ((g_vm->getGameID() != GType_Ringworld) && (g_vm->getGameID() != GType_Ringworld2)
			&& T2_GLOBALS._uiElements._active)
		T2_GLOBALS._uiElements.hide();

	if (g_globals->_sceneObjects->contains(&g_globals->_sceneText)) {
		g_globals->_sceneText.remove();
		g_globals->_sceneObjects->draw();
	}

	Common::Point pos(160, 100);
	Rect textRect;
	int maxWidth = 120;
	bool keepOnscreen = false;
	bool centerText = g_vm->getGameID() != GType_BlueForce;
	Common::List<int> playList;

	if (resNum != 0) {
		va_list va;
		va_start(va, lineNum);

		if (resNum == -1)
			msg = Common::String(va_arg(va, const char *));

		if (g_vm->getGameID() == GType_Ringworld2) {
			// Pre-process the string for any sound information
			while (msg.hasPrefix("!")) {
				msg.deleteChar(0);
				playList.push_back(atoi(msg.c_str()));

				while (!msg.empty() && (*msg.c_str() >= '0' && *msg.c_str() <= '9'))
					msg.deleteChar(0);
			}
		}

		int mode;
		do {
			// Get next instruction
			mode = va_arg(va, int);

			switch (mode) {
			case SET_WIDTH:
				// Set width
				maxWidth = va_arg(va, int);
				g_globals->_sceneText._width = maxWidth;
				break;
			case SET_X:
				// Set the X Position
				pos.x = va_arg(va, int);
				break;
			case SET_Y:
				// Set the Y Position
				pos.y = va_arg(va, int);
				break;
			case SET_FONT:
				// Set the font number
				g_globals->_sceneText._fontNumber = va_arg(va, int);
				g_globals->gfxManager()._font.setFontNumber(g_globals->_sceneText._fontNumber);
				break;
			case SET_BG_COLOR: {
				// Set the background color
				int bgColor = va_arg(va, int);
				g_globals->gfxManager()._font._colors.background = bgColor;
				if (!bgColor)
					g_globals->gfxManager().setFillFlag(false);
				break;
			}
			case SET_FG_COLOR:
				// Set the foreground color
				g_globals->_sceneText._color1 = va_arg(va, int);
				g_globals->gfxManager()._font._colors.foreground = g_globals->_sceneText._color1;
				break;
			case SET_KEEP_ONSCREEN:
				// Suppresses immediate display
				keepOnscreen = va_arg(va, int) != 0;
				break;
			case SET_EXT_BGCOLOR: {
				// Set secondary bg color
				int v = va_arg(va, int);
				g_globals->_sceneText._color2 = v;
				g_globals->gfxManager()._font._colors2.background = v;
				break;
			}
			case SET_EXT_FGCOLOR: {
				// Set secondary fg color
				int v = va_arg(va, int);
				g_globals->_sceneText._color3 = v;
				g_globals->gfxManager()._font._colors.foreground = v;
				break;
			}
			case SET_POS_MODE:
				// Set whether a custom x/y is used
				centerText = va_arg(va, int) != 0;
				break;
			case SET_TEXT_MODE:
				// Set the text mode
				g_globals->_sceneText._textMode = (TextAlign)va_arg(va, int);
				break;
			default:
				break;
			}
		} while (mode != LIST_END);

		va_end(va);
	}

	if (resNum) {
		// Get required bounding size
		GfxFont font;
		font.setFontNumber(g_globals->_sceneText._fontNumber);
		font.getStringBounds(msg.c_str(), textRect, maxWidth);

		// Center the text at the specified position, and then constrain it to be-
		textRect.center(pos.x, pos.y);
		textRect.contain(g_globals->gfxManager()._bounds);

		if (centerText) {
			g_globals->_sceneText._color1 = g_globals->_sceneText._color2;
			g_globals->_sceneText._color2 = 0;
			g_globals->_sceneText._color3 = 0;
		}

		g_globals->_sceneText.setup(msg);
		if (centerText) {
			g_globals->_sceneText.setPosition(Common::Point(
				g_globals->_sceneManager._scene->_sceneBounds.left + textRect.left,
				g_globals->_sceneManager._scene->_sceneBounds.top + textRect.top), 0);
		} else {
			g_globals->_sceneText.setPosition(pos, 0);
		}

		g_globals->_sceneText.fixPriority(255);

		// In Return to Ringworld, if in voice mode only, don't show the text
		if ((g_vm->getGameID() == GType_Ringworld2) && (R2_GLOBALS._speechSubtitles & SPEECH_VOICE)
				&& !(R2_GLOBALS._speechSubtitles & SPEECH_TEXT))
			g_globals->_sceneText.hide();

		g_globals->_sceneObjects->draw();
	}

	// For Return to Ringworld, play the voice overs in sequence
	if ((g_vm->getGameID() == GType_Ringworld2) && (R2_GLOBALS._speechSubtitles & SPEECH_VOICE)
			&& !playList.empty()) {
		R2_GLOBALS._playStream.play(*playList.begin(), NULL);
		playList.pop_front();
	}

	// Unless the flag is set to keep the message on-screen, show it until a mouse or keypress, then remove it
	if (!keepOnscreen && !msg.empty()) {
		Event event;

		// Keep event on-screen until a mouse or keypress
		while (!g_vm->shouldQuit() && !g_globals->_events.getEvent(event,
				EVENT_BUTTON_DOWN | EVENT_KEYPRESS)) {
			GLOBALS._screenSurface.updateScreen();
			g_system->delayMillis(10);

			if ((g_vm->getGameID() == GType_Ringworld2) && (R2_GLOBALS._speechSubtitles & SPEECH_VOICE)) {
				// Allow the play stream to do processing
				R2_GLOBALS._playStream.dispatch();
				if (!R2_GLOBALS._playStream.isPlaying()) {
					// Check if there are further voice samples to play
					if (!playList.empty()) {
						R2_GLOBALS._playStream.play(*playList.begin(), NULL);
						playList.pop_front();
					} else if (!(R2_GLOBALS._speechSubtitles & SPEECH_TEXT)) {
						// If not showing text, don't both waiting for a click to end
						break;
					}
				}
			}
		}

		if (g_vm->getGameID() == GType_Ringworld2)
			R2_GLOBALS._playStream.stop();

		g_globals->_sceneText.remove();
	}

	if ((g_vm->getGameID() != GType_Ringworld) && (g_vm->getGameID() != GType_Ringworld2) 
			&& T2_GLOBALS._uiElements._active) {
		// Show user interface
		T2_GLOBALS._uiElements.show();

		// Re-show the cursor
		BF_GLOBALS._events.setCursor(BF_GLOBALS._events.getCursor());
	}
}

void SceneItem::display2(int resNum, int lineNum) {
	switch (g_vm->getGameID()) {
	case GType_BlueForce:
		display(resNum, lineNum, SET_WIDTH, 312,
			SET_X, 4 + GLOBALS._sceneManager._scene->_sceneBounds.left,
			SET_Y, GLOBALS._sceneManager._scene->_sceneBounds.top + UI_INTERFACE_Y + 2,
			SET_FONT, 4, SET_BG_COLOR, 1, SET_FG_COLOR, 19, SET_EXT_BGCOLOR, 9,
			SET_EXT_FGCOLOR, 13, LIST_END);
		break;
	case GType_Ringworld2:
		display(resNum, lineNum, SET_WIDTH, 280, SET_X, 160, SET_Y, 20, SET_POS_MODE, ALIGN_CENTER,
			SET_EXT_BGCOLOR, 60, LIST_END);
		break;
	default:
		display(resNum, lineNum, SET_WIDTH, 200, SET_EXT_BGCOLOR, 7, LIST_END);
		break;
	}
}

void SceneItem::display(const Common::String &msg) {
	assert(g_vm->getGameID() == GType_BlueForce);

	display(-1, -1, msg.c_str(),
		SET_WIDTH, 312,
		SET_X, 4 + GLOBALS._sceneManager._scene->_sceneBounds.left,
		SET_Y, GLOBALS._sceneManager._scene->_sceneBounds.top + UI_INTERFACE_Y + 2,
		SET_FONT, 4, SET_BG_COLOR, 1, SET_FG_COLOR, 19, SET_EXT_BGCOLOR, 9,
		SET_EXT_FGCOLOR, 13, LIST_END);
}

/*--------------------------------------------------------------------------*/

SceneHotspot::SceneHotspot(): SceneItem() {
	_lookLineNum = _useLineNum = _talkLineNum = 0;
	_resNum = 0;
}

void SceneHotspot::synchronize(Serializer &s) {
	SceneItem::synchronize(s);

	if (g_vm->getGameID() == GType_Ringworld2) {
		// In R2R, the following fields were moved into the SceneItem class
		s.syncAsSint16LE(_resNum);
		s.syncAsSint16LE(_lookLineNum);
		s.syncAsSint16LE(_useLineNum);
		s.syncAsSint16LE(_talkLineNum);
	}
}

bool SceneHotspot::startAction(CursorType action, Event &event) {
	switch (g_vm->getGameID()) {
	case GType_BlueForce: {
		BlueForce::SceneExt *scene = (BlueForce::SceneExt *)BF_GLOBALS._sceneManager._scene;
		assert(scene);
		return scene->display(action);
	}
	case GType_Ringworld2: {
		switch (action) {
		case CURSOR_LOOK:
			if (_lookLineNum != -1) {
				SceneItem::display2(_resNum, _lookLineNum);
				return true;
			}
			break;
		case CURSOR_USE:
			if (_useLineNum != -1) {
				SceneItem::display2(_resNum, _useLineNum);
				return true;
			}
			break;
		case CURSOR_TALK:
			if (_talkLineNum != -1) {
				SceneItem::display2(_resNum, _talkLineNum);
				return true;
			}
			break;
		default:
			break;
		}

		return ((Ringworld2::SceneExt *)GLOBALS._sceneManager._scene)->display(action, event);
	}
	default:
		return SceneItem::startAction(action, event);
	}
}

void SceneHotspot::doAction(int action) {
	switch ((int)action) {
	case CURSOR_LOOK:
		if (g_vm->getGameID() == GType_BlueForce)
			SceneItem::display(LOOK_SCENE_HOTSPOT);
		else
			display(1, 0, SET_Y, 20, SET_WIDTH, 200, SET_EXT_BGCOLOR, 7, LIST_END);
		break;
	case CURSOR_USE:
		if (g_vm->getGameID() == GType_BlueForce)
			SceneItem::display(USE_SCENE_HOTSPOT);
		else
			display(1, 5, SET_Y, 20, SET_WIDTH, 200, SET_EXT_BGCOLOR, 7, LIST_END);
		break;
	case CURSOR_TALK:
		if (g_vm->getGameID() == GType_BlueForce)
			SceneItem::display(TALK_SCENE_HOTSPOT);
		else
			display(1, 15, SET_Y, 20, SET_WIDTH, 200, SET_EXT_BGCOLOR, 7, LIST_END);
		break;
	case CURSOR_WALK:
		break;
	default:
		if (g_vm->getGameID() == GType_BlueForce)
			SceneItem::display(DEFAULT_SCENE_HOTSPOT);
		else
			display(2, action, SET_Y, 20, SET_WIDTH, 200, SET_EXT_BGCOLOR, 7, LIST_END);
		break;
	}
}

void SceneHotspot::setDetails(int ys, int xs, int ye, int xe, const int resnum, const int lookLineNum, const int useLineNum) {
	setBounds(ys, xe, ye, xs);
	_resNum = resnum;
	_lookLineNum = lookLineNum;
	_useLineNum = useLineNum;
	_talkLineNum = -1;
	g_globals->_sceneItems.addItems(this, NULL);
}

void SceneHotspot::setDetails(const Rect &bounds, int resNum, int lookLineNum, int talkLineNum, int useLineNum, int mode, SceneItem *item) {
	setBounds(bounds);
	_resNum = resNum;
	_lookLineNum = lookLineNum;
	_talkLineNum = talkLineNum;
	_useLineNum = useLineNum;

	switch (mode) {
	case 2:
		g_globals->_sceneItems.push_front(this);
		break;
	case 4:
		g_globals->_sceneItems.addBefore(item, this);
		break;
	case 5:
		g_globals->_sceneItems.addAfter(item, this);
		break;
	default:
		g_globals->_sceneItems.push_back(this);
		break;
	}
}

void SceneHotspot::setDetails(int sceneRegionId, int resNum, int lookLineNum, int talkLineNum, int useLineNum, int mode) {
	_sceneRegionId = sceneRegionId;
	_resNum = resNum;
	_lookLineNum = lookLineNum;
	_talkLineNum = talkLineNum;
	_useLineNum = useLineNum;

	// Handle adding hotspot to scene items list as necessary
	switch (mode) {
	case 2:
		GLOBALS._sceneItems.push_front(this);
		break;
	case 3:
		break;
	default:
		GLOBALS._sceneItems.push_back(this);
		break;
	}
}

void SceneHotspot::setDetails(int resNum, int lookLineNum, int talkLineNum, int useLineNum, int mode, SceneItem *item) {
	_resNum = resNum;
	_lookLineNum = lookLineNum;
	_talkLineNum = talkLineNum;
	_useLineNum = useLineNum;

	switch (mode) {
	case 2:
		g_globals->_sceneItems.push_front(this);
		break;
	case 4:
		g_globals->_sceneItems.addBefore(item, this);
		break;
	case 5:
		g_globals->_sceneItems.addAfter(item, this);
		break;
	default:
		g_globals->_sceneItems.push_back(this);
		break;
	}
}

void SceneHotspot::setDetails(int resNum, int lookLineNum, int talkLineNum, int useLineNum) {
	_resNum = resNum;
	_lookLineNum = lookLineNum;
	_talkLineNum = talkLineNum;
	_useLineNum = useLineNum;
}

/*--------------------------------------------------------------------------*/

void SceneObjectWrapper::setSceneObject(SceneObject *so) {
	_sceneObject = so;
	so->_strip = 1;
	so->_flags |= OBJFLAG_PANES;
}

void SceneObjectWrapper::synchronize(Serializer &s) {
	EventHandler::synchronize(s);
	SYNC_POINTER(_sceneObject);
}

void SceneObjectWrapper::remove() {
	delete this;
}

void SceneObjectWrapper::dispatch() {
	if (g_vm->getGameID() == GType_Ringworld)
		check();
}

void SceneObjectWrapper::check() {
	_visageImages.setVisage(_sceneObject->_visage);
	int visageCount = _visageImages.getFrameCount();
	int angle = _sceneObject->_angle;
	int strip = _sceneObject->_strip;

	if (visageCount == 4) {
		if ((angle > 314) || (angle < 45))
			strip = 4;
		if ((angle > 44) && (angle < 135))
			strip = 1;
		if ((angle >= 135) && (angle < 225))
			strip = 3;
		if ((angle >= 225) && (angle < 315))
			strip = 2;
	} else if (visageCount == 8) {
		if ((angle > 330) || (angle < 30))
			strip = 4;
		if ((angle >= 30) && (angle < 70))
			strip = 7;
		if ((angle >= 70) && (angle < 110))
			strip = 1;
		if ((angle >= 110) && (angle < 150))
			strip = 5;
		if ((angle >= 150) && (angle < 210))
			strip = 3;
		if ((angle >= 210) && (angle < 250))
			strip = 6;
		if ((angle >= 250) && (angle < 290))
			strip = 2;
		if ((angle >= 290) && (angle < 331))
			strip = 8;
	}

	if (strip > visageCount)
		strip = visageCount;

	_sceneObject->setStrip(strip);
}

/*--------------------------------------------------------------------------*/

SceneObject::SceneObject() : SceneHotspot() {
	_endAction = NULL;
	_mover = NULL;
	_objectWrapper = NULL;
	_flags = 0;
	_walkStartFrame = 0;
	_animateMode = ANIM_MODE_NONE;
	_updateStartFrame = 0;
	_moveDiff.x = 5;
	_moveDiff.y = 3;
	_numFrames = 10;
	_moveRate = 10;
	_regionBitList = 0;
	_sceneRegionId = 0;
	_percent = 100;
	_flags |= OBJFLAG_PANES;
	_priority = 0;

	_frameChange = 0;
	_visage = 0;
	_strip = 0;
	_frame = 0;
	_effect = EFFECT_NONE;
	_shade = _oldShade = 0;
	_linkedActor = NULL;

	_field8A = Common::Point(0, 0);
	_angle = 0;
	_xs = 0;
	_xe = 0;
	_endFrame = 0;
	_field68 = 0;
	_regionIndex = 0;
	_field9C = NULL;
}

SceneObject::SceneObject(const SceneObject &so) : SceneHotspot() {
	*this = so;
	if (_objectWrapper)
		// Create a fresh object wrapper for this object
		_objectWrapper = new SceneObjectWrapper();
}

SceneObject::~SceneObject() {
	delete _mover;
	delete _objectWrapper;
}

int SceneObject::getNewFrame() {
	int frameNum = _frame + _frameChange;

	if (_frameChange > 0) {
		if (frameNum > getFrameCount()) {
			frameNum = 1;
			if (_animateMode == ANIM_MODE_1)
				++frameNum;
		}
	} else if (frameNum < 1) {
		frameNum = getFrameCount();
	}

	return frameNum;
}

int SceneObject::getFrameCount() {
	_visageImages.setVisage(_visage, _strip);
	return _visageImages.getFrameCount();
}

void SceneObject::animEnded() {
	_animateMode = ANIM_MODE_NONE;
	if (_endAction) {
		Action *endAction = _endAction;
		if (g_vm->getGameID() == GType_Ringworld2)
			_endAction = NULL;

		endAction->signal();
	}
}

int SceneObject::changeFrame() {
	int frameNum = _frame;
	uint32 mouseCtr = g_globals->_events.getFrameNumber();

	if ((_updateStartFrame <= mouseCtr) || (_animateMode == ANIM_MODE_1)) {
		if (_numFrames > 0) {
			int v = 60 / _numFrames;
			_updateStartFrame = mouseCtr + v;

			frameNum = getNewFrame();
		}
	}

	return frameNum;
}

void SceneObject::setPosition(const Common::Point &p, int yDiff) {
	_position = p;
	_yDiff = yDiff;
	_flags |= OBJFLAG_PANES;
}

void SceneObject::setZoom(int percent) {
	assert((percent >= -1) && (percent < 999));
	if (percent != _percent) {
		_percent = percent;
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::updateZoom() {
	changeZoom(_percent);
}

void SceneObject::changeZoom(int percent) {
	if (percent == -1)
		_flags &= ~OBJFLAG_ZOOMED;
	else {
		_flags |= OBJFLAG_ZOOMED;
		setZoom(percent);
	}
}

void SceneObject::setStrip(int stripNum) {
	if (stripNum != _strip) {
		_strip = stripNum;
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::setStrip2(int stripNum) {
	if (stripNum == -1)
		_flags &= ~OBJFLAG_SUPPRESS_DISPATCH;
	else {
		_flags |= OBJFLAG_SUPPRESS_DISPATCH;
		setStrip(stripNum);
	}
}

void SceneObject::setFrame(int frameNum) {
	if (frameNum != _frame) {
		_frame = frameNum;
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::setFrame2(int frameNum) {
	if (frameNum != -1) {
		_flags |= OBJFLAG_NO_UPDATES;
		setFrame(frameNum);
	} else {
		_flags &= ~OBJFLAG_NO_UPDATES;
	}
}

void SceneObject::setPriority(int priority) {
	if (priority != _priority) {
		_priority = priority;
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::fixPriority(int priority) {
	if (priority == -1) {
		_flags &= ~OBJFLAG_FIXED_PRIORITY;
	} else {
		_flags |= OBJFLAG_FIXED_PRIORITY;
		setPriority(priority);
	}
}

void SceneObject::setVisage(int visage) {
	if (visage != _visage) {
		_visage = visage;
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::setObjectWrapper(SceneObjectWrapper *objWrapper) {
	if (_objectWrapper)
		_objectWrapper->remove();
	_objectWrapper = objWrapper;
	if (objWrapper)
		objWrapper->setSceneObject(this);
}

void SceneObject::addMover(ObjectMover *mover, ...) {
	if (_mover)
		_mover->remove();
	_mover = mover;

	if (mover) {
		// Set up the assigned mover
		_walkStartFrame = g_globals->_events.getFrameNumber();
		if (_moveRate != 0)
			_walkStartFrame = 60 / _moveRate;

		// Signal the mover that movement is beginning
		va_list va;
		va_start(va, mover);
		mover->startMove(this, va);
		va_end(va);
	}
}

void SceneObject::getHorizBounds() {
	Rect tempRect;

	GfxSurface frame = getFrame();
	tempRect.resize(frame, _position.x, _position.y - _yDiff, _percent);

	_xs = tempRect.left;
	_xe = tempRect.right;
}

int SceneObject::getRegionIndex() {
	return g_globals->_sceneRegions.indexOf(_position);
}

int SceneObject::checkRegion(const Common::Point &pt) {
	Rect tempRect;
	int regionIndex = 0;

	// Temporarily change the position
	Common::Point savedPos = _position;
	_position = pt;

	int regIndex = g_globals->_sceneRegions.indexOf(pt);
	if (_regionBitList & (1 << regIndex))
		regionIndex = regIndex;

	// Restore position
	_position = savedPos;

	// Get the object's frame bounds
	GfxSurface frame = getFrame();
	tempRect.resize(frame, _position.x, _position.y - _yDiff, _percent);

	int yPos, newY;
	if ((_position.y - _yDiff) <= (pt.y - _yDiff)) {
		yPos = _position.y - _yDiff;
		newY = pt.y;
	} else {
		yPos = pt.y - _yDiff;
		newY = _position.y;
	}
	newY -= _yDiff;

	SynchronizedList<SceneObject *>::iterator i;
	for (i = g_globals->_sceneObjects->begin(); (regionIndex == 0) && (i != g_globals->_sceneObjects->end()); ++i) {
		if ((*i) && ((*i)->_flags & OBJFLAG_CHECK_REGION)) {
			int objYDiff = (*i)->_position.y - _yDiff;
			if ((objYDiff >= yPos) && (objYDiff <= newY) &&
				((*i)->_xs < tempRect.right) && ((*i)->_xe > tempRect.left)) {
				// Found index
				regionIndex = (*i)->_regionIndex;
				break;
			}
		}
	}

	return regionIndex;
}

void SceneObject::animate(AnimateMode animMode, ...) {
	_animateMode = animMode;
	_updateStartFrame = g_globals->_events.getFrameNumber();
	if (_numFrames)
		_updateStartFrame += 60 / _numFrames;

	va_list va;
	va_start(va, animMode);

	switch (_animateMode) {
	case ANIM_MODE_NONE:
		_endAction = NULL;
		break;

	case ANIM_MODE_1:
		_frameChange = 1;
		_field2E = _position;
		_endAction = 0;
		break;

	case ANIM_MODE_2:
		_frameChange = 1;
		_endAction = NULL;
		break;

	case ANIM_MODE_3:
		_frameChange = -1;
		_endAction = NULL;
		break;

	case ANIM_MODE_4:
		_endFrame = va_arg(va, int);
		_frameChange = va_arg(va, int);
		_endAction = va_arg(va, Action *);
		if (_endFrame == _frame)
			setFrame(getNewFrame());
		break;

	case ANIM_MODE_5:
		_frameChange = 1;
		_endFrame = getFrameCount();
		_endAction = va_arg(va, Action *);
		if (_endFrame == _frame)
			setFrame(getNewFrame());
		break;

	case ANIM_MODE_6:
		_frameChange = -1;
		_endAction = va_arg(va, Action *);
		_endFrame = 1;
		if (_frame == _endFrame)
			setFrame(getNewFrame());
		break;

	case ANIM_MODE_7:
		_endFrame = va_arg(va, int);
		_endAction = va_arg(va, Action *);
		_frameChange = 1;
		break;

	case ANIM_MODE_8:
	case ANIM_MODE_9:
		if (_animateMode == ANIM_MODE_9 && g_vm->getGameID() == GType_Ringworld2) {
			_frameChange = -1;
			_field2E = _position;
		} else {
			_field68 = va_arg(va, int);
			_endAction = va_arg(va, Action *);
			_frameChange = 1;
			_endFrame = getFrameCount();
			if (_frame == _endFrame)
				setFrame(getNewFrame());
		}
		break;
	}
	va_end(va);
}

SceneObject *SceneObject::clone() const {
	SceneObject *obj = new SceneObject(*this);
	return obj;
}

void SceneObject::copy(SceneObject *src) {
	*this = *src;

	_objectWrapper = NULL;
	_mover = NULL;
	_endAction = NULL;
}

void SceneObject::checkAngle(const SceneObject *obj) {
	checkAngle(obj->_position);
}

void SceneObject::checkAngle(const Common::Point &pt) {
	int angleAmount = GfxManager::getAngle(_position, pt);
	if (angleAmount != -1) {
		_angle = angleAmount;

		if (_animateMode == ANIM_MODE_9)
			_angle = (angleAmount + 180) % 360;
	}

	if (_objectWrapper && (g_vm->getGameID() == GType_Ringworld))
		_objectWrapper->dispatch();
}

void SceneObject::hide() {
	_flags |= OBJFLAG_HIDE;
	if (_flags & OBJFLAG_HIDING)
		_flags |= OBJFLAG_PANES;
}

void SceneObject::show() {
	if (_flags & OBJFLAG_HIDE) {
		_flags &= ~OBJFLAG_HIDE;
		_flags |= OBJFLAG_PANES;
	}
}

int SceneObject::getSpliceArea(const SceneObject *obj) {
	int xd = ABS(_position.x - obj->_position.x);
	int yd = ABS(_position.y - obj->_position.y);

	return (xd * xd + yd) / 2;
}

void SceneObject::synchronize(Serializer &s) {
	SceneHotspot::synchronize(s);

	s.syncAsUint32LE(_updateStartFrame);
	s.syncAsUint32LE(_walkStartFrame);
	s.syncAsSint16LE(_field2E.x); s.syncAsSint16LE(_field2E.y);
	s.syncAsSint16LE(_percent);
	s.syncAsSint16LE(_priority);
	s.syncAsSint16LE(_angle);
	s.syncAsUint32LE(_flags);
	s.syncAsSint16LE(_xs);
	s.syncAsSint16LE(_xe);
	_paneRects[0].synchronize(s);
	_paneRects[1].synchronize(s);
	s.syncAsSint32LE(_visage);
	SYNC_POINTER(_objectWrapper);
	s.syncAsSint32LE(_strip);
	SYNC_ENUM(_animateMode, AnimateMode);
	s.syncAsSint32LE(_frame);
	s.syncAsSint32LE(_endFrame);
	s.syncAsSint32LE(_field68);
	s.syncAsSint32LE(_frameChange);
	s.syncAsSint32LE(_numFrames);
	s.syncAsSint32LE(_regionIndex);
	SYNC_POINTER(_mover);
	s.syncAsSint16LE(_moveDiff.x); s.syncAsSint16LE(_moveDiff.y);
	s.syncAsSint32LE(_moveRate);
	if (g_vm->getGameID() == GType_Ringworld2) {
		s.syncAsSint16LE(_field8A.x);
		s.syncAsSint16LE(_field8A.y);
	}
	SYNC_POINTER(_endAction);
	s.syncAsUint32LE(_regionBitList);

	if (g_vm->getGameID() == GType_Ringworld2) {
		s.syncAsSint16LE(_effect);
		s.syncAsSint16LE(_shade);
		s.syncAsSint16LE(_oldShade);
		SYNC_POINTER(_linkedActor);
	}
}

void SceneObject::postInit(SceneObjectList *OwnerList) {
	if (!OwnerList)
		OwnerList = g_globals->_sceneObjects;

	bool isExisting = OwnerList->contains(this); 
	if (!isExisting || ((_flags & OBJFLAG_REMOVE) != 0)) {
		_percent = 100;
		_priority = 255;
		_flags = OBJFLAG_ZOOMED;
		_visage = 0;
		_strip = 1;
		_frame = 1;
		_objectWrapper = NULL;
		_animateMode = ANIM_MODE_NONE;
		_endAction = 0;
		_mover = NULL;
		_yDiff = 0;
		_moveDiff.x = 5;
		_moveDiff.y = 3;
		_moveRate = 10;
		_regionIndex = 0x40;
		_numFrames = 10;
		_regionBitList = 0;

		if (!isExisting)
			OwnerList->push_back(this);
		_flags |= OBJFLAG_PANES;
	}
}

void SceneObject::remove() {
	SceneItem::remove();
	if (g_globals->_sceneObjects->contains(this))
		// For objects in the object list, flag the object for removal in the next drawing, so that
		// the drawing code has a chance to restore the area previously covered by the object
		_flags |= OBJFLAG_PANES | OBJFLAG_REMOVE | OBJFLAG_HIDE;
	else
		// Not in the list, so immediately remove the object
		removeObject();
}

void SceneObject::dispatch() {
	if (g_vm->getGameID() == GType_Ringworld2) {
		if (_shade != _oldShade)
			_flags |= OBJFLAG_PANES;
		_oldShade = _shade;
	}

	uint32 currTime = g_globals->_events.getFrameNumber();
	if (_action)
		_action->dispatch();

	if (_mover && (_walkStartFrame <= currTime)) {
		if (_moveRate) {
			int frameInc = 60 / _moveRate;
			_walkStartFrame = currTime + frameInc;
		}
		_mover->dispatch();
	}

	if (!(_flags & OBJFLAG_NO_UPDATES)) {
		switch (_animateMode) {
		case ANIM_MODE_1:
			if (isNoMover())
				setFrame(1);
			else if ((_field2E.x != _position.x) || (_field2E.y != _position.y)) {
				setFrame(changeFrame());
				_field2E = _position;

			}
			break;

		case ANIM_MODE_2:
		case ANIM_MODE_3:
			setFrame(changeFrame());

			break;
		case ANIM_MODE_4:
		case ANIM_MODE_5:
		case ANIM_MODE_6:
			if (_frame == _endFrame)
				animEnded();
			else
				setFrame(changeFrame());
			break;

		case ANIM_MODE_7:
			if (changeFrame() != _frame) {
				// Pick a new random frame
				int frameNum = 0;
				do {
					int count = getFrameCount();
					frameNum = g_globals->_randomSource.getRandomNumber(count - 1);
				} while (frameNum == _frame);

				setFrame(frameNum);
				if (_endFrame) {
					if (--_endFrame == 0)
						animEnded();
				}
			}
			break;

		case ANIM_MODE_8:
			if (_frame == _endFrame) {
				if (_frameChange != -1) {
					_frameChange = -1;
					_endFrame = 1;

					setFrame(changeFrame());
				} else if (!_field68 || (--_field68 > 0)) {
					_frameChange = 1;
					_endFrame = getFrameCount();

					setFrame(changeFrame());
				} else {
					animEnded();
				}
			} else {
				setFrame(changeFrame());
			}
			break;

		case ANIM_MODE_9:
			if (_frame == _endFrame) {
				if (_frameChange != -1) {
					_frameChange = -1;
					_strip = ((_strip - 1) ^ 1) + 1;
					_endFrame = 1;
				} else if ((_field68 == 0) || (--_field68 != 0)) {
					_frameChange = 1;
					_endFrame = getFrameCount();

					setFrame(changeFrame());
				} else {
					animEnded();
				}
			} else {
				setFrame(changeFrame());
			}
			break;

		default:
			break;
		}
	}

	// Handle updating the zoom and/or priority
	if (!(_flags & OBJFLAG_ZOOMED)) {
		int yp = CLIP((int)_position.y, 0, 255);
		setZoom(g_globals->_sceneManager._scene->_zoomPercents[yp]);
	}
	if (!(_flags & OBJFLAG_FIXED_PRIORITY)) {
		setPriority(_position.y);
	}

	if (g_vm->getGameID() == GType_Ringworld2) {
		if (_linkedActor) {
			_linkedActor->setPosition(_position);
			_linkedActor->setStrip(_strip);
			_linkedActor->setFrame(_frame);
		}

		int regionIndex = getRegionIndex();
		if ((_effect == EFFECT_SHADED) && (regionIndex < 11))
			_shade = regionIndex;
	}
}

void SceneObject::calcAngle(const Common::Point &pt) {
	int newAngle = GfxManager::getAngle(_position, pt);
	if (newAngle != -1)
		_angle = newAngle;
}

void SceneObject::removeObject() {
	g_globals->_sceneItems.remove(this);
	g_globals->_sceneObjects->remove(this);

	if (_objectWrapper) {
		_objectWrapper->remove();
		_objectWrapper = NULL;
	}
	if (_mover) {
		_mover->remove();
		_mover = NULL;
	}
	if (_flags & OBJFLAG_CLONED)
		// Cloned temporary object, so delete it
		delete this;
}

GfxSurface SceneObject::getFrame() {
	_visageImages.setVisage(_visage, _strip);
	GfxSurface frame = _visageImages.getFrame(_frame);

	// If shading is needed, post apply the shadiing onto the frame
	if ((g_vm->getGameID() == GType_Ringworld2) && (_shade >= 1)) {
		Graphics::Surface s = frame.lockSurface();
		byte *p = (byte *)s.getPixels();
		byte *endP = p + s.w * s.h;
		
		while (p < endP) {
			if (*p != frame._transColor)
				*p = R2_GLOBALS._fadePaletteMap[_shade - 1][*p];
			++p;
		}

		frame.unlockSurface();
	}

	return frame;
}

void SceneObject::reposition() {
	GfxSurface frame = getFrame();
	_bounds.resize(frame, _position.x, _position.y - _yDiff, _percent);
	_xs = _bounds.left;
	_xe = _bounds.right;
}

/**
 * Draws an object into the scene
 */
void SceneObject::draw() {
	Rect destRect = _bounds;
	destRect.translate(-g_globals->_sceneManager._scene->_sceneBounds.left,
		-g_globals->_sceneManager._scene->_sceneBounds.top);
	Region *priorityRegion = g_globals->_sceneManager._scene->_priorities.find(_priority);
	GfxSurface frame = getFrame();
	g_globals->gfxManager().copyFrom(frame, destRect, priorityRegion);
}

/**
 * Refreshes the background around the area of a scene object prior to it's being redrawn,
 * in case it is moving
 */
void SceneObject::updateScreen() {
	Rect srcRect = _paneRects[CURRENT_PANENUM];
	const Rect &sceneBounds = g_globals->_sceneManager._scene->_sceneBounds;
	srcRect.left = (srcRect.left / 4) * 4;
	srcRect.right = ((srcRect.right + 3) / 4) * 4;
	srcRect.clip(g_globals->_sceneManager._scene->_sceneBounds);

	if (g_vm->getGameID() != GType_Ringworld) {
		if (T2_GLOBALS._uiElements._visible)
			srcRect.bottom = MIN<int16>(srcRect.bottom, T2_GLOBALS._interfaceY);
	}

	if (srcRect.isValidRect()) {
		Rect destRect  = srcRect;
		destRect.translate(-sceneBounds.left, -sceneBounds.top);
		srcRect.translate(-g_globals->_sceneOffset.x, -g_globals->_sceneOffset.y);

		g_globals->_screenSurface.copyFrom(g_globals->_sceneManager._scene->_backSurface, srcRect, destRect);
	}
}

void SceneObject::updateAngle(const Common::Point &pt) {
	checkAngle(pt);
	if (_objectWrapper)
		_objectWrapper->check();
}

void SceneObject::changeAngle(int angle) {
	_angle = angle;
	if (_objectWrapper)
		_objectWrapper->check();
}

void SceneObject::setup(int visage, int stripFrameNum, int frameNum, int posX, int posY, int priority) {
	postInit();
	setVisage(visage);
	setStrip(stripFrameNum);
	setFrame(frameNum);
	setPosition(Common::Point(posX, posY), 0);
	fixPriority(priority);
}

void SceneObject::setup(int visage, int stripFrameNum, int frameNum) {
	if (g_vm->getGameID() != GType_Ringworld2)
		postInit();

	setVisage(visage);
	setStrip(stripFrameNum);
	setFrame(frameNum);
}

/*--------------------------------------------------------------------------*/

void BackgroundSceneObject::postInit(SceneObjectList *OwnerList) {
	SceneObjectList dummyList;
	SceneObjectList *pList = !g_globals->_sceneManager._scene ? &dummyList :
		&g_globals->_sceneManager._scene->_bgSceneObjects;

	SceneObject::postInit(pList);
}

void BackgroundSceneObject::draw() {
	assert(g_globals->_sceneManager._scene);
	Rect destRect = _bounds;
	destRect.translate(-g_globals->_sceneManager._scene->_sceneBounds.left,
		-g_globals->_sceneManager._scene->_sceneBounds.top);
	Region *priorityRegion = g_globals->_sceneManager._scene->_priorities.find(_priority);
	GfxSurface frame = getFrame();
	g_globals->_sceneManager._scene->_backSurface.copyFrom(frame, destRect, priorityRegion);
}

SceneObject *BackgroundSceneObject::clone() const {
	BackgroundSceneObject *obj = new BackgroundSceneObject(*this);
	return obj;
}

void BackgroundSceneObject::setup2(int visage, int stripFrameNum, int frameNum, int posX, int posY, int priority, int effect) {
	// Check if the given object is already in the background object list
	if (R2_GLOBALS._sceneManager._scene->_bgSceneObjects.contains(this)) {
		_flags |= OBJFLAG_REMOVE;

		// Clone the item
		SceneObject *obj = clone();
		obj->_flags |= OBJFLAG_CLONED;
		R2_GLOBALS._sceneManager._scene->_bgSceneObjects.push_back(obj);

		_flags |= ~OBJFLAG_REMOVE;
	}

	postInit();
	setVisage(visage);
	setStrip(stripFrameNum);
	setFrame(frameNum);
	setPosition(Common::Point(posX, posY));
	fixPriority(priority);
}

void BackgroundSceneObject::copySceneToBackground() {
	GLOBALS._sceneManager._scene->_backSurface.copyFrom(g_globals->gfxManager().getSurface(), 0, 0);

	// WORKAROUND: Since savegames don't store the active screen data, once we copy the 
	// foreground objects to the background, we have to prevent the scene being saved.
	if (g_vm->getGameID() == GType_Ringworld2)
		((Ringworld2::SceneExt *)GLOBALS._sceneManager._scene)->_preventSaving = true;
}

/*--------------------------------------------------------------------------*/

void SceneObjectList::draw() {
	Common::Array<SceneObject *> objList;
	int paneNum = 0;
	int xAmount = 0, yAmount = 0;

	if (_objList.size() == 0) {
		// Alternate draw mode

		if (g_globals->_paneRefreshFlag[paneNum] == 1) {
			// Load the background
			g_globals->_sceneManager._scene->refreshBackground(0, 0);

			Rect tempRect = g_globals->_sceneManager._scene->_sceneBounds;
			tempRect.translate(-g_globals->_sceneOffset.x, -g_globals->_sceneOffset.y);
			ScenePalette::changeBackground(tempRect, g_globals->_sceneManager._fadeMode);
		} else {
			g_globals->_paneRegions[CURRENT_PANENUM].draw();
		}

		g_globals->_paneRegions[CURRENT_PANENUM].setRect(0, 0, 0, 0);
		g_globals->_sceneManager.fadeInIfNecessary();

	} else {
		// If there is a scroll follower, check whether it has moved off-screen
		if (g_globals->_scrollFollower) {
			const Rect &scrollerRect = g_globals->_sceneManager._scrollerRect;
			Common::Point objPos(
				g_globals->_scrollFollower->_position.x - g_globals->_sceneManager._scene->_sceneBounds.left,
				g_globals->_scrollFollower->_position.y - g_globals->_sceneManager._scene->_sceneBounds.top);
			int loadCount = 0;

			if (objPos.x >= scrollerRect.right) {
				xAmount = 8;
				loadCount = 20;
			}
			if (objPos.x < scrollerRect.left) {
				xAmount = -8;
				loadCount = 20;
			}
			if (objPos.y >= scrollerRect.bottom) {
				yAmount = 2;
				loadCount = 25;
			}
			if (objPos.y < scrollerRect.top) {
				yAmount = -2;
				loadCount = 25;
			}

			if (loadCount > 0)
				g_globals->_sceneManager.setBgOffset(Common::Point(xAmount, yAmount), loadCount);
		}

		if (g_globals->_sceneManager._sceneLoadCount > 0) {
			--g_globals->_sceneManager._sceneLoadCount;
			g_globals->_sceneManager._scene->loadBackground(g_globals->_sceneManager._sceneBgOffset.x,
				g_globals->_sceneManager._sceneBgOffset.y);
		}

		// Set up the flag mask
		uint32 flagMask = (paneNum == 0) ? OBJFLAG_PANE_0 : OBJFLAG_PANE_1;

		// Initial loop to set up object list and update object position, priority, and flags
		for (SynchronizedList<SceneObject *>::iterator i = g_globals->_sceneObjects->begin();
				i != g_globals->_sceneObjects->end(); ++i) {
			SceneObject *obj = *i;
			objList.push_back(obj);

			if (!(obj->_flags & OBJFLAG_HIDE))
				obj->_flags &= ~OBJFLAG_HIDING;

			// Reposition the bounds of the object to match the desired position
			obj->reposition();

			// Handle updating object priority
			if (!(obj->_flags & OBJFLAG_FIXED_PRIORITY)) {
				obj->_priority = MIN((int)obj->_position.y,
					(int)g_globals->_sceneManager._scene->_backgroundBounds.bottom - 1);
			}

			if ((g_globals->_paneRefreshFlag[paneNum] != 0) || !g_globals->_paneRegions[paneNum].empty()) {
				obj->_flags |= flagMask;
			}
		}

		// Check for any intersections, and then sort the object list by priority
		checkIntersection(objList, objList.size(), CURRENT_PANENUM);
		sortList(objList);

		if (g_globals->_paneRefreshFlag[paneNum] == 1) {
			// Load the background
			g_globals->_sceneManager._scene->refreshBackground(0, 0);
		}

		g_globals->_sceneManager._scene->_sceneBounds.left &= ~3;
		g_globals->_sceneManager._scene->_sceneBounds.right &= ~3;
		g_globals->_sceneOffset.x &= ~3;

		if (g_globals->_paneRefreshFlag[paneNum] != 0) {
			// Change the background
			Rect tempRect = g_globals->_sceneManager._scene->_sceneBounds;
			tempRect.translate(-g_globals->_sceneOffset.x, -g_globals->_sceneOffset.y);
			ScenePalette::changeBackground(tempRect, g_globals->_sceneManager._fadeMode);
		} else {
			for (uint objIndex = 0; objIndex < objList.size(); ++objIndex) {
				SceneObject *obj = objList[objIndex];

				if ((obj->_flags & flagMask) && obj->_paneRects[paneNum].isValidRect())
					obj->updateScreen();
			}

			g_globals->_paneRegions[paneNum].draw();
		}

		g_globals->_paneRegions[paneNum].setRect(0, 0, 0, 0);

		// FIXME: Currently, removing objects causes screen flickers when the removed object intersects
		// another drawn object, since the background is briefly redrawn over the object. For now, I'm
		// using a forced jump back to redraw objects. In the long term, I should figure out how the
		// original game does this properly
		bool redrawFlag = true;
		while (redrawFlag) {
			redrawFlag = false;

			// Main draw loop
			for (uint objIndex = 0; objIndex < objList.size(); ++objIndex) {
				SceneObject *obj = objList[objIndex];

				if ((obj->_flags & flagMask) && !(obj->_flags & OBJFLAG_HIDE)) {
					obj->_paneRects[paneNum] = obj->_bounds;
					obj->draw();
				}
			}

			// Update the palette
			g_globals->_sceneManager.fadeInIfNecessary();
			g_globals->_sceneManager._loadMode = 0;
			g_globals->_paneRefreshFlag[paneNum] = 0;

			// Loop through the object list, removing any objects and refreshing the screen as necessary
			for (uint objIndex = 0; objIndex < objList.size() && !redrawFlag; ++objIndex) {
				SceneObject *obj = objList[objIndex];

				if (obj->_flags & OBJFLAG_HIDE)
					obj->_flags |= OBJFLAG_HIDING;
				obj->_flags &= ~flagMask;
				if (obj->_flags & OBJFLAG_REMOVE) {
					obj->_flags |= OBJFLAG_PANES;

					checkIntersection(objList, objIndex, CURRENT_PANENUM);

					obj->updateScreen();
					obj->removeObject();

					objList.remove_at(objIndex);
					redrawFlag = true;
				}
			}
		}
	}
}

void SceneObjectList::checkIntersection(Common::Array<SceneObject *> &ObjList, uint ObjIndex, int PaneNum) {
	uint32 flagMask = (PaneNum == 0) ? OBJFLAG_PANE_0 : OBJFLAG_PANE_1;
	SceneObject *obj = (ObjIndex == ObjList.size()) ? NULL : ObjList[ObjIndex];
	Rect rect1;

	for (uint idx = 0; idx < ObjList.size(); ++idx) {
		SceneObject *currObj = ObjList[idx];

		if (ObjIndex == ObjList.size()) {
			if (currObj->_flags & flagMask)
				checkIntersection(ObjList, idx, PaneNum);
		} else if (idx != ObjIndex) {
			Rect &paneRect = obj->_paneRects[PaneNum];
			Rect objBounds = currObj->_bounds;
			if (paneRect.isValidRect())
				objBounds.extend(paneRect);

			Rect objBounds2 = currObj->_bounds;
			if (paneRect.isValidRect())
				objBounds2.extend(paneRect);

			objBounds.left &= ~3;
			objBounds.right += 3;
			objBounds.right &= ~3;
			objBounds2.left &= ~3;
			objBounds2.right += 3;
			objBounds2.right &= ~3;

			if (objBounds.intersects(objBounds2) && !(currObj->_flags & flagMask)) {
				currObj->_flags |= flagMask;
				checkIntersection(ObjList, idx, PaneNum);
			}
		}
	}
}

struct SceneObjectLess {
	bool operator()(const SceneObject *x, const SceneObject *y) const {
		if (y->_priority > x->_priority)
			return true;
		else if ((y->_priority == x->_priority) && (y->_position.y > x->_position.y))
			return true;
		else if ((y->_priority == x->_priority) && (y->_position.y == x->_position.y) &&
				 (y->_yDiff > x->_yDiff))
			return true;

		return false;
	}
};

void SceneObjectList::sortList(Common::Array<SceneObject *> &ObjList) {
	Common::sort(ObjList.begin(), ObjList.end(), SceneObjectLess());
}

void SceneObjectList::activate() {
	SceneObjectList *objectList = g_globals->_sceneObjects;
	g_globals->_sceneObjects = this;
	g_globals->_sceneObjects_queue.push_front(this);

	// Flag all the objects as modified
	SynchronizedList<SceneObject *>::iterator i;
	for (i = begin(); i != end(); ++i) {
		(*i)->_flags |= OBJFLAG_PANES;
	}

	// Replicate all existing objects on the old object list
	for (i = objectList->begin(); i != objectList->end(); ++i) {
		SceneObject *sceneObj = (*i)->clone();
		sceneObj->_flags |= OBJFLAG_HIDE | OBJFLAG_REMOVE | OBJFLAG_CLONED;
		push_front(sceneObj);
	}
}

void SceneObjectList::deactivate() {
	if (g_globals->_sceneObjects_queue.size() <= 1)
		return;

	SceneObjectList *objectList = *g_globals->_sceneObjects_queue.begin();
	g_globals->_sceneObjects_queue.pop_front();
	g_globals->_sceneObjects = *g_globals->_sceneObjects_queue.begin();

	SynchronizedList<SceneObject *>::iterator i;
	for (i = objectList->begin(); i != objectList->end(); ++i) {
		if (!((*i)->_flags & OBJFLAG_CLONED)) {
			SceneObject *sceneObj = (*i)->clone();
			sceneObj->_flags |= OBJFLAG_HIDE | OBJFLAG_REMOVE | OBJFLAG_CLONED;
			g_globals->_sceneObjects->push_front(sceneObj);
		}
	}
}

void SceneObjectList::synchronize(Serializer &s) {
	if (s.getVersion() >= 2)
		SavedObject::synchronize(s);
	_objList.synchronize(s);
}

/*--------------------------------------------------------------------------*/

SceneText::SceneText() : SceneObject() {
	_fontNumber = 2;
	_width = 160;
	_textMode = ALIGN_LEFT;
	_color1 = 0;
	_color2 = 0;
	_color3 = 0;
}

SceneText::~SceneText() {
}

void SceneText::setup(const Common::String &msg) {
	GfxManager gfxMan(_textSurface);
	gfxMan.activate();
	Rect textRect;

	if ((g_vm->getGameID() != GType_Ringworld) && g_globals->_sceneObjects->contains(this) &&
			(_flags & OBJFLAG_REMOVE)) {
		// Trying to setup a SceneText scheduled to be removed, so remove it now
		_bounds.expandPanes();
		this->removeObject();
		g_globals->_sceneObjects->remove(this);
	}

	gfxMan._font.setFontNumber(_fontNumber);
	gfxMan._font._colors.foreground = _color1;
	gfxMan._font._colors2.background = _color2;
	gfxMan._font._colors2.foreground = _color3;

	gfxMan.getStringBounds(msg.c_str(), textRect, _width);
	_bounds.setWidth(textRect.width());
	_bounds.setHeight(textRect.height());

	// Set up a new blank surface to hold the text
	_textSurface.create(textRect.width(), textRect.height());
	_textSurface._transColor = 0xff;
	_textSurface.fillRect(textRect, _textSurface._transColor);

	// Write the text to the surface
	gfxMan._bounds = textRect;
	gfxMan._font.writeLines(msg.c_str(), textRect, _textMode);

	// Do post-init, which adds this SceneText object to the scene
	postInit();
	gfxMan.deactivate();
}

void SceneText::synchronize(Serializer &s) {
	SceneObject::synchronize(s);

	s.syncAsSint16LE(_fontNumber);
	s.syncAsSint16LE(_width);
	s.syncAsSint16LE(_color1);
	s.syncAsSint16LE(_color2);
	s.syncAsSint16LE(_color3);
	SYNC_ENUM(_textMode, TextAlign);

	if (s.getVersion() >= 5)
		_textSurface.synchronize(s);
}

void SceneText::updateScreen() {
	// FIXME: Hack for Blue Force to handle not refreshing the screen if the user interface
	// has been re-activated after showing some scene text
	if ((g_vm->getGameID() == GType_Ringworld) || (_bounds.top < UI_INTERFACE_Y) ||
			!T2_GLOBALS._uiElements._visible)
		SceneObject::updateScreen();
}

/*--------------------------------------------------------------------------*/

Visage::Visage() {
	_resNum = -1;
	_rlbNum = -1;
	_data = NULL;
	_flipHoriz = false;
	_flipVert = false;
}

Visage::Visage(const Visage &v) {
	_resNum = v._resNum;
	_rlbNum = v._rlbNum;
	_data = v._data;
	if (_data)
		g_vm->_memoryManager.incLocks(_data);
	_flipHoriz = false;
	_flipVert = false;
}

Visage &Visage::operator=(const Visage &s) {
	_resNum = s._resNum;
	_rlbNum = s._rlbNum;
	_data = s._data;
	if (_data)
		g_vm->_memoryManager.incLocks(_data);

	return *this;
}

void Visage::setVisage(int resNum, int rlbNum) {
	if ((_resNum != resNum) || (_rlbNum != rlbNum)) {
		_resNum = resNum;
		_rlbNum = rlbNum;
		DEALLOCATE(_data);

		if (g_vm->getGameID() == GType_Ringworld) {
			// In Ringworld, we immediately get the data
			_data = g_resourceManager->getResource(RES_VISAGE, resNum, rlbNum);
		} else {
			// Games after Ringworld have an extra indirection via the visage index file
			byte *indexData = g_resourceManager->getResource(RES_VISAGE, resNum, 9999);
			if (rlbNum == 9999) {
				_data = indexData;
			} else {
				if (rlbNum == 0)
					rlbNum = 1;

				// Check how many slots there are
				uint16 count = READ_LE_UINT16(indexData);
				if (rlbNum > count)
					rlbNum = count;

				// Get the flags/rlbNum to use
				uint32 v = READ_LE_UINT32(indexData + (rlbNum - 1) * 4 + 2);
				int flags = v >> 30;

				if (flags & 3) {
					rlbNum = (int)(v & 0xff);
				}
				_flipHoriz = flags & 1;
				_flipVert = flags & 2;

				_data = g_resourceManager->getResource(RES_VISAGE, resNum, rlbNum);

				DEALLOCATE(indexData);
			}
		}

		assert(_data);
	}
}

Visage::~Visage() {
	DEALLOCATE(_data);
}

GfxSurface Visage::getFrame(int frameNum) {
	int numFrames = READ_LE_UINT16(_data);
	if (frameNum > numFrames)
		frameNum = numFrames;
	if (frameNum > 0)
		--frameNum;

	int offset = READ_LE_UINT32(_data + 2 + frameNum * 4);
	byte *frameData = _data + offset;

	GfxSurface result = surfaceFromRes(frameData);
	if (_flipHoriz) flipHorizontal(result);
	if (_flipVert) flipVertical(result);

	return result;
}

int Visage::getFrameCount() const {
	return READ_LE_UINT16(_data);
}

void Visage::flipHorizontal(GfxSurface &gfxSurface) {
	Graphics::Surface s = gfxSurface.lockSurface();

	for (int y = 0; y < s.h; ++y) {
		// Flip the line
		byte *lineP = (byte *)s.getBasePtr(0, y);
		for (int x = 0; x < (s.w / 2); ++x)
			SWAP(lineP[x], lineP[s.w - x - 1]);
	}

	gfxSurface.unlockSurface();
}

void Visage::flipVertical(GfxSurface &gfxSurface) {
	Graphics::Surface s = gfxSurface.lockSurface();

	for (int y = 0; y < s.h / 2; ++y) {
		// Flip the lines1
		byte *line1P = (byte *)s.getBasePtr(0, y);
		byte *line2P = (byte *)s.getBasePtr(0, s.h - y - 1);

		for (int x = 0; x < s.w; ++x)
			SWAP(line1P[x], line2P[x]);
	}

	gfxSurface.unlockSurface();
}

/*--------------------------------------------------------------------------*/

Player::Player(): SceneObject() {
	_canWalk = false;
	_enabled = false;
	_uiEnabled = false;
	_field8C = 0;

	// Return to Ringworld specific fields
	_characterIndex = R2_NONE;

	for (int i = 0; i < MAX_CHARACTERS; ++i) {
		_characterScene[i] = 0;
		_characterStrip[i] = 0;
		_characterFrame[i] = 0;
		_oldCharacterScene[i] = 0;
	}
}

void Player::postInit(SceneObjectList *OwnerList) {
	SceneObject::postInit();

	_canWalk = true;
	_uiEnabled = true;
	_percent = 100;
	_field8C = 10;

	if  (g_vm->getGameID() != GType_Ringworld2)
	{
		_moveDiff.x = 4;
		_moveDiff.y = 2;
	}
	else
	{
		_moveDiff.x = 3;
		_moveDiff.y = 2;
		_effect = EFFECT_SHADED;
		_shade = 0;
		_linkedActor = NULL;

		setObjectWrapper(new SceneObjectWrapper());
		setPosition(_characterPos[_characterIndex]);
		setStrip(_characterStrip[_characterIndex]);
		setFrame(_characterFrame[_characterIndex]);
		_characterScene[_characterIndex] = GLOBALS._sceneManager._sceneNumber;
	}
}

void Player::disableControl() {
	_canWalk = false;
	g_globals->_events.setCursor(CURSOR_NONE);
	_enabled = false;

	if (g_vm->getGameID() != GType_Ringworld2) {
		_uiEnabled = false;

		if ((g_vm->getGameID() != GType_Ringworld) && T2_GLOBALS._uiElements._active)
			T2_GLOBALS._uiElements.hide();
	}
}

void Player::enableControl() {
	CursorType cursor;

	_canWalk = true;
	_enabled = true;
	if (g_vm->getGameID() != GType_Ringworld2)
		_uiEnabled = true;

	switch (g_vm->getGameID()) {
	case GType_BlueForce:
	case GType_Ringworld2:
		cursor = g_globals->_events.getCursor();
		g_globals->_events.setCursor(cursor);

		if (g_vm->getGameID() == GType_BlueForce && T2_GLOBALS._uiElements._active)
			T2_GLOBALS._uiElements.show();
		break;

	default:
		// Ringworld
		g_globals->_events.setCursor(CURSOR_WALK);

		switch (g_globals->_events.getCursor()) {
		case CURSOR_WALK:
		case CURSOR_LOOK:
		case CURSOR_USE:
		case CURSOR_TALK:
			g_globals->_events.setCursor(g_globals->_events.getCursor());
			break;
		default:
			g_globals->_events.setCursor(CURSOR_WALK);
			break;
		}
		break;
	}
}

void Player::disableControl(CursorType cursorId, CursorType objectId) {
	if (cursorId != -1)
		R2_GLOBALS._events.setCursor(cursorId);
	else if (objectId != CURSOR_NONE)
		R2_GLOBALS._events.setCursor(objectId);

	disableControl();
}

void Player::enableControl(CursorType cursorId, CursorType objectId) {
	enableControl();

	if (cursorId != -1)
		R2_GLOBALS._events.setCursor(cursorId);
	else if (objectId != CURSOR_NONE)
		R2_GLOBALS._events.setCursor(objectId);
}

void Player::process(Event &event) {
	if ((g_vm->getGameID() != GType_Ringworld) && _action)
		_action->process(event);

	if (!event.handled && (event.eventType == EVENT_BUTTON_DOWN) &&
			(g_globals->_events.getCursor() == CURSOR_WALK) && g_globals->_player._canWalk &&
			(_position != event.mousePos) && g_globals->_sceneObjects->contains(this)) {

		if ((g_vm->getGameID() != GType_Ringworld) && !BF_GLOBALS._player._enabled)
			return;

		PlayerMover *newMover = new PlayerMover();
		Common::Point destPos(event.mousePos.x + g_globals->_sceneManager._scene->_sceneBounds.left,
			event.mousePos.y + g_globals->_sceneManager._scene->_sceneBounds.top);

		addMover(newMover, &destPos, NULL);
		event.handled = true;
	}
}

void Player::synchronize(Serializer &s) {
	SceneObject::synchronize(s);

	s.syncAsByte(_canWalk);
	s.syncAsByte(_uiEnabled);
	s.syncAsSint16LE(_field8C);

	if (g_vm->getGameID() != GType_Ringworld)
		s.syncAsByte(_enabled);

	if (g_vm->getGameID() == GType_Ringworld2) {
		s.syncAsSint16LE(_characterIndex);
		for (int i = 0; i < MAX_CHARACTERS; ++i) {
			s.syncAsSint16LE(_characterScene[i]);
			s.syncAsSint16LE(_oldCharacterScene[i]);
			s.syncAsSint16LE(_characterPos[i].x);
			s.syncAsSint16LE(_characterPos[i].y);
			s.syncAsSint16LE(_characterStrip[i]);
			s.syncAsSint16LE(_characterFrame[i]);
		}
	}
}

/*--------------------------------------------------------------------------*/

Region::Region(int resNum, int rlbNum, ResourceType ctlType) {
	_regionId = rlbNum;

	byte *regionData = g_resourceManager->getResource(ctlType, resNum, rlbNum);
	assert(regionData);

	load(regionData);

	DEALLOCATE(regionData);
}

Region::Region(int regionId, const byte *regionData) {
	_regionId = regionId;
	load(regionData);
}

void Region::load(const byte *regionData) {
	// Set the region bounds
	_bounds.top = READ_LE_UINT16(regionData + 6);
	_bounds.left = READ_LE_UINT16(regionData + 8);
	_bounds.bottom = READ_LE_UINT16(regionData + 10);
	_bounds.right = READ_LE_UINT16(regionData + 12);

	// Special handling for small size regions
	_regionSize = READ_LE_UINT16(regionData);
	if (_regionSize == 14)
		// No line slices
		return;

	// Set up the line slices
	for (int y = 0; y < (_regionSize == 22 ? 1 : _bounds.height()); ++y) {
		int slicesCount = READ_LE_UINT16(regionData + 16 + y * 4);
		int slicesOffset = READ_LE_UINT16(regionData + 14 + y * 4);
		assert(slicesCount < 100);
		LineSliceSet sliceSet;
		sliceSet.load(slicesCount, regionData + 14 + slicesOffset);

		_ySlices.push_back(sliceSet);
	}
}

/**
 * Returns true if the given region contains the specified point
 * @param pt	Specified position
 */
bool Region::contains(const Common::Point &pt) {
	// First check if the point falls inside the overall bounding rectangle
	if (!_bounds.contains(pt) || _ySlices.empty())
		return false;

	// Get the correct Y line to use
	const LineSliceSet &line = getLineSlices(pt.y);

	// Loop through the horizontal slice list to see if the point falls in one
	for (uint idx = 0; idx < line.items.size(); ++idx) {
		if ((pt.x >= line.items[idx].xs) && (pt.x < line.items[idx].xe))
			return true;
	}

	return false;
}

/**
 * Returns true if the given region is empty
 */
bool Region::empty() const {
	return !_bounds.isValidRect() && (_regionSize == 14);
}

void Region::clear() {
	_bounds.set(0, 0, 0, 0);
	_regionId = 0;
	_regionSize = 0;
}

void Region::setRect(const Rect &r) {
	setRect(r.left, r.top, r.right, r.bottom);
}

void Region::setRect(int xs, int ys, int xe, int ye) {
	bool validRect = (ys < ye) && (xs < xe);
	_ySlices.clear();

	if (!validRect) {
		_regionSize = 14;
		_bounds.set(0, 0, 0, 0);
	} else {
		_regionSize = 22;
		_bounds.set(xs, ys, xe, ye);

		LineSliceSet sliceSet;
		sliceSet.load2(1, xs, xe);

		_ySlices.push_back(sliceSet);
	}
}

const LineSliceSet &Region::getLineSlices(int yp) {
	return _ySlices[(_regionSize == 22) ? 0 : yp - _bounds.top];
}

LineSliceSet Region::sectPoints(int yp, const LineSliceSet &sliceSet) {
	if ((yp < _bounds.top) || (yp >= _bounds.bottom))
		return LineSliceSet();

	const LineSliceSet &ySet = getLineSlices(yp);
	return mergeSlices(sliceSet, ySet);
}

LineSliceSet Region::mergeSlices(const LineSliceSet &set1, const LineSliceSet &set2) {
	LineSliceSet result;

	uint set1Index = 0, set2Index = 0;

	while ((set1Index < set1.items.size()) && (set2Index < set2.items.size())) {
		if (set1.items[set1Index].xe <= set2.items[set2Index].xs) {
			++set1Index;
		} else if (set2.items[set2Index].xe <= set1.items[set1Index].xs) {
			++set2Index;
		} else {
			bool set1Flag = set1.items[set1Index].xs >= set2.items[set2Index].xs;
			const LineSlice &slice = set1Flag ? set1.items[set1Index] : set2.items[set2Index];

			result.add(slice.xs, MIN(set1.items[set1Index].xe, set2.items[set2Index].xe));
			if (set1Flag)
				++set1Index;
			else
				++set2Index;
		}
	}

	return result;
}

/**
 * Copies the background covered by the given region to the screen surface
 */
void Region::draw() {
	Rect &sceneBounds = g_globals->_sceneManager._scene->_sceneBounds;

	for (int yp = sceneBounds.top; yp < sceneBounds.bottom; ++yp) {
		// Generate a line slice set
		LineSliceSet tempSet;
		tempSet.add(sceneBounds.left, sceneBounds.right);
		LineSliceSet newSet = sectPoints(yp, tempSet);

		// Loop through the calculated slices
		for (uint idx = 0; idx < newSet.items.size(); ++idx) {
			Rect rect1(newSet.items[idx].xs, yp, newSet.items[idx].xe, yp + 1);
			rect1.left &= ~3;
			rect1.right = (rect1.right + 3) & ~3;

			Rect rect2 = rect1;
			rect1.translate(-g_globals->_sceneOffset.x, -g_globals->_sceneOffset.y);
			rect2.translate(-sceneBounds.left, -sceneBounds.top);

			g_globals->gfxManager().getSurface().copyFrom(g_globals->_sceneManager._scene->_backSurface,
				rect1, rect2);
		}
	}
}

void Region::uniteLine(int yp, LineSliceSet &sliceSet) {
	// First expand the bounds as necessary to fit in the row
	if (_ySlices.empty()) {
		_bounds = Rect(sliceSet.items[0].xs, yp, sliceSet.items[sliceSet.items.size() - 1].xe, yp + 1);
		_ySlices.push_back(LineSliceSet());
	}
	while (yp < _bounds.top) {
		_ySlices.insert_at(0, LineSliceSet());
		--_bounds.top;
	}
	while (yp >= _bounds.bottom) {
		_ySlices.push_back(LineSliceSet());
		++_bounds.bottom;
	}

	// Merge the existing line set into the line
	LineSliceSet &destSet = _ySlices[yp - _bounds.top];
	for (uint srcIndex = 0; srcIndex < sliceSet.items.size(); ++srcIndex) {
		LineSlice &srcSlice = sliceSet.items[srcIndex];

		// Check if overlaps existing slices
		uint destIndex = 0;
		while (destIndex < destSet.items.size()) {
			LineSlice &destSlice = destSet.items[destIndex];
			if (((srcSlice.xs >= destSlice.xs) && (srcSlice.xs <= destSlice.xe)) ||
				((srcSlice.xe >= destSlice.xs) && (srcSlice.xe <= destSlice.xe)) ||
				((srcSlice.xs < destSlice.xs) && (srcSlice.xe > destSlice.xe))) {
				// Intersecting, so merge them
				destSlice.xs = MIN(srcSlice.xs, destSlice.xs);
				destSlice.xe = MAX(srcSlice.xe, destSlice.xe);
				break;
			}
			++destIndex;
		}
		if (destIndex == destSet.items.size()) {
			// No intersecting region found, so add it to the list
			destSet.items.push_back(srcSlice);
		}
	}

	// Check whether to expand the left/bounds bounds
	if (destSet.items[0].xs < _bounds.left)
		_bounds.left = destSet.items[0].xs;
	if (destSet.items[destSet.items.size() - 1].xe > _bounds.right)
		_bounds.right = destSet.items[destSet.items.size() - 1].xe;
}

void Region::uniteRect(const Rect &rect) {
	for (int yp = rect.top; yp < rect.bottom; ++yp) {
		LineSliceSet sliceSet;
		sliceSet.add(rect.left, rect.right);
		uniteLine(yp, sliceSet);
	}
}

/*--------------------------------------------------------------------------*/

void SceneRegions::load(int sceneNum) {
	clear();
	bool altRegions = g_vm->getFeatures() & GF_ALT_REGIONS;
	byte *regionData = g_resourceManager->getResource(RES_CONTROL, sceneNum, altRegions ? 1 : 9999, true);

	if (regionData) {
		int regionCount = READ_LE_UINT16(regionData);
		for (int regionCtr = 0; regionCtr < regionCount; ++regionCtr) {
			int regionId = READ_LE_UINT16(regionData + regionCtr * 6 + 2);

			if (altRegions) {
				// Load data from within this resource
				uint32 dataOffset = READ_LE_UINT32(regionData + regionCtr * 6 + 4);
				push_back(Region(regionId, regionData + dataOffset));
			} else {
				// Load region from a separate resource
				push_back(Region(sceneNum, regionId));
			}
		}

		DEALLOCATE(regionData);
	}
}

int SceneRegions::indexOf(const Common::Point &pt) {
	for (SceneRegions::iterator i = begin(); i != end(); ++i) {
		if ((*i).contains(pt))
			return (*i)._regionId;
	}

	return 0;
}

/*--------------------------------------------------------------------------*/

void SceneItemList::addItems(SceneItem *first, ...) {
	va_list va;
	va_start(va, first);

	SceneItem *p = first;
	while (p) {
		push_back(p);
		p = va_arg(va, SceneItem *);
	}
	va_end(va);
}

/*--------------------------------------------------------------------------*/

RegionSupportRec WalkRegion::_processList[PROCESS_LIST_SIZE];

void RegionSupportRec::process() {
	if (_xDiff < _yDiff) {
		_halfDiff += _xDiff;
		if (_halfDiff > _yDiff) {
			_halfDiff -= _yDiff;
			_xp += _xDirection;
		}
	} else {
		do {
			_xp += _xDirection;
			_halfDiff += _yDiff;
		} while (_halfDiff <= _xDiff);
		_halfDiff -= _xDiff;
	}
	--_yDiff2;
}

/*--------------------------------------------------------------------------*/

void WalkRegion::loadRegion(byte *dataP, int size) {
	// First clear the region
	clear();

	// Decode the data for the region
	int dataCount, regionHeight;
	loadProcessList(dataP, size, dataCount, regionHeight);

	int processIndex = 0, idx2 = 0, count;
	for (int yp = _processList[0]._yp; yp < regionHeight; ++yp) {
		process3(yp, dataCount, processIndex, idx2);
		process4(yp, processIndex, idx2, count);

		loadRecords(yp, count, processIndex);
	}
}

void WalkRegion::loadProcessList(byte *dataP, int dataSize, int &dataIndex, int &regionHeight) {
	dataIndex = 0;
	int x1 = READ_LE_UINT16(dataP + (dataSize - 1) * 4);
	int y1 = READ_LE_UINT16(dataP + (dataSize - 1) * 4 + 2);
	regionHeight = y1;

	for (int idx = 0; idx < dataSize; ++idx) {
		int xp = READ_LE_UINT16(dataP + idx * 4);
		int yp = READ_LE_UINT16(dataP + idx * 4 + 2);
		if (yp != y1) {
			/*
			 * Commented out: v doesn't seem to be used
			int v;
			if (idx == (dataSize - 1))
				v = READ_LE_UINT16(dataP + 2);
			else
				v = process1(idx, dataP, dataSize);
			*/
			process2(dataIndex, x1, y1, xp, yp);
			++dataIndex;
		}

		// Keep regionHeight as the maximum of any y
		if (yp > regionHeight)
			regionHeight = yp;

		x1 = xp;
		y1 = yp;
	}
}

int WalkRegion::process1(int idx, byte *dataP, int dataSize) {
	int idx2 = idx + 1;
	if (idx2 == dataSize)
		idx2 = 0;

	while (READ_LE_UINT16(dataP + idx2 * 4 + 2) == READ_LE_UINT16(dataP + idx * 4 + 2)) {
		if (idx2 == (dataSize - 1))
			idx2 = 0;
		else
			++idx2;
	}

	return READ_LE_UINT16(dataP + idx2 * 4 + 2);
}

void WalkRegion::process2(int dataIndex, int x1, int y1, int x2, int y2) {
	int xDiff = ABS(x2 - x1);
	int yDiff = ABS(y2 - y1);
	int halfDiff = MAX(xDiff, yDiff) / 2;
	int yMax = MIN(y1, y2);

	while (dataIndex && (_processList[dataIndex - 1]._yp > yMax)) {
		_processList[dataIndex] = _processList[dataIndex - 1];
		--dataIndex;
	}
	_processList[dataIndex]._yp = yMax;

	_processList[dataIndex]._xp = (y1 >= y2) ? x2 : x1;
	_processList[dataIndex]._xDiff = xDiff;
	_processList[dataIndex]._yDiff = yDiff;
	_processList[dataIndex]._halfDiff = halfDiff;

	int xTemp = (y1 >= y2) ? x1 - x2 : x2 - x1;
	_processList[dataIndex]._xDirection = (xTemp == 0) ? 0 : ((xTemp < 0) ? -1 : 1);
	_processList[dataIndex]._yDiff2 = yDiff;
}

void WalkRegion::process3(int yp, int dataCount, int &idx1, int &idx2) {
	while ((idx2 < (dataCount - 1)) && (_processList[idx2 + 1]._yp <= yp))
		++idx2;
	while (!_processList[idx1]._yDiff2)
		++idx1;
}

void WalkRegion::process4(int yp, int idx1, int idx2, int &count) {
	count = 0;
	for (int idx = idx1; idx <= idx2; ++idx) {
		if (_processList[idx]._yDiff2 > 0)
			++count;
		process5(idx, idx1);
	}
}

void WalkRegion::process5(int idx1, int idx2) {
	while ((idx1 > idx2) && (_processList[idx1 - 1]._xp > _processList[idx1]._xp)) {
		SWAP(_processList[idx1], _processList[idx1 - 1]);
		--idx1;
	}
}

void WalkRegion::loadRecords(int yp, int size, int processIndex) {
	LineSliceSet sliceSet;
	int sliceCount =  size / 2;

	for (int idx = 0; idx < sliceCount; ++idx, ++processIndex) {
		while (!_processList[processIndex]._yDiff2)
			++processIndex;

		int sliceXs = _processList[processIndex]._xp;
		_processList[processIndex].process();

		do {
			++processIndex;
		} while (!_processList[processIndex]._yDiff2);

		int sliceXe = _processList[processIndex]._xp;
		_processList[processIndex].process();

		sliceSet.items.push_back(LineSlice(sliceXs, sliceXe));
	}

	uniteLine(yp, sliceSet);
}

/*--------------------------------------------------------------------------*/

void WRField18::load(byte *data) {
	_pt1.x = READ_LE_UINT16(data);
	_pt1.y = READ_LE_UINT16(data + 2);
	_pt2.x = READ_LE_UINT16(data + 4);
	_pt2.y = READ_LE_UINT16(data + 6);
	_v = READ_LE_UINT16(data + 8);
}

/*--------------------------------------------------------------------------*/

void WalkRegions::clear() {
	_regionList.clear();
	_field18.clear();
	_idxList.clear();
	_idxList2.clear();
	_disabledRegions.clear();
}

void WalkRegions::load(int sceneNum) {
	clear();
	_resNum = sceneNum;

	if (g_vm->getFeatures() & GF_ALT_REGIONS) {
		loadRevised();
	} else {
		loadOriginal();
	}
}

/**
 * This version handles loading walk regions for Ringworld floppy version and Demo #1
 */
void WalkRegions::loadOriginal() {
	byte *regionData = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 1, true);
	if (!regionData) {
		// No data, so return
		_resNum = -1;
		return;
	}

	byte *dataP;
	int dataSize;

	// Load the field 18 list
	dataP = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 2);
	dataSize = g_vm->_memoryManager.getSize(dataP);
	assert(dataSize % 10 == 0);

	byte *p = dataP;
	for (int idx = 0; idx < (dataSize / 10); ++idx, p += 10) {
		WRField18 rec;
		rec.load(p);
		_field18.push_back(rec);
	}

	DEALLOCATE(dataP);

	// Load the idx list
	dataP = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 3);
	dataSize = g_vm->_memoryManager.getSize(dataP);
	assert(dataSize % 2 == 0);

	p = dataP;
	for (int idx = 0; idx < (dataSize / 2); ++idx, p += 2)
		_idxList.push_back(READ_LE_UINT16(p));

	DEALLOCATE(dataP);

	// Load the secondary idx list
	dataP = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 4);
	dataSize = g_vm->_memoryManager.getSize(dataP);
	assert(dataSize % 2 == 0);

	p = dataP;
	for (int idx = 0; idx < (dataSize / 2); ++idx, p += 2)
		_idxList2.push_back(READ_LE_UINT16(p));

	DEALLOCATE(dataP);

	// Handle the loading of the actual regions themselves
	dataP = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 5);

	byte *pWalkRegion = regionData + 16;
	byte *srcP = dataP;
	for (; (int16)READ_LE_UINT16(pWalkRegion) != -20000; pWalkRegion += 16) {
		WalkRegion wr;

		// Set the Walk region specific fields
		wr._pt.x = (int16)READ_LE_UINT16(pWalkRegion);
		wr._pt.y = (int16)READ_LE_UINT16(pWalkRegion + 2);
		wr._idxListIndex = READ_LE_UINT32(pWalkRegion + 4);
		wr._idxList2Index = READ_LE_UINT32(pWalkRegion + 8);

		// Read in the region data
		int size = READ_LE_UINT16(srcP);
		srcP += 2;
		wr.loadRegion(srcP, size);

		srcP += size * 4;
		_regionList.push_back(wr);
	}

	DEALLOCATE(dataP);
	DEALLOCATE(regionData);
}

/**
 * This version handles loading walk regions for Ringworld CD version and Demo #2. Given it's the newer
 * version, it may also be used by future game titles
 */
void WalkRegions::loadRevised() {
	byte *regionData = g_resourceManager->getResource(RES_WALKRGNS, _resNum, 2, true);
	if (!regionData) {
		// No data, so return
		_resNum = -1;
		return;
	}

	byte *data1P = regionData + READ_LE_UINT32(regionData);
	byte *data2P = regionData + READ_LE_UINT32(regionData + 4);
	byte *data3P = regionData + READ_LE_UINT32(regionData + 8);
	byte *data4P = regionData + READ_LE_UINT32(regionData + 12);
	byte *regionOffset = regionData + 16;
	int dataSize;

	// Load the field 18 list
	dataSize = READ_LE_UINT32(regionData + 8) - READ_LE_UINT32(regionData + 4);
	assert(dataSize % 10 == 0);

	byte *p = data2P;
	for (int idx = 0; idx < (dataSize / 10); ++idx, p += 10) {
		WRField18 rec;
		rec.load(p);
		_field18.push_back(rec);
	}

	// Load the idx list
	dataSize = READ_LE_UINT32(regionData + 12) - READ_LE_UINT32(regionData + 8);
	assert(dataSize % 2 == 0);

	p = data3P;
	for (int idx = 0; idx < (dataSize / 2); ++idx, p += 2)
		_idxList.push_back(READ_LE_UINT16(p));

	// Load the secondary idx list
	dataSize = READ_LE_UINT32(regionData + 16) - READ_LE_UINT32(regionData + 12);
	assert(dataSize % 2 == 0);

	p = data4P;
	for (int idx = 0; idx < (dataSize / 2); ++idx, p += 2)
		_idxList2.push_back(READ_LE_UINT16(p));

	// Handle the loading of the actual regions themselves
	byte *pWalkRegion = data1P + 16;
	for (; (int16)READ_LE_UINT16(pWalkRegion) != -20000; pWalkRegion += 16, regionOffset += 4) {
		WalkRegion wr;
		byte *srcP = regionData + READ_LE_UINT32(regionOffset);

		// Set the Walk region specific fields
		wr._pt.x = (int16)READ_LE_UINT16(pWalkRegion);
		wr._pt.y = (int16)READ_LE_UINT16(pWalkRegion + 2);
		wr._idxListIndex = READ_LE_UINT32(pWalkRegion + 4);
		wr._idxList2Index = READ_LE_UINT32(pWalkRegion + 8);

		// Read in the region data
		wr._regionId = 0;
		wr.load(srcP);

		_regionList.push_back(wr);
	}

	DEALLOCATE(regionData);
}

/**
 * Returns the index of the walk region that contains the given point
 * @param pt		Point to locate
 * @param indexList	List of region indexes that should be ignored
 */
int WalkRegions::indexOf(const Common::Point &pt, const Common::List<int> *indexList) {
	for (uint idx = 0; idx < _regionList.size(); ++idx) {
		if ((!indexList || !contains(*indexList, int(idx + 1))) && _regionList[idx].contains(pt))
			return idx + 1;
	}

	return -1;
}

void WalkRegions::synchronize(Serializer &s) {
	// Synchronize the list of disabled regions as a list of values terminated with a '-1'
	int regionId = 0;
	if (s.isLoading()) {
		_disabledRegions.clear();

		s.syncAsSint16LE(regionId);
		while (regionId != -1) {
			_disabledRegions.push_back(regionId);
			s.syncAsSint16LE(regionId);
		}
	} else {
		Common::List<int>::iterator i;
		for (i = _disabledRegions.begin(); i != _disabledRegions.end(); ++i) {
			regionId = *i;
			s.syncAsSint16LE(regionId);
		}

		regionId = -1;
		s.syncAsSint16LE(regionId);
	}
}

void WalkRegions::disableRegion(int regionId) {
	if (!contains(_disabledRegions, regionId))
		_disabledRegions.push_back(regionId);
}

void WalkRegions::enableRegion(int regionId) {
	_disabledRegions.remove(regionId);
}


/*--------------------------------------------------------------------------*/

void ScenePriorities::load(int resNum) {
	_resNum = resNum;
	clear();

	bool altMode = (g_vm->getFeatures() & GF_ALT_REGIONS) != 0;
	byte *regionData = g_resourceManager->getResource(RES_PRIORITY, resNum, altMode ? 1 : 9999, true);
	if (!regionData)
		return;

	int regionCount = READ_LE_UINT16(regionData);
	for (int regionCtr = 0; regionCtr < regionCount; ++regionCtr) {
		if (altMode) {
			// Region data is embedded within the resource
			uint16 regionId = READ_LE_UINT16(regionData + regionCtr * 6 + 2);
			uint32 dataOffset = READ_LE_UINT32(regionData + regionCtr * 6 + 4);
			push_back(Region(regionId, regionData + dataOffset));
		} else {
			// The data contains the index of another resource containing the region data
			int rlbNum = READ_LE_UINT16(regionData + regionCtr * 6 + 2);

			push_back(Region(resNum, rlbNum, RES_PRIORITY));
		}
	}

	DEALLOCATE(regionData);
}

Region *ScenePriorities::find(int priority) {
	// If no priority regions are loaded, then return the placeholder region
	if (empty()) {
		if (g_vm->getGameID() == GType_Ringworld)
			return &_defaultPriorityRegion;
		return NULL;
	}

	if (priority > 255)
		priority = 255;

	// Loop through the regions to find the closest for the given priority level
	int minRegionId = 9998;
	Region *region = NULL;
	for (ScenePriorities::iterator i = begin(); i != end(); ++i) {
		Region *r = &(*i);
		int regionId = r->_regionId;

		if ((regionId > priority) && (regionId < minRegionId)) {
			minRegionId = regionId;
			region = r;
		}
	}

	assert(region);
	return region;
}

/*--------------------------------------------------------------------------*/

void FloatSet::add(double v1, double v2, double v3) {
	_float1 += v1;
	_float2 += v2;
	_float3 += v3;
}

void FloatSet::proc1(double v) {
	double diff = (cos(v) * _float1) - (sin(v) * _float2);
	_float2 = (sin(v) * _float1) + (cos(v) * _float2);
	_float1 = diff;
}

double FloatSet::sqrt(FloatSet &floatSet) {
	double f1Diff = _float1 - floatSet._float1;
	double f2Diff = _float2 - floatSet._float2;
	double f3Diff = _float3 - floatSet._float3;

	return ::sqrt(f1Diff * f1Diff + f2Diff * f2Diff + f3Diff * f3Diff);
}

/*--------------------------------------------------------------------------*/

GameHandler::GameHandler() : EventHandler() {
	_nextWaitCtr = 1;
	_waitCtr.setCtr(1);
	_field14 = 10;
}

GameHandler::~GameHandler() {
	if (g_globals)
		g_globals->_game->removeHandler(this);
}

void GameHandler::execute() {
	if (_waitCtr.decCtr() == 0) {
		_waitCtr.setCtr(_nextWaitCtr);
		dispatch();
	}
}

void GameHandler::synchronize(Serializer &s) {
	if (s.getVersion() >= 2)
		EventHandler::synchronize(s);

	_lockCtr.synchronize(s);
	_waitCtr.synchronize(s);
	s.syncAsSint16LE(_nextWaitCtr);
	s.syncAsSint16LE(_field14);
}

/*--------------------------------------------------------------------------*/

SceneHandler::SceneHandler() {
	_saveGameSlot = -1;
	_loadGameSlot = -1;
	_prevFrameNumber = 0;
	_delayTicks = 0;
}

void SceneHandler::registerHandler() {
	postInit();
	g_globals->_game->addHandler(this);
}

uint32 SceneHandler::getFrameDifference() {
	return GLOBALS._events.getFrameNumber() - _prevFrameNumber;
}

void SceneHandler::postInit(SceneObjectList *OwnerList) {
	_delayTicks = 2;

	g_globals->_scenePalette.loadPalette(0);
	g_globals->_scenePalette.refresh();

	g_globals->_soundManager.postInit();
	g_globals->_soundManager.buildDriverList(true);
	g_globals->_soundManager.installConfigDrivers();

	g_globals->_game->start();
}

void SceneHandler::process(Event &event) {
	// Main keypress handler
	if (!event.handled) {
		g_globals->_game->processEvent(event);

		if (event.eventType == EVENT_KEYPRESS)
			g_globals->_events.setCursorFromFlag();
	}

	// Check for displaying right-click dialog
	if ((event.eventType == EVENT_BUTTON_DOWN) && (event.btnState == BTNSHIFT_RIGHT) &&
			g_globals->_player._uiEnabled &&
			((g_vm->getGameID() != GType_Ringworld2) || (R2_GLOBALS._sceneManager._sceneNumber != 1330))) {
		g_globals->_game->rightClick();

		event.handled = true;
		return;
	}

	// If there is an active scene, pass the event to it
	if (g_globals->_sceneManager._scene)
		g_globals->_sceneManager._scene->process(event);

	if (!event.handled) {
		// Separate check for F5 - Save key
		if ((event.eventType == EVENT_KEYPRESS) && (event.kbd.keycode == Common::KEYCODE_F5)) {
			// F5 - Save
			g_globals->_game->saveGame();
			event.handled = true;
			g_globals->_events.setCursorFromFlag();
		}

		// Check for debugger
		if ((event.eventType == EVENT_KEYPRESS) && (event.kbd.keycode == Common::KEYCODE_d) &&
			(event.kbd.flags & Common::KBD_CTRL)) {
			// Attach to the debugger
			g_vm->_debugger->attach();
			g_vm->_debugger->onFrame();
		}

		if ((event.eventType == EVENT_KEYPRESS) && g_globals->_player._enabled) {
			// Keyboard shortcuts for different actions
			switch (event.kbd.keycode) {
			case Common::KEYCODE_w:
				g_globals->_events.setCursor(GLOBALS._player._canWalk ? CURSOR_WALK : CURSOR_USE);
				event.handled = true;
				break;
			case Common::KEYCODE_l:
				g_globals->_events.setCursor(CURSOR_LOOK);
				event.handled = true;
				break;
			case Common::KEYCODE_u:
				g_globals->_events.setCursor(CURSOR_USE);
				event.handled = true;
				break;
			case Common::KEYCODE_t:
				g_globals->_events.setCursor(CURSOR_TALK);
				event.handled = true;
				break;
			default:
				break;
			}
		}

		// Mouse press handling
		bool enabled = (g_vm->getGameID() != GType_Ringworld) ? g_globals->_player._enabled :
			g_globals->_player._uiEnabled;
		if (enabled && (event.eventType == EVENT_BUTTON_DOWN) && !g_globals->_sceneItems.empty()) {
			// Check if the mouse is on the player
			if (g_globals->_player.contains(event.mousePos)) {
				playerAction(event);
				if (event.handled)
					return;
			}

			// Scan the item list to find one the mouse is within
			SynchronizedList<SceneItem *>::iterator i;
			for (i = g_globals->_sceneItems.begin(); i != g_globals->_sceneItems.end(); ++i) {
				SceneItem *item = *i;				
				if (item->contains(event.mousePos)) {
					// Pass the action to the item
					bool handled = item->startAction(g_globals->_events.getCursor(), event);
					if (!handled)
						// Item wasn't handled, keep scanning
						continue;

					if ((g_vm->getGameID() == GType_Ringworld) || (g_globals->_events.getCursor() == CURSOR_9999)) {
						event.handled = g_globals->_events.getCursor() != CURSOR_WALK;

						if (g_globals->_player._uiEnabled && g_globals->_player._canWalk &&
								(g_globals->_events.getCursor() != CURSOR_LOOK)) {
							g_globals->_events.setCursor(CURSOR_WALK);
						} else if (g_globals->_player._canWalk && (g_globals->_events.getCursor() != CURSOR_LOOK)) {
							g_globals->_events.setCursor(CURSOR_WALK);
						} else if (g_globals->_player._uiEnabled && (g_globals->_events.getCursor() != CURSOR_LOOK)) {
							g_globals->_events.setCursor(CURSOR_USE);
						}

						if (g_vm->getGameID() != GType_Ringworld)
							event.handled = true;
					} else if (g_vm->getGameID() != GType_Ringworld) {
						event.handled = true;
					}
					break;
				}
			}

			// Handle any fallback text display
			processEnd(event);
		}

		// Handle player processing
		g_globals->_player.process(event);
	}
}

void SceneHandler::dispatch() {
	// Handle game saving and loading
	if (_saveGameSlot != -1) {
		int saveSlot = _saveGameSlot;
		_saveGameSlot = -1;
		Common::Error err = g_saver->save(saveSlot, _saveName);
		// FIXME: Make use of the description string in err to enhance
		// the error reported to the user.
		if (err.getCode() != Common::kNoError)
			GUIErrorMessage(SAVE_ERROR_MSG);
	}
	if (_loadGameSlot != -1) {
		int priorSceneBeforeLoad = GLOBALS._sceneManager._previousScene;
		int currentSceneBeforeLoad = GLOBALS._sceneManager._sceneNumber;

		int loadSlot = _loadGameSlot;
		_loadGameSlot = -1;
		g_saver->restore(loadSlot);
		g_globals->_events.setCursorFromFlag();

		postLoad(priorSceneBeforeLoad, currentSceneBeforeLoad);
	}

	g_globals->_soundManager.dispatch();
	g_globals->_scenePalette.signalListeners();

	// Dispatch to any objects registered in the scene
	g_globals->_sceneObjects->recurse(SceneHandler::dispatchObject);

	// If a scene is active, then dispatch to it
	if (g_globals->_sceneManager._scene)
		g_globals->_sceneManager._scene->dispatch();

	// Not actually used
	//_eventListeners.forEach(SceneHandler::handleListener);

	// Handle pending events
	Event event;
	if (g_globals->_events.getEvent(event)) {
		// Process pending events
		do {
			process(event);
		} while (g_globals->_events.getEvent(event));
	} else if (g_vm->getGameID() != GType_Ringworld) {
		// For Blue Force, 'none' events need to be generated in the absence of any
		event.eventType = EVENT_NONE;
		event.mousePos = g_globals->_events._mousePos;
		process(event);
	}

	// Handle drawing the contents of the scene
	if ((g_vm->getGameID() != GType_Ringworld2) || (R2_GLOBALS._animationCtr == 0)) {
		if (g_globals->_sceneManager._scene)
			g_globals->_sceneObjects->draw();
	}

	// Check to see if any scene change is required
	g_globals->_sceneManager.checkScene();

	// Signal the ScummVM debugger
	g_vm->_debugger->onFrame();

	// Delay between frames
	g_globals->_events.delay(_delayTicks);
}

void SceneHandler::dispatchObject(EventHandler *obj) {
	obj->dispatch();
}

void SceneHandler::saveListener(Serializer &ser) {
}

} // End of namespace TsAGE