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
use crate::api::dungeon_mode::sprites::DungeonSpriteHandler;
use crate::api::dungeon_mode::traps::TrapId;
use crate::api::dungeon_mode::*;
use crate::api::dungeons::{DungeonGroupId, DungeonId};
use crate::api::enums::{
    DungeonObjective, FloorLoopStatus, FloorType, ForcedLossReason, MissionType, MissionTypeGroup,
    Weather,
};
use crate::api::iq::IqSkillId;
use crate::api::items::{Item, ItemId};
use crate::api::monsters::MonsterSpeciesId;
use crate::api::overlay::OverlayLoadLease;
use crate::ffi;
use alloc::vec::Vec;
use core::mem::MaybeUninit;

/// The Rust-safe wrapped master struct that contains the state of the dungeon.
/// Can be owned or mutably borrowed from a low-level [`ffi::dungeon`].
///
/// To get a reference to the global dungeon struct, use [`GlobalDungeonData::get`] and then
/// [`GlobalDungeonData::inner`].
///
/// To access the raw struct, use [`Self::inner`].
pub struct Dungeon<T: AsRef<ffi::dungeon> + AsMut<ffi::dungeon>>(T);

/// Dungeon structs.
///
/// To get a reference to the global dungeon struct instead, use [`GlobalDungeonData::get`]
/// and then [`GlobalDungeonData::inner`].
impl Dungeon<ffi::dungeon> {
    /// Create a new empty dungeon struct.
    /// Note that this struct is mostly zeroed and since we don't know all the field values,
    /// it could be (=probably is) invalid.
    pub fn new() -> Self {
        Self(Default::default())
    }

    /// Create a new wrapper for an owned dungeon state.
    pub fn from_owned(dungeon: ffi::dungeon) -> Self {
        Self(dungeon)
    }
}

/// Manipulate the dungeon.
impl<T: AsRef<ffi::dungeon> + AsMut<ffi::dungeon>> Dungeon<T> {
    /// Dungeon ID.
    pub fn id(&self) -> DungeonId {
        self.0.as_ref().id.val()
    }

    /// Set Dungeon ID.
    pub fn set_id(&mut self, id: DungeonId) {
        self.0.as_mut().id.set_val(id);
    }

    /// Dungeon group ID.
    pub fn group_id(&self) -> DungeonGroupId {
        self.0.as_ref().group_id.val()
    }

    /// Set Dungeon group ID.
    pub fn set_group_id(&mut self, id: DungeonGroupId) {
        self.0.as_mut().group_id.set_val(id);
    }

    /// Floor number.
    pub fn floor(&self) -> u8 {
        self.0.as_ref().floor
    }

    /// Set Floor number.
    pub fn set_floor(&mut self, floor: u8) {
        self.0.as_mut().floor = floor;
    }

    /// Rescue floor number.
    pub fn rescue_floor(&self) -> u8 {
        self.0.as_ref().rescue_floor
    }

    /// Set Rescue floor number.
    pub fn set_rescue_floor(&mut self, rescue_floor: u8) {
        self.0.as_mut().rescue_floor = rescue_floor;
    }

    /// Whether or not IQ is disabled.
    pub fn is_iq_disabled(&self) -> bool {
        self.0.as_ref().iq_disabled > 0
    }

    /// Set whether or not IQ is disabled.
    pub fn set_iq_disabled(&mut self, value: bool) {
        self.0.as_mut().iq_disabled = value as ffi::bool_
    }

    /// Whether or not recruiting is enabled.
    pub fn is_recruiting_enabled(&self) -> bool {
        self.0.as_ref().recruiting_enabled > 0
    }

    /// Set whether or not recruiting is enabled.
    pub fn set_recruiting_enabled(&mut self, value: bool) {
        self.0.as_mut().recruiting_enabled = value as ffi::bool_
    }

    /// Whether or not the current mission is a story mission.
    ///
    /// If not, allows leader changing and continuing without the partner
    pub fn is_story_mission(&self) -> bool {
        self.0.as_ref().nonstory_flag == 0
    }

    /// Set whether or not the current mission is a story mission.
    ///
    /// If not, allows leader changing and continuing without the partner
    pub fn set_story_mission(&mut self, value: bool) {
        self.0.as_mut().nonstory_flag = !value as ffi::bool_
    }

    /// Whether or not sending home is disabled.
    pub fn is_send_home_disabled(&self) -> bool {
        self.0.as_ref().send_home_disabled > 0
    }

    /// Set whether or not sending home is disabled.
    pub fn set_send_home_disabled(&mut self, value: bool) {
        self.0.as_mut().send_home_disabled = value as ffi::bool_
    }

    /// Hidden Land flag.
    ///
    /// Disables sending home/leader changing, lose if partner faints. Set for dungeons
    /// between DUNGEON_HIDDEN_LAND and DUNGEON_TEMPORAL_PINNACLE.
    pub fn is_hidden_land(&self) -> bool {
        self.0.as_ref().send_home_disabled > 0
    }

    /// Set whether or not sending home is disabled.
    ///
    /// Disables sending home/leader changing, lose if partner faints. Set for dungeons
    /// between DUNGEON_HIDDEN_LAND and DUNGEON_TEMPORAL_PINNACLE.
    pub fn set_hidden_land(&mut self, value: bool) {
        self.0.as_mut().send_home_disabled = value as ffi::bool_
    }

    /// Info about the next mission destination floor, if applicable
    pub fn get_mission_destination(&self) -> &ffi::mission_destination_info {
        &self.0.as_ref().mission_destination
    }

    /// Info about the next mission destination floor, if applicable
    pub fn get_mission_destination_mut(&mut self) -> &mut ffi::mission_destination_info {
        &mut self.0.as_mut().mission_destination
    }

    /// Gets the fractional turn speed.
    ///
    /// Controls when a monster at a certain speed stage is able to act.
    ///
    /// At normal speed, this will tick up by 4 each turn (can act when x % 4 == 3)
    /// At +1 speed, ticks up by 2 each turn (can act when x % 2 == 1)
    /// At +2 speed, ticks up by 1 or 2 each turn (can act when x % 4 != 0)
    /// At +3 speed, ticks up by 1 each turn (an act every tick)
    pub fn get_fractional_turn(&self) -> u16 {
        self.0.as_ref().fractional_turn
    }

    /// Sets the fractional turn speed.
    ///
    /// Controls when a monster at a certain speed stage is able to act.
    ///
    /// At normal speed, this will tick up by 4 each turn (can act when x % 4 == 3)
    /// At +1 speed, ticks up by 2 each turn (can act when x % 2 == 1)
    /// At +2 speed, ticks up by 1 or 2 each turn (can act when x % 4 != 0)
    /// At +3 speed, ticks up by 1 each turn (an act every tick)
    pub fn set_fractional_turn(&mut self, value: u16) {
        self.0.as_mut().fractional_turn = value
    }

    /// Enemy spawn counter.
    ///
    /// Counts from 0-35, spawns happen at 0.
    pub fn get_enemy_spawn_counter(&self) -> u16 {
        self.0.as_ref().enemy_spawn_counter
    }

    /// Sets the enemy spawn counter.
    ///
    /// Counts from 0-35, spawns happen at 0.
    pub fn set_enemy_spawn_counter(&mut self, value: u16) {
        self.0.as_mut().enemy_spawn_counter = value
    }

    /// Countdown to the wind blowing you out of the dungeon.
    pub fn get_wind_turns(&self) -> i16 {
        self.0.as_ref().wind_turns
    }

    /// Sets the wind countdown.
    pub fn set_wind_turns(&mut self, value: i16) {
        self.0.as_mut().wind_turns = value
    }

    /// Enemy density. 0, prevents the enemy_spawn_counter for increasing
    pub fn get_enemy_density(&self) -> u16 {
        self.0.as_ref().enemy_density
    }

    /// Sets the enemy density. 0, prevents the enemy_spawn_counter for increasing
    pub fn set_enemy_density(&mut self, value: u16) {
        self.0.as_mut().enemy_density = value
    }

    /// If you've stolen from Kecleon (actual dungeon state)
    pub fn is_thief_alert(&self) -> bool {
        self.0.as_ref().thief_alert as ffi::bool_ > 0
    }

    /// Sets the thief alert state.
    pub fn set_thief_alert(&mut self, value: bool) {
        self.0.as_mut().thief_alert = value as ffi::bool_
    }

    /// If you've stolen from Kecleon (triggers music and other events?)
    pub fn is_thief_alert_event(&self) -> bool {
        self.0.as_ref().thief_alert_event as ffi::bool_ > 0
    }

    /// Sets the thief alert event state.
    pub fn set_thief_alert_event(&mut self, value: bool) {
        self.0.as_mut().thief_alert_event = value as ffi::bool_
    }

    /// You Entered a Monster House (actual dungeon state)
    pub fn is_monster_house_triggered(&self) -> bool {
        self.0.as_ref().monster_house_triggered as ffi::bool_ > 0
    }

    /// Sets the monster house triggered state.
    pub fn set_monster_house_triggered(&mut self, value: bool) {
        self.0.as_mut().monster_house_triggered = value as ffi::bool_
    }

    /// You Entered a Monster House (triggers music and other events?)
    pub fn is_monster_house_triggered_event(&self) -> bool {
        self.0.as_ref().monster_house_triggered_event as ffi::bool_ > 0
    }

    /// Sets the monster house triggered event state.
    pub fn set_monster_house_triggered_event(&mut self, value: bool) {
        self.0.as_mut().monster_house_triggered_event = value as ffi::bool_
    }

    /// Objective of the current dungeon. Returns None if the objective is invalid.
    pub fn get_dungeon_objective(&self) -> Option<DungeonObjective> {
        self.0.as_ref().dungeon_objective.val().try_into().ok()
    }

    /// Set objective of the current dungeon
    pub fn set_dungeon_objective(&mut self, objective: DungeonObjective) {
        self.0
            .as_mut()
            .dungeon_objective
            .set_val(objective as ffi::dungeon_objective::Type)
    }

    /// Gets the number of times the player can still be rescued in this dungeon.
    pub fn get_rescue_attempts_left(&self) -> i8 {
        self.0.as_ref().rescue_attempts_left
    }

    /// Sets the number of times the player can still be rescued in this dungeon.
    pub fn set_rescue_attempts_left(&mut self, value: i8) {
        self.0.as_mut().rescue_attempts_left = value
    }

    /// Dungeon generation info.
    pub fn get_dungeon_generation_info(&self) -> &ffi::dungeon_generation_info {
        &self.0.as_ref().gen_info
    }

    /// Dungeon generation info.
    pub fn get_dungeon_generation_info_mut(&mut self) -> &mut ffi::dungeon_generation_info {
        &mut self.0.as_mut().gen_info
    }

    /// Get the current weather. Returns None if the weather is invalid.
    pub fn get_weather(&self) -> Option<Weather> {
        self.0.as_ref().weather.val().try_into().ok()
    }

    /// Sets the current weather
    pub fn set_weather(&mut self, weather: Weather) {
        self.0
            .as_mut()
            .weather
            .set_val(weather as ffi::weather_id::Type)
    }

    /// Get the natural weather of this floor. Returns None if the weather is invalid.
    pub fn get_natural_weather(&self) -> Option<Weather> {
        self.0.as_ref().natural_weather.val().try_into().ok()
    }

    /// sets the natural weather of this floor.
    pub fn set_natural_weather(&mut self, weather: Weather) {
        self.0
            .as_mut()
            .weather
            .set_val(weather as ffi::weather_id::Type)
    }

    /// Turns left for each weather type in enum weather_id (except [`Weather::Random`]). If
    /// multiple of these are nonzero, the one with the highest number of turns left is chosen.
    /// Ties are broken in enum order
    pub fn get_weather_turns(&self) -> &[u16; 8] {
        &self.0.as_ref().weather_turns
    }

    /// Turns left for each weather type in enum weather_id (except [`Weather::Random`]). If
    /// multiple of these are nonzero, the one with the highest number of turns left is chosen.
    /// Ties are broken in enum order
    pub fn get_weather_turns_mut(&mut self) -> &mut [u16; 8] {
        &mut self.0.as_mut().weather_turns
    }

    /// Turns left for artificial permaweather from weather-setting abilities like Drought,
    /// Sand Stream, Drizzle, and Snow Warning; one counter for each weather type in enum
    /// weather_id (except WEATHER_RANDOM). Any nonzero value triggers that weather condition
    /// (it's usually set  to 1 or 0). If the weather's source is removed, this value becomes the
    /// normal number of turns  left for that weather condition. Priority in the event of multiple
    /// nonzero counters is the same as with weather_turns.
    pub fn get_artificial_permaweather_turns(&self) -> &[u16; 8] {
        &self.0.as_ref().artificial_permaweather_turns
    }

    /// Turns left for artificial permaweather from weather-setting abilities like Drought,
    /// Sand Stream, Drizzle, and Snow Warning; one counter for each weather type in enum
    /// weather_id (except WEATHER_RANDOM). Any nonzero value triggers that weather condition
    /// (it's usually set  to 1 or 0). If the weather's source is removed, this value becomes the
    /// normal number of turns  left for that weather condition. Priority in the event of multiple
    /// nonzero counters is the same as with weather_turns.
    pub fn set_artificial_permaweather_turns(&mut self) -> &mut [u16; 8] {
        &mut self.0.as_mut().artificial_permaweather_turns
    }

    /// For damaging weather conditions like sandstorm. Counts down from 9-0, damage on 9.
    pub fn get_weather_damage_counter(&self) -> u8 {
        self.0.as_ref().weather_damage_counter
    }

    /// Sets the weather damage counter.
    pub fn set_weather_damage_counter(&mut self, counter: u8) {
        self.0.as_mut().weather_damage_counter = counter
    }

    /// Number of turns left for the Mud Sport condition.
    pub fn get_mud_sport_turns(&self) -> u8 {
        self.0.as_ref().mud_sport_turns
    }

    /// Sets the number of turns left for the Mud Sport condition.
    pub fn set_mud_sport_turns(&mut self, counter: u8) {
        self.0.as_mut().mud_sport_turns = counter
    }

    /// Number of turns left for the Water Sport condition.
    pub fn get_water_sport_turns(&self) -> u8 {
        self.0.as_ref().water_sport_turns
    }

    /// Sets the number of turns left for the Water Sport condition.
    pub fn set_water_sport_turns(&mut self, counter: u8) {
        self.0.as_mut().water_sport_turns = counter
    }

    /// Whether or not current weather is nullified by Cloud Nine or Air Lock.
    pub fn is_weather_nullified(&self) -> bool {
        self.0.as_ref().nullify_weather > 0
    }

    /// Sets whether or not current weather is nullified by Cloud Nine or Air Lock.
    pub fn set_weather_nullified(&mut self, nullified: bool) {
        self.0.as_mut().nullify_weather = nullified as ffi::bool_
    }

    /// Whether or not Gravity is in effect.
    pub fn is_gravity_in_effect(&self) -> bool {
        self.0.as_ref().gravity > 0
    }

    /// Sets whether or not Gravity is in effect.
    pub fn set_gravity_in_effect(&mut self, gravity: bool) {
        self.0.as_mut().gravity = gravity as ffi::bool_
    }

    /// Entity that is taking its turn at this moment.
    pub fn get_current_active_entity(&self) -> Option<&DungeonEntity> {
        let ptr = self.0.as_ref().current_active_entity;
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &*ptr })
        }
    }

    /// Entity that is taking its turn at this moment.
    pub fn get_current_active_entity_mut(&self) -> Option<&mut DungeonEntity> {
        let ptr = self.0.as_ref().current_active_entity;
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Monster that will become the leader of the team after changing leaders.
    pub fn get_new_leader(&self) -> Option<&DungeonEntity> {
        let ptr = self.0.as_ref().new_leader;
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &*ptr })
        }
    }

    /// Monster that will become the leader of the team after changing leaders.
    pub fn get_new_leader_mut(&self) -> Option<&mut DungeonEntity> {
        let ptr = self.0.as_ref().new_leader;
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Get whether the floor will be advanced at the end of the turn (unless the leader fainted).
    pub fn get_end_floor_flag(&self) -> bool {
        self.0.as_ref().end_floor_flag > 0
    }

    /// Set whether the floor will be advanced at the end of the turn (unless the leader fainted).
    pub fn set_end_floor_flag(&mut self, flag: bool) {
        self.0.as_mut().end_floor_flag = flag as ffi::bool_
    }

    /// Get whether the floor will be advanced at the end of the turn (even if the leader fainted).
    pub fn get_end_floor_flag_force(&self) -> bool {
        self.0.as_ref().end_floor_no_death_check_flag > 0
    }

    /// Set whether the floor will be advanced at the end of the turn (even if the leader fainted).
    pub fn set_end_floor_flag_force(&mut self, flag: bool) {
        self.0.as_mut().end_floor_no_death_check_flag = flag as ffi::bool_
    }

    /// False if the leader isn't doing anything right now. True if it's currently performing
    /// an action (such as walking or attacking)
    pub fn get_leader_action_flag(&self) -> bool {
        self.0.as_ref().no_action_in_progress == 0
    }

    /// Gets the table of all entities.
    pub fn get_entities(&self) -> EntityTableRef {
        EntityTableRef(&self.0.as_ref().entity_table)
    }

    /// Gets the table of all entities, mutably.
    pub fn get_entities_mut(&mut self) -> EntityTableMut {
        EntityTableMut(&mut self.0.as_mut().entity_table)
    }

    /// Gets the tile grid.
    pub fn get_tiles(&self) -> DungeonTileGridRef<56, 32> {
        DungeonTileGridRef(&self.0.as_ref().tile_ptrs)
    }

    /// Gets the tile grid, mutably.
    pub fn get_tiles_mut(&mut self) -> DungeonTileGridMut<56, 32> {
        DungeonTileGridMut(&mut self.0.as_mut().tile_ptrs)
    }

    /// Dungeon floor properties.
    pub fn get_floor_properties(&self) -> &ffi::floor_properties {
        &self.0.as_ref().floor_properties
    }

    /// Dungeon floor properties.
    pub fn get_floor_properties_mut(&mut self) -> &mut ffi::floor_properties {
        &mut self.0.as_mut().floor_properties
    }

    /// Color table. Used to apply a tint to the colors shown on screen.
    /// Changes depending on the current weather.
    pub fn get_color_table(&self) -> &[ffi::rgb; 256] {
        &self.0.as_ref().color_table
    }

    /// Color table, mutably. Used to apply a tint to the colors shown on screen.
    /// Changes depending on the current weather.
    pub fn get_color_table_mut(&mut self) -> &mut [ffi::rgb; 256] {
        &mut self.0.as_mut().color_table
    }

    /// Whether the current floor should continue or end and why. Returns None for invalid values.
    pub fn get_floor_loop_status(&self) -> Option<FloorLoopStatus> {
        self.0.as_ref().floor_loop_status.val().try_into().ok()
    }

    /// Whether the current floor should continue or end and why.
    pub fn set_floor_loop_status(&mut self, loop_status: FloorLoopStatus) {
        self.0
            .as_mut()
            .floor_loop_status
            .set_val(loop_status as ffi::floor_loop_status::Type);
    }

    /// If true, the message log won't be shown and the yellow beam animation won't
    /// appear over team members after the leader faints
    pub fn is_skip_faint_animation_flag_set(&self) -> bool {
        self.0.as_ref().skip_faint_animation_flag > 0
    }

    /// If true, the message log won't be shown and the yellow beam animation won't
    /// appear over team members after the leader faints
    pub fn set_skip_faint_animation_flag(&mut self, flag: bool) {
        self.0.as_mut().skip_faint_animation_flag = flag as ffi::bool_
    }

    /// True if the leader is running. Causes the leader's action for the next turn
    /// to be set to [`ffi::action::ACTION_WALK`] until it hits an obstacle.
    pub fn is_leader_running(&self) -> bool {
        self.0.as_ref().leader_running > 0
    }

    /// True if the leader is running. Causes the leader's action for the next turn
    /// to be set to [`ffi::action::ACTION_WALK`] until it hits an obstacle.
    pub fn set_leader_running(&mut self, running: bool) {
        self.0.as_mut().leader_running = running as ffi::bool_
    }

    /// List of spawn entries for this floor.
    pub fn get_spawn_entries(&self) -> &[ffi::monster_spawn_entry; 16] {
        &self.0.as_ref().spawn_entries
    }

    /// List of spawn entries for this floor, mutably.
    pub fn get_spawn_entries_mut(&mut self) -> &mut [ffi::monster_spawn_entry; 16] {
        &mut self.0.as_mut().spawn_entries
    }

    /// List of the indices in the complete monster spawn table for this floor that were
    /// spawned in this floor.
    pub fn get_spawn_table_entries_chosen(&self) -> &[u16; 16] {
        &self.0.as_ref().spawn_table_entries_chosen
    }

    /// List of the indices in the complete monster spawn table for this floor that were
    /// spawned in this floor.
    pub fn get_spawn_table_entries_chosen_mut(&mut self) -> &mut [u16; 16] {
        &mut self.0.as_mut().spawn_table_entries_chosen
    }

    /// Highest level among all the enemies that spawn on this floor
    pub fn get_highest_enemy_level(&self) -> u16 {
        self.0.as_ref().highest_enemy_level
    }

    /// Highest level among all the enemies that spawn on this floor
    pub fn set_highest_enemy_level(&mut self, level: u16) {
        self.0.as_mut().highest_enemy_level = level
    }
}

/// Equivalent to [`Dungeon::new`].
impl Default for Dungeon<ffi::dungeon> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: AsRef<ffi::dungeon> + AsMut<ffi::dungeon>> Dungeon<T> {
    /// Access the raw struct.
    pub fn inner(&self) -> &ffi::dungeon {
        self.0.as_ref()
    }
    /// Access the raw struct mutably.
    pub fn inner_mut(&mut self) -> &mut ffi::dungeon {
        self.0.as_mut()
    }
}

impl AsRef<ffi::dungeon> for ffi::dungeon {
    fn as_ref(&self) -> &ffi::dungeon {
        self
    }
}

impl AsMut<ffi::dungeon> for ffi::dungeon {
    fn as_mut(&mut self) -> &mut ffi::dungeon {
        self
    }
}

/// Note that this struct is mostly zeroed and since we don't know all the field values,
/// it could be (=probably is) invalid.
impl Default for ffi::dungeon {
    // This is the default implementation of bindgen.
    fn default() -> Self {
        let mut s = ::core::mem::MaybeUninit::<Self>::uninit();
        unsafe {
            ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
            s.assume_init()
        }
    }
}

/// Helper struct for dealing with the current floor, the global dungeon and the mission state.
///
/// This is essentially an extension and wrapper of [`Dungeon`] that works on the
/// global dungeon struct only.
///
/// To generate dungeons and manipulate floors layouts, you can get the game's
/// builtin generator with [`Self::get_builtin_dungeon_generator`], or configure the global
/// state of the current floor correctly and use [`Self::generate_floor`].
pub struct GlobalDungeonData<'a>(
    &'a OverlayLoadLease<29>,
    Dungeon<&'a mut ffi::dungeon>,
    DungeonEffectsEmitter<'a>,
    DungeonSpriteHandler<'a>,
);

impl<'a> GlobalDungeonData<'a> {
    /// Checks if the global dungeon pointer is null.
    pub fn is_global_dungeon_ptr_null(_ov29: &OverlayLoadLease<29>) -> bool {
        // SAFETY: We have a lease and know OV29 is loaded.
        unsafe { ffi::GetDungeonPtrMaster() }.is_null()
    }

    /// Returns a mutable reference to the global dungeon struct wrapped in this struct.
    ///
    /// # Safety
    /// This is unsafe, since it borrows the global dungeon struct (essentially a `static mut`)
    /// mutably.
    ///
    /// You need to make sure no other borrows over the global dungeon struct
    /// (or any of it's values) exist.
    pub unsafe fn get(ov29: &'a OverlayLoadLease<29>) -> Self {
        let ptr = ffi::GetDungeonPtrMaster();
        assert!(!ptr.is_null(), "Global dungeon pointer is null!");
        Self(
            ov29,
            Dungeon(&mut *ffi::GetDungeonPtrMaster()),
            DungeonEffectsEmitter(ov29),
            DungeonSpriteHandler(ov29),
        )
    }

    /// This will allocate a new dungeon struct and update the global dungeon pointer to it.
    ///
    /// # Safety
    /// This is unsafe, since it borrows the global dungeon struct (essentially a `static mut`)
    /// mutably. It also invalidates any previously borrowed global dungeon struct.
    ///
    /// You need to make sure no other borrows over the global dungeon struct
    /// (or any of it's values) exist.
    pub unsafe fn alloc(ov29: &'a OverlayLoadLease<29>) -> Self {
        Self(
            ov29,
            Dungeon(&mut *ffi::DungeonAlloc()),
            DungeonEffectsEmitter(ov29),
            DungeonSpriteHandler(ov29),
        )
    }

    /// Get the effects handler.
    pub fn effects(&'a mut self) -> &'a mut DungeonEffectsEmitter<'a> {
        &mut self.2
    }

    /// Get the sprites handler.
    pub fn sprites(&'a mut self) -> &'a mut DungeonSpriteHandler<'a> {
        &mut self.3
    }

    /// Zeros out the struct pointed to by the global dungeon pointer.
    ///
    /// # Safety
    /// This is unsafe, since it updates the global dungeon struct (essentially a `static mut`).
    pub unsafe fn z_init(&mut self) {
        ffi::DungeonZInit()
    }

    /// Frees the dungeons struct pointer to by the master dungeon pointer,
    /// and nullifies the pointer.
    ///
    /// # Safety
    /// This is unsafe, since it completely invalidates borrows of the old global dungeon struct
    /// and then invalidates the global dungeon pointer.
    pub unsafe fn free(self) {
        ffi::DungeonFree()
    }

    /// Returns a reference to the inner dungeon struct.
    pub fn inner(&self) -> &Dungeon<&'a mut ffi::dungeon> {
        &self.1
    }

    /// Returns a mutable reference to the inner dungeon struct.
    pub fn inner_mut(&mut self) -> &mut Dungeon<&'a mut ffi::dungeon> {
        &mut self.1
    }

    /// Called at the start of a dungeon. Initializes the dungeon struct from specified dungeon
    /// data. Includes a loop that does not break until the dungeon is cleared, and another one
    /// inside it that runs until the current floor ends.
    pub fn run_dungeon(
        &mut self,
        dungeon_init_data: &mut ffi::dungeon_init,
        dungeon: &mut ffi::dungeon,
    ) -> i32 {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::RunDungeon(dungeon_init_data, dungeon) }
    }

    /// Returns an abstraction over the game's builtin dungeon generator. This
    /// struct implements [`dungeon_generator::DungeonFloorGeneration`], which is the
    /// recommended way to work with it, see the documentation of [`dungeon_generator`].
    ///
    /// # Note
    /// Note that the builtin dungeon generator works on the global dungeon struct directly.
    pub fn get_builtin_dungeon_generator(
        &'a mut self,
    ) -> dungeon_generator::game_builtin::GlobalDungeonStructureGenerator<'a> {
        dungeon_generator::game_builtin::GlobalDungeonStructureGenerator(self.0.clone(), self)
    }

    /// Generates a dungeon floor.
    ///
    /// If not changed by a patch, this function will use the game's default built in generator
    /// and generate the floor based on the current global configuration for the floor.
    ///
    /// For more granular control over the floor generation, you can get an abstraction over
    /// the builtin generator with [`Self::get_builtin_dungeon_generator`].
    ///
    pub fn generate_floor(&'a mut self) {
        self.get_builtin_dungeon_generator()
            .generate_floor_internal();
    }

    /// Gets the floor type. Returns None if the global dungeon struct contains invalid data.
    pub fn get_floor_type(&self) -> Option<FloorType> {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetFloorType() }.try_into().ok()
    }

    /// Checks if the current fixed floor is the "substitute room" (Fixed Room ID 0x6E).
    pub fn is_substitute_room(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::FixedRoomIsSubstituteRoom() > 0 }
    }

    /// Note: unverified, ported from Irdkwia's notes
    pub fn is_current_fixed_room_boss_fight(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsCurrentFixedRoomBossFight() > 0 }
    }

    /// Checks if the current fixed room on the dungeon generation info corresponds to a fixed,
    /// full-floor layout.
    ///
    /// The first non-full-floor fixed room is 0xA5, which is for Sealed Chambers.
    pub fn is_full_floor_fixed_room(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsFullFloorFixedRoom() > 0 }
    }

    /// Checks if the current dungeon floor number is even.
    /// This is probably, among other things(?), used to determine whether male or female monsters
    /// should be spawned.
    /// Has a special check to return false for Labyrinth Cave B10F (the Gabite boss fight).
    pub fn is_even_floor(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::FloorNumberIsEven() > 0 }
    }

    /// Returns the tile at the given coordinates.
    ///
    /// If the coordinates are out-of-bounds, this seems to return a copy of a default tile.
    pub fn get_tile(&self, x: i32, y: i32) -> &DungeonTile {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { &*ffi::GetTileSafe(x, y) }
    }

    /// Returns the tile at the given coordinates.
    ///
    /// If the coordinates are out-of-bounds, this seems to return a copy of a default tile.
    pub fn get_tile_mut(&mut self, x: i32, y: i32) -> &mut DungeonTile {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { &mut *ffi::GetTileSafe(x, y) }
    }

    /// Checks if gravity is active on the floor.
    pub fn is_gravity_active(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GravityIsActive() > 0 }
    }

    /// Checks if the current floor is a secret bazaar or a secret room.
    pub fn is_secret_floor(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsSecretFloor() > 0 }
    }

    /// Checks if the current floor is the Secret Bazaar.
    pub fn is_secret_bazaar(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsSecretBazaar() > 0 }
    }

    /// Checks if the current floor is the Secret Room fixed floor (from hidden stairs).
    pub fn is_secret_room(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsSecretRoom() > 0 }
    }

    /// Checks if the current floor is a normal layout.
    ///
    /// "Normal" means any layout that is NOT one of the following:
    /// - Hidden stairs floors
    /// - Golden Chamber
    /// - Challenge Request floor
    /// - Outlaw hideout
    /// - Treasure Memo floor
    /// - Full-room fixed floors (ID < 0xA5) [0xA5 == Sealed Chamber]
    pub fn is_normal_floor(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsNormalFloor() > 0 }
    }

    /// Gets the boost_hidden_stairs_spawn_chance field on the dungeon struct.
    pub fn should_boost_hidden_stairs_spawn_chance(&self) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::ShouldBoostHiddenStairsSpawnChance() > 0 }
    }

    /// Sets the boost_hidden_stairs_spawn_chance field on the dungeon struct to the given value.
    pub fn set_should_boost_hidden_stairs_spawn_chance(&mut self, value: bool) {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetShouldBoostHiddenStairsSpawnChance(value as ffi::bool_) }
    }

    /// Clears the tile (terrain and spawns) on which Hidden Stairs are spawned, if applicable.
    pub fn clear_hidden_stairs(&mut self) {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::ClearHiddenStairs() }
    }

    /// Checks if a position (x, y) is out of bounds on the map:
    /// !((0 <= x <= 55) && (0 <= y <= 31)).
    pub fn is_pos_out_of_bounds(&self, x: i32, y: i32) -> bool {
        // SAFETY:We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::PosIsOutOfBounds(x, y) > 0 }
    }

    /// Checks if the current floor is either the Secret Bazaar or a Secret Room.
    pub fn is_hidden_stairs_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsHiddenStairsFloor() > 0 }
    }

    /// Checks if the current floor is an active mission destination of type
    /// [`MissionType::TakeItemFromOutlaw`], [`MissionType::ArrestOutlaw`] or
    /// [`MissionType::ChallengeRequest`].
    pub fn is_outlaw_or_challenge_request_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsOutlawOrChallengeRequestFloor() > 0 }
    }

    /// Checks if the current floor is a mission destination floor.
    pub fn is_destination_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloor() > 0 }
    }

    /// Checks if the current floor is an active mission destination of a given type group.
    pub fn is_current_mission_type(&self, mission_type_group: MissionTypeGroup) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsCurrentMissionType(mission_type_group as ffi::mission_type::Type) > 0 }
    }

    /// Checks if the current floor is an active mission destination of a given type.
    pub fn is_current_mission_type_exact(&self, mission_type: MissionType) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe {
            ffi::IsCurrentMissionTypeExact(
                mission_type.group() as ffi::mission_type::Type,
                mission_type.c_subtype(),
            ) > 0
        }
    }

    /// Checks if the current floor is a mission destination for a Monster House outlaw mission.
    pub fn is_outlaw_monster_house_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsOutlawMonsterHouseFloor() > 0 }
    }

    /// Checks if the current floor is a Golden Chamber floor.
    pub fn is_golden_chamber(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsGoldenChamber() > 0 }
    }

    /// Checks if the current floor is a boss floor for a Legendary Challenge Letter mission.
    pub fn is_legendary_challenge_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsLegendaryChallengeFloor() > 0 }
    }

    /// Checks if the current floor is the boss floor in Star Cave Pit for Jirachi's
    /// Challenge Letter mission.
    pub fn is_jirachi_challenge_floor(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsJirachiChallengeFloor() > 0 }
    }

    /// Checks if the current floor is a mission destination floor with a special monster.
    ///
    /// See [`Self::floor_has_mission_monster`] for details.
    pub fn is_destination_floor_with_monster(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloorWithMonster() > 0 }
    }

    /// Returns the index of the room that contains the stairs.
    pub fn get_stairs_room(&self) -> u8 {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetStairsRoom() }
    }

    /// Checks if a given floor is a mission destination with a special monster, either a target to rescue or an enemy to defeat.
    ///
    /// Mission types with a monster on the destination floor:
    /// - Rescue client
    /// - Rescue target
    /// - Escort to target
    /// - Deliver item
    /// - Search for target
    /// - Take item from outlaw
    /// - Arrest outlaw
    /// - Challenge Request
    pub fn floor_has_mission_monster(&self) -> bool {
        Self::floor_has_mission_monster_static(&self.1.inner().mission_destination, self.0)
    }

    /// Static version of [`Self::floor_has_mission_monster`]. See it for details.
    pub fn floor_has_mission_monster_static(
        mission_destination: &ffi::mission_destination_info,
        _ov29: &OverlayLoadLease<29>,
    ) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::FloorHasMissionMonster(force_mut_ptr!(mission_destination)) > 0 }
    }

    /// Checks if the target enemy of the mission on the current floor has been defeated.
    pub fn is_mission_target_enemy_defeated(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::MissionTargetEnemyIsDefeated() > 0 }
    }

    /// Set the flag for whether or not the target enemy of the current mission has been defeated.
    pub fn set_mission_target_enemy_defeated(&mut self, flag: bool) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetMissionTargetEnemyDefeated(flag as ffi::bool_) }
    }

    /// Checks if the current floor is a mission destination floor with a fixed room.
    ///
    /// The entire floor can be a fixed room layout, or it can just contain a Sealed Chamber.
    pub fn is_destination_floor_with_fixed_room(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloorWithFixedRoom() > 0 }
    }

    /// Get the ID of the item that needs to be retrieve on the current floor for a mission,
    /// if one exists.
    pub fn get_item_to_retrieve(&self) -> ItemId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetItemToRetrieve() }
    }

    /// Get the ID of the item that needs to be delivered to a mission client on the current floor,
    /// if one exists.
    pub fn get_item_to_deliver(&self) -> ItemId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetItemToDeliver() }
    }

    /// Get the ID of the special target item for a Sealed Chamber or Treasure Memo mission on
    /// the current floor.
    pub fn get_special_target_item(&self) -> ItemId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetSpecialTargetItem() }
    }

    /// Checks if the current floor is a mission destination floor with a special item.
    ///
    /// This excludes missions involving taking an item from an outlaw.
    pub fn is_destination_floor_with_item(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloorWithItem() > 0 }
    }

    /// Checks if the current floor is a mission destination floor with a "hidden outlaw" that
    /// behaves like a normal enemy.
    pub fn is_destination_floor_with_hidden_outlaw(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloorWithHiddenOutlaw() > 0 }
    }

    /// Checks if the current floor is a mission destination floor with a "fleeing outlaw" that
    /// runs away.
    pub fn is_destination_floor_with_fleeing_outlaw(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::IsDestinationFloorWithFleeingOutlaw() > 0 }
    }

    /// Get the monster ID of the target enemy to be defeated on the current floor for a mission,
    /// if one exists.
    pub fn get_mission_target_enemy(&self) -> MonsterSpeciesId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetMissionTargetEnemy() }
    }

    /// Get the monster ID of the specified minion group on the current floor for a mission,
    /// if it exists.
    ///
    /// Note that a single minion group can correspond to multiple actual minions of the same
    /// species. There can be up to 2 minion groups.
    pub fn get_mission_enemy_minion_group(&self, minion_group_index: i32) -> MonsterSpeciesId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetMissionEnemyMinionGroup(minion_group_index) }
    }

    /// Gets the value of [`ffi::dungeon::target_monster_not_found_flag`].
    pub fn get_target_monster_not_found_flag(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetTargetMonsterNotFoundFlag() > 0 }
    }

    /// Sets [`ffi::dungeon::target_monster_not_found_flag`] to the specified value.
    pub fn set_target_monster_not_found_flag(&mut self, value: bool) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetTargetMonsterNotFoundFlag(value as ffi::bool_) }
    }

    /// Gets a reference to the entity that is currently leading the team, or None if none of
    /// the first 4 entities is a valid monster with its is_team_leader flag set.
    // Needs a mut reference, since:
    // It also sets LEADER_PTR to the result before returning it.
    pub fn get_leader(&mut self) -> Option<&DungeonEntity> {
        let ptr = unsafe { ffi::GetLeader() };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &*ptr })
        }
    }

    /// Gets a mutable reference to the entity that is currently leading the team, or None if none
    /// of the first 4 entities is a valid monster with its is_team_leader flag set.
    pub fn get_leader_mut(&mut self) -> Option<&mut DungeonEntity> {
        let ptr = unsafe { ffi::GetLeader() };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Returns true if certain special restrictions are enabled.
    ///
    /// If true, you will get kicked out of the dungeon if a team member that passes the
    /// [`DungeonId::is_special_joined_at_location2`] check faints.
    ///
    /// Returns `!ffi::dungeon::nonstory_flag || ffi::dungeon::hidden_land_flag`
    ///
    pub fn story_restrictions_enabled(&self) -> bool {
        unsafe { ffi::StoryRestrictionsEnabled() > 0 }
    }

    /// Returns true if the specified monster is included in the floor's monster spawn list
    /// (the modified list after a maximum of 14 different species were chosen).
    pub fn is_on_monster_spawn_list(&self, monster_id: MonsterSpeciesId) -> bool {
        unsafe { ffi::IsOnMonsterSpawnList(monster_id) > 0 }
    }

    /// Loads fixed room data from BALANCE/fixed.bin into the buffer pointed to by
    /// `FIXED_ROOM_DATA_PTR` (see symbol table).
    ///
    /// # Safety
    /// This modifies a global buffer. `FIXED_ROOM_DATA_PTR` needs to be valid, no references
    /// to it's content must exist.
    pub unsafe fn load_fixed_room_data(&mut self) {
        ffi::LoadFixedRoomData()
    }

    /// Loads fixed room data from BALANCE/fixed.bin into the buffer pointed to by
    /// `FIXED_ROOM_DATA_PTR` (see symbol table).
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn load_fixed_room(
        &mut self,
        param_1: i32,
        param_2: i32,
        param_3: i32,
        param_4: ffi::undefined4,
    ) -> i32 {
        ffi::LoadFixedRoom(param_1, param_2, param_3, param_4)
    }

    /// Sets the forced loss reason to a given value.
    pub fn set_forced_loss_reason(&mut self, reason: ForcedLossReason) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetForcedLossReason(reason as ffi::forced_loss_reason::Type) }
    }

    /// Gets the forced loss reason, returns None if it's invalid.
    pub fn get_forced_loss_reason(&self) -> Option<ForcedLossReason> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetForcedLossReason() }.try_into().ok()
    }

    /// Tries to change the current leader to the monster specified by [`ffi::dungeon::new_leader`].
    /// Accounts for situations that can prevent changing leaders, such as having stolen from a
    /// Kecleon shop. If one of those situations prevents changing leaders, prints the
    /// corresponding message to the message log.
    pub fn change_leader(&mut self) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::ChangeLeader() }
    }

    /// Handles a fainted monster (reviving does not count as fainting).
    ///
    /// # Arguments
    /// * `fainted_entity`: Fainted entity
    /// * `faint_reason`: Faint reason (move ID or greater than the max move id for other causes)
    /// * `killer`: Entity responsible of the fainting
    pub fn handle_faint(
        &mut self,
        fainted_entity: &mut DungeonEntity,
        faint_reason: ffi::faint_reason,
        killer: &mut DungeonEntity,
    ) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::HandleFaint(fainted_entity, faint_reason, killer) }
    }

    /// Returns a reference to the minimap_display_data struct in the dungeon struct, if it
    /// exists.
    pub fn get_minimap_data(&self) -> Option<&ffi::minimap_display_data> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::GetMinimapData() };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &*ptr })
        }
    }

    /// Returns a mutable reference to the minimap_display_data struct in the dungeon struct, if it
    /// exists.
    pub fn get_minimap_data_mut(&mut self) -> Option<&mut ffi::minimap_display_data> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::GetMinimapData() };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Sets [`ffi::minimap_display_data::field_0xE447`] to the specified value
    pub fn set_minimap_data_e447(&mut self, value: u8) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetMinimapDataE447(value) }
    }

    /// Gets the value of [`ffi::minimap_display_data::field_0xE447`].
    pub fn get_minimap_data_e447(&mut self) -> u8 {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetMinimapDataE447() }
    }

    /// Sets [`ffi::minimap_display_data::field_0xE448`] to the specified value
    pub fn set_minimap_data_e448(&mut self, value: u8) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetMinimapDataE448(value) }
    }

    /// Opens the message log window.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn open_message_log(&mut self, param_1: ffi::undefined4, param_2: ffi::undefined4) {
        ffi::OpenMessageLog(param_1, param_2)
    }

    /// Checks if a given dungeon tip was not displayed yet and if so, displays it.
    ///
    /// If `log` is true, the tip will also be written to the message log.
    pub fn display_dungeon_tip(&mut self, tip: &mut ffi::message_tip, log: bool) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::DisplayDungeonTip(tip, log as ffi::bool_) }
    }

    /// Displays a message in a dialogue box that optionally waits for player input before closing.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn display_message(
        &mut self,
        param_1: ffi::undefined4,
        message_id: i32,
        wait_for_input: bool,
    ) {
        ffi::DisplayMessage(param_1, message_id, wait_for_input as ffi::bool_)
    }

    /// Displays a message in a dialogue box that optionally waits for player input before closing.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn display_message2(
        &mut self,
        param_1: ffi::undefined4,
        message_id: i32,
        wait_for_input: bool,
    ) {
        ffi::DisplayMessage2(param_1, message_id, wait_for_input as ffi::bool_)
    }

    /// Attempts to trigger a forced loss of the type set with [`Self::set_forced_loss_reason`].
    ///
    /// Returns whether the forced loss happens or not.
    ///
    /// The flag controls, if the function will not check for the end of the floor condition and
    /// will skip other (unknown) actions in case of forced loss.
    pub fn try_forced_loss(&mut self, skip_floor_end_check: bool) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::TryForcedLoss(skip_floor_end_check as ffi::bool_) > 0 }
    }

    /// Sets the Map Surveyor flag in the dungeon struct to true if a team member has Map Surveyor,
    /// sets it to false otherwise.
    ///
    /// This function has two variants: in the EU ROM, it will return true if the flag was changed.
    /// The NA version will return the new value of the flag instead.
    pub fn update_map_surveyor_flag(&mut self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::UpdateMapSurveyorFlag() > 0 }
    }

    /// Get the id of the monster to be randomly spawned.
    pub fn get_monster_id_to_spawn(&mut self, is_for_monster_house: bool) -> MonsterSpeciesId {
        let weight_id = is_for_monster_house as i32;
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetMonsterIdToSpawn(weight_id) }
    }

    /// Get the level of the monster to be spawned, given its id.
    ///
    /// Returns the level of the monster to be spawned, or 1 if the specified ID can't be found on
    /// the floor's spawn table.
    pub fn get_monster_level_to_spawn(&mut self, monster_id: MonsterSpeciesId) -> u8 {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetMonsterLevelToSpawn(monster_id) }
    }

    /// Ticks down a turn counter for a status condition. If the counter equals 0x7F,
    /// it will not be decreased.
    ///
    /// Returns the new counter value.
    pub fn tick_status_turn_counter(&mut self, counter: &mut u8) -> u8 {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::TickStatusTurnCounter(counter) }
    }

    /// The main function which executes the actions that take place in a fractional turn.
    ///
    /// Called in a loop by [`Self::run_dungeon`] while [`Self::is_floor_over`] returns
    /// false.
    ///
    /// The flag should set to true when the function is first called during a floor.
    pub fn run_fractional_turn(&mut self, is_first_loop: bool) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::RunFractionalTurn(is_first_loop as ffi::bool_) }
    }

    /// Handles the leader's turn. Includes a movement speed check that might cause it to return
    /// early if the leader isn't fast enough to act in this fractional turn. If that check
    /// (and some others) pass, the function does not return until the leader performs an action.
    ///
    /// Returns true, if the leader has performed an action.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn run_leader_turn(&mut self, param_1: ffi::undefined) -> bool {
        ffi::RunLeaderTurn(param_1) > 0
    }

    /// Sets the leader's action field depending on the inputs given by the player.
    ///
    /// This function also accounts for other special situations that can force a certain action,
    /// such as when the leader is running. The function also takes care of opening the main menu
    /// when X is pressed.
    ///
    /// The function generally doesn't return until the player has an action set.
    pub fn set_leader_action(&mut self) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SetLeaderAction() }
    }

    /// Called at the beginning of [`Self::run_fractional_turn`]. Executed only if
    /// FRACTIONAL_TURN_SEQUENCE\[fractional_turn * 2\] is not 0.
    /// First it calls [`Self::try_spawn_monster_and_tick_spawn_counter`], then tries to activate
    /// the Plus and Minus abilities for both allies and enemies, and finally calls
    /// [`Self::try_forced_loss`].
    pub fn try_spawn_monster_and_activate_plus_minus(&mut self) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::TrySpawnMonsterAndActivatePlusMinus() }
    }

    /// Checks if the current floor should end, and updates [`ffi::dungeon::floor_loop_status`]
    /// if required.
    ///
    /// If the player has been defeated, sets [`ffi::dungeon::floor_loop_status`] to
    /// [`ffi::floor_loop_status::FLOOR_LOOP_LEADER_FAINTED`].
    ///
    /// If [`ffi::dungeon::end_floor_flag`] is 1 or 2, sets [`ffi::dungeon::floor_loop_status`] to
    /// [`ffi::floor_loop_status::FLOOR_LOOP_NEXT_FLOOR`].
    pub fn is_floor_over(&self) -> bool {
        // SAFETY: We hold a valid reference to the global dungeon struct.
        unsafe { ffi::IsFloorOver() > 0 }
    }

    /// Decrements [`ffi::dungeon::wind_turns`] and displays a wind warning message if required.
    pub fn decrement_wind_counter(&self) {
        // SAFETY: We hold a valid reference to the global dungeon struct.
        unsafe { ffi::DecrementWindCounter() }
    }

    /// If the current floor number is even, returns female Kecleon's id (default: 0x3D7),
    /// otherwise returns male Kecleon's id (default: 0x17F).
    pub fn get_kecleon_id_to_spawn_by_floor(&self) -> MonsterSpeciesId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetKecleonIdToSpawnByFloor() }
    }

    /// If the monster id parameter is 0x97 (Mew), returns false if either
    /// [`ffi::dungeon::mew_cannot_spawn`] or the second parameter are true.
    ///
    /// Called before spawning an enemy, appears to be checking if Mew can spawn on the current floor.
    pub fn mew_spawn_check(&self, monster_id: MonsterSpeciesId, force_fail_if_mew: bool) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::MewSpawnCheck(monster_id, force_fail_if_mew as ffi::bool_) > 0 }
    }

    /// Note: unverified, ported from Irdkwia's notes
    pub fn get_random_spawn_monster_id(&self) -> MonsterSpeciesId {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetRandomSpawnMonsterID() }
    }

    /// Returns an entity reference to the first team member which has the specified iq skill.
    pub fn get_team_member_with_iq_skill(&self, iq_skill: IqSkillId) -> Option<&DungeonEntity> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::GetTeamMemberWithIqSkill(iq_skill) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &*ptr })
        }
    }

    /// Returns an entity reference to the first team member which has the specified iq skill.
    pub fn get_team_member_with_iq_skill_mut(
        &mut self,
        iq_skill: IqSkillId,
    ) -> Option<&mut DungeonEntity> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::GetTeamMemberWithIqSkill(iq_skill) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Returns true if any team member has the specified iq skill.
    pub fn team_member_has_enabled_iq_skill(&self, iq_skill: IqSkillId) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::TeamMemberHasEnabledIqSkill(iq_skill) > 0 }
    }

    /// Returns true the leader has the specified iq skill.
    pub fn team_leader_has_enabled_iq_skill(&self, iq_skill: IqSkillId) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::TeamLeaderIqSkillIsEnabled(iq_skill) > 0 }
    }

    /// Initializes the team when entering a dungeon.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn init_team(&mut self, param_1: ffi::undefined) {
        ffi::InitTeam(param_1)
    }

    /// Initializes a team member. Run at the start of each floor in a dungeon.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn init_team_member(
        &mut self,
        arg1: MonsterSpeciesId,
        x_pos: i16,
        y_pos: i16,
        team_member_data: &mut ffi::team_member,
        param_5: ffi::undefined,
        param_6: ffi::undefined,
        param_7: ffi::undefined,
        param_8: ffi::undefined,
        param_9: ffi::undefined,
    ) {
        ffi::InitTeamMember(
            arg1,
            x_pos,
            y_pos,
            team_member_data,
            param_5,
            param_6,
            param_7,
            param_8,
            param_9,
        )
    }

    /// Generates the monster ID in the egg from the given mission. Uses the base form of the monster.
    ///
    /// Note: unverified, ported from Irdkwia's notes
    pub fn generate_mission_egg_monster(&mut self, mission: &mut ffi::mission) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GenerateMissionEggMonster(mission) }
    }

    /// Spawns the given monster on a tile. Returns None, if the game returned a null-pointer after
    /// the spawn.
    pub fn spawn_monster(
        &mut self,
        spawn_data: &mut ffi::spawned_monster_data,
        force_awake: bool,
    ) -> Option<&mut DungeonEntity> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::SpawnMonster(spawn_data, force_awake as ffi::bool_) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// A convenience wrapper around `Self::spawn_trap` and `DungeonTile::bind_trap`
    /// (or to be precise the game's functions, see implementation!).
    ///
    /// Always passes 0 for the team parameter (making it an enemy trap).
    pub fn spawn_enemy_trap_bound(
        &mut self,
        trap_id: TrapId,
        x_position: i16,
        y_position: i16,
        flags: u8,
        is_visible: bool,
    ) {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe {
            ffi::SpawnEnemyTrapAtPos(
                trap_id,
                x_position,
                y_position,
                flags,
                is_visible as ffi::bool_,
            )
        };
    }

    /// Spawns a trap on the floor. Fails if there are more than 64 traps already on the floor.
    ///
    /// This modifies the appropriate fields on the dungeon struct, initializing new entries
    /// in the entity table and the trap info list.
    pub fn spawn_trap(
        &mut self,
        trap_id: TrapId,
        position: &ffi::position,
        team: u8,
        flags: u8,
    ) -> Option<&mut DungeonEntity> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::SpawnTrap(trap_id, force_mut_ptr!(position), team, flags) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Spawns an item on the floor. Fails if there are more than 64 items already on the floor.
    ///
    /// This calls [`Self::spawn_item_entity`], fills in the item info struct, sets the entity to
    /// be visible, binds the entity to the tile it occupies, updates the n_items counter on the
    /// dungeon struct, and various other bits of bookkeeping.
    ///
    /// Hint: Consider using [`Self::generate_and_spawn_item`] instead for ease of use.
    pub fn spawn_item(
        &'a mut self,
        position: &ffi::position,
        item: &'a mut Item,
        flag: bool,
    ) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::SpawnItem(force_mut_ptr!(position), item, flag as ffi::bool_) > 0 }
    }

    /// Generates an item with [`Item::generate_explicit`], then spawns it with
    /// [`Self::spawn_item`].
    ///
    /// If the check-in-bag flag is set and the player's bag already contains an item with the
    /// given ID, a Reviver Seed will be spawned instead.
    ///
    /// It seems like this function is only ever called in one place, with an item ID of 0x49
    /// (Reviver Seed).
    pub fn generate_and_spawn_item(
        &mut self,
        item_id: ItemId,
        x: i16,
        y: i16,
        quantity: u16,
        sticky: bool,
        check_in_bag: bool,
    ) {
        unsafe {
            ffi::GenerateAndSpawnItem(
                item_id,
                x,
                y,
                quantity,
                sticky as ffi::bool_,
                check_in_bag as ffi::bool_,
            )
        }
    }

    /// Spawns a blank item entity on the floor.
    /// Fails if there are more than 64 items already on the floor.
    ///
    /// This initializes a new entry in the entity table and points it to the corresponding
    /// slot in the item info list.
    pub fn spawn_item_entity(&mut self, position: &ffi::position) -> Option<&mut DungeonEntity> {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        let ptr = unsafe { ffi::SpawnItemEntity(force_mut_ptr!(position)) };
        if ptr.is_null() {
            None
        } else {
            Some(unsafe { &mut *ptr })
        }
    }

    /// Appears to spawn an enemy item drop at a specified location, with a log message.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn spawn_enemy_item_drop(
        &mut self,
        entity: &mut DungeonEntity,
        item_entity: &mut DungeonEntity,
        item: &mut Item,
        param_4: i32,
        dir_xy: &mut i16,
        param_6: ffi::undefined,
    ) {
        ffi::SpawnEnemyItemDrop(entity, item_entity, item, param_4, dir_xy, param_6)
    }

    /// Wraps [`Self::spawn_enemy_item_drop`] in a more convenient interface.
    ///
    /// # Safety
    /// The caller must make sure the undefined params are valid for this function.
    pub unsafe fn spawn_enemy_item_drop_wrapper(
        &mut self,
        entity: &mut DungeonEntity,
        pos: &mut ffi::position,
        item: &mut Item,
        param_4: ffi::undefined4,
    ) {
        ffi::SpawnEnemyItemDropWrapper(entity, pos, item, param_4)
    }

    /// Determine if a defeated monster should drop a Unown Stone, and generate the item if so.
    ///
    /// Checks that the current dungeon isn't a Marowak Dojo training maze, and that the monster
    /// is an Unown. If so, there's a 21% chance that an Unown Stone will be generated.
    pub fn try_generate_unown_drop(monster_id: MonsterSpeciesId) -> Option<Item> {
        unsafe {
            let mut res: MaybeUninit<Item> = MaybeUninit::zeroed();
            let generated = ffi::TryGenerateUnownStoneDrop(res.as_mut_ptr(), monster_id) > 0;
            if generated {
                Some(res.assume_init())
            } else {
                None
            }
        }
    }

    /// Runs a check over all monsters on the field for the ability Slow Start, and lowers the
    /// speed of those who have it.
    pub fn try_activate_slow_start(&mut self) {
        // SAFETY: We have a lease on the overlay existing.
        unsafe { ffi::TryActivateSlowStart() }
    }

    /// Runs a check over all monsters on the field for abilities that affect the weather and
    /// changes the floor's weather accordingly.
    pub fn try_activate_artificial_weather_abilities(&mut self) {
        // SAFETY: We have a lease on the overlay existing.
        unsafe { ffi::TryActivateArtificialWeatherAbilities() }
    }

    /// First ticks up the spawn counter, and if it's equal or greater than the spawn cooldown,
    /// it will try to spawn an enemy if the number of enemies is below the spawn cap.
    ///
    /// If the spawn counter is greater than 900, it will instead perform the special spawn caused
    /// by the ability Illuminate.
    pub fn try_spawn_monster_and_tick_spawn_counter(&mut self) {
        // SAFETY: We have a lease on the overlay existing.
        unsafe { ffi::TrySpawnMonsterAndTickSpawnCounter() }
    }

    /// Returns [`ffi::dungeon_generation_info::field_0xc`] for the global dungeon struct.
    pub fn get_dungeon_gen_info_unk_0c(&self) -> ffi::undefined4 {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::GetDungeonGenInfoUnk0C() }
    }

    /// Checks if a value obtained from [`ffi::team_member::member_index`] is equal to certain
    /// values.
    ///
    /// This is known to return true for some or all of the guest monsters (if the value is equal
    /// to 0x55AA or 0x5AA5).
    ///
    /// # Note
    /// The underlying function [`ffi::CheckTeamMemberField8`] does not need overlay29 to be loaded.
    pub fn check_team_member_index(&self, team_member: &ffi::team_member) -> bool {
        unsafe { ffi::CheckTeamMemberField8(team_member.member_index as ffi::undefined2) > 0 }
    }

    /// Checks whether any of the items in the bag or any of the items carried by team members has
    /// any of the specified flags set in its flags field:
    ///
    /// `(0 = f_exists, 1 = f_in_shop, 2 = f_unpaid, etc.)`
    ///
    /// Returns true if any of the items of the team has the specified flags set, false otherwise.
    pub fn check_team_items_flag(&self, flags: i32) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::CheckTeamItemsFlags(flags) > 0 }
    }

    /// Checks if there's an active challenge request on the current dungeon.
    pub fn check_active_challenge_request(&self) -> bool {
        // SAFETY: We hold a valid mutable reference to the global dungeon struct.
        unsafe { ffi::CheckActiveChallengeRequest() > 0 }
    }

    /// Check if the current dungeon is one of the training mazes in Marowak Dojo
    /// (this excludes Final Maze).
    pub fn is_marowak_training_maze(&self) -> bool {
        unsafe { ffi::IsMarowakTrainingMaze() > 0 }
    }

    #[cfg_attr(docsrs, doc(cfg(feature = "eu")))]
    #[cfg(feature = "eu")]
    /// This function is exclusive to the EU ROM. Seems to perform a check to see if the monster
    /// who just fainted was a team member who should cause the minimap to be updated (or something
    /// like that, maybe related to the Map Surveyor IQ skill) and if it passes, updates the
    /// minimap.
    ///
    /// The function ends by calling another 2 functions. In US ROMs, calls to this are
    /// replaced by calls to those two functions. This seems to indicate that this function fixes
    /// some edge case glitch that can happen when a team member faints.
    ///
    /// # Arguments
    /// * `non_team_member_fainted` - False if the fainted entity was a team member.
    /// * `set_unk_byte` - True to set an unknown byte in the RAM to 1.
    pub fn faint_check(&mut self, non_team_member_fainted: bool, set_unk_byte: bool) {
        unsafe {
            ffi::EuFaintCheck(
                non_team_member_fainted as ffi::bool_,
                set_unk_byte as ffi::bool_,
            )
        }
    }
}

/// Functions for reading data from an entity table.
pub trait EntityTableRead {
    /// All monsters, whether they're used or not.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_monsters(&self) -> Vec<&DungeonEntity>;

    /// Actually used monsters.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_active_monsters(&self) -> Vec<&DungeonEntity>;

    /// All items.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_items(&self) -> Vec<&DungeonEntity>;

    /// All traps.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_traps(&self) -> Vec<&DungeonEntity>;

    /// Hidden stairs entity.
    ///
    /// Returns None if null. Note that it still may be invalid, check the validity flag!
    fn get_hidden_stairs(&self) -> Option<&DungeonEntity>;
}

/// Functions for writing data into an entity table.
pub trait EntityTableWrite: EntityTableRead {
    /// All monsters, whether they're used or not.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_monsters_mut(&mut self) -> Vec<&mut DungeonEntity>;

    /// Actually used monsters.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_active_monsters_mut(&mut self) -> Vec<&mut DungeonEntity>;

    /// All items.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_items_mut(&mut self) -> Vec<&mut DungeonEntity>;

    /// All traps.
    ///
    /// Null entries are not included, and reading is stopped at them.
    /// Note that some may be invalid, check the validity flag!
    fn get_traps_mut(&mut self) -> Vec<&mut DungeonEntity>;

    /// Hidden stairs entity.
    ///
    /// Returns None if null. Note that it still may be invalid, check the validity flag!
    fn get_hidden_stairs_mut(&mut self) -> Option<&mut DungeonEntity>;
}

/// See [`EntityTableRead`].
pub struct EntityTableRef<'a>(&'a ffi::entity_table);
/// See [`EntityTableRead`] and [`EntityTableWrite`].
pub struct EntityTableMut<'a>(&'a mut ffi::entity_table);

impl<'a> EntityTableRead for EntityTableRef<'a> {
    fn get_monsters(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.monster_slot_ptrs)
    }

    fn get_active_monsters(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.active_monster_ptrs)
    }

    fn get_items(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.item_ptrs)
    }

    fn get_traps(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.trap_ptrs)
    }

    fn get_hidden_stairs(&self) -> Option<&DungeonEntity> {
        let ptr = self.0.header.hidden_stairs_ptr;
        if ptr.is_null() {
            None
        } else {
            // SAFETY: We checked the pointer.
            Some(unsafe { &*ptr })
        }
    }
}

impl<'a> EntityTableRead for EntityTableMut<'a> {
    fn get_monsters(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.monster_slot_ptrs)
    }

    fn get_active_monsters(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.active_monster_ptrs)
    }

    fn get_items(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.item_ptrs)
    }

    fn get_traps(&self) -> Vec<&DungeonEntity> {
        check_and_return(&self.0.header.trap_ptrs)
    }

    fn get_hidden_stairs(&self) -> Option<&DungeonEntity> {
        let ptr = self.0.header.hidden_stairs_ptr;
        if ptr.is_null() {
            None
        } else {
            // SAFETY: We checked the pointer.
            Some(unsafe { &*ptr })
        }
    }
}

impl<'a> EntityTableWrite for EntityTableMut<'a> {
    fn get_monsters_mut(&mut self) -> Vec<&mut DungeonEntity> {
        check_and_return_mut(&mut self.0.header.monster_slot_ptrs)
    }

    fn get_active_monsters_mut(&mut self) -> Vec<&mut DungeonEntity> {
        check_and_return_mut(&mut self.0.header.active_monster_ptrs)
    }

    fn get_items_mut(&mut self) -> Vec<&mut DungeonEntity> {
        check_and_return_mut(&mut self.0.header.item_ptrs)
    }

    fn get_traps_mut(&mut self) -> Vec<&mut DungeonEntity> {
        check_and_return_mut(&mut self.0.header.trap_ptrs)
    }

    fn get_hidden_stairs_mut(&mut self) -> Option<&mut DungeonEntity> {
        let ptr = self.0.header.hidden_stairs_ptr;
        if ptr.is_null() {
            None
        } else {
            // SAFETY: We checked the pointer.
            Some(unsafe { &mut *ptr })
        }
    }
}

fn check_and_return(ent: &[*mut ffi::entity]) -> Vec<&DungeonEntity> {
    let mut res: Vec<&DungeonEntity> = Vec::with_capacity(ent.len());
    for e in ent {
        if e.is_null() {
            break;
        }
        // SAFETY: We checked the pointer.
        res.push(unsafe { &**e });
    }
    res
}

fn check_and_return_mut(ent: &mut [*mut ffi::entity]) -> Vec<&mut DungeonEntity> {
    let mut res: Vec<&mut DungeonEntity> = Vec::with_capacity(ent.len());
    for e in ent {
        if e.is_null() {
            break;
        }
        // SAFETY: We checked the pointer.
        res.push(unsafe { &mut **e });
    }
    res
}