1use 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
55pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
57pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct Milli(pub i32);
63
64impl Milli {
65 pub fn get(self) -> f64 {
67 f64::from(self.0) / 1000.0
68 }
69}
70
71impl fmt::Display for Milli {
72 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Province {
88 pub id: i32,
90 pub owner: Option<Tag>,
92 pub controller: Option<Tag>,
94 pub base_tax: Milli,
96 pub base_production: Milli,
98 pub base_manpower: Milli,
100 pub land: bool,
102 pub wasteland: bool,
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct Country {
109 pub tag: Option<Tag>,
111 pub capital: Option<i32>,
113 pub province_count: i32,
115 pub observer: bool,
117 pub treasury: Option<Milli>,
119 pub stability: Option<Milli>,
121 pub prestige: Option<Milli>,
123 pub manpower: Option<Milli>,
125 pub monthly_income: Option<Milli>,
128}
129
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub struct War {
133 pub id: u64,
135 pub attacker: Option<Tag>,
137 pub defender: Option<Tag>,
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
143pub enum Side {
144 Attackers,
146 Defenders,
148}
149
150#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
152pub enum UnitKind {
153 Army,
155 Navy,
157 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
173pub struct Mission(pub i32);
174
175impl Mission {
176 pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
178 pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
180 pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
182 pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
184 pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
186}
187
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub struct Unit {
191 pub kind: UnitKind,
193 pub id: u64,
195 pub country: Option<Tag>,
197 pub location: Option<i32>,
199 pub mission: Mission,
201 pub subunits: u32,
203 pub strength: Milli,
205 pub leader: Option<u64>,
207}
208
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211pub struct UnitRef {
212 pub id: u64,
214 pub country: Option<Tag>,
216 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
240pub enum ExplorationList {
241 Coast,
243 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
258pub struct ModifierId(pub i32);
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
262pub enum MonarchKind {
263 Ruler,
265 Heir,
267 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
291pub struct Monarch {
292 pub kind: MonarchKind,
294 pub id: u64,
296 pub country: Option<Tag>,
298 pub female: bool,
300 pub regency: bool,
302 pub adm: i32,
304 pub dip: i32,
306 pub mil: i32,
308 pub claim: Milli,
310 pub birth: Date,
312 pub leader: Option<u64>,
314}
315
316#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
318pub struct FlagId(pub i32);
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
322pub struct Flag {
323 pub id: FlagId,
325 pub date: Date,
327}
328
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331pub struct PendingEvent {
332 pub pending_id: i32,
334 pub country: Option<Tag>,
336 pub province: Option<i32>,
338 pub options: u32,
340 pub hidden: bool,
342 pub auto_select: Date,
344}
345
346#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
348pub enum StatisticKind {
349 Income,
351 Score,
353 NationSize,
355 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
372pub struct StatisticPoint {
373 pub year: i32,
375 pub value: i32,
377}
378
379#[derive(Clone, Debug, PartialEq, Eq)]
382pub struct TimedModifier {
383 pub key: String,
385 pub hidden: bool,
387 pub ruler: bool,
389 pub start: Option<Date>,
391 pub end: Option<Date>,
393}
394
395#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
399pub enum RelationKind {
400 Alliance,
402 RoyalMarriage,
404 Guarantee,
406 MilitaryAccess,
408 GivingMilitaryAccess,
410 Subsidies,
412 Dependency,
414 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
435pub struct Relation {
436 pub first: Option<Tag>,
438 pub second: Option<Tag>,
440 pub start: Option<Date>,
442 pub end: Option<Date>,
444}
445
446#[derive(Clone, Copy, Debug, PartialEq, Eq)]
448pub struct PlayerTags {
449 pub tag: Option<Tag>,
451 pub own: Option<Tag>,
454 pub observed: Option<Tag>,
456 pub observer: bool,
458}
459
460#[derive(Clone, Copy, Debug, PartialEq, Eq)]
462pub struct DiplomacyStatus {
463 pub opinion: i32,
467 pub timed_sum: i32,
470 pub trust: u32,
472 pub favors: Milli,
474 pub truce: bool,
476}
477
478#[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 let mut value: T = unsafe { std::mem::zeroed() };
495 let size = size_of::<T>() as u32;
496 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 pub fn get(host: &Host) -> Option<Self> {
511 let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
513 Some(Self { table })
514 }
515
516 pub fn c_api(&self) -> Table<AnvilGameWorldService> {
518 self.table
519 }
520
521 pub fn player(&self) -> Result<Option<Tag>> {
523 let f = function!(self.table, AnvilGameWorldService, player)?;
524 let mut tag = EMPTY_TAG;
525 check(unsafe { f(&mut tag) }, || "world player")?;
527 Ok(Tag::from_raw(&tag))
528 }
529
530 pub fn province_limit(&self) -> i32 {
532 function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
534 }
535
536 pub fn province(&self, id: i32) -> Result<Province> {
538 let f = function!(self.table, AnvilGameWorldService, province)?;
539 let mut raw: AnvilGameProvince = sized();
540 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 pub fn province_name(&self, id: i32) -> Result<String> {
558 let f = function!(self.table, AnvilGameWorldService, province_name)?;
559 read_text(
561 || format!("world province_name {id}"),
562 |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
563 )
564 }
565
566 pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
568 let f = function!(self.table, AnvilGameWorldService, province_cores)?;
569 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 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 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 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 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 pub fn war_ids(&self) -> Result<Vec<u64>> {
615 let f = function!(self.table, AnvilGameWorldService, war_ids)?;
616 read_list(
618 0u64,
619 || "world war_ids".to_owned(),
620 |out, capacity, count| unsafe { f(out, capacity, count) },
621 )
622 }
623
624 pub fn war(&self, id: u64) -> Result<War> {
626 let f = function!(self.table, AnvilGameWorldService, war)?;
627 let mut raw: AnvilGameWar = sized();
628 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 pub fn war_name(&self, id: u64) -> Result<String> {
639 let f = function!(self.table, AnvilGameWorldService, war_name)?;
640 read_text(
642 || format!("world war_name {id:#x}"),
643 |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
644 )
645 }
646
647 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 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 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 check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
672 format!("world modifier_id {key}")
673 })?;
674 Ok(ModifierId(id))
675 }
676
677 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 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 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 check(unsafe { f(province, id.0, &mut value) }, || {
695 format!("world province_modifier {province} {}", id.0)
696 })?;
697 Ok(Milli(value))
698 }
699
700 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
841 format!("world flag_id {name}")
842 })?;
843 Ok(FlagId(id))
844 }
845
846 pub fn flag_name(&self, id: FlagId) -> Result<String> {
848 let f = function!(self.table, AnvilGameWorldService, flag_name)?;
849 read_text(
851 || format!("world flag_name {}", id.0),
852 |buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
853 )
854 }
855
856 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 flags(
862 || format!("world country_flags {tag}"),
863 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
864 )
865 }
866
867 pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
869 let f = function!(self.table, AnvilGameWorldService, province_flags)?;
870 flags(
872 || format!("world province_flags {province}"),
873 |out, capacity, count| unsafe { f(province, out, capacity, count) },
874 )
875 }
876
877 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 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 pub fn global_flags(&self) -> Result<Vec<Flag>> {
890 let f = function!(self.table, AnvilGameWorldService, global_flags)?;
891 flags(
893 || "world global_flags".to_owned(),
894 |out, capacity, count| unsafe { f(out, capacity, count) },
895 )
896 }
897
898 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 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 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 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 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 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 pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
937 let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
938 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 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 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 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 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 pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
983 let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
984 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 pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
993 let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
994 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 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 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 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 let raw = timed_list(context, |out, capacity, count| unsafe {
1037 list(text.as_ptr(), out, capacity, count)
1038 })?;
1039 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 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 let raw = timed_list(context, |out, capacity, count| unsafe {
1057 list(province, out, capacity, count)
1058 })?;
1059 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 pub fn province_view(&self) -> Result<i32> {
1069 let f = function!(self.table, AnvilGameWorldService, province_view)?;
1070 let mut province = 0i32;
1071 check(unsafe { f(&mut province) }, || {
1073 "world province_view".to_owned()
1074 })?;
1075 Ok(province)
1076 }
1077
1078 pub fn selected_province(&self) -> Result<i32> {
1081 let f = function!(self.table, AnvilGameWorldService, selected_province)?;
1082 let mut province = 0i32;
1083 check(unsafe { f(&mut province) }, || {
1085 "world selected_province".to_owned()
1086 })?;
1087 Ok(province)
1088 }
1089
1090 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 check(unsafe { f(x, y, &mut province) }, || {
1098 format!("world province_at {x},{y}")
1099 })?;
1100 Ok(province)
1101 }
1102
1103 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 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 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 let all = read_text(context, |buffer, capacity, length| unsafe {
1137 keys(province, buffer, capacity, length)
1138 })?;
1139 Ok(split_names(&all))
1140 }
1141
1142 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 let empty: AnvilGameRelation = unsafe { std::mem::zeroed() };
1148 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 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 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 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 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 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 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 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 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 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 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 pub fn player_tags(&self) -> Result<PlayerTags> {
1245 let f = function!(self.table, AnvilGameWorldService, player_tags)?;
1246 let mut raw: AnvilGamePlayer = sized();
1247 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 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 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 pub fn region_name(&self, region: i32) -> Result<String> {
1275 let f = function!(self.table, AnvilGameWorldService, region_name)?;
1276 read_text(
1278 || format!("world region_name {region}"),
1279 |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1280 )
1281 }
1282
1283 pub fn region_key(&self, region: i32) -> Result<String> {
1285 let f = function!(self.table, AnvilGameWorldService, region_key)?;
1286 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 let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
1300 read_list(empty, context, call)
1301}
1302
1303fn 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
1327fn 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}