use std::fmt;
use std::mem::size_of;
use crate::error::{check, Result};
use crate::host::Host;
use crate::sys::{
AnvilGameCountry, AnvilGameProvince, AnvilGameTag, AnvilGameUnit, AnvilGameUnitRef,
AnvilGameWar, AnvilGameWorldService, ANVIL_GAME_COUNTRY_OBSERVER, ANVIL_GAME_PROVINCE_LAND,
ANVIL_GAME_PROVINCE_WASTELAND, 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)]
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())
}
}