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, AnvilGameFlag, AnvilGameMonarch, AnvilGamePendingEvent,
AnvilGameProvince, AnvilGameStatisticPoint, AnvilGameTag, AnvilGameTimedModifier,
AnvilGameUnit, AnvilGameUnitRef, AnvilGameWar, AnvilGameWorldService,
ANVIL_GAME_COUNTRY_OBSERVER, 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_PROVINCE_LAND, ANVIL_GAME_PROVINCE_WASTELAND,
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::text::{read_list, read_text, Tag};
pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Milli(pub i32);
impl Milli {
pub fn get(self) -> f64 {
f64::from(self.0) / 1000.0
}
}
impl fmt::Display for Milli {
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'))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Province {
pub id: i32,
pub owner: Option<Tag>,
pub controller: Option<Tag>,
pub base_tax: Milli,
pub base_production: Milli,
pub base_manpower: Milli,
pub land: bool,
pub wasteland: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Country {
pub tag: Option<Tag>,
pub capital: Option<i32>,
pub province_count: i32,
pub observer: bool,
pub treasury: Option<Milli>,
pub stability: Option<Milli>,
pub prestige: Option<Milli>,
pub manpower: Option<Milli>,
pub monthly_income: Option<Milli>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct War {
pub id: u64,
pub attacker: Option<Tag>,
pub defender: Option<Tag>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Side {
Attackers,
Defenders,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UnitKind {
Army,
Navy,
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),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Mission(pub i32);
impl Mission {
pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Unit {
pub kind: UnitKind,
pub id: u64,
pub country: Option<Tag>,
pub location: Option<i32>,
pub mission: Mission,
pub subunits: u32,
pub strength: Milli,
pub leader: Option<u64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnitRef {
pub id: u64,
pub country: Option<Tag>,
pub kind: UnitKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ModifierId(pub i32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MonarchKind {
Ruler,
Heir,
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,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Monarch {
pub kind: MonarchKind,
pub id: u64,
pub country: Option<Tag>,
pub female: bool,
pub regency: bool,
pub adm: i32,
pub dip: i32,
pub mil: i32,
pub claim: Milli,
pub birth: Date,
pub leader: Option<u64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FlagId(pub i32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Flag {
pub id: FlagId,
pub date: Date,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PendingEvent {
pub pending_id: i32,
pub country: Option<Tag>,
pub province: Option<i32>,
pub options: u32,
pub hidden: bool,
pub auto_select: Date,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StatisticKind {
Income,
Score,
NationSize,
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,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StatisticPoint {
pub year: i32,
pub value: i32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TimedModifier {
pub key: String,
pub hidden: bool,
pub ruler: bool,
pub start: Option<Date>,
pub end: Option<Date>,
}
#[derive(Clone, Copy)]
pub struct World {
table: &'static 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 {
let mut value: T = unsafe { std::mem::zeroed() };
let size = size_of::<T>() as u32;
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 {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilGameWorldService {
self.table
}
pub fn player(&self) -> Result<Option<Tag>> {
let f = function!(self.table, AnvilGameWorldService, player)?;
let mut tag = EMPTY_TAG;
check(unsafe { f(&mut tag) }, || "world player")?;
Ok(Tag::from_raw(&tag))
}
pub fn province_limit(&self) -> i32 {
function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
}
pub fn province(&self, id: i32) -> Result<Province> {
let f = function!(self.table, AnvilGameWorldService, province)?;
let mut raw: AnvilGameProvince = sized();
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,
})
}
pub fn province_name(&self, id: i32) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, province_name)?;
read_text(
|| format!("world province_name {id}"),
|buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
)
}
pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
let f = function!(self.table, AnvilGameWorldService, province_cores)?;
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())
}
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();
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),
})
}
pub fn country_provinces(&self, tag: Tag) -> Result<Vec<i32>> {
let f = function!(self.table, AnvilGameWorldService, country_provinces)?;
let text = tag.c_text();
read_list(
0i32,
|| format!("world country_provinces {tag}"),
|out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
)
}
pub fn war_ids(&self) -> Result<Vec<u64>> {
let f = function!(self.table, AnvilGameWorldService, war_ids)?;
read_list(
0u64,
|| "world war_ids".to_owned(),
|out, capacity, count| unsafe { f(out, capacity, count) },
)
}
pub fn war(&self, id: u64) -> Result<War> {
let f = function!(self.table, AnvilGameWorldService, war)?;
let mut raw: AnvilGameWar = sized();
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),
})
}
pub fn war_name(&self, id: u64) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, war_name)?;
read_text(
|| format!("world war_name {id:#x}"),
|buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
)
}
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,
};
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())
}
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;
check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
format!("world modifier_id {key}")
})?;
Ok(ModifierId(id))
}
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;
check(unsafe { f(text.as_ptr(), id.0, &mut value) }, || {
format!("world country_modifier {tag} {}", id.0)
})?;
Ok(Milli(value))
}
pub fn province_modifier(&self, province: i32, id: ModifierId) -> Result<Milli> {
let f = function!(self.table, AnvilGameWorldService, province_modifier)?;
let mut value = 0i32;
check(unsafe { f(province, id.0, &mut value) }, || {
format!("world province_modifier {province} {}", id.0)
})?;
Ok(Milli(value))
}
pub fn country_units(&self, tag: Tag) -> Result<Vec<u64>> {
let f = function!(self.table, AnvilGameWorldService, country_units)?;
let text = tag.c_text();
read_list(
0u64,
|| format!("world country_units {tag}"),
|out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
)
}
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();
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),
})
}
pub fn unit_name(&self, tag: Tag, id: u64) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, unit_name)?;
let text = tag.c_text();
read_text(
|| format!("world unit_name {tag} {id:#x}"),
|buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
)
}
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();
read_text(
|| format!("world unit_leader_name {tag} {id:#x}"),
|buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
)
}
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,
};
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())
}
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();
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),
})
}
pub fn monarch_name(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, monarch_name)?;
let text = tag.c_text();
read_text(
|| format!("world monarch_name {tag} {kind:?}"),
|buffer, capacity, length| unsafe {
f(text.as_ptr(), kind.raw(), buffer, capacity, length)
},
)
}
pub fn monarch_dynasty(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, monarch_dynasty)?;
let text = tag.c_text();
read_text(
|| format!("world monarch_dynasty {tag} {kind:?}"),
|buffer, capacity, length| unsafe {
f(text.as_ptr(), kind.raw(), buffer, capacity, length)
},
)
}
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;
check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
format!("world flag_id {name}")
})?;
Ok(FlagId(id))
}
pub fn flag_name(&self, id: FlagId) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, flag_name)?;
read_text(
|| format!("world flag_name {}", id.0),
|buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
)
}
pub fn country_flags(&self, tag: Tag) -> Result<Vec<Flag>> {
let f = function!(self.table, AnvilGameWorldService, country_flags)?;
let text = tag.c_text();
flags(
|| format!("world country_flags {tag}"),
|out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
)
}
pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
let f = function!(self.table, AnvilGameWorldService, province_flags)?;
flags(
|| format!("world province_flags {province}"),
|out, capacity, count| unsafe { f(province, out, capacity, count) },
)
}
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();
flags(
|| format!("world monarch_flags {tag} {kind:?}"),
|out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
)
}
pub fn global_flags(&self) -> Result<Vec<Flag>> {
let f = function!(self.table, AnvilGameWorldService, global_flags)?;
flags(
|| "world global_flags".to_owned(),
|out, capacity, count| unsafe { f(out, capacity, count) },
)
}
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;
let result = unsafe { f(text.as_ptr(), name_c.as_ptr(), &mut value) };
check(result, || format!("world country_variable {tag} {name}"))?;
Ok(Milli(value))
}
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;
check(unsafe { f(province, name_c.as_ptr(), &mut value) }, || {
format!("world province_variable {province} {name}")
})?;
Ok(Milli(value))
}
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();
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))
}
pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
let all = read_text(
|| format!("world province_variable_names {province}"),
|buffer, capacity, length| unsafe { f(province, buffer, capacity, length) },
)?;
Ok(split_names(&all))
}
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());
read_list(
0i32,
|| format!("world pending_events {tag:?}"),
|out, capacity, count| unsafe { f(tag_ptr, out, capacity, count) },
)
}
pub fn pending_event(&self, pending_id: i32) -> Result<PendingEvent> {
let f = function!(self.table, AnvilGameWorldService, pending_event)?;
let mut raw: AnvilGamePendingEvent = sized();
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),
})
}
pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
read_text(
|| format!("world pending_event_key {pending_id}"),
|buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
)
}
pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
read_text(
|| format!("world pending_event_title {pending_id}"),
|buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
)
}
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 };
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())
}
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}");
let raw = timed_list(context, |out, capacity, count| unsafe {
list(text.as_ptr(), out, capacity, count)
})?;
let all = read_text(context, |buffer, capacity, length| unsafe {
keys(text.as_ptr(), buffer, capacity, length)
})?;
timed_modifiers(&raw, &all, context)
}
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}");
let raw = timed_list(context, |out, capacity, count| unsafe {
list(province, out, capacity, count)
})?;
let all = read_text(context, |buffer, capacity, length| unsafe {
keys(province, buffer, capacity, length)
})?;
timed_modifiers(&raw, &all, context)
}
pub fn province_view(&self) -> Result<i32> {
let f = function!(self.table, AnvilGameWorldService, province_view)?;
let mut province = 0i32;
check(unsafe { f(&mut province) }, || {
"world province_view".to_owned()
})?;
Ok(province)
}
}
fn timed_list(
context: impl Fn() -> String,
call: impl FnMut(*mut AnvilGameTimedModifier, u32, *mut u32) -> crate::sys::AnvilResult,
) -> Result<Vec<AnvilGameTimedModifier>> {
let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
read_list(empty, context, call)
}
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())
}
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())
}