File: terrain.cc

package info (click to toggle)
crawl 2%3A0.34.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 100,188 kB
  • sloc: cpp: 363,709; ansic: 27,765; javascript: 9,516; python: 8,463; perl: 3,293; java: 3,132; xml: 2,380; makefile: 1,835; sh: 611; objc: 250; cs: 15; sed: 9; lisp: 3
file content (2756 lines) | stat: -rw-r--r-- 78,876 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
/**
 * @file
 * @brief Terrain related functions.
**/

#include "AppHdr.h"

#include "terrain.h"

#include <algorithm>
#include <functional>
#include <sstream>

#include "act-iter.h"
#include "areas.h"
#include "attack.h"
#include "branch.h"
#include "cloud.h"
#include "coord.h"
#include "coordit.h"
#include "dgn-event.h"
#include "dgn-overview.h"
#include "directn.h"
#include "dungeon.h"
#include "env.h"
#include "tile-env.h"
#include "fight.h"
#include "feature.h"
#include "fprop.h"
#include "god-abil.h"
#include "item-prop.h"
#include "items.h"
#include "level-state-type.h"
#include "libutil.h"
#include "losglobal.h"
#include "map-knowledge.h" // set_terrain_visible
#include "mapmark.h"
#include "message.h"
#include "mon-behv.h"
#include "mon-gear.h"
#include "mon-place.h"
#include "mon-poly.h"
#include "mon-util.h"
#include "ouch.h"
#include "player.h"
#include "random.h"
#include "religion.h"
#include "species.h"
#include "spl-damage.h" // ramparts_damage
#include "spl-transloc.h"
#include "state.h"
#include "stringutil.h"
#include "tag-version.h"
#include "tileview.h"
#include "transform.h"
#include "traps.h"
#include "travel.h"
#include "viewchar.h"
#include "view.h"

static bool _revert_terrain_to(coord_def pos, dungeon_feature_type feat);

actor* actor_at(const coord_def& c)
{
    if (!in_bounds(c))
        return nullptr;
    if (c == you.pos())
        return &you;
    return monster_at(c);
}

/** Can a malign gateway be placed on this feature?
 */
bool feat_is_malign_gateway_suitable(dungeon_feature_type feat)
{
    return feat == DNGN_FLOOR || feat == DNGN_SHALLOW_WATER;
}

/** Is this feature a type of wall?
 */
bool feat_is_wall(dungeon_feature_type feat)
{
    return get_feature_def(feat).flags & FFT_WALL;
}

/** Is this feature one of the main stone downstairs of a level?
 */
bool feat_is_stone_stair_down(dungeon_feature_type feat)
{
     return feat == DNGN_STONE_STAIRS_DOWN_I
            || feat == DNGN_STONE_STAIRS_DOWN_II
            || feat == DNGN_STONE_STAIRS_DOWN_III;
}

/** Is this feature one of the main stone upstairs of a level?
 */
bool feat_is_stone_stair_up(dungeon_feature_type feat)
{
    return feat == DNGN_STONE_STAIRS_UP_I
           || feat == DNGN_STONE_STAIRS_UP_II
           || feat == DNGN_STONE_STAIRS_UP_III;
}

/** Is this feature one of the main stone stairs of a level?
 */
bool feat_is_stone_stair(dungeon_feature_type feat)
{
    return feat_is_stone_stair_up(feat) || feat_is_stone_stair_down(feat);
}

/** Is it possible to call this feature a staircase? (purely cosmetic)
 */
bool feat_is_staircase(dungeon_feature_type feat)
{
    if (feat_is_stone_stair(feat))
        return true;

    // All branch entries/exits are staircases, except for Zot, Hell & Vaults.
    if (feat == DNGN_ENTER_VAULTS
        || feat == DNGN_EXIT_VAULTS
        || feat == DNGN_ENTER_HELL || feat == DNGN_EXIT_HELL
        || feat_is_hell_subbranch_exit(feat)
        || feat == DNGN_ENTER_ZOT
        || feat == DNGN_EXIT_ZOT)
    {
        return false;
    }

    return feat_is_branch_entrance(feat)
           || feat_is_branch_exit(feat)
           || feat == DNGN_ABYSSAL_STAIR;
}

/** Is this the exit from a sub-branch of Hell?
 */
bool feat_is_hell_subbranch_exit(dungeon_feature_type feat)
{
    static bool init, cached[NUM_FEATURES+1];
    if (!init)
    {
        for (branch_iterator it; it; ++it)
        {
            if (is_hell_subbranch(it->id))
                cached[it->exit_stairs] = true;
        }
        init = true;
    }
    return cached[feat];
}

/**
 * Define a memoized function from dungeon_feature_type to bool.
 * This macro should be followed by the non-memoized version of the
 * function body: see feat_is_branch_entrance below for an example.
 *
 * @param funcname The name of the function to define.
 * @param paramname The name under which the function's single parameter,
 *        of type dungeon_feature_type, is visible in the function body.
 */
#define FEATFN_MEMOIZED(funcname, paramname) \
    static bool _raw_ ## funcname (dungeon_feature_type); \
    bool funcname (dungeon_feature_type feat) \
    { \
        static int cached[NUM_FEATURES+1] = { 0 }; \
        if (!cached[feat]) cached[feat] = _raw_ ## funcname (feat) ? 1 : -1; \
        return cached[feat] > 0; \
    } \
    static bool _raw_ ## funcname (dungeon_feature_type paramname)

/** Is this feature a branch entrance that should show up on ^O?
 */
FEATFN_MEMOIZED(feat_is_branch_entrance, feat)
{
    for (branch_iterator it; it; ++it)
    {
        if (it->entry_stairs == feat
            && is_connected_branch(it->id))
        {
            return true;
        }
    }

    return false;
}

/** Counterpart to feat_is_branch_entrance.
 */
FEATFN_MEMOIZED(feat_is_branch_exit, feat)
{
    for (branch_iterator it; it; ++it)
    {
        if (it->exit_stairs == feat
            && is_connected_branch(it->id))
        {
            return true;
        }
    }

    return false;
}

/** Is this feature an entrance to a portal branch?
 */
FEATFN_MEMOIZED(feat_is_portal_entrance, feat)
{
    // These are have different rules from normal connected branches, but they
    // also have different rules from "portal vaults," and are more similar to
    // real branches in some respects.
    if (feat == DNGN_ENTER_ABYSS || feat == DNGN_ENTER_PANDEMONIUM)
        return false;

    for (branch_iterator it; it; ++it)
    {
        if (it->entry_stairs == feat
            && !is_connected_branch(it->id))
        {
            return true;
        }
    }
#if TAG_MAJOR_VERSION == 34
    if (feat == DNGN_ENTER_PORTAL_VAULT)
        return true;
#endif

    return false;
}

/** Counterpart to feat_is_portal_entrance.
 */
FEATFN_MEMOIZED(feat_is_portal_exit, feat)
{
    if (feat == DNGN_EXIT_ABYSS || feat == DNGN_EXIT_PANDEMONIUM)
        return false;

    for (branch_iterator it; it; ++it)
    {
        if (it->exit_stairs == feat
            && !is_connected_branch(it->id))
        {
            return true;
        }
    }
#if TAG_MAJOR_VERSION == 34
    if (feat == DNGN_EXIT_PORTAL_VAULT)
        return true;
#endif

    return false;
}

/** Is this feature a kind of portal?
 */
bool feat_is_portal(dungeon_feature_type feat)
{
    return feat == DNGN_MALIGN_GATEWAY
        || feat_is_portal_entrance(feat)
        || feat_is_portal_exit(feat);
}

/** Is this feature a kind of level exit?
 */
bool feat_is_stair(dungeon_feature_type gridc)
{
    return feat_is_travelable_stair(gridc) || feat_is_gate(gridc);
}

/** Is this feature a level exit stair with a consistent endpoint?
 */
bool feat_is_travelable_stair(dungeon_feature_type feat)
{
    return feat_is_stone_stair(feat)
           || feat_is_escape_hatch(feat)
           || feat_is_branch_entrance(feat)
           || feat_is_branch_exit(feat);
}

/** Is this feature an escape hatch?
 */
bool feat_is_escape_hatch(dungeon_feature_type feat)
{
    return feat == DNGN_ESCAPE_HATCH_DOWN
           || feat == DNGN_ESCAPE_HATCH_UP;
}

/** Is this feature a gate?
  * XXX: Why does this matter??
 */
bool feat_is_gate(dungeon_feature_type feat)
{
    if (feat_is_portal_entrance(feat)
        || feat_is_portal_exit(feat)
        || feat_is_hell_subbranch_exit(feat))
    {
        return true;
    }

    switch (feat)
    {
    case DNGN_ENTER_ABYSS:
    case DNGN_EXIT_THROUGH_ABYSS:
    case DNGN_EXIT_ABYSS:
    case DNGN_ABYSSAL_STAIR:
    case DNGN_ENTER_PANDEMONIUM:
    case DNGN_EXIT_PANDEMONIUM:
    case DNGN_TRANSIT_PANDEMONIUM:
    case DNGN_ENTER_VAULTS:
    case DNGN_EXIT_VAULTS:
    case DNGN_ENTER_ZOT:
    case DNGN_EXIT_ZOT:
    case DNGN_ENTER_HELL:
    case DNGN_EXIT_HELL:
    case DNGN_ENTER_DIS:
    case DNGN_ENTER_GEHENNA:
    case DNGN_ENTER_COCYTUS:
    case DNGN_ENTER_TARTARUS:
        return true;
    default:
        return false;
    }
}

/** What command do you use to traverse this feature?
 *
 *  @param feat the feature.
 *  @returns CMD_GO_UPSTAIRS if it's a stair up, CMD_GO_DOWNSTAIRS if it's a
 *           stair down, and CMD_NO_CMD if it can't be used to move.
 */
command_type feat_stair_direction(dungeon_feature_type feat)
{
    if (feat_is_portal_entrance(feat)
        || feat_is_branch_entrance(feat))
    {
        return CMD_GO_DOWNSTAIRS;
    }
    if (feat_is_portal_exit(feat)
        || feat_is_branch_exit(feat))
    {
        return CMD_GO_UPSTAIRS;
    }

    if (feat_is_altar(feat))
        return CMD_GO_DOWNSTAIRS; // arbitrary; consistent with shops

    switch (feat)
    {
    case DNGN_STONE_STAIRS_UP_I:
    case DNGN_STONE_STAIRS_UP_II:
    case DNGN_STONE_STAIRS_UP_III:
    case DNGN_ESCAPE_HATCH_UP:
    case DNGN_EXIT_HELL:
        return CMD_GO_UPSTAIRS;

    case DNGN_STONE_STAIRS_DOWN_I:
    case DNGN_STONE_STAIRS_DOWN_II:
    case DNGN_STONE_STAIRS_DOWN_III:
    case DNGN_ESCAPE_HATCH_DOWN:
    case DNGN_ENTER_ABYSS:
    case DNGN_EXIT_THROUGH_ABYSS:
    case DNGN_EXIT_ABYSS:
    case DNGN_ABYSSAL_STAIR:
    case DNGN_ENTER_PANDEMONIUM:
    case DNGN_EXIT_PANDEMONIUM:
    case DNGN_TRANSIT_PANDEMONIUM:
    case DNGN_TRANSPORTER:
    case DNGN_ENTER_SHOP:
        return CMD_GO_DOWNSTAIRS;

    default:
        return CMD_NO_CMD;
    }
}

/** Can you normally see through this feature?
 */
bool feat_is_opaque(dungeon_feature_type feat)
{
    return get_feature_def(feat).flags & FFT_OPAQUE;
}

/** Can you move into this feature in normal play?
 */
bool feat_is_solid(dungeon_feature_type feat)
{
    return get_feature_def(feat).flags & FFT_SOLID;
}

/** Can you wall jump against this feature? (Wu Jian)?
 */
bool feat_can_wall_jump_against(dungeon_feature_type feat)
{
    return feat_is_wall(feat)
           || feat == DNGN_GRATE
           || feat_is_closed_door(feat)
           || feat_is_tree(feat)
           || feat_is_statuelike(feat);
}

/** Can you move into this cell in normal play?
 */
bool cell_is_solid(const coord_def &c)
{
    return feat_is_solid(env.grid(c));
}

/** Can spells and other abilities target this cell?
 */
bool cell_is_invalid_target(const coord_def &c)
{
    return cell_is_solid(c) && !actor_at(c);
}

/** Can a human stand on this feature without flying?
 */
bool feat_has_solid_floor(dungeon_feature_type feat)
{
    return !feat_is_solid(feat) && feat != DNGN_DEEP_WATER
           && feat != DNGN_LAVA;
}

/** Is there enough dry floor on this feature to stand without penalty?
 */
bool feat_has_dry_floor(dungeon_feature_type feat)
{
    return feat_has_solid_floor(feat) && !feat_is_water(feat) && feat != DNGN_MUD;
}

/** Is this feature a variety of door?
 */
bool feat_is_door(dungeon_feature_type feat)
{
    return feat_is_closed_door(feat) || feat_is_open_door(feat);
}

/** Is this feature a variety of closed door?
 */
bool feat_is_closed_door(dungeon_feature_type feat)
{
    return feat == DNGN_CLOSED_DOOR
           || feat == DNGN_CLOSED_CLEAR_DOOR
           || feat_is_runed(feat)
           || feat == DNGN_SEALED_DOOR
           || feat == DNGN_SEALED_CLEAR_DOOR;
}

/** Is this feature a variety of open door?
 */
bool feat_is_open_door(dungeon_feature_type feat)
{
    return feat == DNGN_OPEN_DOOR
        || feat == DNGN_OPEN_CLEAR_DOOR
        || feat == DNGN_BROKEN_DOOR
        || feat == DNGN_BROKEN_CLEAR_DOOR;
}

/** Has this feature been sealed by a vault warden?
 */
bool feat_is_sealed(dungeon_feature_type feat)
{
    return feat == DNGN_SEALED_STAIRS_DOWN
        || feat == DNGN_SEALED_STAIRS_UP
        || feat == DNGN_SEALED_DOOR
        || feat == DNGN_SEALED_CLEAR_DOOR;
}

/** Is this feature a type of runed door?
 */
bool feat_is_runed(dungeon_feature_type feat)
{
    return feat == DNGN_RUNED_DOOR || feat == DNGN_RUNED_CLEAR_DOOR;
}

/** Is the original feature at this position runed, as in a runed door?
 */
bool cell_is_runed(const coord_def &p)
{
    // the orig_terrain call will check the actual terrain if there's no change
    return feat_is_runed(orig_terrain(p));
}

/** Is this feature a type of statue, i.e., granite or an idol?
 */
bool feat_is_statuelike(dungeon_feature_type feat)
{
    return feat == DNGN_ORCISH_IDOL
      || feat == DNGN_GRANITE_STATUE
      || feat == DNGN_METAL_STATUE
      || feat == DNGN_ZOT_STATUE;
}

/** Is this feature permanent, unalterable rock?
 */
bool feat_is_permarock(dungeon_feature_type feat)
{
    return feat == DNGN_PERMAROCK_WALL || feat == DNGN_CLEAR_PERMAROCK_WALL;
}

/** Is this feature an open expanse used only as a map border?
 */
bool feat_is_endless(dungeon_feature_type feat)
{
    return feat == DNGN_OPEN_SEA || feat == DNGN_LAVA_SEA
           || feat == DNGN_ENDLESS_SALT;
}

/** Can this feature be dug?
 */
bool feat_is_diggable(dungeon_feature_type feat)
{
    return feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL
           || feat == DNGN_SLIMY_WALL || feat == DNGN_GRATE
           || feat == DNGN_ORCISH_IDOL || feat == DNGN_GRANITE_STATUE
           || feat == DNGN_PETRIFIED_TREE || feat == DNGN_FRIGID_WALL;
}

/** Is this feature a type of trap?
 *
 *  @param feat the feature.
 *  @returns true if it's a trap.
 */
bool feat_is_trap(dungeon_feature_type feat)
{
    if (!is_valid_feature_type(feat))
        return false; // ???
    return get_feature_def(feat).flags & FFT_TRAP;
}

/** Is this feature a type of water that is too deep for most creatures to
*   wade through?
*/
bool feat_is_deep_water(dungeon_feature_type feat)
{
    return feat == DNGN_DEEP_WATER
           || feat == DNGN_OPEN_SEA;
}

/** Is this feature a type of water that is shallow enough to wade through?
*/
bool feat_is_shallow_water(dungeon_feature_type feat)
{
    return feat == DNGN_SHALLOW_WATER
           || feat == DNGN_TOXIC_BOG
           || feat == DNGN_MANGROVE;
}

/** Is this feature a type of water, with the concomitant dangers/bonuses?
 */
bool feat_is_water(dungeon_feature_type feat)
{
    return feat_is_shallow_water(feat)
           || feat_is_deep_water(feat);
}

/** Is this feature a kind of lava?
 */
bool feat_is_lava(dungeon_feature_type feat)
{
    return feat == DNGN_LAVA || feat == DNGN_LAVA_SEA;
}

static const pair<god_type, dungeon_feature_type> _god_altars[] =
{
    { GOD_ZIN, DNGN_ALTAR_ZIN },
    { GOD_SHINING_ONE, DNGN_ALTAR_SHINING_ONE },
    { GOD_KIKUBAAQUDGHA, DNGN_ALTAR_KIKUBAAQUDGHA },
    { GOD_YREDELEMNUL, DNGN_ALTAR_YREDELEMNUL },
    { GOD_XOM, DNGN_ALTAR_XOM },
    { GOD_VEHUMET, DNGN_ALTAR_VEHUMET },
    { GOD_OKAWARU, DNGN_ALTAR_OKAWARU },
    { GOD_MAKHLEB, DNGN_ALTAR_MAKHLEB },
    { GOD_SIF_MUNA, DNGN_ALTAR_SIF_MUNA },
    { GOD_TROG, DNGN_ALTAR_TROG },
    { GOD_NEMELEX_XOBEH, DNGN_ALTAR_NEMELEX_XOBEH },
    { GOD_ELYVILON, DNGN_ALTAR_ELYVILON },
    { GOD_LUGONU, DNGN_ALTAR_LUGONU },
    { GOD_BEOGH, DNGN_ALTAR_BEOGH },
    { GOD_JIYVA, DNGN_ALTAR_JIYVA },
    { GOD_FEDHAS, DNGN_ALTAR_FEDHAS },
    { GOD_CHEIBRIADOS, DNGN_ALTAR_CHEIBRIADOS },
    { GOD_ASHENZARI, DNGN_ALTAR_ASHENZARI },
    { GOD_DITHMENOS, DNGN_ALTAR_DITHMENOS },
    { GOD_GOZAG, DNGN_ALTAR_GOZAG },
    { GOD_QAZLAL, DNGN_ALTAR_QAZLAL },
    { GOD_RU, DNGN_ALTAR_RU },
#if TAG_MAJOR_VERSION == 34
    { GOD_PAKELLAS, DNGN_ALTAR_PAKELLAS },
#endif
    { GOD_USKAYAW, DNGN_ALTAR_USKAYAW },
    { GOD_HEPLIAKLQANA, DNGN_ALTAR_HEPLIAKLQANA },
    { GOD_WU_JIAN, DNGN_ALTAR_WU_JIAN },
    { GOD_IGNIS, DNGN_ALTAR_IGNIS },
    { GOD_ECUMENICAL, DNGN_ALTAR_ECUMENICAL },
};

COMPILE_CHECK(ARRAYSZ(_god_altars) == NUM_GODS );

/** Whose altar is this feature?
 *
 *  @param feat the feature.
 *  @returns GOD_NO_GOD if not an altar, otherwise the god_type of the god.
 */
god_type feat_altar_god(dungeon_feature_type feat)
{
    for (const auto &altar : _god_altars)
        if (altar.second == feat)
            return altar.first;

    return GOD_NO_GOD;
}

/** What feature is the altar of this god?
 *
 *  @param god the god.
 *  @returns DNGN_FLOOR for an invalid god, the god's altar otherwise.
 */
dungeon_feature_type altar_for_god(god_type god)
{
    for (const auto &altar : _god_altars)
        if (altar.first == god)
            return altar.second;

    return DNGN_FLOOR;
}

/** Is this feature an altar to any god?
 */
FEATFN_MEMOIZED(feat_is_altar, grid)
{
    return feat_altar_god(grid) != GOD_NO_GOD;
}

/** Is this feature an altar to the player's god?
 *
 *  @param feat the feature.
 *  @returns true if the player has a god and this is its altar.
 */
bool feat_is_player_altar(dungeon_feature_type grid)
{
    return !you_worship(GOD_NO_GOD) && you_worship(feat_altar_god(grid));
}

/** Is this feature a tree?
 */
bool feat_is_tree(dungeon_feature_type feat)
{
    return feat == DNGN_TREE || feat == DNGN_MANGROVE
        || feat == DNGN_PETRIFIED_TREE || feat == DNGN_DEMONIC_TREE;
}

/** Is this feature flammable?
 */
bool feat_is_flammable(dungeon_feature_type feat)
{
    return feat == DNGN_TREE || feat == DNGN_MANGROVE
        || feat == DNGN_DEMONIC_TREE;
}


/** Is this feature made of metal?
 */
bool feat_is_metal(dungeon_feature_type feat)
{
    return feat == DNGN_METAL_WALL || feat == DNGN_GRATE;
}

/** Is this feature ambivalent about whether we're going up or down?
 */
bool feat_is_bidirectional_portal(dungeon_feature_type feat)
{
    return get_feature_dchar(feat) == DCHAR_ARCH
           && feat_stair_direction(feat) != CMD_NO_CMD
           && !feat_is_hell_subbranch_exit(feat)
           && feat != DNGN_ENTER_ZOT
           && feat != DNGN_EXIT_ZOT
           && feat != DNGN_ENTER_VAULTS
           && feat != DNGN_EXIT_VAULTS
           && feat != DNGN_EXIT_HELL
           && feat != DNGN_ENTER_HELL;
}
/** Will this stair-like feature stick around after the player stops using it? (In descent mode?)
 */
bool feat_is_descent_exitable(dungeon_feature_type feat)
{
    return feat == DNGN_EXIT_DUNGEON
           || feat == DNGN_EXIT_HELL
           || feat == DNGN_EXIT_COCYTUS
           || feat == DNGN_EXIT_GEHENNA
           || feat == DNGN_EXIT_TARTARUS
           || feat == DNGN_EXIT_DIS;
}

/** Is this feature a type of fountain?
 */
bool feat_is_fountain(dungeon_feature_type feat)
{
    return feat == DNGN_FOUNTAIN_BLUE
           || feat == DNGN_FOUNTAIN_SPARKLING
           || feat == DNGN_FOUNTAIN_BLOOD
           || feat == DNGN_FOUNTAIN_EYES
           || feat == DNGN_DRY_FOUNTAIN;
}

/** Is this feature a pile of food?
 */
bool feat_is_food(dungeon_feature_type feat)
{
    return feat == DNGN_CACHE_OF_FRUIT
           || feat == DNGN_CACHE_OF_MEAT
           || feat == DNGN_CACHE_OF_BAKED_GOODS;
}

/** Is this feature non-solid enough that you can reach past it?
 */
bool feat_is_reachable_past(dungeon_feature_type feat)
{
    return !feat_is_opaque(feat)
        && !feat_is_wall(feat)
        && !feat_is_closed_door(feat)
        && feat != DNGN_GRATE;
}

/** Is this feature important to the game?
 *
 *  @param feat the feature.
 *  @returns true for altars, stairs/portals, and malign gateways (???).
 */
FEATFN_MEMOIZED(feat_is_critical, feat)
{
    return feat_stair_direction(feat) != CMD_NO_CMD
           || feat_altar_god(feat) != GOD_NO_GOD
           || feat == DNGN_TRANSPORTER_LANDING
           || feat == DNGN_MALIGN_GATEWAY
           || feat == DNGN_ORB_DAIS;
}

/** Can you use this feature for a map border?
 */
bool feat_is_valid_border(dungeon_feature_type feat)
{
    return feat_is_wall(feat)
           || feat_is_tree(feat)
           || feat == DNGN_OPEN_SEA
           || feat == DNGN_LAVA_SEA
           || feat == DNGN_ENDLESS_SALT;
}

/** Can this feature be a mimic?
 *
 *  @param feat the feature
 *  @param strict if true, disallow features for which being a mimic would be bad in
                  normal generation; vaults can still use such mimics.
 *  @returns whether this could make a valid mimic type.
 */
bool feat_is_mimicable(dungeon_feature_type feat, bool strict)
{
    if (!strict && feat != DNGN_FLOOR && feat != DNGN_SHALLOW_WATER
        && feat != DNGN_DEEP_WATER)
    {
        return true;
    }

    if (feat == DNGN_ENTER_ZIGGURAT)
        return false;

    if (feat == DNGN_ENTER_SHOP)
        return true;

    return false;
}

/** Can creatures on this feature be shafted?
 *
 * @param feat The feature in question.
 * @returns Whether creatures standing on this feature can be shafted (by
 *          magical effects, Formicid digging, etc).
 */
bool feat_is_shaftable(dungeon_feature_type feat)
{
    return feat_has_dry_floor(feat)
           && !feat_is_stair(feat)
           && !feat_is_portal(feat);
}

int count_neighbours_with_func(const coord_def& c, bool (*checker)(dungeon_feature_type))
{
    int count = 0;
    for (adjacent_iterator ai(c); ai; ++ai)
    {
        if (checker(env.grid(*ai)))
            count++;
    }
    return count;
}

// For internal use by find_connected_identical only.
static void _find_connected_identical(const coord_def &d,
                                      dungeon_feature_type ft,
                                      set<coord_def>& out,
                                      bool known_only)
{
    if (env.grid(d) != ft || (known_only && !env.map_knowledge(d).known()))
        return;

    string prop = env.markers.property_at(d, MAT_ANY, "connected_exclude");

    if (!prop.empty())
    {
        // Don't treat this square as connected to anything. Ignore it.
        // Continue the search in other directions.
        return;
    }

    if (out.insert(d).second)
    {
        _find_connected_identical(coord_def(d.x+1, d.y), ft, out, known_only);
        _find_connected_identical(coord_def(d.x-1, d.y), ft, out, known_only);
        _find_connected_identical(coord_def(d.x, d.y+1), ft, out, known_only);
        _find_connected_identical(coord_def(d.x, d.y-1), ft, out, known_only);
    }
}

// Find all connected cells containing ft, starting at d.
void find_connected_identical(const coord_def &d, set<coord_def>& out, bool known_only)
{
    string prop = env.markers.property_at(d, MAT_ANY, "connected_exclude");

    if (!prop.empty())
        out.insert(d);
    else
        _find_connected_identical(d, env.grid(d), out, known_only);
}

void get_door_description(int door_size, const char** adjective, const char** noun)
{
    const char* descriptions[] =
    {
        "miniscule " , "buggy door",
        ""           , "door",
        "large "     , "door",
        ""           , "gate",
        "huge "      , "gate",
    };

    int max_idx = static_cast<int>(ARRAYSZ(descriptions) - 2);
    const unsigned int idx = min(door_size*2, max_idx);

    *adjective = descriptions[idx];
    *noun = descriptions[idx+1];
}

static unique_ptr<map_mask_boolean> _slime_wall_precomputed_neighbour_mask;

static void _precompute_slime_wall_neighbours()
{
    map_mask_boolean &mask(*_slime_wall_precomputed_neighbour_mask);
    for (rectangle_iterator ri(1); ri; ++ri)
    {
        if (env.grid(*ri) == DNGN_SLIMY_WALL)
        {
            for (adjacent_iterator ai(*ri); ai; ++ai)
                mask(*ai) = true;
        }
    }
}

unwind_slime_wall_precomputer::unwind_slime_wall_precomputer(bool docompute)
    : did_compute_mask(false)
{
    if (!(env.level_state & LSTATE_SLIMY_WALL))
        return;

    if (docompute && !_slime_wall_precomputed_neighbour_mask)
    {
        did_compute_mask = true;
        _slime_wall_precomputed_neighbour_mask.reset(
            new map_mask_boolean(false));
        _precompute_slime_wall_neighbours();
    }
}

unwind_slime_wall_precomputer::~unwind_slime_wall_precomputer()
{
    if (did_compute_mask)
        _slime_wall_precomputed_neighbour_mask.reset(nullptr);
}

bool slime_wall_neighbour(const coord_def& c)
{
    if (!(env.level_state & LSTATE_SLIMY_WALL))
        return false;

    if (_slime_wall_precomputed_neighbour_mask)
        return (*_slime_wall_precomputed_neighbour_mask)(c);

    // Not using count_adjacent_slime_walls because the early return might
    // be relevant for performance here. TODO: profile it and find out.
    for (adjacent_iterator ai(c); ai; ++ai)
        if (env.grid(*ai) == DNGN_SLIMY_WALL)
            return true;
    return false;
}

int count_adjacent_slime_walls(const coord_def &pos)
{
    int count = 0;
    for (adjacent_iterator ai(pos); ai; ++ai)
        if (env.grid(*ai) == DNGN_SLIMY_WALL)
            count++;

    return count;
}

int slime_wall_corrosion(actor* act)
{
    ASSERT(act);

    if (actor_slime_wall_immune(act))
        return 0;

    return count_adjacent_slime_walls(act->pos()) * 4;
}

// slime wall damage under Jiyva's oozemancy; this should only affect monsters
void slime_wall_damage(actor* act, int delay)
{
    ASSERT(act);

    if (actor_slime_wall_immune(act))
        return;

    const int walls = count_adjacent_slime_walls(act->pos());
    if (!walls)
        return;

    const int strength = div_rand_round(3 * walls * delay, BASELINE_DELAY);
    const int base_dam = roll_dice(2, strength);
    const int dam = resist_adjust_damage(act, BEAM_ACID, base_dam);
    if (dam > 0 && you.see_cell_no_trans(act->pos()))
    {
        const char *verb = act->is_icy() ? "melt" : "burn";
        mprf((walls > 1) ? "The walls %s %s!" : "The wall %ss %s!",
              verb, act->name(DESC_THE).c_str());
        act->hurt(&you, dam, BEAM_ACID);
        if (act->alive())
            behaviour_event(act->as_monster(), ME_WHACK, &you, you.pos());
    }
}

int count_adjacent_icy_walls(const coord_def &pos)
{
    int count = 0;
    for (adjacent_iterator ai(pos); ai; ++ai)
        if (is_icecovered(*ai))
            count++;

    return count;
}

// Could an actor standing at a given position see a wall next to a given cell?
bool near_visible_wall(coord_def observer_pos, coord_def cell)
{
    if (!cell_see_cell(observer_pos, cell, LOS_NO_TRANS))
        return false;
    for (adjacent_iterator ai(cell); ai; ++ai)
        if (feat_is_wall(env.grid(*ai))
            && cell_see_cell(observer_pos, *ai, LOS_NO_TRANS))
        {
            return true;
        }
    return false;
}

void feat_splash_noise(dungeon_feature_type feat)
{
    if (crawl_state.generating_level)
        return;

    switch (feat)
    {
    case DNGN_SHALLOW_WATER:
    case DNGN_DEEP_WATER:
        mprf(MSGCH_SOUND, "You hear a splash.");
        return;

    case DNGN_LAVA:
        mprf(MSGCH_SOUND, "You hear a sizzling splash.");
        return;

    default:
        return;
    }
}

FEATFN_MEMOIZED(feat_suppress_blood, feat)
{
    if (feat_is_tree(feat))
        return true;

    if (feat == DNGN_DRY_FOUNTAIN || feat == DNGN_RUNELIGHT)
        return true;

    // covers shops and altars
    if (feat_stair_direction(feat) != CMD_NO_CMD)
        return true;

    if (feat == DNGN_MALIGN_GATEWAY)
        return true;

    if (feat == DNGN_TRAP_SHAFT)
        return true;

    return false;

}

/** Does this feature destroy any items that fall into it?
 */
bool feat_destroys_items(dungeon_feature_type feat)
{
    return feat == DNGN_LAVA;
}

/** Does this feature make items that fall into it permanently inaccessible?
 */
bool feat_eliminates_items(dungeon_feature_type feat)
{
    return feat_destroys_items(feat)
            // intentionally use the species version rather than the player
            // version: switching to an amphibious form doesn't give you access
            // to the items.
            || feat == DNGN_DEEP_WATER && !species::likes_water(you.species);
}

static coord_def _dgn_find_nearest_square(
    const coord_def &pos,
    function<bool (const coord_def &)> acceptable,
    function<bool (const coord_def &)> traversable = nullptr)
{
    bool visited[GXM][GYM];
    memset(&visited, 0, sizeof(visited));

    vector<coord_def> points[2];
    int iter = 0;
    points[iter].push_back(pos);

    // TODO: Deduplicate this BFS code (see commit for other two instances).
    while (!points[iter].empty())
    {
        // Iterate each layer of BFS in random order to avoid bias.
        shuffle_array(points[iter]);
        for (const auto &p : points[iter])
        {
            if (p != pos && acceptable(p))
                return p;

            visited[p.x][p.y] = true;
            for (adjacent_iterator ai(p); ai; ++ai)
            {
                const coord_def np = coord_def(ai->x, ai->y);
                if (!in_bounds(np) || visited[np.x][np.y])
                    continue;

                if (traversable && !traversable(np))
                    continue;

                points[!iter].push_back(np);
            }
        }

        points[iter].clear();
        iter = !iter;
    }

    return coord_def(0, 0); // Not found.
}

static bool _item_safe_square(const coord_def &pos)
{
    const dungeon_feature_type feat = env.grid(pos);
    return feat_is_traversable(feat)
            && !feat_is_closed_door(feat)
            && !feat_destroys_items(feat);
}

static bool _item_traversable_square(const coord_def &pos)
{
    return !cell_is_solid(pos);
}

static bool _item_visible_square(const coord_def &pos)
{
    return _item_safe_square(pos) && you.see_cell(pos) && you.pos() != pos;
}

// Moves an item on the floor to the nearest adjacent floor-space.
static bool _dgn_shift_item(const coord_def &pos, item_def &item,
                            bool keep_visible)
{
    // First try to avoid pushing things through solid features...
    coord_def np = _dgn_find_nearest_square(pos,
                                            keep_visible ? _item_visible_square
                                                         : _item_safe_square,
                                            _item_traversable_square);
    // ... but if we have to, so be it.
    if (!in_bounds(np) || np == pos)
        np = _dgn_find_nearest_square(pos, _item_safe_square);

    if (in_bounds(np) && np != pos)
    {
        int index = item.index();
        move_item_to_grid(&index, np);

        return true;
    }
    return false;
}

static bool _is_feature_shift_target(const coord_def &pos)
{
    return env.grid(pos) == DNGN_FLOOR && !dungeon_events.has_listeners_at(pos)
           && !actor_at(pos);
}

// Moves everything at src to dst. This is not a swap operation: src will be
// left with the same feature it started with, and should be overwritten with
// something new. Assumes there are no actors in the destination square.
//
// Things that are moved:
// 1. Dungeon terrain (set to DNGN_UNSEEN)
// 2. Actors (including the player)
// 3. Items
// 4. Clouds
// 5. Terrain properties
// 6. Terrain colours
// 7. Vault (map) mask
// 8. Vault id mask
// 9. Map markers, dungeon listeners, shopping list
//10. Player's knowledge
void dgn_move_entities_at(coord_def src, coord_def dst,
                          bool move_player,
                          bool move_monster,
                          bool move_items)
{
    if (!in_bounds(dst) || !in_bounds(src) || src == dst)
        return;

    move_notable_thing(src, dst);

    dungeon_feature_type dfeat = env.grid(src);
    if (dfeat == DNGN_ENTER_SHOP)
    {
        ASSERT(shop_at(src));
        env.shop[dst] = env.shop[src];
        env.shop[dst].pos = dst;
        env.shop.erase(src);
        env.grid(src) = DNGN_FLOOR;
    }
    else if (feat_is_trap(dfeat))
    {
        ASSERT(trap_at(src));
        env.trap[dst] = env.trap[src];
        env.trap[dst].pos = dst;
        env.trap.erase(src);
        env.grid(src) = DNGN_FLOOR;
    }

    env.grid(dst) = dfeat;

    if (move_monster || move_player)
        ASSERT(!actor_at(dst));

    if (move_monster)
    {
        if (monster* mon = monster_at(src))
        {
            mon->move_to(dst, MV_INTERNAL);
            if (mon->type == MONS_ELDRITCH_TENTACLE)
            {
                if (mon->props.exists(BASE_POSITION_KEY))
                {
                    coord_def delta = dst - src;
                    coord_def base_pos = mon->props[BASE_POSITION_KEY].get_coord();
                    base_pos += delta;
                    mon->props[BASE_POSITION_KEY].get_coord() = base_pos;
                }

            }
        }
    }

    if (move_player && you.pos() == src)
        you.shiftto(dst);

    if (move_items)
        move_item_stack_to_grid(src, dst);

    if (cell_is_solid(dst))
    {
        delete_cloud(src);
        delete_cloud(dst); // in case there was already a clear there
    }
    else
        move_cloud(src, dst);

    // Move terrain colours and properties.
    env.pgrid(dst) = env.pgrid(src);
    env.grid_colours(dst) = env.grid_colours(src);
#ifdef USE_TILE
    tile_env.bk_fg(dst) = tile_env.bk_fg(src);
    tile_env.bk_bg(dst) = tile_env.bk_bg(src);
    tile_env.bk_cloud(dst) = tile_env.bk_cloud(src);
#endif
    tile_env.flv(dst) = tile_env.flv(src);

    // Move vault masks.
    env.level_map_mask(dst) = env.level_map_mask(src);
    env.level_map_ids(dst) = env.level_map_ids(src);

    // Move markers, dungeon listeners and shopping list.
    env.markers.move(src, dst);
    dungeon_events.move_listeners(src, dst);
    shopping_list.move_things(src, dst);

    // Move player's knowledge.
    env.map_knowledge(dst) = env.map_knowledge(src);
    env.map_seen.set(dst, env.map_seen(src));
    StashTrack.move_stash(src, dst);
}

static bool _dgn_shift_feature(const coord_def &pos)
{
    const dungeon_feature_type dfeat = env.grid(pos);
    if (!feat_is_critical(dfeat) && !env.markers.find(pos, MAT_ANY))
        return false;

    const coord_def dest =
        _dgn_find_nearest_square(pos, _is_feature_shift_target);

    dgn_move_entities_at(pos, dest, false, false, false);
    return true;
}

void dgn_check_terrain_items(const coord_def &pos, bool preserve_items,
                             bool keep_in_sight)
{
    const dungeon_feature_type feat = env.grid(pos);

    int item = env.igrid(pos);
    while (item != NON_ITEM)
    {
        const int curr = item;
        item = env.item[item].link;

        if (!feat_is_solid(feat) && !feat_destroys_items(feat))
            continue;

        // Game-critical item.
        if (preserve_items || env.item[curr].is_critical())
            _dgn_shift_item(pos, env.item[curr], keep_in_sight);
        else
        {
            feat_splash_noise(feat);
            item_was_destroyed(env.item[curr]);
            destroy_item(curr);
        }
    }
}

static void _dgn_check_terrain_monsters(const coord_def &pos)
{
    if (monster* m = monster_at(pos))
        m->trigger_movement_effects();
}

// Clear blood or off of terrain that shouldn't have it. Also clear of blood if
// a bloody wall has been dug out and replaced by a floor, or if a bloody floor
// has been replaced by a wall.
static void _dgn_check_terrain_covering(const coord_def &pos,
                                     dungeon_feature_type old_feat,
                                     dungeon_feature_type new_feat)
{
    if (!testbits(env.pgrid(pos), FPROP_BLOODY))
        return;

    if (new_feat == DNGN_UNSEEN)
    {
        // Caller has already changed the grid, and old_feat is actually
        // the new feat.
        if (old_feat != DNGN_FLOOR && !feat_is_solid(old_feat))
            env.pgrid(pos) &= ~(FPROP_BLOODY);
    }
    else
    {
        if (feat_is_solid(old_feat) != feat_is_solid(new_feat)
            || feat_is_water(new_feat) || new_feat == DNGN_LAVA
            || feat_is_critical(new_feat))
        {
            env.pgrid(pos) &= ~(FPROP_BLOODY);
        }
    }
}

static void _dgn_check_terrain_player(const coord_def pos)
{
    if (crawl_state.generating_level || !crawl_state.need_save)
        return; // don't reference player if they don't currently exist

    if (pos != you.pos())
        return;

    if (you.can_pass_through(pos))
        you.trigger_movement_effects(MV_NO_TRAVEL_STOP);
    else
        push_or_teleport_actor_from(pos);
}

static void _current_terrain_changed(coord_def pos,
                                     dungeon_feature_type nfeat,
                                     bool preserve_features,
                                     bool preserve_items,
                                     bool wizmode,
                                     unsigned short flv_nfeat,
                                     unsigned short flv_nfeat_idx)
{
    if (env.grid(pos) == nfeat)
        return;

    // Cannot change the terrain beneath the orb's starting location by any means.
    if (env.grid(pos) == DNGN_ORB_DAIS)
        return;

    // If we're trying to place a wall on top of a monster, push it out of the
    // way first.
    if (feat_is_wall(nfeat) && monster_at(pos))
        push_or_teleport_actor_from(pos);
    if (feat_is_trap(nfeat) && env.trap.find(pos) == env.trap.end())
        place_specific_trap(pos, trap_type_from_feature(nfeat), 1);


    _dgn_check_terrain_covering(pos, env.grid(pos), nfeat);

    if (nfeat != DNGN_UNSEEN)
    {
        if (preserve_features)
            _dgn_shift_feature(pos);

        env.grid(pos) = nfeat;
        tile_env.flv(pos).feat = flv_nfeat;
        tile_env.flv(pos).feat_idx = flv_nfeat_idx;

        if (is_notable_terrain(nfeat) && you.see_cell(pos))
            seen_notable_thing(nfeat, pos);

        // Don't destroy a trap which was just placed.
        if (!feat_is_trap(nfeat))
            destroy_trap(pos);
    }

    dgn_check_terrain_items(pos, preserve_items);
    _dgn_check_terrain_monsters(pos);
    if (!wizmode)
        _dgn_check_terrain_player(pos);

    set_terrain_changed(pos);

    // Deal with doors being created by changing features.
    tile_init_flavour(pos);

    // If we just placed a trap under an actor, trigger it immediately.
    if (actor* act = actor_at(pos))
        if (feat_is_trap(nfeat))
            if (trap_def* ptrap = trap_at(pos))
                ptrap->trigger(*act);
}

static void _permanent_terrain_changed(coord_def pos,
                                       dungeon_feature_type nfeat)
{
    // XXX: do we ever call this with nfeat == DNGN_UNSEEN?
    if (nfeat != DNGN_UNSEEN)
        unnotice_feature(level_pos(level_id::current(), pos));
    env.level_map_mask(pos) &= ~MMT_MIMIC;
}

/**
 * Change a given feature to a new type, cleaning up associated issues
 * (monsters/items in walls, blood on water, etc) in the process.
 *
 * @param pos               The location to be changed.
 * @param nfeat             The feature to be changed to.
 * @param preserve_features Whether to shunt the old feature to a nearby loc.
 * @param preserve_items    Whether to shunt items to a nearby loc, if they
 *                          can't stay in this one.
 * @param wizmode           Whether this is a wizmode terrain change,
 *                          & shouldn't check whether the player can actually
 *                          exist in the new feature.
 */
void dungeon_terrain_changed(const coord_def &pos,
                             dungeon_feature_type nfeat,
                             bool preserve_features,
                             bool preserve_items,
                             bool wizmode)
{
    // XXX: If there is a temporary terrain change, reverting it will also
    // revert this change. This isn't always what we want and doesn't work well
    // with us calling _permanent_terrain_changed.
    _permanent_terrain_changed(pos, nfeat);
    _current_terrain_changed(pos, nfeat, preserve_features, preserve_items,
                             wizmode, 0, 0);
}

void dungeon_change_base_terrain(coord_def pos, dungeon_feature_type nfeat)
{
    bool temp_terrain = false;
    for (map_marker* marker : env.markers.get_markers_at(pos))
    {
        if (marker->get_type() != MAT_TERRAIN_CHANGE)
            continue;

        map_terrain_change_marker* tmarker =
            dynamic_cast<map_terrain_change_marker*>(marker);
        tmarker->old_feature = nfeat;
        tmarker->flv_old_feature = 0;
        tmarker->flv_old_feature_idx = 0;
        temp_terrain = true;
    }
    _permanent_terrain_changed(pos, nfeat);
    if (temp_terrain)
        return;
    _current_terrain_changed(pos, nfeat, false, true, false, 0, 0);
}

static void _announce_swap_real(coord_def orig_pos, coord_def dest_pos)
{
    const dungeon_feature_type orig_feat = env.grid(dest_pos);

    const string orig_name =
        feature_description_at(dest_pos, false,
                            you.see_cell(orig_pos) ? DESC_THE : DESC_A);

    string prep = feat_preposition(orig_feat, false);

    string orig_actor, dest_actor;
    if (orig_pos == you.pos())
        orig_actor = "you";
    else if (const monster* m = monster_at(orig_pos))
    {
        if (you.can_see(*m))
            orig_actor = m->name(DESC_THE);
    }

    if (dest_pos == you.pos())
        dest_actor = "you";
    else if (const monster* m = monster_at(dest_pos))
    {
        if (you.can_see(*m))
            dest_actor = m->name(DESC_THE);
    }

    ostringstream str;
    str << orig_name << " ";
    if (you.see_cell(orig_pos) && !you.see_cell(dest_pos))
    {
        str << "suddenly disappears";
        if (!orig_actor.empty())
            str << " from " << prep << " " << orig_actor;
    }
    else if (!you.see_cell(orig_pos) && you.see_cell(dest_pos))
    {
        str << "suddenly appears";
        if (!dest_actor.empty())
            str << " " << prep << " " << dest_actor;
    }
    else
    {
        str << "moves";
        if (!orig_actor.empty())
            str << " from " << prep << " " << orig_actor;
        if (!dest_actor.empty())
            str << " to " << prep << " " << dest_actor;
    }
    str << "!";
    mpr(str.str());
}

static void _announce_swap(coord_def pos1, coord_def pos2)
{
    if (!you.see_cell(pos1) && !you.see_cell(pos2))
        return;

    const dungeon_feature_type feat1 = env.grid(pos1);
    const dungeon_feature_type feat2 = env.grid(pos2);

    if (feat1 == feat2)
        return;

    const bool notable_seen1 = is_notable_terrain(feat1) && you.see_cell(pos1);
    const bool notable_seen2 = is_notable_terrain(feat2) && you.see_cell(pos2);

    if (notable_seen1 && notable_seen2)
    {
        _announce_swap_real(pos1, pos2);
        _announce_swap_real(pos2, pos1);
    }
    else if (notable_seen1)
        _announce_swap_real(pos2, pos1);
    else if (notable_seen2)
        _announce_swap_real(pos1, pos2);
    else if (you.see_cell(pos2))
        _announce_swap_real(pos1, pos2);
    else
        _announce_swap_real(pos2, pos1);
}

bool swap_features(const coord_def &pos1, const coord_def &pos2,
                   bool swap_everything, bool announce)
{
    ASSERT_IN_BOUNDS(pos1);
    ASSERT_IN_BOUNDS(pos2);
    ASSERT(pos1 != pos2);

    if (is_sanctuary(pos1) || is_sanctuary(pos2))
        return false;

    const dungeon_feature_type feat1 = env.grid(pos1);
    const dungeon_feature_type feat2 = env.grid(pos2);

    if (is_notable_terrain(feat1) && !you.see_cell(pos1)
        && env.map_knowledge(pos1).known())
    {
        return false;
    }

    if (is_notable_terrain(feat2) && !you.see_cell(pos2)
        && env.map_knowledge(pos2).known())
    {
        return false;
    }

    const unsigned short col1 = env.grid_colours(pos1);
    const unsigned short col2 = env.grid_colours(pos2);

    const terrain_property_t prop1 = env.pgrid(pos1);
    const terrain_property_t prop2 = env.pgrid(pos2);

    trap_def* trap1 = trap_at(pos1);
    trap_def* trap2 = trap_at(pos2);

    shop_struct* shop1 = shop_at(pos1);
    shop_struct* shop2 = shop_at(pos2);

    // Find a temporary holding place for pos1 stuff to be moved to
    // before pos2 is moved to pos1.
    coord_def temp(-1, -1);
    for (int x = X_BOUND_1 + 1; x < X_BOUND_2; x++)
    {
        for (int y = Y_BOUND_1 + 1; y < Y_BOUND_2; y++)
        {
            coord_def pos(x, y);
            if (pos == pos1 || pos == pos2)
                continue;

            if (!env.markers.find(pos, MAT_ANY)
                && !is_notable_terrain(env.grid(pos))
                && !cloud_at(pos))
            {
                temp = pos;
                break;
            }
        }
        if (in_bounds(temp))
            break;
    }

    if (!in_bounds(temp))
    {
        mprf(MSGCH_ERROR, "swap_features(): No boring squares on level?");
        return false;
    }

    // OK, now we guarantee the move.

    (void) move_notable_thing(pos1, temp);
    env.markers.move(pos1, temp);
    dungeon_events.move_listeners(pos1, temp);
    env.grid(pos1) = DNGN_UNSEEN;
    env.pgrid(pos1) = terrain_property_t{};

    (void) move_notable_thing(pos2, pos1);
    env.markers.move(pos2, pos1);
    dungeon_events.move_listeners(pos2, pos1);
    env.pgrid(pos1) = prop2;
    env.pgrid(pos2) = prop1;

    (void) move_notable_thing(temp, pos2);
    env.markers.move(temp, pos2);
    dungeon_events.move_listeners(temp, pos2);

    // Swap features and colours.
    env.grid(pos2) = feat1;
    env.grid(pos1) = feat2;

    env.grid_colours(pos1) = col2;
    env.grid_colours(pos2) = col1;

    // Swap traps.
    if (trap1 && !trap2)
    {
        env.trap[pos2] = env.trap[pos1];
        env.trap[pos2].pos = pos2;
        env.trap.erase(pos1);
    }
    else if (!trap1 && trap2)
    {
        env.trap[pos1] = env.trap[pos2];
        env.trap[pos1].pos = pos1;
        env.trap.erase(pos2);
    }
    else if (trap1 && trap2)
    {
        trap_def tmp = env.trap[pos1];
        env.trap[pos1] = env.trap[pos2];
        env.trap[pos2] = tmp;
        env.trap[pos1].pos = pos1;
        env.trap[pos2].pos = pos2;
    }

    // Swap shops.
    if (shop1 && !shop2)
    {
        env.shop[pos2] = env.shop[pos1];
        env.shop[pos2].pos = pos2;
        env.shop.erase(pos1);
    }
    else if (!shop1 && shop2)
    {
        env.shop[pos1] = env.shop[pos2];
        env.shop[pos1].pos = pos1;
        env.shop.erase(pos2);
    }
    else if (shop1 && shop2)
    {
        shop_struct tmp = env.shop[pos1];
        env.shop[pos1] = env.shop[pos2];
        env.shop[pos2] = tmp;
        env.shop[pos1].pos = pos1;
        env.shop[pos2].pos = pos2;
    }

    if (!swap_everything)
    {
        dgn_check_terrain_items(pos1, false);
        _dgn_check_terrain_monsters(pos1);
        _dgn_check_terrain_player(pos1);
        set_terrain_changed(pos1);

        dgn_check_terrain_items(pos2, false);
        _dgn_check_terrain_monsters(pos2);
        _dgn_check_terrain_player(pos2);
        set_terrain_changed(pos2);

        if (announce)
            _announce_swap(pos1, pos2);
        return true;
    }

    // Swap items.
    for (stack_iterator si(pos1); si; ++si)
        si->pos = pos1;

    for (stack_iterator si(pos2); si; ++si)
        si->pos = pos2;

    // Swap monsters.
    // Note that trapping nets, etc., move together
    // with the monster/player, so don't clear them.
    const int m1 = env.mgrid(pos1);
    const int m2 = env.mgrid(pos2);

    env.mgrid(pos1) = m2;
    env.mgrid(pos2) = m1;

    if (monster_at(pos1))
    {
        env.mons[env.mgrid(pos1)].set_position(pos1);
        env.mons[env.mgrid(pos1)].clear_invalid_constrictions();
    }
    if (monster_at(pos2))
    {
        env.mons[env.mgrid(pos2)].set_position(pos2);
        env.mons[env.mgrid(pos2)].clear_invalid_constrictions();
    }

    swap_clouds(pos1, pos2);

    if (pos1 == you.pos())
    {
        you.set_position(pos2);
        you.clear_invalid_constrictions();
        viewwindow();
        update_screen();
    }
    else if (pos2 == you.pos())
    {
        you.set_position(pos1);
        you.clear_invalid_constrictions();
        viewwindow();
        update_screen();
    }

    set_terrain_changed(pos1);
    set_terrain_changed(pos2);

    if (announce)
        _announce_swap(pos1, pos2);

    return true;
}

static bool _ok_dest_cell(const actor* orig_actor,
                          const dungeon_feature_type orig_feat,
                          const coord_def dest_pos)
{
    const dungeon_feature_type dest_feat = env.grid(dest_pos);

    if (orig_feat == dest_feat)
        return false;

    if (is_notable_terrain(dest_feat))
        return false;

    if (trap_at(dest_pos))
        return false;

    actor* dest_actor = actor_at(dest_pos);

    if (orig_actor && !orig_actor->is_habitable_feat(dest_feat))
        return false;
    if (dest_actor && !dest_actor->is_habitable_feat(orig_feat))
        return false;

    return true;
}

bool slide_feature_over(const coord_def &src, coord_def preferred_dest,
                        bool announce)
{
    ASSERT_IN_BOUNDS(src);

    const dungeon_feature_type orig_feat = env.grid(src);
    const actor* orig_actor = actor_at(src);

    if (in_bounds(preferred_dest)
        && _ok_dest_cell(orig_actor, orig_feat, preferred_dest))
    {
        ASSERT(preferred_dest != src);
    }
    else
    {
        int squares = 0;
        for (adjacent_iterator ai(src); ai; ++ai)
        {
            if (_ok_dest_cell(orig_actor, orig_feat, *ai)
                && one_chance_in(++squares))
            {
                preferred_dest = *ai;
            }
        }
    }

    if (!in_bounds(preferred_dest))
        return false;

    ASSERT(preferred_dest != src);
    return swap_features(src, preferred_dest, false, announce);
}

/**
 * Apply harmful environmental effects from the current tile terrain to the
 * player.
 *
 * @param entry     The terrain type in question.
 */
void fall_into_a_pool(dungeon_feature_type terrain)
{
    if (terrain == DNGN_DEEP_WATER && (you.can_water_walk()
                                       || form_can_swim()))
    {
        return;
    }

    mprf("You fall into the %s!",
         (terrain == DNGN_LAVA)       ? "lava" :
         (terrain == DNGN_DEEP_WATER) ? "water"
                                      : "programming rift");
    // included in default force_more_message
    enable_emergency_flight();
}

typedef map<string, dungeon_feature_type> feat_desc_map;
static feat_desc_map feat_desc_cache;

void init_feat_desc_cache()
{
    for (int i = 0; i < NUM_FEATURES; i++)
    {
        dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);
        string               desc = feature_description(feat);

        lowercase(desc);
        if (!feat_desc_cache.count(desc))
            feat_desc_cache[desc] = feat;
    }
}

dungeon_feature_type feat_by_desc(string desc)
{
    lowercase(desc);

#if TAG_MAJOR_VERSION == 34
    // hard-coded because all the dry fountain variants match this description,
    // and they have a lower enum value, so the first is incorrectly returned
    if (desc == "a dry fountain")
        return DNGN_DRY_FOUNTAIN;
#endif

    return lookup(feat_desc_cache, desc, DNGN_UNSEEN);
}

// If active is true, the player is just stepping onto the feature, with the
// message: "<feature> slides away as you move <prep> it!"
// Else, the actor is already on the feature:
// "<feature> moves from <prep origin> to <prep destination>!"
string feat_preposition(dungeon_feature_type feat, bool active, const actor* who)
{
    const bool         airborne = !who || who->airborne();
    const command_type dir      = feat_stair_direction(feat);

    if (dir == CMD_NO_CMD)
    {
        if (feat == DNGN_STONE_ARCH)
            return "beside";
        else if (feat_is_solid(feat)) // Passwall?
        {
            if (active)
                return "inside";
            else
                return "around";
        }
        else if (!airborne)
        {
            if (feat == DNGN_LAVA || feat_is_water(feat))
            {
                if (active)
                    return "into";
                else
                    return "around";
            }
            else
            {
                if (active)
                    return "onto";
                else
                    return "under";
            }
        }
    }

    if (dir == CMD_GO_UPSTAIRS && feat_is_escape_hatch(feat))
    {
        if (active)
            return "under";
        else
            return "above";
    }

    if (airborne)
    {
        if (active)
            return "over";
        else
            return "beneath";
    }

    if (dir == CMD_GO_DOWNSTAIRS
        && (feat_is_staircase(feat) || feat_is_escape_hatch(feat)))
    {
        if (active)
            return "onto";
        else
            return "beneath";
    }
    else
        return "beside";
}

string stair_climb_verb(dungeon_feature_type feat)
{
    ASSERT(feat_stair_direction(feat) != CMD_NO_CMD);

    if (feat_is_staircase(feat))
        return "climb";
    else if (feat_is_escape_hatch(feat))
        return "use";
    else
        return "pass through";
}

/** Find the feature with this name.
 *
 *  @param name The name (not the user-visible one) to be matched.
 *  @returns DNGN_UNSEEN if name is "", DNGN_FLOOR if the name is for a
 *           dead/forbidden god, and the first entry in the enum with a
 *           matching name otherwise.
 */
dungeon_feature_type dungeon_feature_by_name(const string &name)
{
    if (name.empty())
        return DNGN_UNSEEN;

    for (unsigned i = 0; i < NUM_FEATURES; ++i)
    {
        dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);

        if (!is_valid_feature_type(feat))
            continue;

        if (get_feature_def(feat).vaultname == name)
        {

            if (feat_is_altar(feat)
                && is_unavailable_god(feat_altar_god(feat)))
            {
                return DNGN_FLOOR;
            }

            return feat;
        }
    }

    return DNGN_UNSEEN;
}

/** Find feature names that contain this name.
 *
 *  @param name The string to be matched.
 *  @returns a list of matching names.
 */
vector<string> dungeon_feature_matches(const string &name)
{
    vector<string> matches;

    if (name.empty())
        return matches;

    for (unsigned i = 0; i < NUM_FEATURES; ++i)
    {
        dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);

        if (!is_valid_feature_type(feat))
            continue;

        const char *featname = get_feature_def(feat).vaultname;
        if (strstr(featname, name.c_str()))
            matches.emplace_back(featname);
    }

    return matches;
}

/** Get the lua/wizmode name for a feature.
 *
 *  @param rfeat The feature type to be found.
 *  @returns nullptr if rfeat is not defined, the vaultname of the corresponding
 *           feature_def otherwise.
 */
const char *dungeon_feature_name(dungeon_feature_type rfeat)
{
    if (!is_valid_feature_type(rfeat))
        return nullptr;

    return get_feature_def(rfeat).vaultname;
}

void destroy_wall(const coord_def& p)
{
    if (!in_bounds(p))
        return;

    // Blood does not transfer onto floor.
    if (is_bloodcovered(p))
        env.pgrid(p) &= ~(FPROP_BLOODY);

    _revert_terrain_to(p,
            env.grid(p) == DNGN_MANGROVE ? DNGN_SHALLOW_WATER : DNGN_FLOOR);
    env.level_map_mask(p) |= MMT_TURNED_TO_FLOOR;
}

const char* feat_type_name(dungeon_feature_type feat)
{
    if (feat_is_door(feat))
        return "door";
    if (feat_is_wall(feat))
        return "wall";
    if (feat == DNGN_GRATE)
        return "grate";
    if (feat_is_tree(feat))
        return "tree";
    if (feat_is_statuelike(feat))
        return "statue";
    if (feat_is_water(feat))
        return "water";
    if (feat_is_lava(feat))
        return "lava";
    if (feat_is_altar(feat))
        return "altar";
    if (feat_is_trap(feat))
        return "trap";
    if (feat_is_escape_hatch(feat))
        return "escape hatch";
    if (feat_is_portal(feat) || feat_is_gate(feat))
        return "portal";
    if (feat_is_travelable_stair(feat))
        return "staircase";
    if (feat == DNGN_ENTER_SHOP || feat == DNGN_ABANDONED_SHOP)
        return "shop";
    if (feat_is_fountain(feat))
        return "fountain";
    if (feat == DNGN_ORB_DAIS)
        return "dais";
    if (feat == DNGN_UNSEEN)
        return "unknown terrain";
    return "floor";
}

void set_terrain_changed(const coord_def p)
{
    if (cell_is_solid(p))
        delete_cloud(p);

    if (env.grid(p) == DNGN_SLIMY_WALL)
        env.level_state |= LSTATE_SLIMY_WALL;
    if (env.grid(p) == DNGN_PASSAGE_OF_GOLUBRIA)
        env.level_state |= LSTATE_GOLUBRIA;
    else if (env.grid(p) == DNGN_OPEN_DOOR)
    {
        // Restore colour from door-change markers
        for (map_marker *marker : env.markers.get_markers_at(p))
        {
            if (marker->get_type() == MAT_TERRAIN_CHANGE)
            {
                map_terrain_change_marker* tmarker =
                    dynamic_cast<map_terrain_change_marker*>(marker);

                if (tmarker->change_type == TERRAIN_CHANGE_DOOR_SEAL
                    && tmarker->colour != BLACK)
                {
                    // Restore the unsealed colour.
                    dgn_set_grid_colour_at(p, tmarker->colour);
                    break;
                }
            }
        }
    }

    env.map_knowledge(p).flags |= MAP_CHANGED_FLAG;

    dungeon_events.fire_position_event(DET_FEAT_CHANGE, p);

    los_terrain_changed(p);
}

/**
 * Does this cell count for exploration piety?
 *
 * Don't count: endless map borders, deep water, lava, and cells explicitly
 * marked. (player_view_update_at in view.cc updates the flags)
 */
bool cell_triggers_conduct(const coord_def p)
{
    return !(feat_is_endless(env.grid(p))
             || env.grid(p) == DNGN_LAVA
             || env.grid(p) == DNGN_DEEP_WATER
             || env.pgrid(p) & FPROP_SEEN_OR_NOEXP);
}

bool is_boring_terrain(dungeon_feature_type feat)
{
    if (!is_notable_terrain(feat))
        return true;

    // Altars in the temple are boring, as are any you can never use.
    if (feat_is_altar(feat) && (player_in_branch(BRANCH_TEMPLE)
        || !player_can_join_god(feat_altar_god(feat), false)))
    {
        return true;
    }

    // These were DNGN_ENTER_HELL, but would never be the first you see.
    if (feat_is_hell_subbranch_exit(feat))
        return true;

    // Only note the first entrance to the Abyss/Pan/Hell
    // which is found.
    if ((feat == DNGN_ENTER_ABYSS || feat == DNGN_ENTER_PANDEMONIUM
         || feat == DNGN_ENTER_HELL)
         && overview_knows_num_portals(feat) > 1)
    {
        return true;
    }

    return false;
}

dungeon_feature_type orig_terrain(coord_def pos)
{
    const map_marker *mark = env.markers.find(pos, MAT_TERRAIN_CHANGE);
    if (!mark)
        return env.grid(pos);

    const map_terrain_change_marker *terch
        = dynamic_cast<const map_terrain_change_marker *>(mark);
    ASSERTM(terch, "%s has incorrect class", mark->debug_describe().c_str());

    return terch->old_feature;
}

dungeon_feature_type orig_terrain_no_mimic(coord_def pos)
{
    if (base_feature_is_mimic_at(pos))
        return DNGN_FLOOR;
    return orig_terrain(pos);
}

void temp_change_terrain(coord_def pos, dungeon_feature_type newfeat, int dur,
                         terrain_change_type type, int mid)
{
    dungeon_feature_type old_feat = env.grid(pos);

    // We can't actually change this, so don't add a map marker that will add
    // a confusing 'summoned' to the feature name when examining it.
    if (old_feat == DNGN_ORB_DAIS)
        return;

    tile_flavour old_flv = tile_env.flv(pos);
    for (map_marker *marker : env.markers.get_markers_at(pos))
    {
        if (marker->get_type() == MAT_TERRAIN_CHANGE)
        {
            map_terrain_change_marker* tmarker =
                    dynamic_cast<map_terrain_change_marker*>(marker);

            // If change type matches, just modify old one; no need to add new one
            if (tmarker->change_type == type)
            {
                if (tmarker->new_feature == newfeat)
                {
                    if (tmarker->duration < dur)
                    {
                        tmarker->duration = dur;
                        tmarker->mon_num = mid;
                    }
                }
                else
                {
                    tmarker->new_feature = newfeat;
                    tmarker->duration = dur;
                    tmarker->mon_num = mid;
                }
                // ensure that terrain change happens. Sometimes a terrain
                // change marker can get stuck; this allows re-doing such
                // cases. Also probably needed by the else case above.
                _current_terrain_changed(pos, newfeat, false, true, false,
                                         0, 0);
                return;
            }
            else
            {
                old_feat = tmarker->old_feature;
                old_flv.feat = tmarker->flv_old_feature;
                old_flv.feat_idx = tmarker->flv_old_feature_idx;
            }
        }
    }

    // If we are trying to change terrain into what it already is, don't actually
    // add another marker (unless the current terrain is due to some OTHER marker)
    if (env.grid(pos) == newfeat && newfeat == old_feat)
        return;

    map_terrain_change_marker *marker =
        new map_terrain_change_marker(pos, old_feat, newfeat, old_flv.feat,
                                      old_flv.feat_idx, dur, type, mid,
                                      env.grid_colours(pos));
    env.markers.add(marker);
    env.markers.clear_need_activate();
    _current_terrain_changed(pos, newfeat, false, true, false, 0, 0);
}

static bool _revert_terrain_to(coord_def pos, dungeon_feature_type feat)
{
    dungeon_feature_type newfeat = feat;
    for (map_marker *marker : env.markers.get_markers_at(pos))
    {
        if (marker->get_type() == MAT_TERRAIN_CHANGE)
        {
            map_terrain_change_marker* tmarker =
                    dynamic_cast<map_terrain_change_marker*>(marker);

            // Don't revert sealed doors to normal doors if we're trying to
            // remove the door altogether
            // Same for destroyed trees and slime walls
            if ((tmarker->change_type == TERRAIN_CHANGE_DOOR_SEAL
                || tmarker->change_type == TERRAIN_CHANGE_FORESTED
                || tmarker->change_type == TERRAIN_CHANGE_SLIME)
                && newfeat == feat)
            {
                env.markers.remove(tmarker);
            }
            else
            {
                newfeat = tmarker->old_feature;
                if (tmarker->new_feature == env.grid(pos))
                    env.markers.remove(tmarker);
            }
        }
    }

    if (env.grid(pos) == DNGN_RUNED_DOOR && newfeat != DNGN_RUNED_DOOR
        || env.grid(pos) == DNGN_RUNED_CLEAR_DOOR
           && newfeat != DNGN_RUNED_CLEAR_DOOR)
    {
        explored_tracked_feature(env.grid(pos));
    }

    env.grid(pos) = newfeat;
    set_terrain_changed(pos);

    tileidx_t old_floortile = tile_env.flv(pos).floor;
    tileidx_t old_floor_idx = tile_env.flv(pos).floor_idx;

    tile_clear_flavour(pos);
    tile_init_flavour(pos);

    // respect vault FTILE directives
    if (newfeat == DNGN_FLOOR)
    {
        if (old_floortile)
            tile_env.flv(pos).floor = old_floortile;
        if (old_floor_idx)
            tile_env.flv(pos).floor_idx = old_floor_idx;
    }

    return true;
}

// If ctype == NUM_TERRAIN_CHANGE_TYPES, will revert *all* terrain changes on
// the given pos.
bool revert_terrain_change(coord_def pos, terrain_change_type ctype)
{
    dungeon_feature_type newfeat = DNGN_UNSEEN;
    unsigned short newfeat_flv = 0;
    unsigned short newfeat_flv_idx = 0;
    int colour = BLACK;

    for (map_marker *marker : env.markers.get_markers_at(pos))
    {
        if (marker->get_type() == MAT_TERRAIN_CHANGE)
        {
            map_terrain_change_marker* tmarker =
                    dynamic_cast<map_terrain_change_marker*>(marker);

            if (tmarker->change_type == ctype || ctype == NUM_TERRAIN_CHANGE_TYPES)
            {
                if (tmarker->colour != BLACK)
                    colour = tmarker->colour;
                if (!newfeat)
                {
                    newfeat = tmarker->old_feature;
                    newfeat_flv = tmarker->flv_old_feature;
                    newfeat_flv_idx = tmarker->flv_old_feature_idx;
                }
                env.markers.remove(tmarker);
            }
            else
            {
                // If we had an old colour, give it to the other marker.
                if (colour != BLACK)
                    tmarker->colour = colour;
                colour = BLACK;
                newfeat = tmarker->new_feature;
                newfeat_flv = 0;
                newfeat_flv_idx = 0;
            }
        }
    }

    if (newfeat == DNGN_UNSEEN)
        return false;

    // Don't revert opened sealed doors.
    if (feat_is_door(newfeat) && env.grid(pos) == DNGN_OPEN_DOOR)
        return false;

    if (ctype == TERRAIN_CHANGE_BOG)
        env.map_knowledge(pos).set_feature(newfeat, colour);
    _current_terrain_changed(pos, newfeat, false, true, false, newfeat_flv,
                             newfeat_flv_idx);
    env.grid_colours(pos) = colour;
    return true;
}

bool is_temp_terrain(coord_def pos)
{
    for (map_marker *marker : env.markers.get_markers_at(pos))
        if (marker->get_type() == MAT_TERRAIN_CHANGE)
            return true;

    return false;
}

bool plant_forbidden_at(const coord_def &p, bool connectivity_only)
{
    // .... Prevent this arrangement by never placing a plant in a way that
    // #P##  locally disconnects two adjacent cells. We scan clockwise around
    // ##.#  p looking for maximal contiguous sequences of traversable cells.
    // #?##  If we find more than one (and they don't join up cyclically),
    //       reject the configuration so the plant doesn't disconnect floor.
    //
    // ...   We do reject many non-problematic cases, such as this one; dpeg
    // #P#   suggests doing a connectivity check in ruination after placing
    // ...   plants, and removing cut-point plants then.

    // First traversable index, last consecutive traversable index, and
    // the next traversable index after last+1.
    int first = -1, last = -1, next = -1;
    int passable = 0;
    for (int i = 0; i < 8; i++)
    {
        coord_def q = p + Compass[i];

        if (feat_is_traversable(env.grid(q), true))
        {
            ++passable;
            if (first < 0)
                first = i;
            else if (last >= 0 && next < 0)
            {
                // Found a maybe-disconnected traversable cell. This is only
                // acceptable if it might connect up at the end.
                if (first == 0)
                    next = i;
                else
                    return true;
            }
        }
        else
        {
            if (first >= 0 && last < 0)
                last = i - 1;
            else if (next >= 0)
                return true;
        }
    }

    // ?#. Forbid this arrangement when the ? squares are walls.
    // #P#  If multiple plants conspire to do something similar, that's
    // ##?  fine: we just want to avoid the most common occurrences.
    //      This would be an info leak (that at least one ? is not a wall)
    //      were it not for the previous check.

    return passable <= 1 && !connectivity_only;
}

/*
 * Find an adjacent space to displace a stack of items or a creature.
 *
 * @param pos the starting position to displace from.
 * @param push_actor true if the goal is to move an actor, false if items
 * @param excluded any spots to rule out a priori. Used for e.g. imprison and
 *                       for multi-space doors.
 *
 * @return a (possibly empty) vector of positions where displacement is
 *                       possible. If `push_actor` is true but there is no
 *                       actor at the position, will return an empty list.
 */
vector<coord_def> get_push_spaces(const coord_def& pos, bool push_actor,
                    const vector<coord_def>* excluded)
{
    vector<coord_def> results;
    actor *act = nullptr;
    if (push_actor)
    {
        act = actor_at(pos);
        if (!act || act->is_stationary() || act->resists_dislodge())
            return results;
    }

    dungeon_feature_type starting_feat = env.grid(pos);
    vector<coord_def> bad_spots; // used for items

    for (adjacent_iterator ai(pos); ai; ++ai)
    {
        dungeon_feature_type feat = env.grid(*ai);

        // Make sure the spot wasn't already vetoed. This is used e.g. for
        // imprison, to pre-exclude all the spots where a wall will be.
        if (excluded && find(begin(*excluded), end(*excluded), *ai)
                            != end(*excluded))
        {
            continue;
        }

        // can never push to a solid space
        if (feat_is_solid(feat))
            continue;

        // Extra checks if we're moving a monster instead of an item
        if (push_actor)
        {
            // these should get deep water and lava for cases where they matter
            if (actor_at(*ai)
                || !act->can_pass_through(*ai)
                || !act->is_habitable(*ai))
            {
                continue;
            }
            results.push_back(*ai);
        }
        else
        {
            if (feat_has_solid_floor(feat))
                results.push_back(*ai);
            else if (starting_feat == DNGN_DEEP_WATER
                && feat == DNGN_DEEP_WATER)
            {
                // Dispreferentially allow pushing items from deep water to
                // deep water. Without this, zin imprison fails over deep
                // water if there are items, even if the player can't see
                // them.
                bad_spots.push_back(*ai);
            }
            // otherwise, can't position an item on this spot
        }
    }
    if (!results.empty())
        return results;
    return bad_spots;
}

bool has_push_spaces(const coord_def& pos, bool push_actor,
                    const vector<coord_def>* excluded)
{
    return !get_push_spaces(pos, push_actor, excluded).empty();
}

/**
 * Push items from `pos`, splashing them around whatever available spaces
 * there are.
 * @param pos the source position.
 * @param excluded positions that are a priori unavailable.
 *
 * @return true if any items moved, false otherwise. (Will return false if there
 *         were no items.)
 */
bool push_items_from(const coord_def& pos, const vector<coord_def>* excluded)
{
    vector<coord_def> targets = get_push_spaces(pos, false, excluded);
    bool result = false;
    if (targets.empty())
        return false;
    // TODO: splashing is flavorful, but how annoying is it in practice?
    while (env.igrid(pos) != NON_ITEM)
        result |= move_top_item(pos, targets[random2(targets.size())]);
    return result;
}

/**
 * Push an actor from `pos` to some available space, if possible.
 *
 * @param pos the source position.
 * @param excluded excluded positions that are a priori unavailable.
 * @param random whether to chose the position randomly, or deterministically.
 *        (Useful for systematically moving a bunch of actors at once, when you
 *        need to worry about domino effects.)
 *
 * @return the new coordinates for the actor.
 */
coord_def push_actor_from(const coord_def& pos,
                          const vector<coord_def>* excluded, bool random)
{
    actor* act = actor_at(pos);
    if (!act)
        return coord_def(0,0);
    vector<coord_def> targets = get_push_spaces(pos, true, excluded);
    if (targets.empty())
        return coord_def(0,0);
    const coord_def newpos = random ? targets[random2(targets.size())]
                                    : targets.front();
    ASSERT(!newpos.origin());
    act->move_to(newpos, MV_INTERNAL);
    // The new position of the monster might be used as an additional veto spot
    // for other monsters.
    return newpos;
}

/**
 * Move an actor from 'pos' to some available space, by increasingly forceful
 * means. Will first try to push into an adjacent moveable space. If none is
 * available, will instead move into the closest habitable space without LOS_RADIUS.
 * (Note: there is no guarantee that this isn't on the other side of a wall, but
 * since this is usually used to push things OUT of walls, that is acceptable).
 * Finally, if this fails, simply teleport the actor at random.
 *
 * @return the new coordinates for the actor.
 */
coord_def push_or_teleport_actor_from(const coord_def& pos)
{
    actor* act = actor_at(pos);
    if (!act)
        return coord_def(0,0);

    if (push_actor_from(pos, nullptr, true).origin())
    {
        for (distance_iterator di(pos, true, true); di; ++di)
        {
            if (!actor_at(*di)
                && ((act->is_player()
                     && you.can_pass_through(*di)
                     && !is_feat_dangerous(env.grid(*di))
                     && !testbits(env.pgrid(*di), FPROP_NO_TELE_INTO))
                    || act->is_monster() && monster_habitable_grid(act->as_monster(), *di)))
            {
                act->move_to(*di, MV_INTERNAL);
                return act->pos();
            }
        }
    }

    return act->pos();
}

/** Close any door at the given position. Handles the grid change, but does not
 * mark terrain or do any event handling.
 *
 * @param dest The location of the door.
 */
void dgn_close_door(const coord_def &dest)
{
    if (!feat_is_open_door(env.grid(dest)))
        return;

    // Yes, this fixes broken doors.
    const auto feat = env.grid(dest);
    if (feat == DNGN_OPEN_CLEAR_DOOR || feat == DNGN_BROKEN_CLEAR_DOOR)
        env.grid(dest) = DNGN_CLOSED_CLEAR_DOOR;
    else
        env.grid(dest) = DNGN_CLOSED_DOOR;
}

/** Open any door at the given position. Handles the grid change, but does not
 * mark terrain or do any event handling.
 *
 * @param dest The location of the door.
 */
void dgn_open_door(const coord_def &dest)
{
    if (!feat_is_closed_door(env.grid(dest)))
        return;

    if (env.grid(dest) == DNGN_CLOSED_CLEAR_DOOR
        || env.grid(dest) == DNGN_RUNED_CLEAR_DOOR)
    {
        env.grid(dest) = DNGN_OPEN_CLEAR_DOOR;
    }
    else
        env.grid(dest) = DNGN_OPEN_DOOR;
}

/** Breaks any door at the given position. Handles the grid change, but does not
 * mark terrain or do any event handling.
 *
 * @param dest The location of the door.
 */
void dgn_break_door(const coord_def &dest)
{
    if (!feat_is_closed_door(env.grid(dest)))
        return;

    if (env.grid(dest) == DNGN_CLOSED_CLEAR_DOOR
        || env.grid(dest) == DNGN_RUNED_CLEAR_DOOR)
    {
        env.grid(dest) = DNGN_BROKEN_CLEAR_DOOR;
    }
    else
        env.grid(dest) = DNGN_BROKEN_DOOR;
}


void ice_wall_damage(monster &mons, int delay)
{
    if (!you.duration[DUR_FROZEN_RAMPARTS]
        || !you.see_cell_no_trans(mons.pos())
        || !could_harm_enemy(&you, &mons))
    {
        return;
    }

    const int walls = count_adjacent_icy_walls(mons.pos());
    if (!walls)
        return;

    const int pow = you.props[FROZEN_RAMPARTS_POWER_KEY].get_int();
    const int undelayed_dam = ramparts_damage(pow).roll();
    const int post_ac_dam = mons.apply_ac(undelayed_dam);
    const int orig_dam = div_rand_round(delay * post_ac_dam, BASELINE_DELAY);

    bolt beam;
    beam.flavour = BEAM_COLD;
    beam.thrower = KILL_YOU;
    int dam = mons_adjust_flavoured(&mons, beam, orig_dam);
    mprf("The wall freezes %s%s%s",
         you.can_see(mons) ? mons.name(DESC_THE).c_str() : "something",
         dam ? "" : " but does no damage",
         attack_strength_punctuation(dam).c_str());

    if (dam > 0)
    {
        mons.hurt(&you, dam, BEAM_COLD);

        if (mons.alive())
        {
            behaviour_event(&mons, ME_WHACK, &you);
            mons.expose_to_element(BEAM_COLD, orig_dam, &you);
        }
    }
}

void frigid_walls_damage(int delay)
{
    for (monster_near_iterator mi(you.pos(), LOS_NO_TRANS); mi; ++mi)
    {
        if (mi->wont_attack())
            continue;

        int wall_count = 0;
        for (adjacent_iterator ai(mi->pos()); ai; ++ai)
            if (env.grid(*ai) == DNGN_FRIGID_WALL)
                ++wall_count;

        if (wall_count == 0)
            continue;

        int base_dmg = get_form()->get_special_damage().roll();
        const int wall_bonus = (wall_count - 1) * 100 / 6;
        base_dmg = div_rand_round(base_dmg * (100 + wall_bonus), 100);

        const int post_ac_dam = mi->apply_ac(base_dmg);
        const int orig_dam = div_rand_round(delay * post_ac_dam, BASELINE_DELAY);

        bolt beam;
        beam.flavour = BEAM_COLD;
        beam.thrower = KILL_YOU;
        int dam = mons_adjust_flavoured(*mi, beam, orig_dam);
        mprf("The frigid air chills %s%s%s",
            you.can_see(**mi) ? mi->name(DESC_THE).c_str() : "something",
            dam ? "" : " but does no damage",
            attack_strength_punctuation(dam).c_str());

        if (dam > 0)
        {
            mi->hurt(&you, dam, BEAM_COLD);

            if (mi->alive())
            {
                behaviour_event(*mi, ME_WHACK, &you);
                mi->expose_to_element(BEAM_COLD, orig_dam, &you);
            }
        }
    }
}

static bool _feat_is_descent_upstairs(dungeon_feature_type feat)
{
    if (feat_is_descent_exitable(feat))
        return false;

    return feat_is_stone_stair_up(feat)
        || feat_is_branch_exit(feat)
        || feat == DNGN_EXIT_VAULTS
        || feat == DNGN_EXIT_ZOT
        || feat == DNGN_ESCAPE_HATCH_UP;
}

void descent_crumble_stairs()
{
    if (!crawl_state.game_is_descent() || env.properties.exists(DESCENT_STAIRS_KEY))
        return;

    for (rectangle_iterator ri(0); ri; ++ri)
    {
        dungeon_feature_type original_feat = orig_terrain(*ri);
        if (!_feat_is_descent_upstairs(original_feat))
            continue;

        dungeon_change_base_terrain(*ri, DNGN_FLOOR);
        if (you.see_cell(*ri) && !is_temp_terrain(*ri))
            mpr("The exit collapses.");
        if (env.map_knowledge(*ri).feat() == original_feat)
        {
            env.map_knowledge(*ri).set_feature(DNGN_FLOOR);
            set_terrain_mapped(*ri);
            redraw_view_at(*ri);
        }
    }

    env.properties[DESCENT_STAIRS_KEY] = true;
}

static void _descent_reveal_around(coord_def p)
{
    force_show_update_at(p);
    view_update_at(p);

    for (radius_iterator ri(p, you.current_vision, C_SQUARE); ri; ++ri)
    {
        if (cell_see_cell_nocache(p, *ri))
        {
            monster* mons = monster_at(*ri);
            if (mons)
                view_monster_equipment(mons);

            force_show_update_at(*ri);
            update_item_at(*ri, true);
            set_terrain_visible(*ri);
            view_update_at(*ri);
        }
    }
}

void descent_reveal_stairs()
{
    // possible this should be in another file.
    for (rectangle_iterator ri(0); ri; ++ri)
    {
        dungeon_feature_type feat = env.grid(*ri);
        if (_feat_is_descent_upstairs(feat))
            _descent_reveal_around(*ri);
    }
}

dungeon_feature_type feat_at_no_mimic(coord_def pos)
{
    if (current_feature_is_mimic_at(pos))
        return DNGN_FLOOR;
    return env.grid(pos);
}