aboutsummaryrefslogtreecommitdiff
path: root/engines/tinsel/polygons.cpp
blob: 7fc7fcd218352b6174bc7e1ef8e5900be0bb4ea4 (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
/* 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.
 *
 * $URL$
 * $Id$
 */

#include "tinsel/actors.h"
#include "tinsel/font.h"
#include "tinsel/handle.h"
#include "tinsel/pcode.h"
#include "tinsel/pid.h"
#include "tinsel/polygons.h"
#include "tinsel/rince.h"
#include "tinsel/sched.h"
#include "common/serializer.h"
#include "tinsel/tinsel.h"
#include "tinsel/token.h"

#include "common/util.h"

namespace Tinsel {


//----------------- LOCAL DEFINES --------------------

/** different types of polygon */
enum POLY_TYPE {
	POLY_PATH, POLY_NPATH, POLY_BLOCK, POLY_REFER, POLY_EFFECT,
	POLY_EXIT, POLY_TAG
};

// Note 7/10/94, with adjacency reduction ANKHMAP max is 3, UNSEEN max is 4
// so reduced this back to 6 (from 12) for now.
#define MAXADJ	6	// Max number of known adjacent paths

struct POLYGON {

	PTYPE	polyType;	// Polygon type

	int	subtype;	// refer type in REFER polygons
				// NODE/NORMAL in PATH polygons

	int	pIndex;		// Index into compiled polygon data

	/*
	 * Data duplicated from compiled polygon data
	 */
	short	cx[4];		// Corners (clockwise direction)
	short	cy[4];
	int	polyID;

	/* For TAG polygons only */
	int tagFlags;
	SCNHANDLE hOverrideTag;

	/* For TAG and EXIT (and EFFECT in future?) polygons only   */
	TSTATE	tagState;
	PSTATE	pointState;

	/* For Path polygons only  */
	bool	tried;

	/*
	 * Internal derived data for speed and conveniance
	 * set up by FiddlyBit()
	 */
	short	ptop;		//
	short	pbottom;	// Enclosing external rectangle
	short	pleft;		//
	short	pright;		//

	short	ltop[4];	//
	short	lbottom[4];	// Rectangles enclosing each side
	short	lleft[4];	//
	short	lright[4];	//

	int	a[4];		// y1-y2       }
	int	b[4];		// x2-x1       } See IsInPolygon()
	long	c[4];		// y1x2 - x1y2 }

	/*
	 * Internal derived data for speed and conveniance
	 * set up by PseudoCentre()
	 */
	int	pcentrex;	// Pseudo-centre
	int	pcentrey;	//

	/**
	 * List of adjacent polygons. For Path polygons only.
	 * set up by SetPathAdjacencies()
	 */
	POLYGON *adjpaths[MAXADJ];

};
typedef POLYGON *PPOLYGON;

#define MAXONROUTE 40

#include "common/pack-start.h"	// START STRUCT PACKING

/** lineinfo struct - one per (node-1) in a node path */
struct LINEINFO {

	int32	a;
	int32	b;
	int32	c;

	int32	a2;             ///< a squared
	int32	b2;             ///< b squared
	int32	a2pb2;          ///< a squared + b squared
	int32	ra2pb2;         ///< root(a squared + b squared)

	int32	ab;
	int32	ac;
	int32	bc;
} PACKED_STRUCT;

#include "common/pack-end.h"	// END STRUCT PACKING

/**
 * POLY structure class. This is implemented as a class, because the structure
 * of POLY's changed between TINSEL v1 and v2.
 *
 * FIXME: Right now, we always read *all* data in a polygon, even if only a single
 * field is needed. This is rather inefficient.
 */
class Poly {
private:
	const byte * const  _pStart;
	const byte *_pData;
	int _recordSize;
	void nextPoly();

public:
	Poly(const byte *pSrc);
	Poly(const byte *pSrc, int startIndex);
	void operator++();
	void setIndex(int index);


	POLY_TYPE getType() const { return (POLY_TYPE)FROM_LE_32(type); }
	int getNodecount() const { return (int)FROM_LE_32(nodecount); }
	int getNodeX(int i) const { return (int)FROM_LE_32(nlistx[i]); }
	int getNodeY(int i) const { return (int)FROM_LE_32(nlisty[i]); }

	// get Inter-node line structure
	const LINEINFO *getLineinfo(int i) const { return ((const LINEINFO *)(_pStart + (int)FROM_LE_32(plinelist))) + i; }

protected:
	POLY_TYPE type;		///< type of polygon
public:
	int32 x[4], y[4];	// Polygon definition
	uint32 xoff, yoff;	// DW2 - polygon offset

	int32 tagx, tagy;	// } For tagged polygons
	SCNHANDLE hTagtext;	// } i.e. EXIT, TAG, EFFECT

	int32 nodex, nodey;	// EXIT, TAG, REFER
	SCNHANDLE hFilm;	///< film reel handle for EXIT, TAG

	int32 reftype;		///< Type of REFER

	int32 id;			// } EXIT and TAG

	int32 scale1, scale2;	// }
	int32 level1, level2;	// DW2 fields
	int32 bright1, bright2;	// DW2 fields
	int32 reel;			// } PATH and NPATH
	int32 zFactor;		// }

protected:
	int32 nodecount;		///<The number of nodes in this polygon
	int32 pnodelistx, pnodelisty;	///<offset in chunk to this array if present
	int32 plinelist;

	const int32 *nlistx;
	const int32 *nlisty;

public:
	SCNHANDLE hScript;	///< handle of code segment for polygon events
};

Poly::Poly(const byte *pSrc) : _pStart(pSrc) {
	_pData = pSrc;
	nextPoly();
	_recordSize = _pData - pSrc;
}

Poly::Poly(const byte *pSrc, int startIndex) : _pStart(pSrc)  {
	_pData = pSrc;
	nextPoly();
	_recordSize = _pData - pSrc;
	setIndex(startIndex);
}

void Poly::operator++() {
	nextPoly();
}

void Poly::setIndex(int index) {
	_pData = _pStart + index * _recordSize;
	nextPoly();
}

static uint32 nextLong(const byte *&p) {
	uint32 result = READ_UINT32(p);
	p += 4;
	return result;
}

void Poly::nextPoly() {
	// Note: For now we perform no endian conversion of the data. We could change that
	// at some point, and remove all endian conversions from the code that uses POLY's
	const byte *pRecord = _pData;

	int typeVal = nextLong(_pData);
	if ((FROM_LE_32(typeVal) == 5) && TinselV2)
		typeVal = TO_LE_32(6);
	type = (POLY_TYPE)typeVal;

	for (int i = 0; i < 4; ++i)
		x[i] = nextLong(_pData);
	for (int i = 0; i < 4; ++i)
		y[i] = nextLong(_pData);

	if (TinselV2) {
		xoff = nextLong(_pData);
		yoff = nextLong(_pData);
		id = nextLong(_pData);
		reftype = nextLong(_pData);
	}

	tagx = nextLong(_pData);
	tagy = nextLong(_pData);
	hTagtext = nextLong(_pData);
	nodex = nextLong(_pData);
	nodey = nextLong(_pData);
	hFilm = nextLong(_pData);

	if (!TinselV2) {
		reftype = nextLong(_pData);
		id = nextLong(_pData);
	}

	scale1 = nextLong(_pData);
	scale2 = nextLong(_pData);

	if (TinselV2) {
		level1 = nextLong(_pData);
		level2 = nextLong(_pData);
		bright1 = nextLong(_pData);
		bright2 = nextLong(_pData);
	}

	reel = nextLong(_pData);
	zFactor = nextLong(_pData);
	nodecount = nextLong(_pData);
	pnodelistx = nextLong(_pData);
	pnodelisty = nextLong(_pData);
	plinelist = nextLong(_pData);

	nlistx = (const int32 *)(_pStart + (int)FROM_LE_32(pnodelistx));
	nlisty = (const int32 *)(_pStart + (int)FROM_LE_32(pnodelisty));

	if (TinselV0)
		// Skip to the last 4 bytes of the record for the hScript value
		_pData = pRecord + 0x62C;

	hScript = nextLong(_pData);
}

//----------------- LOCAL GLOBAL DATA --------------------

static int MaxPolys = MAX_POLY;

static POLYGON *Polys[MAX_POLY+1];

static POLYGON *Polygons = 0;

static SCNHANDLE pHandle = 0;	// } Set at start of each scene
static int noofPolys = 0;		// }

static POLYGON extraBlock;	// Used for dynamic blocking

static int pathsOnRoute = 0;
static const POLYGON *RoutePaths[MAXONROUTE];

static POLYGON *RouteEnd = 0;

#ifdef DEBUG
int highestYet = 0;
#endif

// dead/alive, offsets
static POLY_VOLATILE volatileStuff[MAX_POLY];

//----------------- LOCAL MACROS --------------------

// The str parameter is no longer used
#define CHECK_HP_OR(mvar, str) assert((mvar >= 0 && mvar <= noofPolys) || mvar == MAX_POLY);
#define CHECK_HP(mvar, str)	assert(mvar >= 0 && mvar <= noofPolys);

//-------------------- METHODS ----------------------

static HPOLYGON PolygonIndex(const POLYGON *pp) {
	for (int i = 0; i <= MAX_POLY; ++i) {
		if (Polys[i] == pp)
			return i;
	}

	error("PolygonIndex(): polygon not found");
}

/**
 * Returns TRUE if the point is within the polygon supplied.
 *
 * Firstly, the point must be within the smallest imaginary rectangle
 * which encloses the polygon.
 *
 * Then, from each corner of the polygon, if the point is within an
 * imaginary rectangle enclosing the clockwise-going side from that
 * corner, the gradient of a line from the corner to the point must be
 * less than (or more negative than) the gradient of that side:
 *
 * If the corners' coordinates are designated (x1, y1) and (x2, y2), and
 * the point in question's (xt, yt), then:
 *     gradient (x1,y1)->(x2,y2) > gradient (x1,y1)->(xt,yt)
 *               (y1-y2)/(x2-x1) > (y1-yt)/(xt-x1)
 *               (y1-y2)*(xt-x1) > (y1-yt)*(x2-x1)
 *        xt(y1-y2) -x1y1 + x1y2 > -yt(x2-x1) + y1x2 - x1y1
 *         xt(y1-y2) + yt(x2-x1) > y1x2 - x1y2
 *
 * If the point passed one of the four 'side tests', and failed none,
 * then it must be within the polygon. If the point was not tested, it
 * may be within the internal rectangle not covered by the above tests.
 *
 * Most polygons contain an internal rectangle which does not fall into
 * any of the above side-related tests. Such a rectangle will always
 * have two polygon corners above it and two corners to the left of it.
 */
bool IsInPolygon(int xt, int yt, HPOLYGON hp) {
	const POLYGON *pp;
	int	i;
	bool BeenTested = false;
	int	pl = 0, pa = 0;

	CHECK_HP_OR(hp, "Out of range polygon handle (1)");
	pp = Polys[hp];
	assert(pp != NULL); // Testing whether in a NULL polygon

	// Shift cursor for relative polygons
	if (TinselV2) {
		xt -= volatileStuff[hp].xoff;
		yt -= volatileStuff[hp].yoff;
	}

	/* Is point within the external rectangle? */
	if (xt < pp->pleft || xt > pp->pright || yt < pp->ptop || yt > pp->pbottom)
		return false;

	// For each corner/side
	for (i = 0; i < 4; i++)	{
		// If within this side's 'testable' area
		// i.e. within the width of the line in y direction of end of line
		// or within the height of the line in x direction of end of line
		if ((xt >= pp->lleft[i] && xt <= pp->lright[i]  && ((yt > pp->cy[i]) == (pp->cy[(i+1)%4] > pp->cy[i])))
		 || (yt >= pp->ltop[i]  && yt <= pp->lbottom[i] && ((xt > pp->cx[i]) == (pp->cx[(i+1)%4] > pp->cx[i])))) {
			if (((long)xt*pp->a[i] + (long)yt*pp->b[i]) < pp->c[i])
				return false;
			else
				BeenTested = true;
		}
	}

	if (BeenTested) {
		// New dodgy code 29/12/94
		if (pp->polyType == BLOCK) {
			// For each corner/side
			for (i = 0; i < 4; i++) {
				// Pretend the corners of blocking polys are not in the poly.
				if (xt == pp->cx[i] && yt == pp->cy[i])
					return false;
			}
		}
		return true;
	} else {
		// Is point within the internal rectangle?
		for (i = 0; i < 4; i++) {
			if (pp->cx[i] < xt)
				pl++;
			if (pp->cy[i] < yt)
				pa++;
		}

		if (pa == 2 && pl == 2)
			return true;
		else
			return false;
	}
}

/**
 * Finds a polygon of the specified type containing the supplied point.
 */
HPOLYGON InPolygon(int xt, int yt, PTYPE type) {
	for (int j = 0; j <= MAX_POLY; j++)	{
		if (Polys[j] && Polys[j]->polyType == type) {
			if (IsInPolygon(xt, yt, j))
				return j;
		}
	}
	return NOPOLY;
}

/**
 * Given a blocking polygon, current co-ordinates of an actor, and the
 * co-ordinates of where the actor is heading, works out which corner of
 * the blocking polygon to head around.
 */

void BlockingCorner(HPOLYGON hp, int *x, int *y, int tarx, int tary) {
	const POLYGON *pp;
	int	i;
	int	xd, yd;		// distance per axis
	int	ThisD, SmallestD = 1000;
	int	D1, D2;
	int	NearestToHere = 1000, NearestToTarget;
	unsigned At = 10;	// Corner already at

	int	bcx[4], bcy[4];	// Bogus corners

	CHECK_HP_OR(hp, "Out of range polygon handle (2)");
	pp = Polys[hp];

	// Work out a point outside each corner
	for (i = 0; i < 4; i++)	{
		int	next, prev;

		// X-direction
		next = pp->cx[i] - pp->cx[(i+1)%4];
		prev = pp->cx[i] - pp->cx[(i+3)%4];
		if (next <= 0 && prev <= 0)
			bcx[i] = pp->cx[i] - 4;		// Both points to the right
		else if (next >= 0 && prev >= 0)
			bcx[i] = pp->cx[i] + 4;		// Both points to the left
		else
			bcx[i] = pp->cx[i];

		// Y-direction
		next = pp->cy[i] - pp->cy[(i+1)%4];
		prev = pp->cy[i] - pp->cy[(i+3)%4];
		if (next <= 0 && prev <= 0)
			bcy[i] = pp->cy[i] - 4;		// Both points below
		else if (next >= 0 && prev >= 0)
			bcy[i] = pp->cy[i] + 4;		// Both points above
		else
			bcy[i] = pp->cy[i];
	}

	// Find nearest corner to where we are,
	// but not the one we're stood at.

	for (i = 0; i < 4; i++) {		// For 4 corners
//		ThisD = ABS(*x - pp->cx[i]) + ABS(*y - pp->cy[i]);
		ThisD = ABS(*x - bcx[i]) + ABS(*y - bcy[i]);
		if (ThisD < SmallestD) {
			// Ignore this corner if it's not in a path
			if (InPolygon(pp->cx[i], pp->cy[i], PATH) == NOPOLY ||
			    InPolygon(bcx[i], bcy[i], PATH) == NOPOLY)
				continue;

			// Are we stood at this corner?
			if (ThisD > 4) {
				// No - it's the nearest we've found yet.
				NearestToHere = i;
				SmallestD = ThisD;
			} else {
				// Stood at/next to this corner
				At = i;
			}
		}
	}

	// If we're not already at a corner, go to the nearest corner

	if (At == 10) {
		// Not stood at a corner
//		assert(NearestToHere != 1000); // At blocking corner, not found near corner!
		// Better to give up than to assert fail!
		if (NearestToHere == 1000) {
			// Send it to where it is now
			// i.e. leave x and y alone
		} else {
			*x = bcx[NearestToHere];
			*y = bcy[NearestToHere];
		}
	} else {
		// Already at a corner. Go to an adjacent corner.
		// First, find out which adjacent corner is nearest the target.
			xd = ABS(tarx - pp->cx[(At + 1) % 4]);
			yd = ABS(tary - pp->cy[(At + 1) % 4]);
			D1 = xd + yd;
			xd = ABS(tarx - pp->cx[(At + 3) % 4]);
			yd = ABS(tary - pp->cy[(At + 3) % 4]);
			D2 = xd + yd;
			NearestToTarget = (D2 > D1) ? (At + 1) % 4 : (At + 3) % 4;
		if (NearestToTarget == NearestToHere) {
			*x = bcx[NearestToHere];
			*y = bcy[NearestToHere];
		} else {
			// Need to decide whether it's better to go to the nearest to
			// here and then on to the target, or to the nearest to the
			// target and on from there.
			xd = ABS(pp->cx[At] - pp->cx[NearestToHere]);
			D1 = xd;
			xd = ABS(pp->cx[NearestToHere] - tarx);
			D1 += xd;

			yd = ABS(pp->cy[At] - pp->cy[NearestToHere]);
			D1 += yd;
			yd = ABS(pp->cy[NearestToHere] - tary);
			D1 += yd;

			xd = ABS(pp->cx[At] - pp->cx[NearestToTarget]);
			D2 = xd;
			xd = ABS(pp->cx[NearestToTarget] - tarx);
			D2 += xd;

			yd = ABS(pp->cy[At] - pp->cy[NearestToTarget]);
			D2 += yd;
			yd = ABS(pp->cy[NearestToTarget] - tary);
			D2 += yd;

			if (D2 > D1) {
				*x = bcx[NearestToHere];
				*y = bcy[NearestToHere];
			} else {
				*x = bcx[NearestToTarget];
				*y = bcy[NearestToTarget];
			}
		}
	}
}


/**
 * Try do drop a perpendicular to each inter-node line from the point
 * and remember the shortest (if any).
 * Find which node is nearest to the point.
 * The shortest of these gives the best point in the node path.
*/
void FindBestPoint(HPOLYGON hp, int *x, int *y, int *pline) {
	const POLYGON *pp;

	int	dropD;		// length of perpendicular (i.e. distance of point from line)
	int	dropX, dropY;	// (X, Y) where dropped perpendicular intersects the line
	int	d1, d2;		// distance from perpendicular intersect to line's end nodes

	int	shortestD = 10000;	// Shortest distance found
	int	nearestL = -1;		// Nearest line
	int	nearestN;		// Nearest Node

	int	h = *x;		// For readability/conveniance
	int	k = *y;		//	- why aren't these #defines?

	CHECK_HP(hp, "Out of range polygon handle (3)");
	pp = Polys[hp];

	// Pointer to polygon data
	Poly ptp(LockMem(pHandle), pp->pIndex);	// This polygon

	// Look for fit of perpendicular to lines between nodes
	for (int i = 0; i < ptp.getNodecount() - 1; i++) {
		const LINEINFO *line = ptp.getLineinfo(i);

		const int32	a = (int)FROM_LE_32(line->a);
		const int32	b = (int)FROM_LE_32(line->b);
		const int32	c = (int)FROM_LE_32(line->c);

#if 1
		// TODO: If the comments of the LINEINFO struct are correct, then it contains mostly
		// duplicate data, probably in an effort to safe CPU cycles. Even on the slowest devices
		// we support, calculating a product of two ints is not an issue.
		// So we can just load & endian convert a,b,c, then replace stuff like
		//   (int)FROM_LE_32(line->ab)
		// by simply a*b, which makes it easier to understand what the code does, too.
		// Just in case there is some bugged data, I leave this code here for verifying it.
		// Let's leave it in for some time.
		//
		// One bad thing: We use sqrt to compute a square root. Might not be a good idea,
		// speed wise. Maybe we should take Vicent's fp_sqroot. But that's a problem for later.

		int32	a2 = (int)FROM_LE_32(line->a2);             ///< a squared
		int32	b2 = (int)FROM_LE_32(line->b2);             ///< b squared
		int32	a2pb2 = (int)FROM_LE_32(line->a2pb2);          ///< a squared + b squared
		int32	ra2pb2 = (int)FROM_LE_32(line->ra2pb2);         ///< root(a squared + b squared)

		int32	ab = (int)FROM_LE_32(line->ab);
		int32	ac = (int)FROM_LE_32(line->ac);
		int32	bc = (int)FROM_LE_32(line->bc);

		assert(a*a == a2);
		assert(b*b == b2);
		assert(a*b == ab);
		assert(a*c == ac);
		assert(b*c == bc);

		assert(a2pb2 == a*a + b*b);
		assert(ra2pb2 == (int)sqrt((float)a*a + (float)b*b));
#endif


		if (a == 0 && b == 0)
			continue;		// Line is just a point!

		// X position of dropped perpendicular intersection with line
		dropX = ((b*b * h) - (a*b * k) - a*c) / (a*a + b*b);

		// X distances from intersection to end nodes
		d1 = dropX - ptp.getNodeX(i);
		d2 = dropX - ptp.getNodeX(i+1);

		// if both -ve or both +ve, no fit
		if ((d1 < 0 && d2 < 0) || (d1 > 0 && d2 > 0))
			continue;
//#if 0
		// Y position of sidweays perpendicular intersection with line
		dropY = ((a*a * k) - (a*b * h) - b*c) / (a*a + b*b);

		// Y distances from intersection to end nodes
		d1 = dropY - ptp.getNodeY(i);
		d2 = dropY - ptp.getNodeY(i+1);

		// if both -ve or both +ve, no fit
		if ((d1 < 0 && d2 < 0) || (d1 > 0 && d2 > 0))
			continue;
//#endif
		dropD = ((a * h) + (b * k) + c) / (int)sqrt((float)a*a + (float)b*b);
		dropD = ABS(dropD);
		if (dropD < shortestD) {
			shortestD = dropD;
			nearestL = i;
		}
	}

	// Distance to nearest node
	nearestN = NearestNodeWithin(hp, h, k);
	dropD = ABS(h - ptp.getNodeX(nearestN)) + ABS(k - ptp.getNodeY(nearestN));

	// Go to a node or a point on a line
	if (dropD < shortestD) {
		// A node is nearest
		*x = ptp.getNodeX(nearestN);
		*y = ptp.getNodeY(nearestN);
		*pline = nearestN;
	} else {
		assert(nearestL != -1);

		// A point on a line is nearest
		const LINEINFO *line = ptp.getLineinfo(nearestL);
		const int32	a = (int)FROM_LE_32(line->a);
		const int32	b = (int)FROM_LE_32(line->b);
		const int32	c = (int)FROM_LE_32(line->c);
		dropX = ((b*b * h) - (a*b * k) - a*c) / (a*a + b*b);
		dropY = ((a*a * k) - (a*b * h) - b*c) / (a*a + b*b);
		*x = dropX;
		*y = dropY;
		*pline = nearestL;
	}

	assert(IsInPolygon(*x, *y, hp)); // Nearest point is not in polygon(!)
}

/**
 * Returns TRUE if two paths are asdjacent.
 */
bool IsAdjacentPath(HPOLYGON hPath1, HPOLYGON hPath2) {
	const POLYGON *pp1, *pp2;

	CHECK_HP(hPath1, "Out of range polygon handle (4)");
	CHECK_HP(hPath2, "Out of range polygon handle (500)");

	if (hPath1 == hPath2)
		return true;

	pp1 = Polys[hPath1];
	pp2 = Polys[hPath2];

	for (int j = 0; j < MAXADJ; j++)
		if (pp1->adjpaths[j] == pp2)
			return true;

	return false;
}

static const POLYGON *TryPath(POLYGON *last, POLYGON *whereto, POLYGON *current) {
	POLYGON *x;

	// For each path adjacent to this one
	for (int j = 0; j < MAXADJ; j++) {
		x = current->adjpaths[j];	// call the adj. path x
		if (x == whereto) {
			RoutePaths[pathsOnRoute++] = x;
			return x;		// Got there!
		}

		if (x == NULL)
			break;			// no more adj. paths to look at

		if (x->tried)
			continue;		// don't double back

		if (x == last)
			continue;		// don't double back

		x->tried = true;
		if (TryPath(current, whereto, x) != NULL) {
			RoutePaths[pathsOnRoute++] = x;
			assert(pathsOnRoute < MAXONROUTE);
			return x;		// Got there in this direction
		} else
			x->tried = false;
	}

	return NULL;
}


/**
 * Sort out the first path to head to for the imminent leg of a walk.
 */
static HPOLYGON PathOnTheWay(HPOLYGON from, HPOLYGON to) {
	// TODO: Fingolfin says: This code currently uses DFS (depth first search),
	// in the TryPath function, to compute a path between 'from' and 'to'.
	// However, a BFS (breadth first search) might yield more natural results,
	// at least in cases where there are multiple possible paths.
	// There is a small risk of regressions caused by such a change, though.
	//
	// Also, the overhead of computing a DFS again and again could be avoided
	// by computing a path matrix (like we do in the SCUMM engine).
	int	i;

	CHECK_HP(from, "Out of range polygon handle (501a)");
	CHECK_HP(to, "Out of range polygon handle (501b)");

	if (IsAdjacentPath(from, to))
		return to;

	for (i = 0; i < MAX_POLY; i++) {		// For each polygon..
		POLYGON *p = Polys[i];
		if (p && p->polyType == PATH)	//...if it's a path
			p->tried = false;
	}
	Polys[from]->tried = true;
	pathsOnRoute = 0;

	const POLYGON *p = TryPath(Polys[from], Polys[to], Polys[from]);

	if (TinselV2 && !p)
		return NOPOLY;

	assert(p != NULL); // Trying to find route between unconnected paths

	// Don't go a roundabout way to an adjacent path.
	for (i = 0; i < pathsOnRoute; i++) {
		CHECK_HP(PolygonIndex(RoutePaths[i]), "Out of range polygon handle (502)");
		if (IsAdjacentPath(from, PolygonIndex(RoutePaths[i])))
			return PolygonIndex(RoutePaths[i]);
	}
	return PolygonIndex(p);
}

/**
 * Indirect method of calling PathOnTheWay().
 * Used to be implemented using coroutines, to put the burden of
 * recursion onto the main stack. Since our "fake" coroutines use the
 * same stack for everything anyway, we can do without the coroutines.
 */
HPOLYGON GetPathOnTheWay(HPOLYGON hFrom, HPOLYGON hTo) {
	CHECK_HP(hFrom, "Out of range polygon handle (6)");
	CHECK_HP(hTo, "Out of range polygon handle (7)");

	// Reuse already computed result
	if (RouteEnd == Polys[hTo]) {
		for (int i = 0; i < pathsOnRoute; i++) {
			CHECK_HP(PolygonIndex(RoutePaths[i]), "Out of range polygon handle (503)");
			if (IsAdjacentPath(hFrom, PolygonIndex(RoutePaths[i]))) {
				return PolygonIndex(RoutePaths[i]);
			}
		}
	}

	RouteEnd = Polys[hTo];
	return PathOnTheWay(hFrom, hTo);
}


/**
 * Given a node path, work out which end node is nearest the given point.
 */
int NearestEndNode(HPOLYGON hPath, int x, int y) {
	const POLYGON *pp;

	int	d1, d2;

	CHECK_HP(hPath, "Out of range polygon handle (8)");
	pp = Polys[hPath];

	Poly ptp(LockMem(pHandle), pp->pIndex);	// This polygon

	const int nodecount = ptp.getNodecount() - 1;

	d1 = ABS(x - ptp.getNodeX(0)) + ABS(y - ptp.getNodeY(0));
	d2 = ABS(x - ptp.getNodeX(nodecount)) + ABS(y - ptp.getNodeY(nodecount));

	return (d2 > d1) ? 0 : nodecount;
}


/**
 * Given a start path and a destination path, find which pair of end
 * nodes is nearest together.
 * Return which node in the start path is part of the closest pair.
 */
int NearEndNode(HPOLYGON hSpath, HPOLYGON hDpath) {
	const POLYGON *pSpath, *pDpath;

	int	dist, NearDist;
	int	NearNode;

	CHECK_HP(hSpath, "Out of range polygon handle (9)");
	CHECK_HP(hDpath, "Out of range polygon handle (10)");
	pSpath = Polys[hSpath];
	pDpath = Polys[hDpath];

	uint8 *pps = LockMem(pHandle);		// All polygons
	Poly ps(pps, pSpath->pIndex);	// Start polygon
	Poly pd(pps, pDpath->pIndex);	// Dest polygon

	// 'top' nodes in each path
	const int ns = ps.getNodecount() - 1;
	const int nd = pd.getNodecount() - 1;

	// start[0] to dest[0]
	NearDist = ABS(ps.getNodeX(0) - pd.getNodeX(0)) + ABS(ps.getNodeY(0) - pd.getNodeY(0));
	NearNode = 0;

	// start[0] to dest[top]
	dist = ABS(ps.getNodeX(0) - pd.getNodeX(nd)) + ABS(ps.getNodeY(0) - pd.getNodeY(nd));
	if (dist < NearDist)
		NearDist = dist;

	// start[top] to dest[0]
	dist = ABS(ps.getNodeX(ns) - pd.getNodeX(0)) + ABS(ps.getNodeY(ns) - pd.getNodeY(0));
	if (dist < NearDist) {
		NearDist = dist;
		NearNode = ns;
	}

	// start[top] to dest[top]
	dist = ABS(ps.getNodeX(ns) - pd.getNodeX(nd)) + ABS(ps.getNodeY(ns) - pd.getNodeY(nd));
	if (dist < NearDist) {
		NearNode = ns;
	}

	return NearNode;
}

/**
 * Given a follow nodes path and a co-ordinate, finds which node in the
 * path is nearest to the co-ordinate.
 */
int NearestNodeWithin(HPOLYGON hNpath, int x, int y) {
	int	ThisDistance, SmallestDistance = 1000;
	int	NearestYet = 0;	// Number of nearest node

	CHECK_HP(hNpath, "Out of range polygon handle (11)");

	Poly ptp(LockMem(pHandle), Polys[hNpath]->pIndex);	// This polygon

	const int numNodes = ptp.getNodecount();	// Number of nodes in this follow nodes path

	for (int i = 0; i < numNodes; i++) {
		ThisDistance = ABS(x - ptp.getNodeX(i)) + ABS(y - ptp.getNodeY(i));

		if (ThisDistance < SmallestDistance) {
			NearestYet = i;
			SmallestDistance = ThisDistance;
		}
	}

	return NearestYet;
}

/**
 * Given a point and start and destination paths, find the nearest
 * corner (if any) of the start path which is within the destination
 * path. If there is no such corner, find the nearest corner of the
 * destination path which falls within the source path.
 */
void NearestCorner(int *x, int *y, HPOLYGON hStartPoly, HPOLYGON hDestPoly) {
	const POLYGON *psp, *pdp;
	int	j;
	int	ncorn = 0;			// nearest corner
	HPOLYGON hNpath = NOPOLY;	// path containing nearest corner
	int ThisD, SmallestD = 1000;

	CHECK_HP(hStartPoly, "Out of range polygon handle (12)");
	CHECK_HP(hDestPoly, "Out of range polygon handle (13)");

	psp = Polys[hStartPoly];
	pdp = Polys[hDestPoly];

	// Nearest corner of start path in destination path.

	for (j = 0; j < 4; j++)	{
		if (IsInPolygon(psp->cx[j], psp->cy[j], hDestPoly)) {
			ThisD = ABS(*x - psp->cx[j]) + ABS(*y - psp->cy[j]);
			if (ThisD < SmallestD) {
				hNpath = hStartPoly;
				ncorn = j;
				// Try to ignore it if virtually stood on it
				if (ThisD > 4)
					SmallestD = ThisD;
			}
		}
	}
	if (SmallestD == 1000) {
		// Nearest corner of destination path in start path.
		for (j = 0; j < 4; j++) {
			if (IsInPolygon(pdp->cx[j], pdp->cy[j], hStartPoly)) {
				ThisD = ABS(*x - pdp->cx[j]) + ABS(*y - pdp->cy[j]);
				if (ThisD < SmallestD) {
					hNpath = hDestPoly;
					ncorn = j;
					// Try to ignore it if virtually stood on it
					if (ThisD > 4)
						SmallestD = ThisD;
				}
			}
		}
	}

	if (hNpath != NOPOLY) {
		*x = Polys[hNpath]->cx[ncorn];
		*y = Polys[hNpath]->cy[ncorn];
	} else
		error("NearestCorner() failure");
}

bool IsPolyCorner(HPOLYGON hPath, int x, int y) {
	CHECK_HP(hPath, "Out of range polygon handle (37)");

	for (int i = 0; i < 4; i++)	{
		if (Polys[hPath]->cx[i] == x && Polys[hPath]->cy[i] == y)
			return true;
	}
	return false;
}

/**
 * Given a path polygon and a Y co-ordinate, return a scale value.
 */
int GetScale(HPOLYGON hPath, int y) {
	int	zones;		// Number of different scales
	int	zlen;		// Depth of each scale zone
	int	scale;
	int	top;

	// To try and fix some unknown potential bug
	if (hPath == NOPOLY)
		return SCALE_LARGE;

	CHECK_HP(hPath, "Out of range polygon handle (14)");

	Poly ptp(LockMem(pHandle), Polys[hPath]->pIndex);

	// Path is of a constant scale?
	if (FROM_LE_32(ptp.scale2) == 0)
		return FROM_LE_32(ptp.scale1);

	assert(FROM_LE_32(ptp.scale1) >= FROM_LE_32(ptp.scale2));

	zones = FROM_LE_32(ptp.scale1) - FROM_LE_32(ptp.scale2) + 1;
	zlen = (Polys[hPath]->pbottom - Polys[hPath]->ptop) / zones;

	scale = FROM_LE_32(ptp.scale1);
	top = Polys[hPath]->ptop;

	do {
		top += zlen;
		if (y < top)
			return scale;
	} while (--scale);

	return FROM_LE_32(ptp.scale2);
}

/**
 * Given a path polygon and a Y co-ordinate, return a brightness value.
 */

int GetBrightness(HPOLYGON hPath, int y) {
	int zones;		// Number of different brightnesses
	int zlen;		// Depth of each brightness zone
	int brightness;
	int top;

	// To try and fix some unknown potential bug
	if (hPath == NOPOLY)
		return 10;

	CHECK_HP(hPath, "Out of range polygon handle (38)");

	Poly ptp(LockMem(pHandle), Polys[hPath]->pIndex);

	// Path is of a constant brightness?
	if (FROM_LE_32(ptp.bright1) == FROM_LE_32(ptp.bright2))
		return FROM_LE_32(ptp.bright1);

	assert(FROM_LE_32(ptp.bright1) >= FROM_LE_32(ptp.bright2));

	zones = FROM_LE_32(ptp.bright1) - FROM_LE_32(ptp.bright2) + 1;
	zlen = (Polys[hPath]->pbottom - Polys[hPath]->ptop) / zones;

	brightness = FROM_LE_32(ptp.bright1);
	top = Polys[hPath]->ptop;

	do {
		top += zlen;
		if (y < top)
			return brightness;
	} while (--brightness);

	return FROM_LE_32(ptp.bright2);
}


/**
 * Give the co-ordinates of a node in a node path.
 */
void getNpathNode(HPOLYGON hNpath, int node, int *px, int *py) {
	CHECK_HP(hNpath, "Out of range polygon handle (15)");
	assert(Polys[hNpath] != NULL && Polys[hNpath]->polyType == PATH && Polys[hNpath]->subtype == NODE); // must be given a node path!

	Poly ptp(LockMem(pHandle), Polys[hNpath]->pIndex);	// This polygon

	// Might have just walked to the node from above.
	if (node == ptp.getNodecount())
		node -= 1;

	*px = ptp.getNodeX(node);
	*py = ptp.getNodeY(node);
}

/**
 * Get compiled tag text handle and tag co-ordinates of a tag polygon.
 */
void GetTagTag(HPOLYGON hp, SCNHANDLE *hTagText, int *tagx, int *tagy) {
	CHECK_HP(hp, "Out of range polygon handle (16)");

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	*tagx = (int)FROM_LE_32(ptp.tagx) + (TinselV2 ? volatileStuff[hp].xoff : 0);
	*tagy = (int)FROM_LE_32(ptp.tagy) + (TinselV2 ? volatileStuff[hp].yoff : 0);
	*hTagText = FROM_LE_32(ptp.hTagtext);
}

/**
 * Get polygon's film reel handle.
 */
SCNHANDLE GetPolyFilm(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (17)");

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	return FROM_LE_32(ptp.hFilm);
}

/**
 * Get handle to polygon's glitter code.
 */
SCNHANDLE GetPolyScript(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (19)");

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	return FROM_LE_32(ptp.hScript);
}

REEL GetPolyReelType(HPOLYGON hp) {
	// To try and fix some unknown potential bug (toyshop entrance)
	if (hp == NOPOLY)
		return REEL_ALL;

	CHECK_HP(hp, "Out of range polygon handle (20)");

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	return (REEL)FROM_LE_32(ptp.reel);
}

int32 GetPolyZfactor(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (21)");
	assert(Polys[hp] != NULL);

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	return (int)FROM_LE_32(ptp.zFactor);
}

int numNodes(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (22)");
	assert(Polys[hp] != NULL);

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	return ptp.getNodecount();
}

// *************************************************************************
//
// Code concerned with killing and reviving TAG and EXIT polygons.
// And code to enable this information to be saved and restored.
//
// *************************************************************************

struct TAGSTATE	{
	int tid;
	bool enabled;
};

#define MAX_SCENES	256
#define MAX_TAGS	2048
#define MAX_EXITS	512

static struct {
	SCNHANDLE sid;
	int	nooftags;
	int	offset;
} SceneTags[MAX_SCENES], SceneExits[MAX_SCENES];

static TAGSTATE TagStates[MAX_TAGS];
static TAGSTATE ExitStates[MAX_EXITS];

static int nextfreeT = 0, numScenesT = 0;
static int nextfreeE = 0, numScenesE = 0;

static int currentTScene = 0;
static int currentEScene = 0;

bool deadPolys[MAX_POLY];	// Currently just for dead blocks

void RebootDeadTags() {
	nextfreeT = numScenesT = 0;
	nextfreeE = numScenesE = 0;

	memset(SceneTags, 0, sizeof(SceneTags));
	memset(SceneExits, 0, sizeof(SceneExits));
	memset(TagStates, 0, sizeof(TagStates));
	memset(ExitStates, 0, sizeof(ExitStates));
	memset(deadPolys, 0, sizeof(deadPolys));
}

/**
 * (Un)serialize the dead tag and exit data for save/restore game.
 */
void syncPolyInfo(Common::Serializer &s) {
	int i;

	for (i = 0; i < MAX_SCENES; i++) {
		s.syncAsUint32LE(SceneTags[i].sid);
		s.syncAsSint32LE(SceneTags[i].nooftags);
		s.syncAsSint32LE(SceneTags[i].offset);
	}

	for (i = 0; i < MAX_SCENES; i++) {
		s.syncAsUint32LE(SceneExits[i].sid);
		s.syncAsSint32LE(SceneExits[i].nooftags);
		s.syncAsSint32LE(SceneExits[i].offset);
	}

	for (i = 0; i < MAX_TAGS; i++) {
		s.syncAsUint32LE(TagStates[i].tid);
		s.syncAsSint32LE(TagStates[i].enabled);
	}

	for (i = 0; i < MAX_EXITS; i++) {
		s.syncAsUint32LE(ExitStates[i].tid);
		s.syncAsSint32LE(ExitStates[i].enabled);
	}

	s.syncAsSint32LE(nextfreeT);
	s.syncAsSint32LE(numScenesT);
	s.syncAsSint32LE(nextfreeE);
	s.syncAsSint32LE(numScenesE);
}

/**
 * This is all totally different to the way the rest of the way polygon
 * data is stored and restored, more specifically, different to how dead
 * tags and exits are handled, because of the piecemeal design-by-just-
 * thought-of-this approach employed.
 */

void SaveDeadPolys(bool *sdp) {
	assert(!TinselV2);
	memcpy(sdp, deadPolys, MAX_POLY*sizeof(bool));
}

void RestoreDeadPolys(bool *sdp) {
	assert(!TinselV2);
	memcpy(deadPolys, sdp, MAX_POLY*sizeof(bool));
}

void SavePolygonStuff(POLY_VOLATILE *sps) {
	assert(TinselV2);
	memcpy(sps, volatileStuff, MAX_POLY*sizeof(POLY_VOLATILE));
}

void RestorePolygonStuff(POLY_VOLATILE *sps) {
	assert(TinselV2);
	memcpy(volatileStuff, sps, MAX_POLY*sizeof(POLY_VOLATILE));
}


/**
 * Scan for a given polygon
 */
static HPOLYGON FindPolygon(PTYPE type, int id) {

	for (int i = 0; i <= MAX_POLY; i++) {
		if (Polys[i] && Polys[i]->polyType == type && Polys[i]->polyID == id) {
			// Found it
			return i;
		}
	}

	// Not found
	return NOPOLY;
}

HPOLYGON FirstPathPoly() {
	for (int i = 0; i < noofPolys; i++) {
		if (Polys[i]->polyType == PATH)
			return i;
	}
	error("FirstPathPoly() - no PATH polygons");
	return NOPOLY;	// for compilers that don't support NORETURN
}

HPOLYGON GetPolyHandle(int i) {
	assert(i >= 0 && i <= MAX_POLY);

	return (Polys[i] != NULL) ? i : NOPOLY;
}

// **************************************************************************
//
// Code called to initialise or wrap up a scene:
//
// **************************************************************************

/**
 * Called at the start of a scene, when all polygons have been
 * initialised, to work out which paths are adjacent to which.
 */
static int DistinctCorners(HPOLYGON hp1, HPOLYGON hp2) {
	const POLYGON *pp1, *pp2;
	int	i, j;
	int	retval = 0;

	CHECK_HP(hp1, "Out of range polygon handle (23)");
	CHECK_HP(hp2, "Out of range polygon handle (24)");
	pp1 = Polys[hp1];
	pp2 = Polys[hp2];

	// Work out (how many of p1's corners is in p2) + (how many of p2's corners is in p1)
	for (i = 0; i < 4; i++) {
		if (IsInPolygon(pp1->cx[i], pp1->cy[i], hp2))
			retval++;
		if (IsInPolygon(pp2->cx[i], pp2->cy[i], hp1))
			retval++;
	}

	// Common corners only count once
	for (i = 0; i < 4; i++) {
		for (j = 0; j < 4; j++) {
			if (pp1->cx[i] == pp2->cx[j] && pp1->cy[i] == pp2->cy[j])
				retval--;
		}
	}
	return retval;
}

/**
 * Returns true if the two paths are on the same level
 */
static bool MatchingLevels(PPOLYGON p1, PPOLYGON p2) {
	byte *pps = LockMem(pHandle);		// All polygons
	Poly pp1(pps, p1->pIndex);	// This polygon 1
	Poly pp2(pps, p2->pIndex);	// This polygon 2

	assert((int32)FROM_LE_32(pp1.level1) <= (int32)FROM_LE_32(pp1.level2));
	assert((int32)FROM_LE_32(pp2.level1) <= (int32)FROM_LE_32(pp2.level2));

	for (int pl = (int32)FROM_LE_32(pp1.level1); pl <= (int32)FROM_LE_32(pp1.level2); pl++) {
		if (pl >= (int32)FROM_LE_32(pp2.level1) && pl <= (int32)FROM_LE_32(pp2.level2))
			return true;
	}

	return false;
}

static void SetPathAdjacencies() {
	POLYGON *p1, *p2;		// Polygon pointers
	int i1, i2;

	// Reset them all
	for (i1 = 0; i1 < noofPolys; i1++)
		memset(Polys[i1]->adjpaths, 0, MAXADJ * sizeof(PPOLYGON));

	// For each polygon..
	for (i1 = 0; i1 < MAX_POLY-1; i1++) {
		// Get polygon, but only carry on if it's a path
		p1 = Polys[i1];
		if (!p1 || p1->polyType != PATH)
			continue;

		// For each subsequent polygon..
		for (i2 = i1 + 1; i2 < MAX_POLY; i2++) {
			// Get polygon, but only carry on if it's a path
			p2 = Polys[i2];
			if (!p2 || p2->polyType != PATH)
				continue;

			// Must be on the same level
			if (TinselV2 && !MatchingLevels(p1, p2))
				continue;

			int j = DistinctCorners(i1, i2);

			if (j >= 2) {
				// Paths are adjacent
				for (j = 0; j < MAXADJ; j++)
					if (p1->adjpaths[j] == NULL) {
						p1->adjpaths[j] = p2;
						break;
					}
#ifdef DEBUG
				if (j > highestYet)
					highestYet = j;
#endif
				assert(j < MAXADJ); // Number of adjacent paths limit
				for (j = 0; j < MAXADJ; j++) {
					if (p2->adjpaths[j] == NULL) {
						p2->adjpaths[j] = p1;
						break;
					}
				}
#ifdef DEBUG
				if (j > highestYet)
					highestYet = j;
#endif
				assert(j < MAXADJ); // Number of adjacent paths limit
			}
		}
	}
}

/**
 * Ensure NPATH nodes are not inside another PATH/NPATH polygon.
 * Only bother with end nodes for now.
 */
#ifdef DEBUG
void CheckNPathIntegrity() {
	uint8		*pps;	// Compiled polygon data
	const POLYGON *rp;	// Run-time polygon structure
	HPOLYGON	hp;
	int		i, j;	// Loop counters
	int		n;	// Last node in current path

	pps = LockMem(pHandle);		// All polygons

	for (i = 0; i < MAX_POLY; i++) {		// For each polygon..
		rp = Polys[i];
		if (rp && rp->polyType == PATH && rp->subtype == NODE) { //...if it's a node path
			// Get compiled polygon structure
			const Poly cp(pps, rp->pIndex);	// This polygon

			n = cp.getNodecount() - 1;		// Last node
			assert(n >= 1); // Node paths must have at least 2 nodes

			hp = PolygonIndex(rp);
			for (j = 0; j <= n; j++) {
				if (!IsInPolygon(cp.getNodeX(j), cp.getNodeY(j), hp)) {
					sprintf(TextBufferAddr(), "Node (%d, %d) is not in its own path (starting (%d, %d))",
						 cp.getNodeX(j), cp.getNodeY(j), rp->cx[0], rp->cy[0]);
					error(TextBufferAddr());
				}
			}

			// Check end nodes are not in adjacent path
			for (j = 0; j < MAXADJ; j++) {	// For each adjacent path
				if (rp->adjpaths[j] == NULL)
					break;

				if (IsInPolygon(cp.getNodeX(0), cp.getNodeY(0), PolygonIndex(rp->adjpaths[j]))) {
					sprintf(TextBufferAddr(), "Node (%d, %d) is in another path (starting (%d, %d))",
						 cp.getNodeX(0), cp.getNodeY(0), rp->adjpaths[j]->cx[0], rp->adjpaths[j]->cy[0]);
					error(TextBufferAddr());
				}
				if (IsInPolygon(cp.getNodeX(n), cp.getNodeY(n), PolygonIndex(rp->adjpaths[j]))) {
					sprintf(TextBufferAddr(), "Node (%d, %d) is in another path (starting (%d, %d))",
						 cp.getNodeX(n), cp.getNodeY(n), rp->adjpaths[j]->cx[0], rp->adjpaths[j]->cy[0]);
					error(TextBufferAddr());
				}
			}
		}
	}
}
#endif

/**
 * Called at the start of a scene, nobbles TAG polygons which should be dead.
 */
static void SetExBlocks() {
	for (int i = 0; i < MAX_POLY; i++) {
		if (deadPolys[i]) {
			if (Polys[i] && Polys[i]->polyType == BLOCK)
				Polys[i]->polyType = EX_BLOCK;
#ifdef DEBUG
			else
				error("Impossible message");
#endif
		}
	}
}

/**
 * Called at the start of a scene, nobbles TAG polygons which should be dead.
 */
static void SetExTags(SCNHANDLE ph) {
	int i, j;
	TAGSTATE *pts;

	for (i = 0; i < numScenesT; i++) {
		if (SceneTags[i].sid == ph) {
			currentTScene = i;

			pts = &TagStates[SceneTags[i].offset];
			for (j = 0; j < SceneTags[i].nooftags; j++, pts++) {
				if (!pts->enabled)
					DisableTag(nullContext, pts->tid);
			}
			return;
		}
	}

	i = numScenesT++;
	currentTScene = i;
	assert(numScenesT < MAX_SCENES); // Dead tag remembering: scene limit

	SceneTags[i].sid = ph;
	SceneTags[i].offset = nextfreeT;
	SceneTags[i].nooftags = 0;

	for (j = 0; j < MAX_POLY; j++) {
		if (Polys[j] && Polys[j]->polyType == TAG) {
			TagStates[nextfreeT].tid = Polys[j]->polyID;
			TagStates[nextfreeT].enabled = true;
			nextfreeT++;
			assert(nextfreeT < MAX_TAGS); // Dead tag remembering: tag limit
			SceneTags[i].nooftags++;
		}
	}
}

/**
 * Called at the start of a scene, nobbles EXIT polygons which should be dead.
 */
static void SetExExits(SCNHANDLE ph) {
	TAGSTATE *pts;
	int i, j;

	for (i = 0; i < numScenesE; i++) {
		if (SceneExits[i].sid == ph) {
			currentEScene = i;

			pts = &ExitStates[SceneExits[i].offset];
			for (j = 0; j < SceneExits[i].nooftags; j++, pts++) {
				if (!pts->enabled)
					DisableExit(pts->tid);
			}
			return;
		}
	}

	i = numScenesE++;
	currentEScene = i;
	assert(numScenesE < MAX_SCENES); // Dead exit remembering: scene limit

	SceneExits[i].sid = ph;
	SceneExits[i].offset = nextfreeE;
	SceneExits[i].nooftags = 0;

	for (j = 0; j < MAX_POLY; j++) {
		if (Polys[j] && Polys[j]->polyType == EXIT) {
			ExitStates[nextfreeE].tid = Polys[j]->polyID;
			ExitStates[nextfreeE].enabled = true;
			nextfreeE++;
			assert(nextfreeE < MAX_EXITS); // Dead exit remembering: exit limit
			SceneExits[i].nooftags++;
		}
	}
}

/**
 * Works out some fixed numbers for a polygon.
 */
static void FiddlyBit(POLYGON *p) {
	int	t1, t2;		// General purpose temp. variables

	// Enclosing external rectangle
	t1 = MAX(p->cx[0], p->cx[1]);
	t2 = MAX(p->cx[2], p->cx[3]);
	p->pright = MAX(t1, t2);

	t1 = MIN(p->cx[0], p->cx[1]);
	t2 = MIN(p->cx[2], p->cx[3]);
	p->pleft = MIN(t1, t2);

	t1 = MAX(p->cy[0], p->cy[1]);
	t2 = MAX(p->cy[2], p->cy[3]);
	p->pbottom = MAX(t1, t2);

	t1 = MIN(p->cy[0], p->cy[1]);
	t2 = MIN(p->cy[2], p->cy[3]);
	p->ptop = MIN(t1, t2);

	// Rectangles enclosing each side and each side's magic numbers
	for (t1 = 0; t1 < 4; t1++) {
		p->lright[t1]   = MAX(p->cx[t1], p->cx[(t1+1)%4]);
		p->lleft[t1]    = MIN(p->cx[t1], p->cx[(t1+1)%4]);

		p->ltop[t1]     = MIN(p->cy[t1], p->cy[(t1+1)%4]);
		p->lbottom[t1]  = MAX(p->cy[t1], p->cy[(t1+1)%4]);

		p->a[t1] = p->cy[t1] - p->cy[(t1+1)%4];
		p->b[t1] = p->cx[(t1+1)%4] - p->cx[t1];
		p->c[t1] = (long)p->cy[t1]*p->cx[(t1+1)%4] - (long)p->cx[t1]*p->cy[(t1+1)%4];
	}
}

/**
 * Allocate a POLYGON structure and reset it to default values
 */
static PPOLYGON GetPolyEntry() {
	int i;		// Loop counter
	PPOLYGON p;

	for (i = 0; i < MaxPolys; i++) {
		if (!Polys[i]) {
			p = Polys[i] = &Polygons[i];

			// What the hell, just clear it all out - it's safer
			memset(p, 0, sizeof(POLYGON));

			return p;
		}
	}

	error("Exceeded MaxPolys");
}

/**
 * Variation of  GetPolyEntry from Tinsel 1 that splits up getting a new
 * polygon structure from initialising it
 */
static PPOLYGON CommonInits(PTYPE polyType, int pno, const Poly &ptp, bool bRestart) {
	int i;
	HPOLYGON hp;
	PPOLYGON p = GetPolyEntry();	// Obtain a slot

	p->polyType = polyType;			// Polygon type
	p->pIndex = pno;

	for (i = 0; i < 4; i++) {		// Polygon definition
		p->cx[i] = (short)FROM_LE_32(ptp.x[i]);
		p->cy[i] = (short)FROM_LE_32(ptp.y[i]);
	}

	if (!bRestart) {
		hp = PolygonIndex(p);
		volatileStuff[hp].xoff = (short)FROM_LE_32(ptp.xoff);
		volatileStuff[hp].yoff = (short)FROM_LE_32(ptp.yoff);
	}

	p->polyID = FROM_LE_32(ptp.id);			// Identifier

	FiddlyBit(p);

	return p;
}

/**
 * Calculate a point approximating to the centre of a polygon.
 * Not very sophisticated.
 */
static void PseudoCentre(POLYGON *p) {
	p->pcentrex = (p->cx[0] + p->cx[1] + p->cx[2] + p->cx[3])/4;
	p->pcentrey = (p->cy[0] + p->cy[1] + p->cy[2] + p->cy[3])/4;

	if (!IsInPolygon(p->pcentrex, p->pcentrey, PolygonIndex(p))) {
		int i, top = 0, bot = 0;

		for (i = p->ptop; i <= p->pbottom; i++) {
			if (IsInPolygon(p->pcentrex, i, PolygonIndex(p))) {
				top = i;
				break;
			}
		}
		for (i = p->pbottom; i >= p->ptop; i--) {
			if (IsInPolygon(p->pcentrex, i, PolygonIndex(p))) {
				bot = i;
				break;
			}
		}
		p->pcentrex = (top+bot)/2;
	}
#ifdef DEBUG
	//	assert(IsInPolygon(p->pcentrex, p->pcentrey, PolygonIndex(p)));  // Pseudo-centre is not in path
	if (!IsInPolygon(p->pcentrex, p->pcentrey, PolygonIndex(p))) {
		sprintf(TextBufferAddr(), "Pseudo-centre is not in path (starting (%d, %d)) - polygon reversed?",
			p->cx[0], p->cy[0]);
		error(TextBufferAddr());
	}
#endif
}

/**
 * Initialise an EXIT polygon.
 */
static void InitExit(const Poly &ptp, int pno, bool bRestart) {
	CommonInits(EXIT, pno, ptp, bRestart);
}

/**
 * Initialise a PATH or NPATH polygon.
 */
static void InitPath(const Poly &ptp, bool NodePath, int pno, bool bRestart) {
	PPOLYGON p = CommonInits(PATH, pno, ptp, bRestart);

	p->subtype = NodePath ? NODE : NORMAL;

	PseudoCentre(p);
}


/**
 * Initialise a BLOCKING polygon.
 */
static void InitBlock(const Poly &ptp, int pno, bool bRestart) {
	CommonInits(BLOCK, pno, ptp, bRestart);
}

/**
 * Initialise an extra BLOCKING polygon related to a moving actor.
 * The width of the polygon depends on the width of the actor which is
 * trying to walk through the actor you first thought of.
 * This is for dynamic blocking.
 */
HPOLYGON InitExtraBlock(PMOVER ca, PMOVER ta) {
	int	caX, caY;	// Calling actor co-ords
	int	taX, taY;	// Test actor co-ords
	int	left, right;

	GetMoverPosition(ca, &caX, &caY);	// Calling actor co-ords
	GetMoverPosition(ta, &taX, &taY);	// Test actor co-ords

	left = GetMoverLeft(ta) - (GetMoverRight(ca) - caX);
	right = GetMoverRight(ta) + (caX - GetMoverLeft(ca));

	memset(&extraBlock, 0, sizeof(extraBlock));

	// The 3s on the y co-ordinates used to be 10s
	extraBlock.cx[0] = (short)(left - 2);
	extraBlock.cy[0] = (short)(taY - 3);
	extraBlock.cx[1] = (short)(right + 2);
	extraBlock.cy[1] = (short)(taY - 3);
	extraBlock.cx[2] = (short)(right + 2);
	extraBlock.cy[2] = (short)(taY + 3);
	extraBlock.cx[3] = (short)(left - 2);
	extraBlock.cy[3] = (short)(taY + 3);

	FiddlyBit(&extraBlock);		// Is this necessary?

	Polys[MAX_POLY] = &extraBlock;
	return MAX_POLY;
}

/**
 * Initialise an EFFECT polygon.
 */
static void InitEffect(const Poly &ptp, int pno, bool bRestart) {
	CommonInits(EFFECT, pno, ptp, bRestart);
}


/**
 * Initialise a REFER polygon.
 */
static void InitRefer(const Poly &ptp, int pno, bool bRestart) {
	PPOLYGON p = CommonInits(REFER, pno, ptp, bRestart);

	p->subtype = FROM_LE_32(ptp.reftype);	// Refer type
}


/**
 * Initialise a TAG polygon.
 */
static void InitTag(const Poly &ptp, int pno, bool bRestart) {
	CommonInits(TAG, pno, ptp, bRestart);
}

/**
 * Called at the restart of a scene, nobbles polygons which are dead.
 */
static void KillDeadPolygons() {
	int i;

	for (i = 0; i < MAX_POLY; i++) {
		if (volatileStuff[i].bDead) {
			assert(Polys[i]);

			switch (Polys[i]->polyType) {
			case BLOCK:
				Polys[i]->polyType = EX_BLOCK;
				break;

			case EFFECT:
				Polys[i]->polyType = EX_EFFECT;
				break;

			case REFER:
				Polys[i]->polyType = EX_REFER;
				break;

			case PATH:
				Polys[i]->polyType = EX_PATH;
				break;

			case TAG:
				Polys[i]->polyType = EX_TAG;
				break;

			default:
				error("Impossible message");
			}
		}
	}
}

/**
 * Called at the start of a scene to initialise the polys in that scene.
 */
void InitPolygons(SCNHANDLE ph, int numPoly, bool bRestart) {
	pHandle = ph;
	noofPolys = numPoly;

	if (Polygons == NULL) {
		// first time - allocate memory for process list
		Polygons = (POLYGON *)calloc(MaxPolys, sizeof(POLYGON));

		// make sure memory allocated
		if (Polygons == NULL) {
			error("Cannot allocate memory for polygon data");
		}
	}

	if (numPoly == 0)
		return;

	for (int i = 0; i < noofPolys; i++)	{
		if (Polys[i]) {
			Polys[i]->pointState = PS_NOT_POINTING;
			Polys[i] = NULL;
		}
	}

	memset(RoutePaths, 0, sizeof(RoutePaths));

	if (!bRestart) {
		if (TinselV2)
			memset(volatileStuff, 0, sizeof(volatileStuff));
		else
			memset(deadPolys, 0, sizeof(deadPolys));
	}

	if (numPoly > 0) {
		Poly ptp(LockMem(ph));

		for (int i = 0; i < numPoly; ++i, ++ptp) {
			switch (ptp.getType()) {
			case POLY_PATH:
				InitPath(ptp, false, i, bRestart);
				break;

			case POLY_NPATH:
				InitPath(ptp, true, i, bRestart);
				break;

			case POLY_BLOCK:
				InitBlock(ptp, i, bRestart);
				break;

			case POLY_REFER:
				InitRefer(ptp, i, bRestart);
				break;

			case POLY_EFFECT:
				InitEffect(ptp, i, bRestart);
				break;

			case POLY_EXIT:
				InitExit(ptp, i, bRestart);
				break;

			case POLY_TAG:
				InitTag(ptp, i, bRestart);
				break;

			default:
				error("Unknown polygon type");
			}
		}
	}

	if (!TinselV2) {
		SetPathAdjacencies();		// Paths need to know the facts
#ifdef DEBUG
		CheckNPathIntegrity();
#endif

		SetExTags(ph);			// Some tags may have been killed
		SetExExits(ph);			// Some exits may have been killed

		if (bRestart)
			SetExBlocks();		// Some blocks may have been killed
	} else {
		if (bRestart) {
			// Some may have been killed if this is a restore
			KillDeadPolygons();
		} else {
			for (int i = numPoly - 1; i >= 0; i--) {
				if (Polys[i]->polyType == TAG) {
					PolygonEvent(nullContext, i, STARTUP, 0, false, 0);
				}
			}
		}

		// Paths need to know the facts
		SetPathAdjacencies();
	}
}

/**
 * Called at the end of a scene to ditch all polygons.
 */
void DropPolygons() {
	pathsOnRoute = 0;
	memset(RoutePaths, 0, sizeof(RoutePaths));
	RouteEnd = NULL;

	for (int i = 0; i < noofPolys; i++)	{
		if (Polys[i]) {
			Polys[i]->pointState = PS_NOT_POINTING;
			Polys[i] = NULL;
		}
	}
	noofPolys = 0;
	free(Polygons);
	Polygons = NULL;
}



PTYPE PolyType(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (25)");

	return Polys[hp]->polyType;
}

int PolySubtype(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (26)");

	return Polys[hp]->subtype;
}

int PolyCentreX(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (27)");

	return Polys[hp]->pcentrex;
}

int PolyCentreY(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (28)");

	return Polys[hp]->pcentrey;
}

int PolyCornerX(HPOLYGON hp, int n) {
	CHECK_HP(hp, "Out of range polygon handle (29)");

	return Polys[hp]->cx[n];
}

int PolyCornerY(HPOLYGON hp, int n) {
	CHECK_HP(hp, "Out of range polygon handle (30)");

	return Polys[hp]->cy[n];
}

PSTATE PolyPointState(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (31)");

	return Polys[hp]->pointState;
}

TSTATE PolyTagState(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (32)");

	return Polys[hp]->tagState;
}

void SetPolyPointState(HPOLYGON hp, PSTATE ps) {
	CHECK_HP(hp, "Out of range polygon handle (34)");

	Polys[hp]->pointState = ps;
}

void SetPolyTagState(HPOLYGON hp, TSTATE ts) {
	CHECK_HP(hp, "Out of range polygon handle (35)");

	Polys[hp]->tagState = ts;
}

void SetPolyTagHandle(HPOLYGON hp, SCNHANDLE th) {
	CHECK_HP(hp, "Out of range polygon handle (36)");

	Polys[hp]->hOverrideTag = th;
}

void MaxPolygons(int numPolys) {
	assert(numPolys <= MAX_POLY);

	MaxPolys = numPolys;
}

/**
 * Get polygon's associated node.
 * The one for WalkTag(), StandTag() etc.
 */
void GetPolyNode(HPOLYGON hp, int *pNodeX, int *pNodeY) {
	CHECK_HP(hp, "GetPolyNode(): Out of range polygon handle");

	Poly ptp(LockMem(pHandle), Polys[hp]->pIndex);

	// WORKAROUND: Invalid node adjustment for DW2 Cartwheel scene refer polygon
	if (TinselV2 && (pHandle == 0x74191900) && (hp == 8)) {
		*pNodeX = 480;
		*pNodeY = 408;
	} else {
		*pNodeX = FROM_LE_32(ptp.nodex);
		*pNodeY = FROM_LE_32(ptp.nodey);
	}

	if (TinselV2) {
		*pNodeX += volatileStuff[hp].xoff;
		*pNodeY += volatileStuff[hp].yoff;
	}
}

void SetPolyPointedTo(HPOLYGON hp, bool bPointedTo) {
	CHECK_HP(hp, "Out of range polygon handle (34)");

	if (bPointedTo)
		Polys[hp]->tagFlags |= POINTING;
	else
		Polys[hp]->tagFlags &= ~POINTING;
}

bool PolyIsPointedTo(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (31)");

	if (TinselV2)
		return (Polys[hp]->tagFlags & POINTING);

	return PolyPointState(hp) == PS_POINTING;
}

void SetPolyTagWanted(HPOLYGON hp, bool bTagWanted, bool bCursor, SCNHANDLE hOverrideTag) {
	CHECK_HP(hp, "Out of range polygon handle (35)");

	if (bTagWanted) {
		Polys[hp]->tagFlags |= TAGWANTED;
		Polys[hp]->hOverrideTag = hOverrideTag;
	} else {
		Polys[hp]->tagFlags &= ~TAGWANTED;
		Polys[hp]->hOverrideTag = 0;
	}

	if (bCursor)
		Polys[hp]->tagFlags |= FOLLOWCURSOR;
	else
		Polys[hp]->tagFlags &= ~FOLLOWCURSOR;
}

bool PolyTagIsWanted(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (32)");

	return (Polys[hp]->tagFlags & TAGWANTED);
}

bool PolyTagFollowsCursor(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (36)");

	return (Polys[hp]->tagFlags & FOLLOWCURSOR);
}

SCNHANDLE GetPolyTagHandle(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (33)");

	return Polys[hp]->hOverrideTag;
}

bool IsTagPolygon(int tagno) {
	return (FindPolygon(TAG, tagno) != NOPOLY || FindPolygon(EX_TAG, tagno) != NOPOLY);
}

int GetTagPolyId(HPOLYGON hp) {
	CHECK_HP(hp, "Out of range polygon handle (GetTagPolyId()");

	assert(Polys[hp]->polyType == TAG || Polys[hp]->polyType == EX_TAG);

	return Polys[hp]->polyID;
}

void GetPolyMidBottom(	HPOLYGON hp, int *pX, int *pY) {
	CHECK_HP(hp, "Out of range polygon handle (GetPolyMidBottom()");

	*pY = Polys[hp]->pbottom + volatileStuff[hp].yoff;
	*pX = (Polys[hp]->pleft + Polys[hp]->pright)/2 + volatileStuff[hp].xoff;
}

int PathCount() {
	int i, count;

	for (i = 0, count = 0; i < noofPolys; i++) {
		if (Polys[i]->polyType == PATH)
			count++;
	}

	return count;
}

/**
 * Convert a BLOCK to an EX_BLOCK poly
 */
void DisableBlock(int block) {
	int i = FindPolygon(BLOCK, block);

	if (i != NOPOLY) {
		Polys[i]->polyType = EX_BLOCK;
		volatileStuff[i].bDead = true;
	}
}

/**
 * Convert an EX_BLOCK to a BLOCK poly
 */
void EnableBlock(int block) {
	int i = FindPolygon(EX_BLOCK, block);

	if (i != NOPOLY) {
		Polys[i]->polyType = BLOCK;
		volatileStuff[i].bDead = false;
	}
}

/**
 * Convert an EFFECT to an EX_EFFECT poly
 */
void DisableEffect(int effect) {
	int i = FindPolygon(EFFECT, effect);

	if (i != NOPOLY) {
		Polys[i]->polyType = EX_EFFECT;
		volatileStuff[i].bDead = true;
	}
}

/**
 * Convert an EX_EFFECT to an EFFECT poly
 */
void EnableEffect(int effect) {
	int i = FindPolygon(EX_EFFECT, effect);

	if (i != NOPOLY) {
		Polys[i]->polyType = EFFECT;
		volatileStuff[i].bDead = false;
	}
}

/**
 * Convert a PATH to an EX_PATH poly
 */
void DisablePath(int path) {
	int i = FindPolygon(PATH, path);

	if (i != NOPOLY) {
		Polys[i]->polyType = EX_PATH;
		volatileStuff[i].bDead = true;

		// Paths need to know the new facts
		SetPathAdjacencies();
	}
}

/**
 * Convert a PATH to an EX_PATH poly
 */
void EnablePath(int path) {
	int i = FindPolygon(EX_PATH, path);

	if (i != NOPOLY) {
		Polys[i]->polyType = PATH;
		volatileStuff[i].bDead = false;

		// Paths need to know the new facts
		SetPathAdjacencies();
	}
}

/**
 * Convert a REFER to an EX_REFER poly
 */
void DisableRefer(int refer) {
	int i = FindPolygon(REFER, refer);

	if (i != NOPOLY) {
		Polys[i]->polyType = EX_REFER;
		volatileStuff[i].bDead = true;
	}
}

/**
 * Convert a REFER to an EX_REFER poly
 */
void EnableRefer(int refer) {
	int i = FindPolygon(EX_REFER, refer);

	if (i != NOPOLY) {
		Polys[i]->polyType = REFER;
		volatileStuff[i].bDead = false;
	}
}

/**
 * Convert an EX_TAG to a TAG poly.
 */
void EnableTag(CORO_PARAM, int tag) {
	CORO_BEGIN_CONTEXT;
		int i;
	CORO_END_CONTEXT(_ctx);

	CORO_BEGIN_CODE(_ctx);

	if ((_ctx->i = FindPolygon(EX_TAG, tag)) != NOPOLY) {
		Polys[_ctx->i]->polyType = TAG;
		volatileStuff[_ctx->i].bDead = false;

		if (TinselV2)
			CORO_INVOKE_ARGS(PolygonEvent, (CORO_SUBCTX, _ctx->i, SHOWEVENT, 0, true, 0));
	} else if ((_ctx->i = FindPolygon(TAG, tag)) != NOPOLY) {
		if (TinselV2)
			CORO_INVOKE_ARGS(PolygonEvent, (CORO_SUBCTX, _ctx->i, SHOWEVENT, 0, true, 0));
	}

	if (!TinselV2) {
		TAGSTATE *pts = &TagStates[SceneTags[currentTScene].offset];
		for (int j = 0; j < SceneTags[currentTScene].nooftags; j++, pts++) {
			if (pts->tid == tag) {
				pts->enabled = true;
				break;
			}
		}
	}

	CORO_END_CODE;
}

/**
 * Convert an EX_EXIT to a EXIT poly.
 */
void EnableExit(int exitno) {
	for (int i = 0; i < MAX_POLY; i++) {
		if (Polys[i] && Polys[i]->polyType == EX_EXIT && Polys[i]->polyID == exitno) {
			Polys[i]->polyType = EXIT;
		}
	}

	TAGSTATE *pts;
	pts = &ExitStates[SceneExits[currentEScene].offset];
	for (int j = 0; j < SceneExits[currentEScene].nooftags; j++, pts++) {
		if (pts->tid == exitno) {
			pts->enabled = true;
			break;
		}
	}
}

/**
 * Move a polygon relative to current offset.
 */
void MovePolygon(PTYPE ptype, int id, int x, int y) {
	int i = FindPolygon(ptype, id);

	// If not found, try its dead equivalent
	if (i == NOPOLY) {
		switch (ptype) {
		case TAG:
			ptype = EX_TAG;
			break;
		default:
			break;
		}

		i = FindPolygon(ptype, id);
	}

	if (i != NOPOLY) {
		volatileStuff[i].xoff += (short)x;
		volatileStuff[i].yoff += (short)y;
	}
}

/**
 * Move a polygon relative to absolute offset.
 */
void MovePolygonTo(PTYPE ptype, int id, int x, int y) {
	int i = FindPolygon(ptype, id);

	// If not found, try its dead equivalent
	if (i == NOPOLY) {
		switch (ptype) {
		case TAG:
			ptype = EX_TAG;
			break;
		default:
			break;
		}

		i = FindPolygon(ptype, id);
	}

	if (i != NOPOLY) {
		volatileStuff[i].xoff = (short)x;
		volatileStuff[i].yoff = (short)y;
	}
}


/**
 * Convert tag number to polygon handle.
 */
HPOLYGON GetTagHandle(int tagno) {
	int i = FindPolygon(TAG, tagno);

	if (i == NOPOLY)
		i = FindPolygon(EX_TAG, tagno);

	assert(i != NOPOLY);

	return GetPolyHandle(i);
}

/**
 * Convert a TAG to an EX_TAG poly.
 */
void DisableTag(CORO_PARAM, int tag) {
	CORO_BEGIN_CONTEXT;
		int i;
	CORO_END_CONTEXT(_ctx);

	CORO_BEGIN_CODE(_ctx);

	if ((_ctx->i = FindPolygon(TAG, tag)) != NOPOLY) {
		Polys[_ctx->i]->polyType = EX_TAG;
		Polys[_ctx->i]->tagFlags = 0;
		Polys[_ctx->i]->tagState = TAG_OFF;
		Polys[_ctx->i]->pointState = PS_NOT_POINTING;

		volatileStuff[_ctx->i].bDead = true;

		if (TinselV2)
			CORO_INVOKE_ARGS(PolygonEvent, (CORO_SUBCTX, _ctx->i, HIDEEVENT, 0, true, 0));
	} else if ((_ctx->i = FindPolygon(EX_TAG, tag)) != NOPOLY) {
		if (TinselV2)
			CORO_INVOKE_ARGS(PolygonEvent, (CORO_SUBCTX, _ctx->i, HIDEEVENT, 0, true, 0));
	}

	if (!TinselV2) {
		TAGSTATE *pts = &TagStates[SceneTags[currentTScene].offset];
		for (int j = 0; j < SceneTags[currentTScene].nooftags; j++, pts++) {
			if (pts->tid == tag) {
				pts->enabled = false;
				break;
			}
		}
	}

	CORO_END_CODE;
}

/**
 * Convert a EXIT to an EX_EXIT poly.
 */
void DisableExit(int exitno) {
	TAGSTATE *pts;

	for (int i = 0; i < MAX_POLY; i++) {
		if (Polys[i] && Polys[i]->polyType == EXIT && Polys[i]->polyID == exitno) {
			Polys[i]->polyType = EX_EXIT;
			Polys[i]->tagState = TAG_OFF;
			Polys[i]->pointState = PS_NOT_POINTING;
		}
	}

	pts = &ExitStates[SceneExits[currentEScene].offset];
	for (int j = 0; j < SceneExits[currentEScene].nooftags; j++, pts++) {
		if (pts->tid == exitno) {
			pts->enabled = false;
			break;
		}
	}
}

} // End of namespace Tinsel