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_CITY, ANVIL_GAME_PROVINCE_COASTAL, ANVIL_GAME_PROVINCE_HRE,
42 ANVIL_GAME_PROVINCE_LAND, ANVIL_GAME_PROVINCE_STATE, ANVIL_GAME_PROVINCE_VALUE_DEVASTATION,
43 ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY, ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER,
44 ANVIL_GAME_PROVINCE_WASTELAND, ANVIL_GAME_RELATION_ALLIANCE, ANVIL_GAME_RELATION_DEPENDENCY,
45 ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS, ANVIL_GAME_RELATION_GUARANTEE,
46 ANVIL_GAME_RELATION_MILITARY_ACCESS, ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
47 ANVIL_GAME_RELATION_SUBSIDIES, ANVIL_GAME_RELATION_WARNING, ANVIL_GAME_STATISTIC_INCOME,
48 ANVIL_GAME_STATISTIC_INFLATION, ANVIL_GAME_STATISTIC_NATION_SIZE, ANVIL_GAME_STATISTIC_SCORE,
49 ANVIL_GAME_TIMED_HIDDEN, ANVIL_GAME_TIMED_NO_END, ANVIL_GAME_TIMED_NO_START,
50 ANVIL_GAME_TIMED_RULER, ANVIL_GAME_UNIT_ARMY, ANVIL_GAME_UNIT_NAVY, ANVIL_GAME_VALUE_MANPOWER,
51 ANVIL_GAME_VALUE_MONTHLY_INCOME, ANVIL_GAME_VALUE_PRESTIGE, ANVIL_GAME_VALUE_STABILITY,
52 ANVIL_GAME_VALUE_TREASURY, ANVIL_GAME_WAR_ATTACKERS, ANVIL_GAME_WAR_DEFENDERS,
53 ANVIL_GAME_WORLD_SERVICE_VERSION,
54};
55use crate::table::Table;
56use crate::text::{read_list, read_text, Tag};
57
58pub const SERVICE: &std::ffi::CStr = c"anvil-game.world";
60pub const VERSION: u32 = ANVIL_GAME_WORLD_SERVICE_VERSION;
62
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
65pub struct Milli(pub i32);
66
67impl Milli {
68 pub fn get(self) -> f64 {
70 f64::from(self.0) / 1000.0
71 }
72}
73
74impl fmt::Display for Milli {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 let sign = if self.0 < 0 { "-" } else { "" };
78 let value = self.0.unsigned_abs();
79 let (whole, part) = (value / 1000, value % 1000);
80 if part == 0 {
81 return write!(f, "{sign}{whole}");
82 }
83 let decimals = format!("{part:03}");
84 write!(f, "{sign}{whole}.{}", decimals.trim_end_matches('0'))
85 }
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub struct Province {
91 pub id: i32,
93 pub owner: Option<Tag>,
95 pub controller: Option<Tag>,
97 pub base_tax: Milli,
99 pub base_production: Milli,
101 pub base_manpower: Milli,
103 pub land: bool,
105 pub wasteland: bool,
107 pub hre: bool,
109 pub city: bool,
111 pub coastal: bool,
113 pub state: bool,
115 pub local_autonomy: Option<Milli>,
117 pub devastation: Option<Milli>,
119 pub trade_power: Option<Milli>,
121}
122
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct Country {
126 pub tag: Option<Tag>,
128 pub capital: Option<i32>,
130 pub province_count: i32,
132 pub observer: bool,
134 pub treasury: Option<Milli>,
136 pub stability: Option<Milli>,
138 pub prestige: Option<Milli>,
140 pub manpower: Option<Milli>,
142 pub monthly_income: Option<Milli>,
145}
146
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub struct War {
150 pub id: u64,
152 pub attacker: Option<Tag>,
154 pub defender: Option<Tag>,
156}
157
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
160pub enum Side {
161 Attackers,
163 Defenders,
165}
166
167#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
169pub enum UnitKind {
170 Army,
172 Navy,
174 Other(u32),
176}
177
178impl UnitKind {
179 fn from_raw(kind: u32) -> Self {
180 match kind {
181 ANVIL_GAME_UNIT_ARMY => Self::Army,
182 ANVIL_GAME_UNIT_NAVY => Self::Navy,
183 other => Self::Other(other),
184 }
185 }
186}
187
188#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
190pub struct Mission(pub i32);
191
192impl Mission {
193 pub const UNKNOWN: Self = Self(crate::sys::ANVIL_GAME_MISSION_UNKNOWN);
195 pub const NONE: Self = Self(crate::sys::ANVIL_GAME_MISSION_NONE as i32);
197 pub const SIEGE: Self = Self(crate::sys::ANVIL_GAME_MISSION_SIEGE as i32);
199 pub const HUNT_REBELS: Self = Self(crate::sys::ANVIL_GAME_MISSION_HUNT_REBELS as i32);
201 pub const DRILL: Self = Self(crate::sys::ANVIL_GAME_MISSION_DRILL as i32);
203}
204
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
207pub struct Unit {
208 pub kind: UnitKind,
210 pub id: u64,
212 pub country: Option<Tag>,
214 pub location: Option<i32>,
216 pub mission: Mission,
218 pub subunits: u32,
220 pub strength: Milli,
222 pub leader: Option<u64>,
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub struct UnitRef {
229 pub id: u64,
231 pub country: Option<Tag>,
233 pub kind: UnitKind,
235}
236
237impl UnitRef {
238 pub(crate) fn to_raw(self) -> AnvilGameUnitRef {
239 AnvilGameUnitRef {
240 id: self.id,
241 country: self
242 .country
243 .map(|tag| tag.to_raw())
244 .unwrap_or(AnvilGameTag { text: [0; 4] }),
245 kind: match self.kind {
246 UnitKind::Army => ANVIL_GAME_UNIT_ARMY,
247 UnitKind::Navy => ANVIL_GAME_UNIT_NAVY,
248 UnitKind::Other(other) => other,
249 },
250 }
251 }
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
257pub enum ExplorationList {
258 Coast,
260 Sea,
262}
263
264impl ExplorationList {
265 fn raw(self) -> i32 {
266 match self {
267 Self::Coast => ANVIL_GAME_EXPLORE_COAST as i32,
268 Self::Sea => ANVIL_GAME_EXPLORE_SEA as i32,
269 }
270 }
271}
272
273#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
275pub struct ModifierId(pub i32);
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
279pub enum MonarchKind {
280 Ruler,
282 Heir,
284 Consort,
286}
287
288impl MonarchKind {
289 fn raw(self) -> u32 {
290 match self {
291 Self::Ruler => ANVIL_GAME_MONARCH_RULER,
292 Self::Heir => ANVIL_GAME_MONARCH_HEIR,
293 Self::Consort => ANVIL_GAME_MONARCH_CONSORT,
294 }
295 }
296
297 fn from_raw(kind: u32) -> Self {
298 match kind {
299 ANVIL_GAME_MONARCH_HEIR => Self::Heir,
300 ANVIL_GAME_MONARCH_CONSORT => Self::Consort,
301 _ => Self::Ruler,
302 }
303 }
304}
305
306#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub struct Monarch {
309 pub kind: MonarchKind,
311 pub id: u64,
313 pub country: Option<Tag>,
315 pub female: bool,
317 pub regency: bool,
319 pub adm: i32,
321 pub dip: i32,
323 pub mil: i32,
325 pub claim: Milli,
327 pub birth: Date,
329 pub leader: Option<u64>,
331}
332
333#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
335pub struct FlagId(pub i32);
336
337#[derive(Clone, Copy, Debug, PartialEq, Eq)]
339pub struct Flag {
340 pub id: FlagId,
342 pub date: Date,
344}
345
346#[derive(Clone, Copy, Debug, PartialEq, Eq)]
348pub struct PendingEvent {
349 pub pending_id: i32,
351 pub country: Option<Tag>,
353 pub province: Option<i32>,
355 pub options: u32,
357 pub hidden: bool,
359 pub auto_select: Date,
361}
362
363#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
365pub enum StatisticKind {
366 Income,
368 Score,
370 NationSize,
372 Inflation,
374}
375
376impl StatisticKind {
377 fn raw(self) -> u32 {
378 match self {
379 Self::Income => ANVIL_GAME_STATISTIC_INCOME,
380 Self::Score => ANVIL_GAME_STATISTIC_SCORE,
381 Self::NationSize => ANVIL_GAME_STATISTIC_NATION_SIZE,
382 Self::Inflation => ANVIL_GAME_STATISTIC_INFLATION,
383 }
384 }
385}
386
387#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
389pub struct StatisticPoint {
390 pub year: i32,
392 pub value: i32,
394}
395
396#[derive(Clone, Debug, PartialEq, Eq)]
399pub struct TimedModifier {
400 pub key: String,
402 pub hidden: bool,
404 pub ruler: bool,
406 pub start: Option<Date>,
408 pub end: Option<Date>,
410}
411
412#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
416pub enum RelationKind {
417 Alliance,
419 RoyalMarriage,
421 Guarantee,
423 MilitaryAccess,
425 GivingMilitaryAccess,
427 Subsidies,
429 Dependency,
431 Warning,
433}
434
435impl RelationKind {
436 fn raw(self) -> u32 {
437 match self {
438 Self::Alliance => ANVIL_GAME_RELATION_ALLIANCE,
439 Self::RoyalMarriage => ANVIL_GAME_RELATION_ROYAL_MARRIAGE,
440 Self::Guarantee => ANVIL_GAME_RELATION_GUARANTEE,
441 Self::MilitaryAccess => ANVIL_GAME_RELATION_MILITARY_ACCESS,
442 Self::GivingMilitaryAccess => ANVIL_GAME_RELATION_GIVING_MILITARY_ACCESS,
443 Self::Subsidies => ANVIL_GAME_RELATION_SUBSIDIES,
444 Self::Dependency => ANVIL_GAME_RELATION_DEPENDENCY,
445 Self::Warning => ANVIL_GAME_RELATION_WARNING,
446 }
447 }
448}
449
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub struct Relation {
453 pub first: Option<Tag>,
455 pub second: Option<Tag>,
457 pub start: Option<Date>,
459 pub end: Option<Date>,
461}
462
463#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465pub struct PlayerTags {
466 pub tag: Option<Tag>,
468 pub own: Option<Tag>,
471 pub observed: Option<Tag>,
473 pub observer: bool,
475}
476
477#[derive(Clone, Copy, Debug, PartialEq, Eq)]
479pub struct DiplomacyStatus {
480 pub opinion: i32,
484 pub timed_sum: i32,
487 pub trust: u32,
489 pub favors: Milli,
491 pub truce: bool,
493}
494
495#[derive(Clone, Copy)]
497pub struct World {
498 table: Table<AnvilGameWorldService>,
499}
500
501impl fmt::Debug for World {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 f.debug_struct("World")
504 .field("size", &self.table.size())
505 .finish()
506 }
507}
508
509fn sized<T>() -> T {
510 let mut value: T = unsafe { std::mem::zeroed() };
512 let size = size_of::<T>() as u32;
513 unsafe { std::ptr::from_mut(&mut value).cast::<u32>().write(size) };
515 value
516}
517
518fn known(value: i32, values: u32, bit: u32) -> Option<Milli> {
519 (values & bit != 0).then_some(Milli(value))
520}
521
522const EMPTY_TAG: AnvilGameTag = AnvilGameTag { text: [0; 4] };
523
524impl World {
525 pub fn get(host: &Host) -> Option<Self> {
528 let table = unsafe { host.service::<AnvilGameWorldService>(SERVICE, VERSION) }?;
530 Some(Self { table })
531 }
532
533 pub fn c_api(&self) -> Table<AnvilGameWorldService> {
535 self.table
536 }
537
538 pub fn player(&self) -> Result<Option<Tag>> {
540 let f = function!(self.table, AnvilGameWorldService, player)?;
541 let mut tag = EMPTY_TAG;
542 check(unsafe { f(&mut tag) }, || "world player")?;
544 Ok(Tag::from_raw(&tag))
545 }
546
547 pub fn province_limit(&self) -> i32 {
549 function!(self.table, AnvilGameWorldService, province_limit).map_or(0, |f| unsafe { f() })
551 }
552
553 pub fn province(&self, id: i32) -> Result<Province> {
555 let f = function!(self.table, AnvilGameWorldService, province)?;
556 let mut raw: AnvilGameProvince = sized();
557 check(unsafe { f(id, &mut raw) }, || {
559 format!("world province {id}")
560 })?;
561 Ok(Province {
562 id: raw.id,
563 owner: Tag::from_raw(&raw.owner),
564 controller: Tag::from_raw(&raw.controller),
565 base_tax: Milli(raw.base_tax),
566 base_production: Milli(raw.base_production),
567 base_manpower: Milli(raw.base_manpower),
568 land: raw.flags & ANVIL_GAME_PROVINCE_LAND != 0,
569 wasteland: raw.flags & ANVIL_GAME_PROVINCE_WASTELAND != 0,
570 hre: raw.flags & ANVIL_GAME_PROVINCE_HRE != 0,
571 city: raw.flags & ANVIL_GAME_PROVINCE_CITY != 0,
572 coastal: raw.flags & ANVIL_GAME_PROVINCE_COASTAL != 0,
573 state: raw.flags & ANVIL_GAME_PROVINCE_STATE != 0,
574 local_autonomy: (raw.values & ANVIL_GAME_PROVINCE_VALUE_LOCAL_AUTONOMY != 0)
575 .then_some(Milli(raw.local_autonomy)),
576 devastation: (raw.values & ANVIL_GAME_PROVINCE_VALUE_DEVASTATION != 0)
577 .then_some(Milli(raw.devastation)),
578 trade_power: (raw.values & ANVIL_GAME_PROVINCE_VALUE_TRADE_POWER != 0)
579 .then_some(Milli(raw.trade_power)),
580 })
581 }
582
583 pub fn province_name(&self, id: i32) -> Result<String> {
585 let f = function!(self.table, AnvilGameWorldService, province_name)?;
586 read_text(
588 || format!("world province_name {id}"),
589 |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
590 )
591 }
592
593 pub fn province_cores(&self, id: i32) -> Result<Vec<Tag>> {
595 let f = function!(self.table, AnvilGameWorldService, province_cores)?;
596 let raw = read_list(
598 EMPTY_TAG,
599 || format!("world province_cores {id}"),
600 |out, capacity, count| unsafe { f(id, out, capacity, count) },
601 )?;
602 Ok(raw.iter().filter_map(Tag::from_raw).collect())
603 }
604
605 pub fn country(&self, tag: Tag) -> Result<Country> {
607 let f = function!(self.table, AnvilGameWorldService, country)?;
608 let text = tag.c_text();
609 let mut raw: AnvilGameCountry = sized();
610 check(unsafe { f(text.as_ptr(), &mut raw) }, || {
612 format!("world country {tag}")
613 })?;
614 let v = raw.values;
615 Ok(Country {
616 tag: Tag::from_raw(&raw.tag),
617 capital: (raw.capital != 0).then_some(raw.capital),
618 province_count: raw.province_count,
619 observer: raw.flags & ANVIL_GAME_COUNTRY_OBSERVER != 0,
620 treasury: known(raw.treasury, v, ANVIL_GAME_VALUE_TREASURY),
621 stability: known(raw.stability, v, ANVIL_GAME_VALUE_STABILITY),
622 prestige: known(raw.prestige, v, ANVIL_GAME_VALUE_PRESTIGE),
623 manpower: known(raw.manpower, v, ANVIL_GAME_VALUE_MANPOWER),
624 monthly_income: known(raw.monthly_income, v, ANVIL_GAME_VALUE_MONTHLY_INCOME),
625 })
626 }
627
628 pub fn country_provinces(&self, tag: Tag) -> Result<Vec<i32>> {
630 let f = function!(self.table, AnvilGameWorldService, country_provinces)?;
631 let text = tag.c_text();
632 read_list(
634 0i32,
635 || format!("world country_provinces {tag}"),
636 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
637 )
638 }
639
640 pub fn war_ids(&self) -> Result<Vec<u64>> {
642 let f = function!(self.table, AnvilGameWorldService, war_ids)?;
643 read_list(
645 0u64,
646 || "world war_ids".to_owned(),
647 |out, capacity, count| unsafe { f(out, capacity, count) },
648 )
649 }
650
651 pub fn war(&self, id: u64) -> Result<War> {
653 let f = function!(self.table, AnvilGameWorldService, war)?;
654 let mut raw: AnvilGameWar = sized();
655 check(unsafe { f(id, &mut raw) }, || format!("world war {id:#x}"))?;
657 Ok(War {
658 id: raw.id,
659 attacker: Tag::from_raw(&raw.attacker),
660 defender: Tag::from_raw(&raw.defender),
661 })
662 }
663
664 pub fn war_name(&self, id: u64) -> Result<String> {
666 let f = function!(self.table, AnvilGameWorldService, war_name)?;
667 read_text(
669 || format!("world war_name {id:#x}"),
670 |buffer, capacity, length| unsafe { f(id, buffer, capacity, length) },
671 )
672 }
673
674 pub fn war_side(&self, id: u64, side: Side) -> Result<Vec<Tag>> {
676 let f = function!(self.table, AnvilGameWorldService, war_side)?;
677 let side_raw = match side {
678 Side::Attackers => ANVIL_GAME_WAR_ATTACKERS,
679 Side::Defenders => ANVIL_GAME_WAR_DEFENDERS,
680 };
681 let raw = read_list(
683 EMPTY_TAG,
684 || format!("world war_side {id:#x}"),
685 |out, capacity, count| unsafe { f(id, side_raw, out, capacity, count) },
686 )?;
687 Ok(raw.iter().filter_map(Tag::from_raw).collect())
688 }
689
690 pub fn modifier_id(&self, key: &str) -> Result<ModifierId> {
694 let f = function!(self.table, AnvilGameWorldService, modifier_id)?;
695 let key_c = crate::text::c_string(key);
696 let mut id = 0i32;
697 check(unsafe { f(key_c.as_ptr(), &mut id) }, || {
699 format!("world modifier_id {key}")
700 })?;
701 Ok(ModifierId(id))
702 }
703
704 pub fn country_modifier(&self, tag: Tag, id: ModifierId) -> Result<Milli> {
706 let f = function!(self.table, AnvilGameWorldService, country_modifier)?;
707 let text = tag.c_text();
708 let mut value = 0i32;
709 check(unsafe { f(text.as_ptr(), id.0, &mut value) }, || {
711 format!("world country_modifier {tag} {}", id.0)
712 })?;
713 Ok(Milli(value))
714 }
715
716 pub fn province_modifier(&self, province: i32, id: ModifierId) -> Result<Milli> {
718 let f = function!(self.table, AnvilGameWorldService, province_modifier)?;
719 let mut value = 0i32;
720 check(unsafe { f(province, id.0, &mut value) }, || {
722 format!("world province_modifier {province} {}", id.0)
723 })?;
724 Ok(Milli(value))
725 }
726
727 pub fn country_units(&self, tag: Tag) -> Result<Vec<u64>> {
729 let f = function!(self.table, AnvilGameWorldService, country_units)?;
730 let text = tag.c_text();
731 read_list(
733 0u64,
734 || format!("world country_units {tag}"),
735 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
736 )
737 }
738
739 pub fn unit(&self, tag: Tag, id: u64) -> Result<Unit> {
741 let f = function!(self.table, AnvilGameWorldService, unit)?;
742 let text = tag.c_text();
743 let mut raw: AnvilGameUnit = sized();
744 check(unsafe { f(text.as_ptr(), id, &mut raw) }, || {
746 format!("world unit {tag} {id:#x}")
747 })?;
748 Ok(Unit {
749 kind: UnitKind::from_raw(raw.kind),
750 id: raw.id,
751 country: Tag::from_raw(&raw.country),
752 location: (raw.location != 0).then_some(raw.location),
753 mission: Mission(raw.mission),
754 subunits: raw.subunits,
755 strength: Milli(raw.strength),
756 leader: (raw.leader != 0).then_some(raw.leader),
757 })
758 }
759
760 pub fn unit_name(&self, tag: Tag, id: u64) -> Result<String> {
762 let f = function!(self.table, AnvilGameWorldService, unit_name)?;
763 let text = tag.c_text();
764 read_text(
766 || format!("world unit_name {tag} {id:#x}"),
767 |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
768 )
769 }
770
771 pub fn unit_leader_name(&self, tag: Tag, id: u64) -> Result<String> {
773 let f = function!(self.table, AnvilGameWorldService, unit_leader_name)?;
774 let text = tag.c_text();
775 read_text(
777 || format!("world unit_leader_name {tag} {id:#x}"),
778 |buffer, capacity, length| unsafe { f(text.as_ptr(), id, buffer, capacity, length) },
779 )
780 }
781
782 pub fn selected_units(&self) -> Result<Vec<UnitRef>> {
784 let f = function!(self.table, AnvilGameWorldService, selected_units)?;
785 let empty = AnvilGameUnitRef {
786 id: 0,
787 country: EMPTY_TAG,
788 kind: 0,
789 };
790 let raw = read_list(
792 empty,
793 || "world selected_units".to_owned(),
794 |out, capacity, count| unsafe { f(out, capacity, count) },
795 )?;
796 Ok(raw
797 .iter()
798 .map(|r| UnitRef {
799 id: r.id,
800 country: Tag::from_raw(&r.country),
801 kind: UnitKind::from_raw(r.kind),
802 })
803 .collect())
804 }
805
806 pub fn monarch(&self, tag: Tag, kind: MonarchKind) -> Result<Monarch> {
811 let f = function!(self.table, AnvilGameWorldService, monarch)?;
812 let text = tag.c_text();
813 let mut raw: AnvilGameMonarch = sized();
814 check(unsafe { f(text.as_ptr(), kind.raw(), &mut raw) }, || {
816 format!("world monarch {tag} {kind:?}")
817 })?;
818 Ok(Monarch {
819 kind: MonarchKind::from_raw(raw.kind),
820 id: raw.id,
821 country: Tag::from_raw(&raw.country),
822 female: raw.flags & ANVIL_GAME_MONARCH_FEMALE != 0,
823 regency: raw.flags & ANVIL_GAME_MONARCH_REGENCY != 0,
824 adm: raw.adm,
825 dip: raw.dip,
826 mil: raw.mil,
827 claim: Milli(raw.claim),
828 birth: Date::from_raw(&raw.birth),
829 leader: (raw.leader != 0).then_some(raw.leader),
830 })
831 }
832
833 pub fn monarch_name(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
835 let f = function!(self.table, AnvilGameWorldService, monarch_name)?;
836 let text = tag.c_text();
837 read_text(
839 || format!("world monarch_name {tag} {kind:?}"),
840 |buffer, capacity, length| unsafe {
841 f(text.as_ptr(), kind.raw(), buffer, capacity, length)
842 },
843 )
844 }
845
846 pub fn monarch_dynasty(&self, tag: Tag, kind: MonarchKind) -> Result<String> {
848 let f = function!(self.table, AnvilGameWorldService, monarch_dynasty)?;
849 let text = tag.c_text();
850 read_text(
852 || format!("world monarch_dynasty {tag} {kind:?}"),
853 |buffer, capacity, length| unsafe {
854 f(text.as_ptr(), kind.raw(), buffer, capacity, length)
855 },
856 )
857 }
858
859 pub fn flag_id(&self, name: &str) -> Result<FlagId> {
863 let f = function!(self.table, AnvilGameWorldService, flag_id)?;
864 let name_c = crate::text::c_string(name);
865 let mut id = 0i32;
866 check(unsafe { f(name_c.as_ptr(), &mut id) }, || {
868 format!("world flag_id {name}")
869 })?;
870 Ok(FlagId(id))
871 }
872
873 pub fn flag_name(&self, id: FlagId) -> Result<String> {
875 let f = function!(self.table, AnvilGameWorldService, flag_name)?;
876 read_text(
878 || format!("world flag_name {}", id.0),
879 |buffer, capacity, length| unsafe { f(id.0, buffer, capacity, length) },
880 )
881 }
882
883 pub fn country_flags(&self, tag: Tag) -> Result<Vec<Flag>> {
885 let f = function!(self.table, AnvilGameWorldService, country_flags)?;
886 let text = tag.c_text();
887 flags(
889 || format!("world country_flags {tag}"),
890 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
891 )
892 }
893
894 pub fn province_flags(&self, province: i32) -> Result<Vec<Flag>> {
896 let f = function!(self.table, AnvilGameWorldService, province_flags)?;
897 flags(
899 || format!("world province_flags {province}"),
900 |out, capacity, count| unsafe { f(province, out, capacity, count) },
901 )
902 }
903
904 pub fn monarch_flags(&self, tag: Tag, kind: MonarchKind) -> Result<Vec<Flag>> {
906 let f = function!(self.table, AnvilGameWorldService, monarch_flags)?;
907 let text = tag.c_text();
908 flags(
910 || format!("world monarch_flags {tag} {kind:?}"),
911 |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
912 )
913 }
914
915 pub fn global_flags(&self) -> Result<Vec<Flag>> {
917 let f = function!(self.table, AnvilGameWorldService, global_flags)?;
918 flags(
920 || "world global_flags".to_owned(),
921 |out, capacity, count| unsafe { f(out, capacity, count) },
922 )
923 }
924
925 pub fn country_variable(&self, tag: Tag, name: &str) -> Result<Milli> {
928 let f = function!(self.table, AnvilGameWorldService, country_variable)?;
929 let text = tag.c_text();
930 let name_c = crate::text::c_string(name);
931 let mut value = 0i32;
932 let result = unsafe { f(text.as_ptr(), name_c.as_ptr(), &mut value) };
934 check(result, || format!("world country_variable {tag} {name}"))?;
935 Ok(Milli(value))
936 }
937
938 pub fn province_variable(&self, province: i32, name: &str) -> Result<Milli> {
940 let f = function!(self.table, AnvilGameWorldService, province_variable)?;
941 let name_c = crate::text::c_string(name);
942 let mut value = 0i32;
943 check(unsafe { f(province, name_c.as_ptr(), &mut value) }, || {
945 format!("world province_variable {province} {name}")
946 })?;
947 Ok(Milli(value))
948 }
949
950 pub fn country_variable_names(&self, tag: Tag) -> Result<Vec<String>> {
952 let f = function!(self.table, AnvilGameWorldService, country_variable_names)?;
953 let text = tag.c_text();
954 let all = read_text(
956 || format!("world country_variable_names {tag}"),
957 |buffer, capacity, length| unsafe { f(text.as_ptr(), buffer, capacity, length) },
958 )?;
959 Ok(split_names(&all))
960 }
961
962 pub fn province_variable_names(&self, province: i32) -> Result<Vec<String>> {
964 let f = function!(self.table, AnvilGameWorldService, province_variable_names)?;
965 let all = read_text(
967 || format!("world province_variable_names {province}"),
968 |buffer, capacity, length| unsafe { f(province, buffer, capacity, length) },
969 )?;
970 Ok(split_names(&all))
971 }
972
973 pub fn pending_events(&self, tag: Option<Tag>) -> Result<Vec<i32>> {
979 let f = function!(self.table, AnvilGameWorldService, pending_events)?;
980 let text = tag.map(|t| t.c_text());
981 let tag_ptr = text.as_ref().map_or(std::ptr::null(), |t| t.as_ptr());
982 read_list(
984 0i32,
985 || format!("world pending_events {tag:?}"),
986 |out, capacity, count| unsafe { f(tag_ptr, out, capacity, count) },
987 )
988 }
989
990 pub fn pending_event(&self, pending_id: i32) -> Result<PendingEvent> {
992 let f = function!(self.table, AnvilGameWorldService, pending_event)?;
993 let mut raw: AnvilGamePendingEvent = sized();
994 check(unsafe { f(pending_id, &mut raw) }, || {
996 format!("world pending_event {pending_id}")
997 })?;
998 Ok(PendingEvent {
999 pending_id: raw.pending_id,
1000 country: Tag::from_raw(&raw.country),
1001 province: (raw.province != 0).then_some(raw.province),
1002 options: raw.options,
1003 hidden: raw.flags & ANVIL_GAME_PENDING_HIDDEN != 0,
1004 auto_select: Date::from_raw(&raw.auto_select),
1005 })
1006 }
1007
1008 pub fn pending_event_key(&self, pending_id: i32) -> Result<String> {
1010 let f = function!(self.table, AnvilGameWorldService, pending_event_key)?;
1011 read_text(
1013 || format!("world pending_event_key {pending_id}"),
1014 |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
1015 )
1016 }
1017
1018 pub fn pending_event_title(&self, pending_id: i32) -> Result<String> {
1020 let f = function!(self.table, AnvilGameWorldService, pending_event_title)?;
1021 read_text(
1023 || format!("world pending_event_title {pending_id}"),
1024 |buffer, capacity, length| unsafe { f(pending_id, buffer, capacity, length) },
1025 )
1026 }
1027
1028 pub fn country_statistics(&self, tag: Tag, kind: StatisticKind) -> Result<Vec<StatisticPoint>> {
1032 let f = function!(self.table, AnvilGameWorldService, country_statistics)?;
1033 let text = tag.c_text();
1034 let empty = AnvilGameStatisticPoint { year: 0, value: 0 };
1035 let raw = read_list(
1037 empty,
1038 || format!("world country_statistics {tag} {kind:?}"),
1039 |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1040 )?;
1041 Ok(raw
1042 .iter()
1043 .map(|p| StatisticPoint {
1044 year: p.year,
1045 value: p.value,
1046 })
1047 .collect())
1048 }
1049
1050 pub fn country_timed_modifiers(&self, tag: Tag) -> Result<Vec<TimedModifier>> {
1054 let list = function!(self.table, AnvilGameWorldService, country_timed_modifiers)?;
1055 let keys = function!(
1056 self.table,
1057 AnvilGameWorldService,
1058 country_timed_modifier_keys
1059 )?;
1060 let text = tag.c_text();
1061 let context = || format!("world country_timed_modifiers {tag}");
1062 let raw = timed_list(context, |out, capacity, count| unsafe {
1064 list(text.as_ptr(), out, capacity, count)
1065 })?;
1066 let all = read_text(context, |buffer, capacity, length| unsafe {
1068 keys(text.as_ptr(), buffer, capacity, length)
1069 })?;
1070 timed_modifiers(&raw, &all, context)
1071 }
1072
1073 pub fn province_timed_modifiers(&self, province: i32) -> Result<Vec<TimedModifier>> {
1075 let list = function!(self.table, AnvilGameWorldService, province_timed_modifiers)?;
1076 let keys = function!(
1077 self.table,
1078 AnvilGameWorldService,
1079 province_timed_modifier_keys
1080 )?;
1081 let context = || format!("world province_timed_modifiers {province}");
1082 let raw = timed_list(context, |out, capacity, count| unsafe {
1084 list(province, out, capacity, count)
1085 })?;
1086 let all = read_text(context, |buffer, capacity, length| unsafe {
1088 keys(province, buffer, capacity, length)
1089 })?;
1090 timed_modifiers(&raw, &all, context)
1091 }
1092
1093 pub fn province_view(&self) -> Result<i32> {
1096 let f = function!(self.table, AnvilGameWorldService, province_view)?;
1097 let mut province = 0i32;
1098 check(unsafe { f(&mut province) }, || {
1100 "world province_view".to_owned()
1101 })?;
1102 Ok(province)
1103 }
1104
1105 pub fn selected_province(&self) -> Result<i32> {
1108 let f = function!(self.table, AnvilGameWorldService, selected_province)?;
1109 let mut province = 0i32;
1110 check(unsafe { f(&mut province) }, || {
1112 "world selected_province".to_owned()
1113 })?;
1114 Ok(province)
1115 }
1116
1117 pub fn province_at(&self, x: i32, y: i32) -> Result<i32> {
1121 let f = function!(self.table, AnvilGameWorldService, province_at)?;
1122 let mut province = 0i32;
1123 check(unsafe { f(x, y, &mut province) }, || {
1125 format!("world province_at {x},{y}")
1126 })?;
1127 Ok(province)
1128 }
1129
1130 pub fn unit_at(&self, x: i32, y: i32) -> Result<UnitRef> {
1133 let f = function!(self.table, AnvilGameWorldService, unit_at)?;
1134 let mut raw = AnvilGameUnitRef {
1135 id: 0,
1136 country: EMPTY_TAG,
1137 kind: 0,
1138 };
1139 check(unsafe { f(x, y, &mut raw) }, || {
1141 format!("world unit_at {x},{y}")
1142 })?;
1143 Ok(UnitRef {
1144 id: raw.id,
1145 country: Tag::from_raw(&raw.country),
1146 kind: UnitKind::from_raw(raw.kind),
1147 })
1148 }
1149
1150 pub fn province_triggered_modifiers(&self, province: i32) -> Result<Vec<String>> {
1156 let keys = function!(
1157 self.table,
1158 AnvilGameWorldService,
1159 province_triggered_modifier_keys
1160 )?;
1161 let context = || format!("world province_triggered_modifiers {province}");
1162 let all = read_text(context, |buffer, capacity, length| unsafe {
1164 keys(province, buffer, capacity, length)
1165 })?;
1166 Ok(split_names(&all))
1167 }
1168
1169 pub fn country_relations(&self, tag: Tag, kind: RelationKind) -> Result<Vec<Relation>> {
1171 let f = function!(self.table, AnvilGameWorldService, country_relations)?;
1172 let text = tag.c_text();
1173 let empty: AnvilGameRelation = unsafe { std::mem::zeroed() };
1175 let raw = read_list(
1177 empty,
1178 || format!("world country_relations {tag} {kind:?}"),
1179 |out, capacity, count| unsafe { f(text.as_ptr(), kind.raw(), out, capacity, count) },
1180 )?;
1181 Ok(raw
1182 .iter()
1183 .map(|r| Relation {
1184 first: Tag::from_raw(&r.first),
1185 second: Tag::from_raw(&r.second),
1186 start: (r.start.size != 0).then(|| Date::from_raw(&r.start)),
1187 end: (r.end.size != 0).then(|| Date::from_raw(&r.end)),
1188 })
1189 .collect())
1190 }
1191
1192 pub fn subject_type(&self, overlord: Tag, subject: Tag) -> Result<String> {
1195 let f = function!(self.table, AnvilGameWorldService, subject_type)?;
1196 let (a, b) = (overlord.c_text(), subject.c_text());
1197 read_text(
1199 || format!("world subject_type {overlord} {subject}"),
1200 |buffer, capacity, length| unsafe {
1201 f(a.as_ptr(), b.as_ptr(), buffer, capacity, length)
1202 },
1203 )
1204 }
1205
1206 pub fn diplomacy_status(&self, from: Tag, to: Tag) -> Result<DiplomacyStatus> {
1210 let f = function!(self.table, AnvilGameWorldService, diplomacy_status)?;
1211 let (a, b) = (from.c_text(), to.c_text());
1212 let mut raw: AnvilGameDiplomacyStatus = sized();
1213 check(unsafe { f(a.as_ptr(), b.as_ptr(), &mut raw) }, || {
1215 format!("world diplomacy_status {from} {to}")
1216 })?;
1217 Ok(DiplomacyStatus {
1218 opinion: raw.opinion,
1219 timed_sum: raw.timed_sum,
1220 trust: raw.trust,
1221 favors: Milli(raw.favors),
1222 truce: raw.flags & ANVIL_GAME_DIPLOMACY_TRUCE != 0,
1223 })
1224 }
1225
1226 pub fn country_rivals(&self, tag: Tag) -> Result<Vec<Tag>> {
1228 let f = function!(self.table, AnvilGameWorldService, country_rivals)?;
1229 let text = tag.c_text();
1230 let raw = read_list(
1232 EMPTY_TAG,
1233 || format!("world country_rivals {tag}"),
1234 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1235 )?;
1236 Ok(raw.iter().filter_map(Tag::from_raw).collect())
1237 }
1238
1239 pub fn country_overlord(&self, tag: Tag) -> Result<Tag> {
1241 let f = function!(self.table, AnvilGameWorldService, country_overlord)?;
1242 let text = tag.c_text();
1243 let mut raw = EMPTY_TAG;
1244 check(unsafe { f(text.as_ptr(), &mut raw) }, || {
1246 format!("world country_overlord {tag}")
1247 })?;
1248 Tag::from_raw(&raw)
1249 .ok_or_else(|| Error::new(ErrorCode::Internal, format!("world country_overlord {tag}")))
1250 }
1251
1252 pub fn country_subjects(&self, tag: Tag) -> Result<Vec<Tag>> {
1254 let f = function!(self.table, AnvilGameWorldService, country_subjects)?;
1255 let text = tag.c_text();
1256 let raw = read_list(
1258 EMPTY_TAG,
1259 || format!("world country_subjects {tag}"),
1260 |out, capacity, count| unsafe { f(text.as_ptr(), out, capacity, count) },
1261 )?;
1262 Ok(raw.iter().filter_map(Tag::from_raw).collect())
1263 }
1264
1265 pub fn player_tags(&self) -> Result<PlayerTags> {
1272 let f = function!(self.table, AnvilGameWorldService, player_tags)?;
1273 let mut raw: AnvilGamePlayer = sized();
1274 check(unsafe { f(&mut raw) }, || "world player_tags")?;
1276 Ok(PlayerTags {
1277 tag: Tag::from_raw(&raw.tag),
1278 own: Tag::from_raw(&raw.own),
1279 observed: Tag::from_raw(&raw.observed),
1280 observer: raw.flags & ANVIL_GAME_PLAYER_OBSERVER != 0,
1281 })
1282 }
1283
1284 pub fn exploration_regions(&self, fleet: &UnitRef, list: ExplorationList) -> Result<Vec<i32>> {
1289 let f = function!(self.table, AnvilGameWorldService, exploration_regions)?;
1290 let raw = fleet.to_raw();
1291 read_list(
1293 0i32,
1294 || format!("world exploration_regions {} {list:?}", fleet.id),
1295 |out, capacity, count| unsafe { f(&raw, list.raw(), out, capacity, count) },
1296 )
1297 }
1298
1299 pub fn region_name(&self, region: i32) -> Result<String> {
1302 let f = function!(self.table, AnvilGameWorldService, region_name)?;
1303 read_text(
1305 || format!("world region_name {region}"),
1306 |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1307 )
1308 }
1309
1310 pub fn region_key(&self, region: i32) -> Result<String> {
1312 let f = function!(self.table, AnvilGameWorldService, region_key)?;
1313 read_text(
1315 || format!("world region_key {region}"),
1316 |buffer, capacity, length| unsafe { f(region, buffer, capacity, length) },
1317 )
1318 }
1319
1320 fn province_key(&self, province: i32, key: u32, name: &str) -> Result<String> {
1321 let f = function!(self.table, AnvilGameWorldService, province_key)?;
1322 read_text(
1324 || format!("world {name} {province}"),
1325 |buffer, capacity, length| unsafe { f(province, key, buffer, capacity, length) },
1326 )
1327 }
1328
1329 fn country_key(&self, tag: Tag, key: u32, name: &str) -> Result<String> {
1330 let f = function!(self.table, AnvilGameWorldService, country_key)?;
1331 let text = tag.c_text();
1332 read_text(
1334 || format!("world {name} {tag}"),
1335 |buffer, capacity, length| unsafe { f(text.as_ptr(), key, buffer, capacity, length) },
1336 )
1337 }
1338
1339 pub fn province_religion(&self, province: i32) -> Result<String> {
1342 self.province_key(
1343 province,
1344 crate::sys::ANVIL_GAME_KEY_RELIGION,
1345 "province_religion",
1346 )
1347 }
1348
1349 pub fn province_culture(&self, province: i32) -> Result<String> {
1352 self.province_key(
1353 province,
1354 crate::sys::ANVIL_GAME_KEY_CULTURE,
1355 "province_culture",
1356 )
1357 }
1358
1359 pub fn province_trade_goods(&self, province: i32) -> Result<String> {
1362 self.province_key(
1363 province,
1364 crate::sys::ANVIL_GAME_KEY_TRADE_GOODS,
1365 "province_trade_goods",
1366 )
1367 }
1368
1369 pub fn country_religion(&self, tag: Tag) -> Result<String> {
1372 self.country_key(tag, crate::sys::ANVIL_GAME_KEY_RELIGION, "country_religion")
1373 }
1374
1375 pub fn country_culture(&self, tag: Tag) -> Result<String> {
1378 self.country_key(tag, crate::sys::ANVIL_GAME_KEY_CULTURE, "country_culture")
1379 }
1380
1381 pub fn province_religion_group(&self, province: i32) -> Result<String> {
1384 self.province_key(
1385 province,
1386 crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
1387 "province_religion_group",
1388 )
1389 }
1390
1391 pub fn province_culture_group(&self, province: i32) -> Result<String> {
1394 self.province_key(
1395 province,
1396 crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
1397 "province_culture_group",
1398 )
1399 }
1400
1401 pub fn province_area(&self, province: i32) -> Result<String> {
1404 self.province_key(province, crate::sys::ANVIL_GAME_KEY_AREA, "province_area")
1405 }
1406
1407 pub fn province_region(&self, province: i32) -> Result<String> {
1410 self.province_key(
1411 province,
1412 crate::sys::ANVIL_GAME_KEY_REGION,
1413 "province_region",
1414 )
1415 }
1416
1417 pub fn province_superregion(&self, province: i32) -> Result<String> {
1420 self.province_key(
1421 province,
1422 crate::sys::ANVIL_GAME_KEY_SUPERREGION,
1423 "province_superregion",
1424 )
1425 }
1426
1427 pub fn province_continent(&self, province: i32) -> Result<String> {
1430 self.province_key(
1431 province,
1432 crate::sys::ANVIL_GAME_KEY_CONTINENT,
1433 "province_continent",
1434 )
1435 }
1436
1437 pub fn province_trade_node(&self, province: i32) -> Result<String> {
1440 self.province_key(
1441 province,
1442 crate::sys::ANVIL_GAME_KEY_TRADE_NODE,
1443 "province_trade_node",
1444 )
1445 }
1446
1447 pub fn country_religion_group(&self, tag: Tag) -> Result<String> {
1450 self.country_key(
1451 tag,
1452 crate::sys::ANVIL_GAME_KEY_RELIGION_GROUP,
1453 "country_religion_group",
1454 )
1455 }
1456
1457 pub fn country_culture_group(&self, tag: Tag) -> Result<String> {
1460 self.country_key(
1461 tag,
1462 crate::sys::ANVIL_GAME_KEY_CULTURE_GROUP,
1463 "country_culture_group",
1464 )
1465 }
1466}
1467
1468fn timed_list(
1469 context: impl Fn() -> String,
1470 call: impl FnMut(*mut AnvilGameTimedModifier, u32, *mut u32) -> crate::sys::AnvilResult,
1471) -> Result<Vec<AnvilGameTimedModifier>> {
1472 let empty: AnvilGameTimedModifier = unsafe { std::mem::zeroed() };
1474 read_list(empty, context, call)
1475}
1476
1477fn timed_modifiers(
1480 raw: &[AnvilGameTimedModifier],
1481 keys: &str,
1482 context: impl Fn() -> String,
1483) -> Result<Vec<TimedModifier>> {
1484 let keys = split_names(keys);
1485 if keys.len() != raw.len() {
1486 return Err(Error::new(ErrorCode::Internal, context()));
1487 }
1488 Ok(raw
1489 .iter()
1490 .zip(keys)
1491 .map(|(m, key)| TimedModifier {
1492 key,
1493 hidden: m.flags & ANVIL_GAME_TIMED_HIDDEN != 0,
1494 ruler: m.flags & ANVIL_GAME_TIMED_RULER != 0,
1495 start: (m.flags & ANVIL_GAME_TIMED_NO_START == 0).then(|| Date::from_raw(&m.start)),
1496 end: (m.flags & ANVIL_GAME_TIMED_NO_END == 0).then(|| Date::from_raw(&m.end)),
1497 })
1498 .collect())
1499}
1500
1501fn split_names(all: &str) -> Vec<String> {
1503 all.split_terminator('\0').map(str::to_owned).collect()
1504}
1505
1506fn flags(
1507 context: impl Fn() -> String,
1508 call: impl FnMut(*mut AnvilGameFlag, u32, *mut u32) -> crate::sys::AnvilResult,
1509) -> Result<Vec<Flag>> {
1510 let empty = AnvilGameFlag {
1511 id: 0,
1512 reserved: 0,
1513 date: AnvilGameDate {
1514 size: 0,
1515 year: 0,
1516 month: 0,
1517 day: 0,
1518 session: 0,
1519 },
1520 };
1521 let raw = read_list(empty, context, call)?;
1522 Ok(raw
1523 .iter()
1524 .map(|f| Flag {
1525 id: FlagId(f.id),
1526 date: Date::from_raw(&f.date),
1527 })
1528 .collect())
1529}