Skip to main content

anvil/
world.rs

1//! `anvil-game.world`: the world of the running session, read straight from
2//! the game (anvil-game 1.11.0; modifiers, units and the selection 1.15.0;
3//! rulers, heirs, consorts, flags and variables 1.20.0; pending events,
4//! statistics and timed modifiers 1.21.0; diplomacy 1.22.0).
5//!
6//! **Thread.** Call it only on the game's main thread after an outer frame:
7//! from a handler of an anvil-game event ([`game`](crate::game)) or from
8//! [`Game::run_on_main_thread`](crate::game::Game::run_on_main_thread) work,
9//! or from a panel click. Anywhere else, and outside a session, a call answers
10//! [`ErrorCode::WrongPhase`] and reads nothing.
11//!
12//! **Results.** [`ErrorCode::NotFound`] for an unknown province ID, tag, war
13//! or unit; [`ErrorCode::NotDeclared`] for a group of calls whose symbols a
14//! port declared absent; [`ErrorCode::Unsupported`] for a call the running
15//! anvil-game is too old to have.
16//!
17//! **What it shows.** Everything, also under terra incognita and in
18//! multiplayer, where that is more than the player sees. A read changes
19//! nothing, so it cannot cause a desync. Values marked "× 1000" are as the
20//! game stores them, as [`Milli`].
21//!
22//! [`ErrorCode::WrongPhase`]: crate::ErrorCode::WrongPhase
23//! [`ErrorCode::NotFound`]: crate::ErrorCode::NotFound
24//! [`ErrorCode::NotDeclared`]: crate::ErrorCode::NotDeclared
25//! [`ErrorCode::Unsupported`]: crate::ErrorCode::Unsupported
26
27use std::fmt;
28use std::mem::size_of;
29
30use crate::error::{check, Error, ErrorCode, Result};
31use crate::game::Date;
32use crate::host::Host;
33use crate::sys::{
34    AnvilGameCountry, AnvilGameDate, AnvilGameDiplomacyStatus, AnvilGameFlag, AnvilGameMonarch,
35    AnvilGamePendingEvent, AnvilGamePlayer, AnvilGameProvince, AnvilGameRelation,
36    AnvilGameStatisticPoint, AnvilGameTag, AnvilGameTimedModifier, AnvilGameUnit, AnvilGameUnitRef,
37    AnvilGameWar, AnvilGameWorldService, ANVIL_GAME_COUNTRY_OBSERVER, ANVIL_GAME_DIPLOMACY_TRUCE,
38    ANVIL_GAME_EXPLORE_COAST, ANVIL_GAME_EXPLORE_SEA, ANVIL_GAME_MONARCH_CONSORT,
39    ANVIL_GAME_MONARCH_FEMALE, ANVIL_GAME_MONARCH_HEIR, ANVIL_GAME_MONARCH_REGENCY,
40    ANVIL_GAME_MONARCH_RULER, ANVIL_GAME_PENDING_HIDDEN, ANVIL_GAME_PLAYER_OBSERVER,
41    ANVIL_GAME_PROVINCE_LAND, ANVIL_GAME_PROVINCE_WASTELAND, ANVIL_GAME_RELATION_ALLIANCE,
42    ANVIL_GAME_RELATION_DEPENDENCY, ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS,
43    ANVIL_GAME_RELATION_GUARANTEE, ANVIL_GAME_RELATION_MILITARY_ACCESS,
44    ANVIL_GAME_RELATION_ROYAL_MARRIAGE, ANVIL_GAME_RELATION_SUBSIDIES, ANVIL_GAME_RELATION_WARNING,
45    ANVIL_GAME_STATISTIC_INCOME, ANVIL_GAME_STATISTIC_INFLATION, ANVIL_GAME_STATISTIC_NATION_SIZE,
46    ANVIL_GAME_STATISTIC_SCORE, ANVIL_GAME_TIMED_HIDDEN, ANVIL_GAME_TIMED_NO_END,
47    ANVIL_GAME_TIMED_NO_START, ANVIL_GAME_TIMED_RULER, ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY,
48    ANVIL_GAME_VALUE_MANPOWER, ANVIL_GAME_VALUE_MONTHLY_INCOME, ANVIL_GAME_VALUE_PRESTIGE,
49    ANVIL_GAME_VALUE_STABILITY, ANVIL_GAME_VALUE_TREASURY, ANVIL_GAME_WAR_ATTACKERS,
50    ANVIL_GAME_WAR_DEFENDERS, ANVIL_GAME_WORLD_SERVICE_VERSION,
51};
52use crate::table::Table;
53use crate::text::{read_list, read_text, Tag};
54
55/// The service's name.
56pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
57/// The service's major version.
58pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;
59
60/// A value the game stores × 1000: `Milli(4500)` is 4.5.
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct Milli(pub i32);
63
64impl Milli {
65    /// The value as a float.
66    pub fn get(self) -> f64 {
67        f64::from(self.0) / 1000.0
68    }
69}
70
71impl fmt::Display for Milli {
72    /// With up to three decimals, trailing zeros dropped: `4.5`, `-12`, `0.125`.
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        let sign = if self.0 < 0 { "-" } else { "" };
75        let value = self.0.unsigned_abs();
76        let (whole, part) = (value / 1000, value % 1000);
77        if part == 0 {
78            return write!(f, "{sign}{whole}");
79        }
80        let decimals = format!("{part:03}");
81        write!(f, "{sign}{whole}.{}", decimals.trim_end_matches('0'))
82    }
83}
84
85/// A province.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Province {
88    /// Its ID.
89    pub id: i32,
90    /// Its owner; `None` for none.
91    pub owner: Option<Tag>,
92    /// Its controller.
93    pub controller: Option<Tag>,
94    /// Base tax, without the capital's bonus.
95    pub base_tax: Milli,
96    /// Base production.
97    pub base_production: Milli,
98    /// Base manpower.
99    pub base_manpower: Milli,
100    /// Not a sea or a lake.
101    pub land: bool,
102    /// A wasteland.
103    pub wasteland: bool,
104}
105
106/// A country. A value this game build does not have is `None`.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct Country {
109    /// Its tag.
110    pub tag: Option<Tag>,
111    /// Its capital province; `None` for none.
112    pub capital: Option<i32>,
113    /// The provinces it owns; above 0 when it exists on the map.
114    pub province_count: i32,
115    /// The observer's pseudo-country.
116    pub observer: bool,
117    /// Ducats.
118    pub treasury: Option<Milli>,
119    /// Stability.
120    pub stability: Option<Milli>,
121    /// Prestige.
122    pub prestige: Option<Milli>,
123    /// Manpower in the game's thousands: `Milli(25000)` is 25 000 men.
124    pub manpower: Option<Milli>,
125    /// The income total of the economy view, before expenses, as of the last
126    /// monthly update.
127    pub monthly_income: Option<Milli>,
128}
129
130/// A running war.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub struct War {
133    /// Its id: the same while the war runs (a later war may reuse it).
134    pub id: u64,
135    /// Who started it.
136    pub attacker: Option<Tag>,
137    /// Whom it was declared on.
138    pub defender: Option<Tag>,
139}
140
141/// A side of a war.
142#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
143pub enum Side {
144    /// The attacker and its allies.
145    Attackers,
146    /// The defender and its allies.
147    Defenders,
148}
149
150/// An army or a navy.
151#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
152pub enum UnitKind {
153    /// An army.
154    Army,
155    /// A navy.
156    Navy,
157    /// A value this crate does not know.
158    Other(u32),
159}
160
161impl UnitKind {
162    fn from_raw(kind: u32) -> Self {
163        match kind {
164            ANVIL_GAME_UNIT_ARMY => Self::Army,
165            ANVIL_GAME_UNIT_NAVY => Self::Navy,
166            other => Self::Other(other),
167        }
168    }
169}
170
171/// What a unit does on its own, by the game's numbers (`ANVIL_GAME_MISSION_*`).
172#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
173pub struct Mission(pub i32);
174
175impl Mission {
176    /// Not one the service could read.
177    pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
178    /// No mission: the player moves it.
179    pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
180    /// Besiege the enemy's provinces on its own.
181    pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
182    /// Hunt rebels.
183    pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
184    /// Drill.
185    pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
186}
187
188/// A unit: an army or a navy.
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub struct Unit {
191    /// Army or navy.
192    pub kind: UnitKind,
193    /// The game's id: the same while the unit exists.
194    pub id: u64,
195    /// The country it belongs to.
196    pub country: Option<Tag>,
197    /// The province it is in or at; `None` for none.
198    pub location: Option<i32>,
199    /// What it does on its own.
200    pub mission: Mission,
201    /// Regiments or ships.
202    pub subunits: u32,
203    /// The sum of the regiments' or ships' strength (men for an army).
204    pub strength: Milli,
205    /// Its leader's id; `None` for no leader.
206    pub leader: Option<u64>,
207}
208
209/// One unit of the player's selection.
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub struct UnitRef {
212    /// The unit's id.
213    pub id: u64,
214    /// The country it belongs to (a player may select units of others to look).
215    pub country: Option<Tag>,
216    /// Army or navy.
217    pub kind: UnitKind,
218}
219
220impl UnitRef {
221    pub(crate) fn to_raw(self) -> AnvilGameUnitRef {
222        AnvilGameUnitRef {
223            id: self.id,
224            country: self
225                .country
226                .map(|tag| tag.to_raw())
227                .unwrap_or(AnvilGameTag { text: [0; 4] }),
228            kind: match self.kind {
229                UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
230                UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
231                UnitKind::Other(other) => other,
232            },
233        }
234    }
235}
236
237/// Which list of the naval exploration dialog [`World::exploration_regions`]
238/// reads (anvil-game 1.25.0).
239#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
240pub enum ExplorationList {
241    /// The regions a coast exploration may take.
242    Coast,
243    /// The regions a sea exploration may take.
244    Sea,
245}
246
247impl ExplorationList {
248    fn raw(self) -> i32 {
249        match self {
250            Self::Coast => ANVIL_GAME_EXPLORE_COAST as i32,
251            Self::Sea => ANVIL_GAME_EXPLORE_SEA as i32,
252        }
253    }
254}
255
256/// The id of a modifier, from its script key ([`World::modifier_id`]).
257#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
258pub struct ModifierId(pub i32);
259
260/// A country's ruler, heir or consort (anvil-game 1.20.0).
261#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
262pub enum MonarchKind {
263    /// The ruler.
264    Ruler,
265    /// The heir.
266    Heir,
267    /// The consort.
268    Consort,
269}
270
271impl MonarchKind {
272    fn raw(self) -> u32 {
273        match self {
274            Self::Ruler => ANVIL_GAME_MONARCH_RULER,
275            Self::Heir => ANVIL_GAME_MONARCH_HEIR,
276            Self::Consort => ANVIL_GAME_MONARCH_CONSORT,
277        }
278    }
279
280    fn from_raw(kind: u32) -> Self {
281        match kind {
282            ANVIL_GAME_MONARCH_HEIR => Self::Heir,
283            ANVIL_GAME_MONARCH_CONSORT => Self::Consort,
284            _ => Self::Ruler,
285        }
286    }
287}
288
289/// A ruler, heir or consort, as the game stores them.
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
291pub struct Monarch {
292    /// Ruler, heir or consort.
293    pub kind: MonarchKind,
294    /// The game's id of the person.
295    pub id: u64,
296    /// The country asked about.
297    pub country: Option<Tag>,
298    /// Female.
299    pub female: bool,
300    /// A regency council or a regent rules for them.
301    pub regency: bool,
302    /// Administrative skill, without modifiers.
303    pub adm: i32,
304    /// Diplomatic skill.
305    pub dip: i32,
306    /// Military skill.
307    pub mil: i32,
308    /// An heir's claim strength; 0 for a ruler or a consort.
309    pub claim: Milli,
310    /// The birth date.
311    pub birth: Date,
312    /// The id of the leader they also are ([`Unit::leader`]); `None` for none.
313    pub leader: Option<u64>,
314}
315
316/// The id of a flag, from its name ([`World::flag_id`]).
317#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
318pub struct FlagId(pub i32);
319
320/// A flag that is set, and when it was set.
321#[derive(Clone, Copy, Debug, PartialEq, Eq)]
322pub struct Flag {
323    /// Its id; [`World::flag_name`] gives the name.
324    pub id: FlagId,
325    /// When it was set.
326    pub date: Date,
327}
328
329/// An event waiting for a country's choice (anvil-game 1.21.0).
330#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331pub struct PendingEvent {
332    /// The id [`commands`](crate::commands)' event option takes; unique while it waits.
333    pub pending_id: i32,
334    /// The country it waits for, by the game's rule; `None` for none.
335    pub country: Option<Tag>,
336    /// The scope's province; `None` for a country event.
337    pub province: Option<i32>,
338    /// The event's options in its file; the window may disable some.
339    pub options: u32,
340    /// Hidden: the game shows no window for it.
341    pub hidden: bool,
342    /// The game chooses for the player the day after this date.
343    pub auto_select: Date,
344}
345
346/// One of the four series of the game's graphs (anvil-game 1.21.0).
347#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
348pub enum StatisticKind {
349    /// The income graph, whole ducats (the game's value ÷ 1000, truncated).
350    Income,
351    /// The score, whole points (÷ 1000, truncated).
352    Score,
353    /// The provinces the country owns, a count.
354    NationSize,
355    /// Inflation, whole percent (÷ 1000, truncated).
356    Inflation,
357}
358
359impl StatisticKind {
360    fn raw(self) -> u32 {
361        match self {
362            Self::Income => ANVIL_GAME_STATISTIC_INCOME,
363            Self::Score => ANVIL_GAME_STATISTIC_SCORE,
364            Self::NationSize => ANVIL_GAME_STATISTIC_NATION_SIZE,
365            Self::Inflation => ANVIL_GAME_STATISTIC_INFLATION,
366        }
367    }
368}
369
370/// One year of a series. The value is whole units, not × 1000.
371#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
372pub struct StatisticPoint {
373    /// The year whose 1 January wrote it: 1720 holds the value at the end of 1719.
374    pub year: i32,
375    /// The value then (0 for a year before the country had one).
376    pub value: i32,
377}
378
379/// A named modifier a country or a province has for a time, as an effect such
380/// as `add_country_modifier` gave it ([`World::country_timed_modifiers`]).
381#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct TimedModifier {
383    /// Its key, as the game's files write it.
384    pub key: String,
385    /// `hidden = yes`: the game's windows do not list it.
386    pub hidden: bool,
387    /// A ruler modifier: it goes with the ruler.
388    pub ruler: bool,
389    /// When it was given; `None` when the game keeps no start date.
390    pub start: Option<Date>,
391    /// When it ends; `None` when it lasts until an effect removes it.
392    pub end: Option<Date>,
393}
394
395/// A kind of relation between two countries (anvil-game 1.22.0). A relation
396/// is one object in both countries' lists: who did what comes from
397/// [`Relation::first`] and [`Relation::second`], never from whose list it is.
398#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
399pub enum RelationKind {
400    /// An alliance.
401    Alliance,
402    /// A royal marriage.
403    RoyalMarriage,
404    /// `first` guarantees `second`.
405    Guarantee,
406    /// The country asked is `first`: it has access to `second`'s land.
407    MilitaryAccess,
408    /// The country asked is `second`: it gives `first` access.
409    GivingMilitaryAccess,
410    /// `first` pays `second`.
411    Subsidies,
412    /// `first` is the overlord, `second` the subject ([`World::subject_type`]).
413    Dependency,
414    /// `first` warns `second`.
415    Warning,
416}
417
418impl RelationKind {
419    fn raw(self) -> u32 {
420        match self {
421            Self::Alliance => ANVIL_GAME_RELATION_ALLIANCE,
422            Self::RoyalMarriage => ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
423            Self::Guarantee => ANVIL_GAME_RELATION_GUARANTEE,
424            Self::MilitaryAccess => ANVIL_GAME_RELATION_MILITARY_ACCESS,
425            Self::GivingMilitaryAccess => ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS,
426            Self::Subsidies => ANVIL_GAME_RELATION_SUBSIDIES,
427            Self::Dependency => ANVIL_GAME_RELATION_DEPENDENCY,
428            Self::Warning => ANVIL_GAME_RELATION_WARNING,
429        }
430    }
431}
432
433/// A relation, as the game's save writes it ([`World::country_relations`]).
434#[derive(Clone, Copy, Debug, PartialEq, Eq)]
435pub struct Relation {
436    /// The guarantor, the one with access, the payer, the overlord, the one who warns.
437    pub first: Option<Tag>,
438    /// The other one.
439    pub second: Option<Tag>,
440    /// When it began; `None` when the game keeps no date.
441    pub start: Option<Date>,
442    /// When it ends; `None` for most, which have no end date.
443    pub end: Option<Date>,
444}
445
446/// The player's tags ([`World::player_tags`]).
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
448pub struct PlayerTags {
449    /// The country the game treats as the player's: what [`World::player`] answers.
450    pub tag: Option<Tag>,
451    /// The player's own tag as the game stores it: the observer's
452    /// pseudo-country in observe mode.
453    pub own: Option<Tag>,
454    /// The observed country as the game stores it.
455    pub observed: Option<Tag>,
456    /// `own` is the observer's pseudo-country: observe mode.
457    pub observer: bool,
458}
459
460/// What one country keeps about another ([`World::diplomacy_status`]).
461#[derive(Clone, Copy, Debug, PartialEq, Eq)]
462pub struct DiplomacyStatus {
463    /// Its opinion of the other, whole points: the number of the diplomacy
464    /// window as the game's cache holds it, refreshed at least monthly for a
465    /// human and yearly for an AI.
466    pub opinion: i32,
467    /// The sum of its timed opinion modifiers toward the other, whole points,
468    /// not clamped: not the opinion.
469    pub timed_sum: i32,
470    /// Trust, 0..100; 50 until something changes it.
471    pub trust: u32,
472    /// Favors, × 1000.
473    pub favors: Milli,
474    /// The two have a truce (its end date is the game's to work out).
475    pub truce: bool,
476}
477
478/// The `anvil-game.world` service.
479#[derive(Clone, Copy)]
480pub struct World {
481    table: Table<AnvilGameWorldService>,
482}
483
484impl fmt::Debug for World {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        f.debug_struct("World")
487            .field("size", &self.table.size())
488            .finish()
489    }
490}
491
492fn sized<T>() -> T {
493    // SAFETY: the world's structs are plain data for which zero is valid.
494    let mut value: T = unsafe { std::mem::zeroed() };
495    let size = size_of::<T>() as u32;
496    // SAFETY: each of them starts with `uint32_t size`.
497    unsafe { std::ptr::from_mut(&mut value).cast::<u32>().write(size) };
498    value
499}
500
501fn known(value: i32, values: u32, bit: u32) -> Option<Milli> {
502    (values & bit != 0).then_some(Milli(value))
503}
504
505const EMPTY_TAG: AnvilGameTag = AnvilGameTag { text: [0; 4] };
506
507impl World {
508    /// The service; `None` without anvil-game 1.11.0 or on a game build whose
509    /// symbols for it are declared absent.
510    pub fn get(host: &Host) -> Option<Self> {
511        // SAFETY: the table type of anvil-game.world version 1.
512        let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
513        Some(Self { table })
514    }
515
516    /// The C table, for what this crate does not wrap.
517    pub fn c_api(&self) -> Table<AnvilGameWorldService> {
518        self.table
519    }
520
521    /// The country the game treats as the player's (the observed one in observe mode).
522    pub fn player(&self) -> Result<Option<Tag>> {
523        let f = function!(self.table, AnvilGameWorldService, player)?;
524        let mut tag = EMPTY_TAG;
525        // SAFETY: the service's function with an out pointer.
526        check(unsafe { f(&mut tag) }, || "world player")?;
527        Ok(Tag::from_raw(&tag))
528    }
529
530    /// Valid province IDs are `1..limit`; 0 where a call is not allowed.
531    pub fn province_limit(&self) -> i32 {
532        // SAFETY: the service's function.
533        function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
534    }
535
536    /// A province.
537    pub fn province(&self, id: i32) -> Result<Province> {
538        let f = function!(self.table, AnvilGameWorldService, province)?;
539        let mut raw: AnvilGameProvince = sized();
540        // SAFETY: the service's function; `size` says how much it may write.
541        check(unsafe { f(id, &mut raw) }, || {
542            format!("world province {id}")
543        })?;
544        Ok(Province {
545            id: raw.id,
546            owner: Tag::from_raw(&raw.owner),
547            controller: Tag::from_raw(&raw.controller),
548            base_tax: Milli(raw.base_tax),
549            base_production: Milli(raw.base_production),
550            base_manpower: Milli(raw.base_manpower),
551            land: raw.flags & ANVIL_GAME_PROVINCE_LAND != 0,
552            wasteland: raw.flags & ANVIL_GAME_PROVINCE_WASTELAND != 0,
553        })
554    }
555
556    /// The name the game displays (it follows the owner's culture).
557    pub fn province_name(&self, id: i32) -> Result<String> {
558        let f = function!(self.table, AnvilGameWorldService, province_name)?;
559        // SAFETY: the service fills at most `capacity` bytes.
560        read_text(
561            || format!("world province_name {id}"),
562            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
563        )
564    }
565
566    /// The tags with a core on the province.
567    pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
568        let f = function!(self.table, AnvilGameWorldService, province_cores)?;
569        // SAFETY: the service fills at most `capacity` tags.
570        let raw = read_list(
571            EMPTY_TAG,
572            || format!("world province_cores {id}"),
573            |out, capacity, count| unsafe { f(id, out, capacity, count) },
574        )?;
575        Ok(raw.iter().filter_map(Tag::from_raw).collect())
576    }
577
578    /// A country (the tag ignores case).
579    pub fn country(&self, tag: Tag) -> Result<Country> {
580        let f = function!(self.table, AnvilGameWorldService, country)?;
581        let text = tag.c_text();
582        let mut raw: AnvilGameCountry = sized();
583        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
584        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
585            format!("world country {tag}")
586        })?;
587        let v = raw.values;
588        Ok(Country {
589            tag: Tag::from_raw(&raw.tag),
590            capital: (raw.capital != 0).then_some(raw.capital),
591            province_count: raw.province_count,
592            observer: raw.flags & ANVIL_GAME_COUNTRY_OBSERVER != 0,
593            treasury: known(raw.treasury, v, ANVIL_GAME_VALUE_TREASURY),
594            stability: known(raw.stability, v, ANVIL_GAME_VALUE_STABILITY),
595            prestige: known(raw.prestige, v, ANVIL_GAME_VALUE_PRESTIGE),
596            manpower: known(raw.manpower, v, ANVIL_GAME_VALUE_MANPOWER),
597            monthly_income: known(raw.monthly_income, v, ANVIL_GAME_VALUE_MONTHLY_INCOME),
598        })
599    }
600
601    /// The IDs of the provinces a country owns, in the game's order.
602    pub fn country_provinces(&self, tag: Tag) -> Result<Vec<i32>> {
603        let f = function!(self.table, AnvilGameWorldService, country_provinces)?;
604        let text = tag.c_text();
605        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` IDs.
606        read_list(
607            0i32,
608            || format!("world country_provinces {tag}"),
609            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
610        )
611    }
612
613    /// The ids of the running wars.
614    pub fn war_ids(&self) -> Result<Vec<u64>> {
615        let f = function!(self.table, AnvilGameWorldService, war_ids)?;
616        // SAFETY: the service fills at most `capacity` ids.
617        read_list(
618            0u64,
619            || "world war_ids".to_owned(),
620            |out, capacity, count| unsafe { f(out, capacity, count) },
621        )
622    }
623
624    /// A running war.
625    pub fn war(&self, id: u64) -> Result<War> {
626        let f = function!(self.table, AnvilGameWorldService, war)?;
627        let mut raw: AnvilGameWar = sized();
628        // SAFETY: `size` says how much it may write.
629        check(unsafe { f(id, &mut raw) }, || format!("world war {id:#x}"))?;
630        Ok(War {
631            id: raw.id,
632            attacker: Tag::from_raw(&raw.attacker),
633            defender: Tag::from_raw(&raw.defender),
634        })
635    }
636
637    /// A war's name as the game shows it.
638    pub fn war_name(&self, id: u64) -> Result<String> {
639        let f = function!(self.table, AnvilGameWorldService, war_name)?;
640        // SAFETY: the service fills at most `capacity` bytes.
641        read_text(
642            || format!("world war_name {id:#x}"),
643            |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
644        )
645    }
646
647    /// The countries on one side of a war now.
648    pub fn war_side(&self, id: u64, side: Side) -> Result<Vec<Tag>> {
649        let f = function!(self.table, AnvilGameWorldService, war_side)?;
650        let side_raw = match side {
651            Side::Attackers => ANVIL_GAME_WAR_ATTACKERS,
652            Side::Defenders => ANVIL_GAME_WAR_DEFENDERS,
653        };
654        // SAFETY: the service fills at most `capacity` tags.
655        let raw = read_list(
656            EMPTY_TAG,
657            || format!("world war_side {id:#x}"),
658            |out, capacity, count| unsafe { f(id, side_raw, out, capacity, count) },
659        )?;
660        Ok(raw.iter().filter_map(Tag::from_raw).collect())
661    }
662
663    /// The id of a modifier from its script key (`land_morale`,
664    /// `local_tax_modifier`), case included. It holds as long as the game
665    /// runs: ask once, as this walks every definition.
666    pub fn modifier_id(&self, key: &str) -> Result<ModifierId> {
667        let f = function!(self.table, AnvilGameWorldService, modifier_id)?;
668        let key_c = crate::text::c_string(key);
669        let mut id = 0i32;
670        // SAFETY: a NUL-terminated key and an out pointer.
671        check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
672            format!("world modifier_id {key}")
673        })?;
674        Ok(ModifierId(id))
675    }
676
677    /// A country's modifier as the game uses it (a yes-or-no one is 1000 or 0).
678    pub fn country_modifier(&self, tag: Tag, id: ModifierId) -> Result<Milli> {
679        let f = function!(self.table, AnvilGameWorldService, country_modifier)?;
680        let text = tag.c_text();
681        let mut value = 0i32;
682        // SAFETY: a NUL-terminated tag and an out pointer.
683        check(unsafe { f(text.as_ptr(), id.0, &mut value) }, || {
684            format!("world country_modifier {tag} {}", id.0)
685        })?;
686        Ok(Milli(value))
687    }
688
689    /// A province's own modifier (not its owner's values).
690    pub fn province_modifier(&self, province: i32, id: ModifierId) -> Result<Milli> {
691        let f = function!(self.table, AnvilGameWorldService, province_modifier)?;
692        let mut value = 0i32;
693        // SAFETY: an out pointer.
694        check(unsafe { f(province, id.0, &mut value) }, || {
695            format!("world province_modifier {province} {}", id.0)
696        })?;
697        Ok(Milli(value))
698    }
699
700    /// The ids of a country's armies and navies, in the game's order.
701    pub fn country_units(&self, tag: Tag) -> Result<Vec<u64>> {
702        let f = function!(self.table, AnvilGameWorldService, country_units)?;
703        let text = tag.c_text();
704        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` ids.
705        read_list(
706            0u64,
707            || format!("world country_units {tag}"),
708            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
709        )
710    }
711
712    /// A unit by its country and id.
713    pub fn unit(&self, tag: Tag, id: u64) -> Result<Unit> {
714        let f = function!(self.table, AnvilGameWorldService, unit)?;
715        let text = tag.c_text();
716        let mut raw: AnvilGameUnit = sized();
717        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
718        check(unsafe { f(text.as_ptr(), id, &mut raw) }, || {
719            format!("world unit {tag} {id:#x}")
720        })?;
721        Ok(Unit {
722            kind: UnitKind::from_raw(raw.kind),
723            id: raw.id,
724            country: Tag::from_raw(&raw.country),
725            location: (raw.location != 0).then_some(raw.location),
726            mission: Mission(raw.mission),
727            subunits: raw.subunits,
728            strength: Milli(raw.strength),
729            leader: (raw.leader != 0).then_some(raw.leader),
730        })
731    }
732
733    /// The name the game shows for a unit ("1st Army").
734    pub fn unit_name(&self, tag: Tag, id: u64) -> Result<String> {
735        let f = function!(self.table, AnvilGameWorldService, unit_name)?;
736        let text = tag.c_text();
737        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
738        read_text(
739            || format!("world unit_name {tag} {id:#x}"),
740            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
741        )
742    }
743
744    /// A unit's leader's name; `NotFound` also for a unit without one.
745    pub fn unit_leader_name(&self, tag: Tag, id: u64) -> Result<String> {
746        let f = function!(self.table, AnvilGameWorldService, unit_leader_name)?;
747        let text = tag.c_text();
748        // SAFETY: as in unit_name.
749        read_text(
750            || format!("world unit_leader_name {tag} {id:#x}"),
751            |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
752        )
753    }
754
755    /// The armies and navies the player has selected, in the game's order.
756    pub fn selected_units(&self) -> Result<Vec<UnitRef>> {
757        let f = function!(self.table, AnvilGameWorldService, selected_units)?;
758        let empty = AnvilGameUnitRef {
759            id: 0,
760            country: EMPTY_TAG,
761            kind: 0,
762        };
763        // SAFETY: the service fills at most `capacity` entries.
764        let raw = read_list(
765            empty,
766            || "world selected_units".to_owned(),
767            |out, capacity, count| unsafe { f(out, capacity, count) },
768        )?;
769        Ok(raw
770            .iter()
771            .map(|r| UnitRef {
772                id: r.id,
773                country: Tag::from_raw(&r.country),
774                kind: UnitKind::from_raw(r.kind),
775            })
776            .collect())
777    }
778
779    /// A country's ruler, heir or consort. `NotFound` when it has none: the
780    /// game then holds a placeholder that every such country shares, and the
781    /// service never reads it. A country no longer on the map keeps its last
782    /// ruler: check [`Country::province_count`] when that matters.
783    pub fn monarch(&self, tag: Tag, kind: MonarchKind) -> Result<Monarch> {
784        let f = function!(self.table, AnvilGameWorldService, monarch)?;
785        let text = tag.c_text();
786        let mut raw: AnvilGameMonarch = sized();
787        // SAFETY: a NUL-terminated tag; `size` says how much it may write.
788        check(unsafe { f(text.as_ptr(), kind.raw(), &mut raw) }, || {
789            format!("world monarch {tag} {kind:?}")
790        })?;
791        Ok(Monarch {
792            kind: MonarchKind::from_raw(raw.kind),
793            id: raw.id,
794            country: Tag::from_raw(&raw.country),
795            female: raw.flags & ANVIL_GAME_MONARCH_FEMALE != 0,
796            regency: raw.flags & ANVIL_GAME_MONARCH_REGENCY != 0,
797            adm: raw.adm,
798            dip: raw.dip,
799            mil: raw.mil,
800            claim: Milli(raw.claim),
801            birth: Date::from_raw(&raw.birth),
802            leader: (raw.leader != 0).then_some(raw.leader),
803        })
804    }
805
806    /// Their name as the game keeps it; empty in an interregnum.
807    pub fn monarch_name(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
808        let f = function!(self.table, AnvilGameWorldService, monarch_name)?;
809        let text = tag.c_text();
810        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
811        read_text(
812            || format!("world monarch_name {tag} {kind:?}"),
813            |buffer, capacity, length| unsafe {
814                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
815            },
816        )
817    }
818
819    /// Their dynasty as the game shows it (a regency council shows the heir's).
820    pub fn monarch_dynasty(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
821        let f = function!(self.table, AnvilGameWorldService, monarch_dynasty)?;
822        let text = tag.c_text();
823        // SAFETY: as in monarch_name.
824        read_text(
825            || format!("world monarch_dynasty {tag} {kind:?}"),
826            |buffer, capacity, length| unsafe {
827                f(text.as_ptr(), kind.raw(), buffer, capacity, length)
828            },
829        )
830    }
831
832    /// The id of a flag from its name, case included. It holds as long as the
833    /// game runs: ask once. `NotFound` for a name nothing has set yet in this
834    /// run of the game.
835    pub fn flag_id(&self, name: &str) -> Result<FlagId> {
836        let f = function!(self.table, AnvilGameWorldService, flag_id)?;
837        let name_c = crate::text::c_string(name);
838        let mut id = 0i32;
839        // SAFETY: a NUL-terminated name and an out pointer.
840        check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
841            format!("world flag_id {name}")
842        })?;
843        Ok(FlagId(id))
844    }
845
846    /// A flag's name.
847    pub fn flag_name(&self, id: FlagId) -> Result<String> {
848        let f = function!(self.table, AnvilGameWorldService, flag_name)?;
849        // SAFETY: the service fills at most `capacity` bytes.
850        read_text(
851            || format!("world flag_name {}", id.0),
852            |buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
853        )
854    }
855
856    /// A country's flags, with the date each was set.
857    pub fn country_flags(&self, tag: Tag) -> Result<Vec<Flag>> {
858        let f = function!(self.table, AnvilGameWorldService, country_flags)?;
859        let text = tag.c_text();
860        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
861        flags(
862            || format!("world country_flags {tag}"),
863            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
864        )
865    }
866
867    /// A province's flags as `has_province_flag` sees them, its permanent ones included.
868    pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
869        let f = function!(self.table, AnvilGameWorldService, province_flags)?;
870        // SAFETY: the service fills at most `capacity` flags.
871        flags(
872            || format!("world province_flags {province}"),
873            |out, capacity, count| unsafe { f(province, out, capacity, count) },
874        )
875    }
876
877    /// A ruler's, heir's or consort's flags; `NotFound` as for [`World::monarch`].
878    pub fn monarch_flags(&self, tag: Tag, kind: MonarchKind) -> Result<Vec<Flag>> {
879        let f = function!(self.table, AnvilGameWorldService, monarch_flags)?;
880        let text = tag.c_text();
881        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` flags.
882        flags(
883            || format!("world monarch_flags {tag} {kind:?}"),
884            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
885        )
886    }
887
888    /// The global flags.
889    pub fn global_flags(&self) -> Result<Vec<Flag>> {
890        let f = function!(self.table, AnvilGameWorldService, global_flags)?;
891        // SAFETY: the service fills at most `capacity` flags.
892        flags(
893            || "world global_flags".to_owned(),
894            |out, capacity, count| unsafe { f(out, capacity, count) },
895        )
896    }
897
898    /// A country's variable by its name, case included. `NotFound` when it
899    /// has none of that name (the game's triggers take that as 0).
900    pub fn country_variable(&self, tag: Tag, name: &str) -> Result<Milli> {
901        let f = function!(self.table, AnvilGameWorldService, country_variable)?;
902        let text = tag.c_text();
903        let name_c = crate::text::c_string(name);
904        let mut value = 0i32;
905        // SAFETY: a NUL-terminated tag and name, and an out pointer.
906        let result = unsafe { f(text.as_ptr(), name_c.as_ptr(), &mut value) };
907        check(result, || format!("world country_variable {tag} {name}"))?;
908        Ok(Milli(value))
909    }
910
911    /// A province's variable by its name.
912    pub fn province_variable(&self, province: i32, name: &str) -> Result<Milli> {
913        let f = function!(self.table, AnvilGameWorldService, province_variable)?;
914        let name_c = crate::text::c_string(name);
915        let mut value = 0i32;
916        // SAFETY: a NUL-terminated name and an out pointer.
917        check(unsafe { f(province, name_c.as_ptr(), &mut value) }, || {
918            format!("world province_variable {province} {name}")
919        })?;
920        Ok(Milli(value))
921    }
922
923    /// The names of a country's variables, in the game's order.
924    pub fn country_variable_names(&self, tag: Tag) -> Result<Vec<String>> {
925        let f = function!(self.table, AnvilGameWorldService, country_variable_names)?;
926        let text = tag.c_text();
927        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` bytes.
928        let all = read_text(
929            || format!("world country_variable_names {tag}"),
930            |buffer, capacity, length| unsafe { f(text.as_ptr(), buffer, capacity, length) },
931        )?;
932        Ok(split_names(&all))
933    }
934
935    /// The names of a province's variables, in the game's order.
936    pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
937        let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
938        // SAFETY: the service fills at most `capacity` bytes.
939        let all = read_text(
940            || format!("world province_variable_names {province}"),
941            |buffer, capacity, length| unsafe { f(province, buffer, capacity, length) },
942        )?;
943        Ok(split_names(&all))
944    }
945
946    /// The ids of the events waiting for a country's choice, in the game's
947    /// order; `None` for the player's own country (`NotFound` in observe
948    /// mode). An entry counts once it was in the game's list at two outer
949    /// frames in a row, which leaves out an AI's choices and hidden events.
950    /// Key on the id: the same event can wait twice.
951    pub fn pending_events(&self, tag: Option<Tag>) -> Result<Vec<i32>> {
952        let f = function!(self.table, AnvilGameWorldService, pending_events)?;
953        let text = tag.map(|t| t.c_text());
954        let tag_ptr = text.as_ref().map_or(std::ptr::null(), |t| t.as_ptr());
955        // SAFETY: a NUL-terminated tag or null; the service fills at most `capacity` ids.
956        read_list(
957            0i32,
958            || format!("world pending_events {tag:?}"),
959            |out, capacity, count| unsafe { f(tag_ptr, out, capacity, count) },
960        )
961    }
962
963    /// A waiting event; `NotFound` for an id that is not waiting (or not yet counted).
964    pub fn pending_event(&self, pending_id: i32) -> Result<PendingEvent> {
965        let f = function!(self.table, AnvilGameWorldService, pending_event)?;
966        let mut raw: AnvilGamePendingEvent = sized();
967        // SAFETY: `size` says how much it may write.
968        check(unsafe { f(pending_id, &mut raw) }, || {
969            format!("world pending_event {pending_id}")
970        })?;
971        Ok(PendingEvent {
972            pending_id: raw.pending_id,
973            country: Tag::from_raw(&raw.country),
974            province: (raw.province != 0).then_some(raw.province),
975            options: raw.options,
976            hidden: raw.flags & ANVIL_GAME_PENDING_HIDDEN != 0,
977            auto_select: Date::from_raw(&raw.auto_select),
978        })
979    }
980
981    /// The waiting event's key as the game's files name it (`flavor_tur.203`).
982    pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
983        let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
984        // SAFETY: the service fills at most `capacity` bytes.
985        read_text(
986            || format!("world pending_event_key {pending_id}"),
987            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
988        )
989    }
990
991    /// The localisation key of its title, not the translated text.
992    pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
993        let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
994        // SAFETY: the service fills at most `capacity` bytes.
995        read_text(
996            || format!("world pending_event_title {pending_id}"),
997            |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
998        )
999    }
1000
1001    /// A country's yearly series of the game's graphs, oldest first. It
1002    /// changes only at [`game::YEAR`](crate::game::YEAR). `NotFound` for a tag
1003    /// without a series (none has one before its first year end).
1004    pub fn country_statistics(&self, tag: Tag, kind: StatisticKind) -> Result<Vec<StatisticPoint>> {
1005        let f = function!(self.table, AnvilGameWorldService, country_statistics)?;
1006        let text = tag.c_text();
1007        let empty = AnvilGameStatisticPoint { year: 0, value: 0 };
1008        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` points.
1009        let raw = read_list(
1010            empty,
1011            || format!("world country_statistics {tag} {kind:?}"),
1012            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1013        )?;
1014        Ok(raw
1015            .iter()
1016            .map(|p| StatisticPoint {
1017                year: p.year,
1018                value: p.value,
1019            })
1020            .collect())
1021    }
1022
1023    /// A country's timed modifiers, in the game's order, each with its key.
1024    /// Call it on the main thread, as every read: the list and the keys come
1025    /// from two calls of the service in the same frame.
1026    pub fn country_timed_modifiers(&self, tag: Tag) -> Result<Vec<TimedModifier>> {
1027        let list = function!(self.table, AnvilGameWorldService, country_timed_modifiers)?;
1028        let keys = function!(
1029            self.table,
1030            AnvilGameWorldService,
1031            country_timed_modifier_keys
1032        )?;
1033        let text = tag.c_text();
1034        let context = || format!("world country_timed_modifiers {tag}");
1035        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` entries or bytes.
1036        let raw = timed_list(context, |out, capacity, count| unsafe {
1037            list(text.as_ptr(), out, capacity, count)
1038        })?;
1039        // SAFETY: as above.
1040        let all = read_text(context, |buffer, capacity, length| unsafe {
1041            keys(text.as_ptr(), buffer, capacity, length)
1042        })?;
1043        timed_modifiers(&raw, &all, context)
1044    }
1045
1046    /// A province's timed modifiers, in the game's order, each with its key.
1047    pub fn province_timed_modifiers(&self, province: i32) -> Result<Vec<TimedModifier>> {
1048        let list = function!(self.table, AnvilGameWorldService, province_timed_modifiers)?;
1049        let keys = function!(
1050            self.table,
1051            AnvilGameWorldService,
1052            province_timed_modifier_keys
1053        )?;
1054        let context = || format!("world province_timed_modifiers {province}");
1055        // SAFETY: the service fills at most `capacity` entries or bytes.
1056        let raw = timed_list(context, |out, capacity, count| unsafe {
1057            list(province, out, capacity, count)
1058        })?;
1059        // SAFETY: as above.
1060        let all = read_text(context, |buffer, capacity, length| unsafe {
1061            keys(province, buffer, capacity, length)
1062        })?;
1063        timed_modifiers(&raw, &all, context)
1064    }
1065
1066    /// The province the game's province view shows while that window is
1067    /// open; `NotFound` while none is open.
1068    pub fn province_view(&self) -> Result<i32> {
1069        let f = function!(self.table, AnvilGameWorldService, province_view)?;
1070        let mut province = 0i32;
1071        // SAFETY: an out pointer.
1072        check(unsafe { f(&mut province) }, || {
1073            "world province_view".to_owned()
1074        })?;
1075        Ok(province)
1076    }
1077
1078    /// The province last selected on the map; 0 while none has been selected
1079    /// in this session (anvil-game 1.24.0).
1080    pub fn selected_province(&self) -> Result<i32> {
1081        let f = function!(self.table, AnvilGameWorldService, selected_province)?;
1082        let mut province = 0i32;
1083        // SAFETY: an out pointer.
1084        check(unsafe { f(&mut province) }, || {
1085            "world selected_province".to_owned()
1086        })?;
1087        Ok(province)
1088    }
1089
1090    /// The province under the point (`x`, `y`) of the game window's client
1091    /// area, in pixels, as the game's hover finds it; 0 off the map
1092    /// (anvil-game 1.24.0).
1093    pub fn province_at(&self, x: i32, y: i32) -> Result<i32> {
1094        let f = function!(self.table, AnvilGameWorldService, province_at)?;
1095        let mut province = 0i32;
1096        // SAFETY: an out pointer.
1097        check(unsafe { f(x, y, &mut province) }, || {
1098            format!("world province_at {x},{y}")
1099        })?;
1100        Ok(province)
1101    }
1102
1103    /// The army or navy the map picks at the same point, as the game's
1104    /// cursor does; `NotFound` when it picks no unit there (anvil-game 1.24.0).
1105    pub fn unit_at(&self, x: i32, y: i32) -> Result<UnitRef> {
1106        let f = function!(self.table, AnvilGameWorldService, unit_at)?;
1107        let mut raw = AnvilGameUnitRef {
1108            id: 0,
1109            country: EMPTY_TAG,
1110            kind: 0,
1111        };
1112        // SAFETY: an out pointer.
1113        check(unsafe { f(x, y, &mut raw) }, || {
1114            format!("world unit_at {x},{y}")
1115        })?;
1116        Ok(UnitRef {
1117            id: raw.id,
1118            country: Tag::from_raw(&raw.country),
1119            kind: UnitKind::from_raw(raw.kind),
1120        })
1121    }
1122
1123    /// The keys of the province triggered modifiers a province has been given
1124    /// (`add_province_triggered_modifier`), in the game's order, whether or
1125    /// not their triggers hold now. With
1126    /// [`province_timed_modifiers`](Self::province_timed_modifiers) they are
1127    /// every key `has_province_modifier` looks for (anvil-game 1.25.0).
1128    pub fn province_triggered_modifiers(&self, province: i32) -> Result<Vec<String>> {
1129        let keys = function!(
1130            self.table,
1131            AnvilGameWorldService,
1132            province_triggered_modifier_keys
1133        )?;
1134        let context = || format!("world province_triggered_modifiers {province}");
1135        // SAFETY: the service fills at most `capacity` bytes.
1136        let all = read_text(context, |buffer, capacity, length| unsafe {
1137            keys(province, buffer, capacity, length)
1138        })?;
1139        Ok(split_names(&all))
1140    }
1141
1142    /// A country's relations of one kind, in the game's order (anvil-game 1.22.0).
1143    pub fn country_relations(&self, tag: Tag, kind: RelationKind) -> Result<Vec<Relation>> {
1144        let f = function!(self.table, AnvilGameWorldService, country_relations)?;
1145        let text = tag.c_text();
1146        // SAFETY: plain data for which zero is valid.
1147        let empty: AnvilGameRelation = unsafe { std::mem::zeroed() };
1148        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` relations.
1149        let raw = read_list(
1150            empty,
1151            || format!("world country_relations {tag} {kind:?}"),
1152            |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1153        )?;
1154        Ok(raw
1155            .iter()
1156            .map(|r| Relation {
1157                first: Tag::from_raw(&r.first),
1158                second: Tag::from_raw(&r.second),
1159                start: (r.start.size != 0).then(|| Date::from_raw(&r.start)),
1160                end: (r.end.size != 0).then(|| Date::from_raw(&r.end)),
1161            })
1162            .collect())
1163    }
1164
1165    /// The key of `subject`'s subject type under `overlord` (`vassal`,
1166    /// `march`); `NotFound` when it is not `overlord`'s subject.
1167    pub fn subject_type(&self, overlord: Tag, subject: Tag) -> Result<String> {
1168        let f = function!(self.table, AnvilGameWorldService, subject_type)?;
1169        let (a, b) = (overlord.c_text(), subject.c_text());
1170        // SAFETY: NUL-terminated tags; the service fills at most `capacity` bytes.
1171        read_text(
1172            || format!("world subject_type {overlord} {subject}"),
1173            |buffer, capacity, length| unsafe {
1174                f(a.as_ptr(), b.as_ptr(), buffer, capacity, length)
1175            },
1176        )
1177    }
1178
1179    /// What `from` keeps about `to`, with its opinion from the game's cache.
1180    /// `NotFound` for a country that owns no province now and while the cache
1181    /// has no entry for `to` yet; `InvalidArgument` for the same country twice.
1182    pub fn diplomacy_status(&self, from: Tag, to: Tag) -> Result<DiplomacyStatus> {
1183        let f = function!(self.table, AnvilGameWorldService, diplomacy_status)?;
1184        let (a, b) = (from.c_text(), to.c_text());
1185        let mut raw: AnvilGameDiplomacyStatus = sized();
1186        // SAFETY: NUL-terminated tags; `size` says how much it may write.
1187        check(unsafe { f(a.as_ptr(), b.as_ptr(), &mut raw) }, || {
1188            format!("world diplomacy_status {from} {to}")
1189        })?;
1190        Ok(DiplomacyStatus {
1191            opinion: raw.opinion,
1192            timed_sum: raw.timed_sum,
1193            trust: raw.trust,
1194            favors: Milli(raw.favors),
1195            truce: raw.flags & ANVIL_GAME_DIPLOMACY_TRUCE != 0,
1196        })
1197    }
1198
1199    /// The countries `tag` has chosen as rivals, in the game's order.
1200    pub fn country_rivals(&self, tag: Tag) -> Result<Vec<Tag>> {
1201        let f = function!(self.table, AnvilGameWorldService, country_rivals)?;
1202        let text = tag.c_text();
1203        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
1204        let raw = read_list(
1205            EMPTY_TAG,
1206            || format!("world country_rivals {tag}"),
1207            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1208        )?;
1209        Ok(raw.iter().filter_map(Tag::from_raw).collect())
1210    }
1211
1212    /// Its overlord; `NotFound` also for a country without one.
1213    pub fn country_overlord(&self, tag: Tag) -> Result<Tag> {
1214        let f = function!(self.table, AnvilGameWorldService, country_overlord)?;
1215        let text = tag.c_text();
1216        let mut raw = EMPTY_TAG;
1217        // SAFETY: a NUL-terminated tag and an out pointer.
1218        check(unsafe { f(text.as_ptr(), &mut raw) }, || {
1219            format!("world country_overlord {tag}")
1220        })?;
1221        Tag::from_raw(&raw)
1222            .ok_or_else(|| Error::new(ErrorCode::Internal, format!("world country_overlord {tag}")))
1223    }
1224
1225    /// Its direct subjects, in the game's order.
1226    pub fn country_subjects(&self, tag: Tag) -> Result<Vec<Tag>> {
1227        let f = function!(self.table, AnvilGameWorldService, country_subjects)?;
1228        let text = tag.c_text();
1229        // SAFETY: a NUL-terminated tag; the service fills at most `capacity` tags.
1230        let raw = read_list(
1231            EMPTY_TAG,
1232            || format!("world country_subjects {tag}"),
1233            |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1234        )?;
1235        Ok(raw.iter().filter_map(Tag::from_raw).collect())
1236    }
1237
1238    /// What [`World::player`] answers and the two tags it is chosen from, read
1239    /// at once (anvil-game 1.23.0). In a normal game `tag` and `own` are the
1240    /// player's country and `observed` is as the game stores it: usually `None`,
1241    /// but it can hold a tag left over; in observe mode `own` is the
1242    /// observer's pseudo-country and `tag` the observed country while there is
1243    /// one.
1244    pub fn player_tags(&self) -> Result<PlayerTags> {
1245        let f = function!(self.table, AnvilGameWorldService, player_tags)?;
1246        let mut raw: AnvilGamePlayer = sized();
1247        // SAFETY: `size` says how much it may write.
1248        check(unsafe { f(&mut raw) }, || "world player_tags")?;
1249        Ok(PlayerTags {
1250            tag: Tag::from_raw(&raw.tag),
1251            own: Tag::from_raw(&raw.own),
1252            observed: Tag::from_raw(&raw.observed),
1253            observer: raw.flags & ANVIL_GAME_PLAYER_OBSERVER != 0,
1254        })
1255    }
1256
1257    /// The regions the fleet may explore, as the game's naval exploration
1258    /// dialog lists them: each region once, in the game's order. It calls the
1259    /// dialog's own function and changes nothing; `InvalidArgument` for an
1260    /// army (anvil-game 1.25.0).
1261    pub fn exploration_regions(&self, fleet: &UnitRef, list: ExplorationList) -> Result<Vec<i32>> {
1262        let f = function!(self.table, AnvilGameWorldService, exploration_regions)?;
1263        let raw = fleet.to_raw();
1264        // SAFETY: a unit reference; the service fills at most `capacity` indexes.
1265        read_list(
1266            0i32,
1267            || format!("world exploration_regions {} {list:?}", fleet.id),
1268            |out, capacity, count| unsafe { f(&raw, list.raw(), out, capacity, count) },
1269        )
1270    }
1271
1272    /// The region's name as the game shows it, in the game's language
1273    /// (anvil-game 1.25.0).
1274    pub fn region_name(&self, region: i32) -> Result<String> {
1275        let f = function!(self.table, AnvilGameWorldService, region_name)?;
1276        // SAFETY: the service fills at most `capacity` bytes.
1277        read_text(
1278            || format!("world region_name {region}"),
1279            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1280        )
1281    }
1282
1283    /// The region's script key, such as `baltic_sea_region` (anvil-game 1.25.0).
1284    pub fn region_key(&self, region: i32) -> Result<String> {
1285        let f = function!(self.table, AnvilGameWorldService, region_key)?;
1286        // SAFETY: the service fills at most `capacity` bytes.
1287        read_text(
1288            || format!("world region_key {region}"),
1289            |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1290        )
1291    }
1292}
1293
1294fn timed_list(
1295    context: impl Fn() -> String,
1296    call: impl FnMut(*mut AnvilGameTimedModifier, u32, *mut u32) -> crate::sys::AnvilResult,
1297) -> Result<Vec<AnvilGameTimedModifier>> {
1298    // SAFETY: plain data for which zero is valid.
1299    let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
1300    read_list(empty, context, call)
1301}
1302
1303// The entries with their keys; a count that differs means the list changed
1304// between the two calls, which happens only off the main thread.
1305fn timed_modifiers(
1306    raw: &[AnvilGameTimedModifier],
1307    keys: &str,
1308    context: impl Fn() -> String,
1309) -> Result<Vec<TimedModifier>> {
1310    let keys = split_names(keys);
1311    if keys.len() != raw.len() {
1312        return Err(Error::new(ErrorCode::Internal, context()));
1313    }
1314    Ok(raw
1315        .iter()
1316        .zip(keys)
1317        .map(|(m, key)| TimedModifier {
1318            key,
1319            hidden: m.flags & ANVIL_GAME_TIMED_HIDDEN != 0,
1320            ruler: m.flags & ANVIL_GAME_TIMED_RULER != 0,
1321            start: (m.flags & ANVIL_GAME_TIMED_NO_START == 0).then(|| Date::from_raw(&m.start)),
1322            end: (m.flags & ANVIL_GAME_TIMED_NO_END == 0).then(|| Date::from_raw(&m.end)),
1323        })
1324        .collect())
1325}
1326
1327/// Names that each end with a NUL, one after the other.
1328fn split_names(all: &str) -> Vec<String> {
1329    all.split_terminator('\0').map(str::to_owned).collect()
1330}
1331
1332fn flags(
1333    context: impl Fn() -> String,
1334    call: impl FnMut(*mut AnvilGameFlag, u32, *mut u32) -> crate::sys::AnvilResult,
1335) -> Result<Vec<Flag>> {
1336    let empty = AnvilGameFlag {
1337        id: 0,
1338        reserved: 0,
1339        date: AnvilGameDate {
1340            size: 0,
1341            year: 0,
1342            month: 0,
1343            day: 0,
1344            session: 0,
1345        },
1346    };
1347    let raw = read_list(empty, context, call)?;
1348    Ok(raw
1349        .iter()
1350        .map(|f| Flag {
1351            id: FlagId(f.id),
1352            date: Date::from_raw(&f.date),
1353        })
1354        .collect())
1355}