anvil-sdk 0.4.0

Safe Rust API for plugins of Anvil, the plugin loader for Europa Universalis IV
Documentation
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
//! `anvil-game.world`: the world of the running session, read straight from
//! the game (anvil-game 1.11.0; modifiers, units and the selection 1.15.0;
//! rulers, heirs, consorts, flags and variables 1.20.0; pending events,
//! statistics and timed modifiers 1.21.0; diplomacy 1.22.0).
//!
//! **Thread.** Call it only on the game's main thread after an outer frame:
//! from a handler of an anvil-game event ([`game`](crate::game)) or from
//! [`Game::run_on_main_thread`](crate::game::Game::run_on_main_thread) work,
//! or from a panel click. Anywhere else, and outside a session, a call answers
//! [`ErrorCode::WrongPhase`] and reads nothing.
//!
//! **Results.** [`ErrorCode::NotFound`] for an unknown province ID, tag, war
//! or unit; [`ErrorCode::NotDeclared`] for a group of calls whose symbols a
//! port declared absent; [`ErrorCode::Unsupported`] for a call the running
//! anvil-game is too old to have.
//!
//! **What it shows.** Everything, also under terra incognita and in
//! multiplayer, where that is more than the player sees. A read changes
//! nothing, so it cannot cause a desync. Values marked "× 1000" are as the
//! game stores them, as [`Milli`].
//!
//! [`ErrorCode::WrongPhase`]: crate::ErrorCode::WrongPhase
//! [`ErrorCode::NotFound`]: crate::ErrorCode::NotFound
//! [`ErrorCode::NotDeclared`]: crate::ErrorCode::NotDeclared
//! [`ErrorCode::Unsupported`]: crate::ErrorCode::Unsupported

use std::fmt;
use std::mem::size_of;

use crate::error::{check, Error, ErrorCode, Result};
use crate::game::Date;
use crate::host::Host;
use crate::sys::{
    AnvilGameCountry, AnvilGameDate, AnvilGameDiplomacyStatus, AnvilGameFlag, AnvilGameMonarch,
    AnvilGamePendingEvent, AnvilGamePlayer, AnvilGameProvince, AnvilGameRelation,
    AnvilGameStatisticPoint, AnvilGameTag, AnvilGameTimedModifier, AnvilGameUnit, AnvilGameUnitRef,
    AnvilGameWar, AnvilGameWorldService, ANVIL_GAME_COUNTRY_OBSERVER, ANVIL_GAME_DIPLOMACY_TRUCE,
    ANVIL_GAME_EXPLORE_COAST, ANVIL_GAME_EXPLORE_SEA, ANVIL_GAME_MONARCH_CONSORT,
    ANVIL_GAME_MONARCH_FEMALE, ANVIL_GAME_MONARCH_HEIR, ANVIL_GAME_MONARCH_REGENCY,
    ANVIL_GAME_MONARCH_RULER, ANVIL_GAME_PENDING_HIDDEN, ANVIL_GAME_PLAYER_OBSERVER,
    ANVIL_GAME_PROVINCE_CITY, ANVIL_GAME_PROVINCE_COASTAL, ANVIL_GAME_PROVINCE_HRE,
    ANVIL_GAME_PROVINCE_LAND, ANVIL_GAME_PROVINCE_STATE, ANVIL_GAME_PROVINCE_VALUE_DEVASTATION,
    ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY, ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER,
    ANVIL_GAME_PROVINCE_WASTELAND, ANVIL_GAME_RELATION_ALLIANCE, ANVIL_GAME_RELATION_DEPENDENCY,
    ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS, ANVIL_GAME_RELATION_GUARANTEE,
    ANVIL_GAME_RELATION_MILITARY_ACCESS, ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
    ANVIL_GAME_RELATION_SUBSIDIES, ANVIL_GAME_RELATION_WARNING, ANVIL_GAME_STATISTIC_INCOME,
    ANVIL_GAME_STATISTIC_INFLATION, ANVIL_GAME_STATISTIC_NATION_SIZE, ANVIL_GAME_STATISTIC_SCORE,
    ANVIL_GAME_TIMED_HIDDEN, ANVIL_GAME_TIMED_NO_END, ANVIL_GAME_TIMED_NO_START,
    ANVIL_GAME_TIMED_RULER, ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY, ANVIL_GAME_VALUE_MANPOWER,
    ANVIL_GAME_VALUE_MONTHLY_INCOME, ANVIL_GAME_VALUE_PRESTIGE, ANVIL_GAME_VALUE_STABILITY,
    ANVIL_GAME_VALUE_TREASURY, ANVIL_GAME_WAR_ATTACKERS, ANVIL_GAME_WAR_DEFENDERS,
    ANVIL_GAME_WORLD_SERVICE_VERSION,
};
use crate::table::Table;
use crate::text::{read_list, read_text, Tag};

/// The service's name.
pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
/// The service's major version.
pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;

/// A value the game stores × 1000: `Milli(4500)` is 4.5.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Milli(pub i32);

impl Milli {
    /// The value as a float.
    pub fn get(self) -> f64 {
        f64::from(self.0) / 1000.0
    }
}

impl fmt::Display for Milli {
    /// With up to three decimals, trailing zeros dropped: `4.5`, `-12`, `0.125`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sign = if self.0 < 0 { "-" } else { "" };
        let value = self.0.unsigned_abs();
        let (whole, part) = (value / 1000, value % 1000);
        if part == 0 {
            return write!(f, "{sign}{whole}");
        }
        let decimals = format!("{part:03}");
        write!(f, "{sign}{whole}.{}", decimals.trim_end_matches('0'))
    }
}

/// A province.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Province {
    /// Its ID.
    pub id: i32,
    /// Its owner; `None` for none.
    pub owner: Option<Tag>,
    /// Its controller.
    pub controller: Option<Tag>,
    /// Base tax, without the capital's bonus.
    pub base_tax: Milli,
    /// Base production.
    pub base_production: Milli,
    /// Base manpower.
    pub base_manpower: Milli,
    /// Not a sea or a lake.
    pub land: bool,
    /// A wasteland.
    pub wasteland: bool,
    /// Part of the Holy Roman Empire (anvil-game 1.26.0; `false` before).
    pub hre: bool,
    /// A city, not a colony (anvil-game 1.26.0; `false` before).
    pub city: bool,
    /// Land the game counts as coastal (anvil-game 1.26.0; `false` before).
    pub coastal: bool,
    /// In a state of its owner's, not a territory (anvil-game 1.27.0; `false` before).
    pub state: bool,
    /// Local autonomy as the game shows it (anvil-game 1.27.0; `None` before or on a build without it).
    pub local_autonomy: Option<Milli>,
    /// Devastation (anvil-game 1.27.0).
    pub devastation: Option<Milli>,
    /// Its trade power in its trade node, as of the game's last update (anvil-game 1.27.0).
    pub trade_power: Option<Milli>,
}

/// A country. A value this game build does not have is `None`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Country {
    /// Its tag.
    pub tag: Option<Tag>,
    /// Its capital province; `None` for none.
    pub capital: Option<i32>,
    /// The provinces it owns; above 0 when it exists on the map.
    pub province_count: i32,
    /// The observer's pseudo-country.
    pub observer: bool,
    /// Ducats.
    pub treasury: Option<Milli>,
    /// Stability.
    pub stability: Option<Milli>,
    /// Prestige.
    pub prestige: Option<Milli>,
    /// Manpower in the game's thousands: `Milli(25000)` is 25 000 men.
    pub manpower: Option<Milli>,
    /// The income total of the economy view, before expenses, as of the last
    /// monthly update.
    pub monthly_income: Option<Milli>,
}

/// A running war.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct War {
    /// Its id: the same while the war runs (a later war may reuse it).
    pub id: u64,
    /// Who started it.
    pub attacker: Option<Tag>,
    /// Whom it was declared on.
    pub defender: Option<Tag>,
}

/// A side of a war.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Side {
    /// The attacker and its allies.
    Attackers,
    /// The defender and its allies.
    Defenders,
}

/// An army or a navy.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UnitKind {
    /// An army.
    Army,
    /// A navy.
    Navy,
    /// A value this crate does not know.
    Other(u32),
}

impl UnitKind {
    fn from_raw(kind: u32) -> Self {
        match kind {
            ANVIL_GAME_UNIT_ARMY => Self::Army,
            ANVIL_GAME_UNIT_NAVY => Self::Navy,
            other => Self::Other(other),
        }
    }
}

/// What a unit does on its own, by the game's numbers (`ANVIL_GAME_MISSION_*`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Mission(pub i32);

impl Mission {
    /// Not one the service could read.
    pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
    /// No mission: the player moves it.
    pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
    /// Besiege the enemy's provinces on its own.
    pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
    /// Hunt rebels.
    pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
    /// Drill.
    pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
}

/// A unit: an army or a navy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Unit {
    /// Army or navy.
    pub kind: UnitKind,
    /// The game's id: the same while the unit exists.
    pub id: u64,
    /// The country it belongs to.
    pub country: Option<Tag>,
    /// The province it is in or at; `None` for none.
    pub location: Option<i32>,
    /// What it does on its own.
    pub mission: Mission,
    /// Regiments or ships.
    pub subunits: u32,
    /// The sum of the regiments' or ships' strength (men for an army).
    pub strength: Milli,
    /// Its leader's id; `None` for no leader.
    pub leader: Option<u64>,
}

/// One unit of the player's selection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnitRef {
    /// The unit's id.
    pub id: u64,
    /// The country it belongs to (a player may select units of others to look).
    pub country: Option<Tag>,
    /// Army or navy.
    pub kind: UnitKind,
}

impl UnitRef {
    pub(crate) fn to_raw(self) -> AnvilGameUnitRef {
        AnvilGameUnitRef {
            id: self.id,
            country: self
                .country
                .map(|tag| tag.to_raw())
                .unwrap_or(AnvilGameTag { text: [0; 4] }),
            kind: match self.kind {
                UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
                UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
                UnitKind::Other(other) => other,
            },
        }
    }
}

/// Which list of the naval exploration dialog [`World::exploration_regions`]
/// reads (anvil-game 1.25.0).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ExplorationList {
    /// The regions a coast exploration may take.
    Coast,
    /// The regions a sea exploration may take.
    Sea,
}

impl ExplorationList {
    fn raw(self) -> i32 {
        match self {
            Self::Coast => ANVIL_GAME_EXPLORE_COAST as i32,
            Self::Sea => ANVIL_GAME_EXPLORE_SEA as i32,
        }
    }
}

/// The id of a modifier, from its script key ([`World::modifier_id`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ModifierId(pub i32);

/// A country's ruler, heir or consort (anvil-game 1.20.0).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MonarchKind {
    /// The ruler.
    Ruler,
    /// The heir.
    Heir,
    /// The consort.
    Consort,
}

impl MonarchKind {
    fn raw(self) -> u32 {
        match self {
            Self::Ruler => ANVIL_GAME_MONARCH_RULER,
            Self::Heir => ANVIL_GAME_MONARCH_HEIR,
            Self::Consort => ANVIL_GAME_MONARCH_CONSORT,
        }
    }

    fn from_raw(kind: u32) -> Self {
        match kind {
            ANVIL_GAME_MONARCH_HEIR => Self::Heir,
            ANVIL_GAME_MONARCH_CONSORT => Self::Consort,
            _ => Self::Ruler,
        }
    }
}

/// A ruler, heir or consort, as the game stores them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Monarch {
    /// Ruler, heir or consort.
    pub kind: MonarchKind,
    /// The game's id of the person.
    pub id: u64,
    /// The country asked about.
    pub country: Option<Tag>,
    /// Female.
    pub female: bool,
    /// A regency council or a regent rules for them.
    pub regency: bool,
    /// Administrative skill, without modifiers.
    pub adm: i32,
    /// Diplomatic skill.
    pub dip: i32,
    /// Military skill.
    pub mil: i32,
    /// An heir's claim strength; 0 for a ruler or a consort.
    pub claim: Milli,
    /// The birth date.
    pub birth: Date,
    /// The id of the leader they also are ([`Unit::leader`]); `None` for none.
    pub leader: Option<u64>,
}

/// The id of a flag, from its name ([`World::flag_id`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FlagId(pub i32);

/// A flag that is set, and when it was set.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Flag {
    /// Its id; [`World::flag_name`] gives the name.
    pub id: FlagId,
    /// When it was set.
    pub date: Date,
}

/// An event waiting for a country's choice (anvil-game 1.21.0).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingEvent {
    /// The id [`commands`](crate::commands)' event option takes; unique while it waits.
    pub pending_id: i32,
    /// The country it waits for, by the game's rule; `None` for none.
    pub country: Option<Tag>,
    /// The scope's province; `None` for a country event.
    pub province: Option<i32>,
    /// The event's options in its file; the window may disable some.
    pub options: u32,
    /// Hidden: the game shows no window for it.
    pub hidden: bool,
    /// The game chooses for the player the day after this date.
    pub auto_select: Date,
}

/// One of the four series of the game's graphs (anvil-game 1.21.0).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StatisticKind {
    /// The income graph, whole ducats (the game's value ÷ 1000, truncated).
    Income,
    /// The score, whole points (÷ 1000, truncated).
    Score,
    /// The provinces the country owns, a count.
    NationSize,
    /// Inflation, whole percent (÷ 1000, truncated).
    Inflation,
}

impl StatisticKind {
    fn raw(self) -> u32 {
        match self {
            Self::Income => ANVIL_GAME_STATISTIC_INCOME,
            Self::Score => ANVIL_GAME_STATISTIC_SCORE,
            Self::NationSize => ANVIL_GAME_STATISTIC_NATION_SIZE,
            Self::Inflation => ANVIL_GAME_STATISTIC_INFLATION,
        }
    }
}

/// One year of a series. The value is whole units, not × 1000.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StatisticPoint {
    /// The year whose 1 January wrote it: 1720 holds the value at the end of 1719.
    pub year: i32,
    /// The value then (0 for a year before the country had one).
    pub value: i32,
}

/// A named modifier a country or a province has for a time, as an effect such
/// as `add_country_modifier` gave it ([`World::country_timed_modifiers`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TimedModifier {
    /// Its key, as the game's files write it.
    pub key: String,
    /// `hidden = yes`: the game's windows do not list it.
    pub hidden: bool,
    /// A ruler modifier: it goes with the ruler.
    pub ruler: bool,
    /// When it was given; `None` when the game keeps no start date.
    pub start: Option<Date>,
    /// When it ends; `None` when it lasts until an effect removes it.
    pub end: Option<Date>,
}

/// A kind of relation between two countries (anvil-game 1.22.0). A relation
/// is one object in both countries' lists: who did what comes from
/// [`Relation::first`] and [`Relation::second`], never from whose list it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelationKind {
    /// An alliance.
    Alliance,
    /// A royal marriage.
    RoyalMarriage,
    /// `first` guarantees `second`.
    Guarantee,
    /// The country asked is `first`: it has access to `second`'s land.
    MilitaryAccess,
    /// The country asked is `second`: it gives `first` access.
    GivingMilitaryAccess,
    /// `first` pays `second`.
    Subsidies,
    /// `first` is the overlord, `second` the subject ([`World::subject_type`]).
    Dependency,
    /// `first` warns `second`.
    Warning,
}

impl RelationKind {
    fn raw(self) -> u32 {
        match self {
            Self::Alliance => ANVIL_GAME_RELATION_ALLIANCE,
            Self::RoyalMarriage => ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
            Self::Guarantee => ANVIL_GAME_RELATION_GUARANTEE,
            Self::MilitaryAccess => ANVIL_GAME_RELATION_MILITARY_ACCESS,
            Self::GivingMilitaryAccess => ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS,
            Self::Subsidies => ANVIL_GAME_RELATION_SUBSIDIES,
            Self::Dependency => ANVIL_GAME_RELATION_DEPENDENCY,
            Self::Warning => ANVIL_GAME_RELATION_WARNING,
        }
    }
}

/// A relation, as the game's save writes it ([`World::country_relations`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Relation {
    /// The guarantor, the one with access, the payer, the overlord, the one who warns.
    pub first: Option<Tag>,
    /// The other one.
    pub second: Option<Tag>,
    /// When it began; `None` when the game keeps no date.
    pub start: Option<Date>,
    /// When it ends; `None` for most, which have no end date.
    pub end: Option<Date>,
}

/// The player's tags ([`World::player_tags`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlayerTags {
    /// The country the game treats as the player's: what [`World::player`] answers.
    pub tag: Option<Tag>,
    /// The player's own tag as the game stores it: the observer's
    /// pseudo-country in observe mode.
    pub own: Option<Tag>,
    /// The observed country as the game stores it.
    pub observed: Option<Tag>,
    /// `own` is the observer's pseudo-country: observe mode.
    pub observer: bool,
}

/// What one country keeps about another ([`World::diplomacy_status`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DiplomacyStatus {
    /// Its opinion of the other, whole points: the number of the diplomacy
    /// window as the game's cache holds it, refreshed at least monthly for a
    /// human and yearly for an AI.
    pub opinion: i32,
    /// The sum of its timed opinion modifiers toward the other, whole points,
    /// not clamped: not the opinion.
    pub timed_sum: i32,
    /// Trust, 0..100; 50 until something changes it.
    pub trust: u32,
    /// Favors, × 1000.
    pub favors: Milli,
    /// The two have a truce (its end date is the game's to work out).
    pub truce: bool,
}

/// The `anvil-game.world` service.
#[derive(Clone, Copy)]
pub struct World {
    table: Table<AnvilGameWorldService>,
}

impl fmt::Debug for World {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("World")
            .field("size", &self.table.size())
            .finish()
    }
}

fn sized<T>() -> T {
    // SAFETY: the world's structs are plain data for which zero is valid.
    let mut value: T = unsafe { std::mem::zeroed() };
    let size = size_of::<T>() as u32;
    // SAFETY: each of them starts with `uint32_t size`.
    unsafe { std::ptr::from_mut(&mut value).cast::<u32>().write(size) };
    value
}

fn known(value: i32, values: u32, bit: u32) -> Option<Milli> {
    (values & bit != 0).then_some(Milli(value))
}

const EMPTY_TAG: AnvilGameTag = AnvilGameTag { text: [0; 4] };

impl World {
    /// The service; `None` without anvil-game 1.11.0 or on a game build whose
    /// symbols for it are declared absent.
    pub fn get(host: &Host) -> Option<Self> {
        // SAFETY: the table type of anvil-game.world version 1.
        let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
        Some(Self { table })
    }

    /// The C table, for what this crate does not wrap.
    pub fn c_api(&self) -> Table<AnvilGameWorldService> {
        self.table
    }

    /// The country the game treats as the player's (the observed one in observe mode).
    pub fn player(&self) -> Result<Option<Tag>> {
        let f = function!(self.table, AnvilGameWorldService, player)?;
        let mut tag = EMPTY_TAG;
        // SAFETY: the service's function with an out pointer.
        check(unsafe { f(&mut tag) }, || "world player")?;
        Ok(Tag::from_raw(&tag))
    }

    /// Valid province IDs are `1..limit`; 0 where a call is not allowed.
    pub fn province_limit(&self) -> i32 {
        // SAFETY: the service's function.
        function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
    }

    /// A province.
    pub fn province(&self, id: i32) -> Result<Province> {
        let f = function!(self.table, AnvilGameWorldService, province)?;
        let mut raw: AnvilGameProvince = sized();
        // SAFETY: the service's function; `size` says how much it may write.
        check(unsafe { f(id, &mut raw) }, || {
            format!("world province {id}")
        })?;
        Ok(Province {
            id: raw.id,
            owner: Tag::from_raw(&raw.owner),
            controller: Tag::from_raw(&raw.controller),
            base_tax: Milli(raw.base_tax),
            base_production: Milli(raw.base_production),
            base_manpower: Milli(raw.base_manpower),
            land: raw.flags & ANVIL_GAME_PROVINCE_LAND != 0,
            wasteland: raw.flags & ANVIL_GAME_PROVINCE_WASTELAND != 0,
            hre: raw.flags & ANVIL_GAME_PROVINCE_HRE != 0,
            city: raw.flags & ANVIL_GAME_PROVINCE_CITY != 0,
            coastal: raw.flags & ANVIL_GAME_PROVINCE_COASTAL != 0,
            state: raw.flags & ANVIL_GAME_PROVINCE_STATE != 0,
            local_autonomy: (raw.values & ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY != 0)
                .then_some(Milli(raw.local_autonomy)),
            devastation: (raw.values & ANVIL_GAME_PROVINCE_VALUE_DEVASTATION != 0)
                .then_some(Milli(raw.devastation)),
            trade_power: (raw.values & ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER != 0)
                .then_some(Milli(raw.trade_power)),
        })
    }

    /// The name the game displays (it follows the owner's culture).
    pub fn province_name(&self, id: i32) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, province_name)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world province_name {id}"),
            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
        )
    }

    /// The tags with a core on the province.
    pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
        let f = function!(self.table, AnvilGameWorldService, province_cores)?;
        // SAFETY: the service fills at most `capacity` tags.
        let raw = read_list(
            EMPTY_TAG,
            || format!("world province_cores {id}"),
            |out, capacity, count| unsafe { f(id, out, capacity, count) },
        )?;
        Ok(raw.iter().filter_map(Tag::from_raw).collect())
    }

    /// A country (the tag ignores case).
    pub fn country(&self, tag: Tag) -> Result<Country> {
        let f = function!(self.table, AnvilGameWorldService, country)?;
        let text = tag.c_text();
        let mut raw: AnvilGameCountry = sized();
        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
            format!("world country {tag}")
        })?;
        let v = raw.values;
        Ok(Country {
            tag: Tag::from_raw(&raw.tag),
            capital: (raw.capital != 0).then_some(raw.capital),
            province_count: raw.province_count,
            observer: raw.flags & ANVIL_GAME_COUNTRY_OBSERVER != 0,
            treasury: known(raw.treasury, v, ANVIL_GAME_VALUE_TREASURY),
            stability: known(raw.stability, v, ANVIL_GAME_VALUE_STABILITY),
            prestige: known(raw.prestige, v, ANVIL_GAME_VALUE_PRESTIGE),
            manpower: known(raw.manpower, v, ANVIL_GAME_VALUE_MANPOWER),
            monthly_income: known(raw.monthly_income, v, ANVIL_GAME_VALUE_MONTHLY_INCOME),
        })
    }

    /// The IDs of the provinces a country owns, in the game's order.
    pub fn country_provinces(&self, tag: Tag) -> Result<Vec<i32>> {
        let f = function!(self.table, AnvilGameWorldService, country_provinces)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` IDs.
        read_list(
            0i32,
            || format!("world country_provinces {tag}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
        )
    }

    /// The ids of the running wars.
    pub fn war_ids(&self) -> Result<Vec<u64>> {
        let f = function!(self.table, AnvilGameWorldService, war_ids)?;
        // SAFETY: the service fills at most `capacity` ids.
        read_list(
            0u64,
            || "world war_ids".to_owned(),
            |out, capacity, count| unsafe { f(out, capacity, count) },
        )
    }

    /// A running war.
    pub fn war(&self, id: u64) -> Result<War> {
        let f = function!(self.table, AnvilGameWorldService, war)?;
        let mut raw: AnvilGameWar = sized();
        // SAFETY: `size` says how much it may write.
        check(unsafe { f(id, &mut raw) }, || format!("world war {id:#x}"))?;
        Ok(War {
            id: raw.id,
            attacker: Tag::from_raw(&raw.attacker),
            defender: Tag::from_raw(&raw.defender),
        })
    }

    /// A war's name as the game shows it.
    pub fn war_name(&self, id: u64) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, war_name)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world war_name {id:#x}"),
            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
        )
    }

    /// The countries on one side of a war now.
    pub fn war_side(&self, id: u64, side: Side) -> Result<Vec<Tag>> {
        let f = function!(self.table, AnvilGameWorldService, war_side)?;
        let side_raw = match side {
            Side::Attackers => ANVIL_GAME_WAR_ATTACKERS,
            Side::Defenders => ANVIL_GAME_WAR_DEFENDERS,
        };
        // SAFETY: the service fills at most `capacity` tags.
        let raw = read_list(
            EMPTY_TAG,
            || format!("world war_side {id:#x}"),
            |out, capacity, count| unsafe { f(id, side_raw, out, capacity, count) },
        )?;
        Ok(raw.iter().filter_map(Tag::from_raw).collect())
    }

    /// The id of a modifier from its script key (`land_morale`,
    /// `local_tax_modifier`), case included. It holds as long as the game
    /// runs: ask once, as this walks every definition.
    pub fn modifier_id(&self, key: &str) -> Result<ModifierId> {
        let f = function!(self.table, AnvilGameWorldService, modifier_id)?;
        let key_c = crate::text::c_string(key);
        let mut id = 0i32;
        // SAFETY: a NUL-terminated key and an out pointer.
        check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
            format!("world modifier_id {key}")
        })?;
        Ok(ModifierId(id))
    }

    /// A country's modifier as the game uses it (a yes-or-no one is 1000 or 0).
    pub fn country_modifier(&self, tag: Tag, id: ModifierId) -> Result<Milli> {
        let f = function!(self.table, AnvilGameWorldService, country_modifier)?;
        let text = tag.c_text();
        let mut value = 0i32;
        // SAFETY: a NUL-terminated tag and an out pointer.
        check(unsafe { f(text.as_ptr(), id.0, &mut value) }, || {
            format!("world country_modifier {tag} {}", id.0)
        })?;
        Ok(Milli(value))
    }

    /// A province's own modifier (not its owner's values).
    pub fn province_modifier(&self, province: i32, id: ModifierId) -> Result<Milli> {
        let f = function!(self.table, AnvilGameWorldService, province_modifier)?;
        let mut value = 0i32;
        // SAFETY: an out pointer.
        check(unsafe { f(province, id.0, &mut value) }, || {
            format!("world province_modifier {province} {}", id.0)
        })?;
        Ok(Milli(value))
    }

    /// The ids of a country's armies and navies, in the game's order.
    pub fn country_units(&self, tag: Tag) -> Result<Vec<u64>> {
        let f = function!(self.table, AnvilGameWorldService, country_units)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` ids.
        read_list(
            0u64,
            || format!("world country_units {tag}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
        )
    }

    /// A unit by its country and id.
    pub fn unit(&self, tag: Tag, id: u64) -> Result<Unit> {
        let f = function!(self.table, AnvilGameWorldService, unit)?;
        let text = tag.c_text();
        let mut raw: AnvilGameUnit = sized();
        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
        check(unsafe { f(text.as_ptr(), id, &mut raw) }, || {
            format!("world unit {tag} {id:#x}")
        })?;
        Ok(Unit {
            kind: UnitKind::from_raw(raw.kind),
            id: raw.id,
            country: Tag::from_raw(&raw.country),
            location: (raw.location != 0).then_some(raw.location),
            mission: Mission(raw.mission),
            subunits: raw.subunits,
            strength: Milli(raw.strength),
            leader: (raw.leader != 0).then_some(raw.leader),
        })
    }

    /// The name the game shows for a unit ("1st Army").
    pub fn unit_name(&self, tag: Tag, id: u64) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, unit_name)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
        read_text(
            || format!("world unit_name {tag} {id:#x}"),
            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
        )
    }

    /// A unit's leader's name; `NotFound` also for a unit without one.
    pub fn unit_leader_name(&self, tag: Tag, id: u64) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, unit_leader_name)?;
        let text = tag.c_text();
        // SAFETY: as in unit_name.
        read_text(
            || format!("world unit_leader_name {tag} {id:#x}"),
            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
        )
    }

    /// The armies and navies the player has selected, in the game's order.
    pub fn selected_units(&self) -> Result<Vec<UnitRef>> {
        let f = function!(self.table, AnvilGameWorldService, selected_units)?;
        let empty = AnvilGameUnitRef {
            id: 0,
            country: EMPTY_TAG,
            kind: 0,
        };
        // SAFETY: the service fills at most `capacity` entries.
        let raw = read_list(
            empty,
            || "world selected_units".to_owned(),
            |out, capacity, count| unsafe { f(out, capacity, count) },
        )?;
        Ok(raw
            .iter()
            .map(|r| UnitRef {
                id: r.id,
                country: Tag::from_raw(&r.country),
                kind: UnitKind::from_raw(r.kind),
            })
            .collect())
    }

    /// A country's ruler, heir or consort. `NotFound` when it has none: the
    /// game then holds a placeholder that every such country shares, and the
    /// service never reads it. A country no longer on the map keeps its last
    /// ruler: check [`Country::province_count`] when that matters.
    pub fn monarch(&self, tag: Tag, kind: MonarchKind) -> Result<Monarch> {
        let f = function!(self.table, AnvilGameWorldService, monarch)?;
        let text = tag.c_text();
        let mut raw: AnvilGameMonarch = sized();
        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
        check(unsafe { f(text.as_ptr(), kind.raw(), &mut raw) }, || {
            format!("world monarch {tag} {kind:?}")
        })?;
        Ok(Monarch {
            kind: MonarchKind::from_raw(raw.kind),
            id: raw.id,
            country: Tag::from_raw(&raw.country),
            female: raw.flags & ANVIL_GAME_MONARCH_FEMALE != 0,
            regency: raw.flags & ANVIL_GAME_MONARCH_REGENCY != 0,
            adm: raw.adm,
            dip: raw.dip,
            mil: raw.mil,
            claim: Milli(raw.claim),
            birth: Date::from_raw(&raw.birth),
            leader: (raw.leader != 0).then_some(raw.leader),
        })
    }

    /// Their name as the game keeps it; empty in an interregnum.
    pub fn monarch_name(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, monarch_name)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
        read_text(
            || format!("world monarch_name {tag} {kind:?}"),
            |buffer, capacity, length| unsafe {
                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
            },
        )
    }

    /// Their dynasty as the game shows it (a regency council shows the heir's).
    pub fn monarch_dynasty(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, monarch_dynasty)?;
        let text = tag.c_text();
        // SAFETY: as in monarch_name.
        read_text(
            || format!("world monarch_dynasty {tag} {kind:?}"),
            |buffer, capacity, length| unsafe {
                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
            },
        )
    }

    /// The id of a flag from its name, case included. It holds as long as the
    /// game runs: ask once. `NotFound` for a name nothing has set yet in this
    /// run of the game.
    pub fn flag_id(&self, name: &str) -> Result<FlagId> {
        let f = function!(self.table, AnvilGameWorldService, flag_id)?;
        let name_c = crate::text::c_string(name);
        let mut id = 0i32;
        // SAFETY: a NUL-terminated name and an out pointer.
        check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
            format!("world flag_id {name}")
        })?;
        Ok(FlagId(id))
    }

    /// A flag's name.
    pub fn flag_name(&self, id: FlagId) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, flag_name)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world flag_name {}", id.0),
            |buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
        )
    }

    /// A country's flags, with the date each was set.
    pub fn country_flags(&self, tag: Tag) -> Result<Vec<Flag>> {
        let f = function!(self.table, AnvilGameWorldService, country_flags)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
        flags(
            || format!("world country_flags {tag}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
        )
    }

    /// A province's flags as `has_province_flag` sees them, its permanent ones included.
    pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
        let f = function!(self.table, AnvilGameWorldService, province_flags)?;
        // SAFETY: the service fills at most `capacity` flags.
        flags(
            || format!("world province_flags {province}"),
            |out, capacity, count| unsafe { f(province, out, capacity, count) },
        )
    }

    /// A ruler's, heir's or consort's flags; `NotFound` as for [`World::monarch`].
    pub fn monarch_flags(&self, tag: Tag, kind: MonarchKind) -> Result<Vec<Flag>> {
        let f = function!(self.table, AnvilGameWorldService, monarch_flags)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
        flags(
            || format!("world monarch_flags {tag} {kind:?}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
        )
    }

    /// The global flags.
    pub fn global_flags(&self) -> Result<Vec<Flag>> {
        let f = function!(self.table, AnvilGameWorldService, global_flags)?;
        // SAFETY: the service fills at most `capacity` flags.
        flags(
            || "world global_flags".to_owned(),
            |out, capacity, count| unsafe { f(out, capacity, count) },
        )
    }

    /// A country's variable by its name, case included. `NotFound` when it
    /// has none of that name (the game's triggers take that as 0).
    pub fn country_variable(&self, tag: Tag, name: &str) -> Result<Milli> {
        let f = function!(self.table, AnvilGameWorldService, country_variable)?;
        let text = tag.c_text();
        let name_c = crate::text::c_string(name);
        let mut value = 0i32;
        // SAFETY: a NUL-terminated tag and name, and an out pointer.
        let result = unsafe { f(text.as_ptr(), name_c.as_ptr(), &mut value) };
        check(result, || format!("world country_variable {tag} {name}"))?;
        Ok(Milli(value))
    }

    /// A province's variable by its name.
    pub fn province_variable(&self, province: i32, name: &str) -> Result<Milli> {
        let f = function!(self.table, AnvilGameWorldService, province_variable)?;
        let name_c = crate::text::c_string(name);
        let mut value = 0i32;
        // SAFETY: a NUL-terminated name and an out pointer.
        check(unsafe { f(province, name_c.as_ptr(), &mut value) }, || {
            format!("world province_variable {province} {name}")
        })?;
        Ok(Milli(value))
    }

    /// The names of a country's variables, in the game's order.
    pub fn country_variable_names(&self, tag: Tag) -> Result<Vec<String>> {
        let f = function!(self.table, AnvilGameWorldService, country_variable_names)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
        let all = read_text(
            || format!("world country_variable_names {tag}"),
            |buffer, capacity, length| unsafe { f(text.as_ptr(), buffer, capacity, length) },
        )?;
        Ok(split_names(&all))
    }

    /// The names of a province's variables, in the game's order.
    pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
        let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
        // SAFETY: the service fills at most `capacity` bytes.
        let all = read_text(
            || format!("world province_variable_names {province}"),
            |buffer, capacity, length| unsafe { f(province, buffer, capacity, length) },
        )?;
        Ok(split_names(&all))
    }

    /// The ids of the events waiting for a country's choice, in the game's
    /// order; `None` for the player's own country (`NotFound` in observe
    /// mode). An entry counts once it was in the game's list at two outer
    /// frames in a row, which leaves out an AI's choices and hidden events.
    /// Key on the id: the same event can wait twice.
    pub fn pending_events(&self, tag: Option<Tag>) -> Result<Vec<i32>> {
        let f = function!(self.table, AnvilGameWorldService, pending_events)?;
        let text = tag.map(|t| t.c_text());
        let tag_ptr = text.as_ref().map_or(std::ptr::null(), |t| t.as_ptr());
        // SAFETY: a NUL-terminated tag or null; the service fills at most `capacity` ids.
        read_list(
            0i32,
            || format!("world pending_events {tag:?}"),
            |out, capacity, count| unsafe { f(tag_ptr, out, capacity, count) },
        )
    }

    /// A waiting event; `NotFound` for an id that is not waiting (or not yet counted).
    pub fn pending_event(&self, pending_id: i32) -> Result<PendingEvent> {
        let f = function!(self.table, AnvilGameWorldService, pending_event)?;
        let mut raw: AnvilGamePendingEvent = sized();
        // SAFETY: `size` says how much it may write.
        check(unsafe { f(pending_id, &mut raw) }, || {
            format!("world pending_event {pending_id}")
        })?;
        Ok(PendingEvent {
            pending_id: raw.pending_id,
            country: Tag::from_raw(&raw.country),
            province: (raw.province != 0).then_some(raw.province),
            options: raw.options,
            hidden: raw.flags & ANVIL_GAME_PENDING_HIDDEN != 0,
            auto_select: Date::from_raw(&raw.auto_select),
        })
    }

    /// The waiting event's key as the game's files name it (`flavor_tur.203`).
    pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world pending_event_key {pending_id}"),
            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
        )
    }

    /// The localisation key of its title, not the translated text.
    pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world pending_event_title {pending_id}"),
            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
        )
    }

    /// A country's yearly series of the game's graphs, oldest first. It
    /// changes only at [`game::YEAR`](crate::game::YEAR). `NotFound` for a tag
    /// without a series (none has one before its first year end).
    pub fn country_statistics(&self, tag: Tag, kind: StatisticKind) -> Result<Vec<StatisticPoint>> {
        let f = function!(self.table, AnvilGameWorldService, country_statistics)?;
        let text = tag.c_text();
        let empty = AnvilGameStatisticPoint { year: 0, value: 0 };
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` points.
        let raw = read_list(
            empty,
            || format!("world country_statistics {tag} {kind:?}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
        )?;
        Ok(raw
            .iter()
            .map(|p| StatisticPoint {
                year: p.year,
                value: p.value,
            })
            .collect())
    }

    /// A country's timed modifiers, in the game's order, each with its key.
    /// Call it on the main thread, as every read: the list and the keys come
    /// from two calls of the service in the same frame.
    pub fn country_timed_modifiers(&self, tag: Tag) -> Result<Vec<TimedModifier>> {
        let list = function!(self.table, AnvilGameWorldService, country_timed_modifiers)?;
        let keys = function!(
            self.table,
            AnvilGameWorldService,
            country_timed_modifier_keys
        )?;
        let text = tag.c_text();
        let context = || format!("world country_timed_modifiers {tag}");
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` entries or bytes.
        let raw = timed_list(context, |out, capacity, count| unsafe {
            list(text.as_ptr(), out, capacity, count)
        })?;
        // SAFETY: as above.
        let all = read_text(context, |buffer, capacity, length| unsafe {
            keys(text.as_ptr(), buffer, capacity, length)
        })?;
        timed_modifiers(&raw, &all, context)
    }

    /// A province's timed modifiers, in the game's order, each with its key.
    pub fn province_timed_modifiers(&self, province: i32) -> Result<Vec<TimedModifier>> {
        let list = function!(self.table, AnvilGameWorldService, province_timed_modifiers)?;
        let keys = function!(
            self.table,
            AnvilGameWorldService,
            province_timed_modifier_keys
        )?;
        let context = || format!("world province_timed_modifiers {province}");
        // SAFETY: the service fills at most `capacity` entries or bytes.
        let raw = timed_list(context, |out, capacity, count| unsafe {
            list(province, out, capacity, count)
        })?;
        // SAFETY: as above.
        let all = read_text(context, |buffer, capacity, length| unsafe {
            keys(province, buffer, capacity, length)
        })?;
        timed_modifiers(&raw, &all, context)
    }

    /// The province the game's province view shows while that window is
    /// open; `NotFound` while none is open.
    pub fn province_view(&self) -> Result<i32> {
        let f = function!(self.table, AnvilGameWorldService, province_view)?;
        let mut province = 0i32;
        // SAFETY: an out pointer.
        check(unsafe { f(&mut province) }, || {
            "world province_view".to_owned()
        })?;
        Ok(province)
    }

    /// The province last selected on the map; 0 while none has been selected
    /// in this session (anvil-game 1.24.0).
    pub fn selected_province(&self) -> Result<i32> {
        let f = function!(self.table, AnvilGameWorldService, selected_province)?;
        let mut province = 0i32;
        // SAFETY: an out pointer.
        check(unsafe { f(&mut province) }, || {
            "world selected_province".to_owned()
        })?;
        Ok(province)
    }

    /// The province under the point (`x`, `y`) of the game window's client
    /// area, in pixels, as the game's hover finds it; 0 off the map
    /// (anvil-game 1.24.0).
    pub fn province_at(&self, x: i32, y: i32) -> Result<i32> {
        let f = function!(self.table, AnvilGameWorldService, province_at)?;
        let mut province = 0i32;
        // SAFETY: an out pointer.
        check(unsafe { f(x, y, &mut province) }, || {
            format!("world province_at {x},{y}")
        })?;
        Ok(province)
    }

    /// The army or navy the map picks at the same point, as the game's
    /// cursor does; `NotFound` when it picks no unit there (anvil-game 1.24.0).
    pub fn unit_at(&self, x: i32, y: i32) -> Result<UnitRef> {
        let f = function!(self.table, AnvilGameWorldService, unit_at)?;
        let mut raw = AnvilGameUnitRef {
            id: 0,
            country: EMPTY_TAG,
            kind: 0,
        };
        // SAFETY: an out pointer.
        check(unsafe { f(x, y, &mut raw) }, || {
            format!("world unit_at {x},{y}")
        })?;
        Ok(UnitRef {
            id: raw.id,
            country: Tag::from_raw(&raw.country),
            kind: UnitKind::from_raw(raw.kind),
        })
    }

    /// The keys of the province triggered modifiers a province has been given
    /// (`add_province_triggered_modifier`), in the game's order, whether or
    /// not their triggers hold now. With
    /// [`province_timed_modifiers`](Self::province_timed_modifiers) they are
    /// every key `has_province_modifier` looks for (anvil-game 1.25.0).
    pub fn province_triggered_modifiers(&self, province: i32) -> Result<Vec<String>> {
        let keys = function!(
            self.table,
            AnvilGameWorldService,
            province_triggered_modifier_keys
        )?;
        let context = || format!("world province_triggered_modifiers {province}");
        // SAFETY: the service fills at most `capacity` bytes.
        let all = read_text(context, |buffer, capacity, length| unsafe {
            keys(province, buffer, capacity, length)
        })?;
        Ok(split_names(&all))
    }

    /// A country's relations of one kind, in the game's order (anvil-game 1.22.0).
    pub fn country_relations(&self, tag: Tag, kind: RelationKind) -> Result<Vec<Relation>> {
        let f = function!(self.table, AnvilGameWorldService, country_relations)?;
        let text = tag.c_text();
        // SAFETY: plain data for which zero is valid.
        let empty: AnvilGameRelation = unsafe { std::mem::zeroed() };
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` relations.
        let raw = read_list(
            empty,
            || format!("world country_relations {tag} {kind:?}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
        )?;
        Ok(raw
            .iter()
            .map(|r| Relation {
                first: Tag::from_raw(&r.first),
                second: Tag::from_raw(&r.second),
                start: (r.start.size != 0).then(|| Date::from_raw(&r.start)),
                end: (r.end.size != 0).then(|| Date::from_raw(&r.end)),
            })
            .collect())
    }

    /// The key of `subject`'s subject type under `overlord` (`vassal`,
    /// `march`); `NotFound` when it is not `overlord`'s subject.
    pub fn subject_type(&self, overlord: Tag, subject: Tag) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, subject_type)?;
        let (a, b) = (overlord.c_text(), subject.c_text());
        // SAFETY: NUL-terminated tags; the service fills at most `capacity` bytes.
        read_text(
            || format!("world subject_type {overlord} {subject}"),
            |buffer, capacity, length| unsafe {
                f(a.as_ptr(), b.as_ptr(), buffer, capacity, length)
            },
        )
    }

    /// What `from` keeps about `to`, with its opinion from the game's cache.
    /// `NotFound` for a country that owns no province now and while the cache
    /// has no entry for `to` yet; `InvalidArgument` for the same country twice.
    pub fn diplomacy_status(&self, from: Tag, to: Tag) -> Result<DiplomacyStatus> {
        let f = function!(self.table, AnvilGameWorldService, diplomacy_status)?;
        let (a, b) = (from.c_text(), to.c_text());
        let mut raw: AnvilGameDiplomacyStatus = sized();
        // SAFETY: NUL-terminated tags; `size` says how much it may write.
        check(unsafe { f(a.as_ptr(), b.as_ptr(), &mut raw) }, || {
            format!("world diplomacy_status {from} {to}")
        })?;
        Ok(DiplomacyStatus {
            opinion: raw.opinion,
            timed_sum: raw.timed_sum,
            trust: raw.trust,
            favors: Milli(raw.favors),
            truce: raw.flags & ANVIL_GAME_DIPLOMACY_TRUCE != 0,
        })
    }

    /// The countries `tag` has chosen as rivals, in the game's order.
    pub fn country_rivals(&self, tag: Tag) -> Result<Vec<Tag>> {
        let f = function!(self.table, AnvilGameWorldService, country_rivals)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
        let raw = read_list(
            EMPTY_TAG,
            || format!("world country_rivals {tag}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
        )?;
        Ok(raw.iter().filter_map(Tag::from_raw).collect())
    }

    /// Its overlord; `NotFound` also for a country without one.
    pub fn country_overlord(&self, tag: Tag) -> Result<Tag> {
        let f = function!(self.table, AnvilGameWorldService, country_overlord)?;
        let text = tag.c_text();
        let mut raw = EMPTY_TAG;
        // SAFETY: a NUL-terminated tag and an out pointer.
        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
            format!("world country_overlord {tag}")
        })?;
        Tag::from_raw(&raw)
            .ok_or_else(|| Error::new(ErrorCode::Internal, format!("world country_overlord {tag}")))
    }

    /// Its direct subjects, in the game's order.
    pub fn country_subjects(&self, tag: Tag) -> Result<Vec<Tag>> {
        let f = function!(self.table, AnvilGameWorldService, country_subjects)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
        let raw = read_list(
            EMPTY_TAG,
            || format!("world country_subjects {tag}"),
            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
        )?;
        Ok(raw.iter().filter_map(Tag::from_raw).collect())
    }

    /// What [`World::player`] answers and the two tags it is chosen from, read
    /// at once (anvil-game 1.23.0). In a normal game `tag` and `own` are the
    /// player's country and `observed` is as the game stores it: usually `None`,
    /// but it can hold a tag left over; in observe mode `own` is the
    /// observer's pseudo-country and `tag` the observed country while there is
    /// one.
    pub fn player_tags(&self) -> Result<PlayerTags> {
        let f = function!(self.table, AnvilGameWorldService, player_tags)?;
        let mut raw: AnvilGamePlayer = sized();
        // SAFETY: `size` says how much it may write.
        check(unsafe { f(&mut raw) }, || "world player_tags")?;
        Ok(PlayerTags {
            tag: Tag::from_raw(&raw.tag),
            own: Tag::from_raw(&raw.own),
            observed: Tag::from_raw(&raw.observed),
            observer: raw.flags & ANVIL_GAME_PLAYER_OBSERVER != 0,
        })
    }

    /// The regions the fleet may explore, as the game's naval exploration
    /// dialog lists them: each region once, in the game's order. It calls the
    /// dialog's own function and changes nothing; `InvalidArgument` for an
    /// army (anvil-game 1.25.0).
    pub fn exploration_regions(&self, fleet: &UnitRef, list: ExplorationList) -> Result<Vec<i32>> {
        let f = function!(self.table, AnvilGameWorldService, exploration_regions)?;
        let raw = fleet.to_raw();
        // SAFETY: a unit reference; the service fills at most `capacity` indexes.
        read_list(
            0i32,
            || format!("world exploration_regions {} {list:?}", fleet.id),
            |out, capacity, count| unsafe { f(&raw, list.raw(), out, capacity, count) },
        )
    }

    /// The region's name as the game shows it, in the game's language
    /// (anvil-game 1.25.0).
    pub fn region_name(&self, region: i32) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, region_name)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world region_name {region}"),
            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
        )
    }

    /// The region's script key, such as `baltic_sea_region` (anvil-game 1.25.0).
    pub fn region_key(&self, region: i32) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, region_key)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world region_key {region}"),
            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
        )
    }

    fn province_key(&self, province: i32, key: u32, name: &str) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, province_key)?;
        // SAFETY: the service fills at most `capacity` bytes.
        read_text(
            || format!("world {name} {province}"),
            |buffer, capacity, length| unsafe { f(province, key, buffer, capacity, length) },
        )
    }

    fn country_key(&self, tag: Tag, key: u32, name: &str) -> Result<String> {
        let f = function!(self.table, AnvilGameWorldService, country_key)?;
        let text = tag.c_text();
        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
        read_text(
            || format!("world {name} {tag}"),
            |buffer, capacity, length| unsafe { f(text.as_ptr(), key, buffer, capacity, length) },
        )
    }

    /// The script key of a province's religion, such as `orthodox`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_religion(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_RELIGION,
            "province_religion",
        )
    }

    /// The script key of a province's culture, such as `russian`; `NotFound`
    /// when it has none (anvil-game 1.26.0).
    pub fn province_culture(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_CULTURE,
            "province_culture",
        )
    }

    /// The script key of a province's trade goods, such as `grain`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_trade_goods(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_TRADE_GOODS,
            "province_trade_goods",
        )
    }

    /// The script key of a country's state religion; `NotFound` when it has
    /// none (anvil-game 1.26.0).
    pub fn country_religion(&self, tag: Tag) -> Result<String> {
        self.country_key(tag, crate::sys::ANVIL_GAME_KEY_RELIGION, "country_religion")
    }

    /// The script key of a country's primary culture; `NotFound` when it has
    /// none (anvil-game 1.26.0).
    pub fn country_culture(&self, tag: Tag) -> Result<String> {
        self.country_key(tag, crate::sys::ANVIL_GAME_KEY_CULTURE, "country_culture")
    }

    /// The script key of the group of a province's religion, such as
    /// `christian`; `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_religion_group(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
            "province_religion_group",
        )
    }

    /// The script key of the group of a province's culture, such as
    /// `east_slavic`; `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_culture_group(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
            "province_culture_group",
        )
    }

    /// The script key of a province's area, such as `uppland_area`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_area(&self, province: i32) -> Result<String> {
        self.province_key(province, crate::sys::ANVIL_GAME_KEY_AREA, "province_area")
    }

    /// The script key of a province's region, such as `scandinavia_region`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_region(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_REGION,
            "province_region",
        )
    }

    /// The script key of a province's superregion, such as
    /// `europe_superregion`; `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_superregion(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_SUPERREGION,
            "province_superregion",
        )
    }

    /// The script key of a province's continent, such as `europe`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_continent(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_CONTINENT,
            "province_continent",
        )
    }

    /// The script key of a province's trade node, such as `baltic_sea`;
    /// `NotFound` when it has none (anvil-game 1.26.0).
    pub fn province_trade_node(&self, province: i32) -> Result<String> {
        self.province_key(
            province,
            crate::sys::ANVIL_GAME_KEY_TRADE_NODE,
            "province_trade_node",
        )
    }

    /// The script key of the group of a country's state religion; `NotFound`
    /// when it has none (anvil-game 1.26.0).
    pub fn country_religion_group(&self, tag: Tag) -> Result<String> {
        self.country_key(
            tag,
            crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
            "country_religion_group",
        )
    }

    /// The script key of the group of a country's primary culture; `NotFound`
    /// when it has none (anvil-game 1.26.0).
    pub fn country_culture_group(&self, tag: Tag) -> Result<String> {
        self.country_key(
            tag,
            crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
            "country_culture_group",
        )
    }
}

fn timed_list(
    context: impl Fn() -> String,
    call: impl FnMut(*mut AnvilGameTimedModifier, u32, *mut u32) -> crate::sys::AnvilResult,
) -> Result<Vec<AnvilGameTimedModifier>> {
    // SAFETY: plain data for which zero is valid.
    let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
    read_list(empty, context, call)
}

// The entries with their keys; a count that differs means the list changed
// between the two calls, which happens only off the main thread.
fn timed_modifiers(
    raw: &[AnvilGameTimedModifier],
    keys: &str,
    context: impl Fn() -> String,
) -> Result<Vec<TimedModifier>> {
    let keys = split_names(keys);
    if keys.len() != raw.len() {
        return Err(Error::new(ErrorCode::Internal, context()));
    }
    Ok(raw
        .iter()
        .zip(keys)
        .map(|(m, key)| TimedModifier {
            key,
            hidden: m.flags & ANVIL_GAME_TIMED_HIDDEN != 0,
            ruler: m.flags & ANVIL_GAME_TIMED_RULER != 0,
            start: (m.flags & ANVIL_GAME_TIMED_NO_START == 0).then(|| Date::from_raw(&m.start)),
            end: (m.flags & ANVIL_GAME_TIMED_NO_END == 0).then(|| Date::from_raw(&m.end)),
        })
        .collect())
}

/// Names that each end with a NUL, one after the other.
fn split_names(all: &str) -> Vec<String> {
    all.split_terminator('\0').map(str::to_owned).collect()
}

fn flags(
    context: impl Fn() -> String,
    call: impl FnMut(*mut AnvilGameFlag, u32, *mut u32) -> crate::sys::AnvilResult,
) -> Result<Vec<Flag>> {
    let empty = AnvilGameFlag {
        id: 0,
        reserved: 0,
        date: AnvilGameDate {
            size: 0,
            year: 0,
            month: 0,
            day: 0,
            session: 0,
        },
    };
    let raw = read_list(empty, context, call)?;
    Ok(raw
        .iter()
        .map(|f| Flag {
            id: FlagId(f.id),
            date: Date::from_raw(&f.date),
        })
        .collect())
}