Skip to main content

unbanished_game/people/
immigration.rs

1//! Immigration: ImmigrationComponent (the town hall) and the nomads it calls (NomadComponent). See
2//! docs/IMMIGRATION.md.
3//!
4//! Once the town is big enough and has its market and trading post, the town hall now and then (in
5//! spring) calls a band of nomads from a map edge. They walk to it and wait; the player takes them
6//! in (they become citizens, in families of four, bringing a disease risk) or they leave, at the
7//! latest in the summer.
8//!
9//! Original: `FUN_14004f020`, `FUN_1400507d0`.
10mod nomads;
11
12// vtable 0x14015fc50; vtable 0x140160140
13
14use unbanished_formats::game::CharacterDescription;
15
16use crate::behaviour::character::{Action, Character, MoveTo};
17use crate::scheduler::ticks;
18use crate::town::Sim;
19use crate::work::construction::Callbacks;
20
21/// `DAT_140178934`.
22const PERIOD: f32 = 300.0;
23/// Event type 14: nomads arrived.
24const ARRIVED: i32 = 0xe;
25/// `Map::Reachable` mask of the edge search.
26const MASK: u32 = 0xe07;
27
28/// A resolved ImmigrationDescription.
29///
30/// Original: `FUN_14004f150`, `FUN_14004f300`.
31#[derive(Debug, Clone, Default, PartialEq)]
32pub struct ImmigrationTemplate {
33    // +0x20
34    /// The nomad template.
35    pub nomad: usize,
36    // +0x28
37    /// The population the town needs.
38    pub population: i32,
39    // +0x30
40    /// Templates the town must have placed (Market, TradingPost).
41    pub required: Vec<usize>,
42    // +0x40, +0x44
43    /// The band's size as a share of the population.
44    pub share: (f32, f32),
45    // +0x48, +0x4c; +0x48 + RandFloat × +0x4c
46    /// Months until the next band: the first value plus a random share of the second.
47    pub wait: (f32, f32),
48    // +0x50, +0x54
49    /// The months a band may come in.
50    pub months: (i32, i32),
51    // +0x58
52    /// From this month waiting nomads leave (not serialized; 7).
53    pub leave: i32,
54    // +0x5c
55    /// Their map-edge margin (not serialized; 10).
56    pub margin: i32,
57    // +0x60, +0x64
58    /// The visitors' disease risk.
59    pub risk: f32,
60    /// How many months the risk lasts.
61    pub risk_months: i32,
62}
63
64// +0x48; +0x50; +0x58
65/// ImmigrationComponent: until a band may come, the nomads arrived, the band.
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct Immigration {
68    /// The time until a band may come.
69    pub timer: i64,
70    /// The nomads that arrived.
71    pub arrived: i32,
72    /// The band.
73    pub nomads: Vec<usize>,
74}
75
76// +0x20; +0x28; +0x30
77/// A nomad description: the citizen template nomads become, the men's and women's material
78/// (for presentation: `StartingTown::nomad_materials`), and the character description.
79///
80/// Original: `FUN_140050880`.
81#[derive(Debug, Clone)]
82pub struct NomadKind {
83    /// The character description.
84    pub character: CharacterDescription,
85}
86
87// +0x28; +0x30; +0x3c; +0x48; +0x50
88/// NomadComponent: its state (0 walking to the town hall, 1 waiting, 2 leaving), the town hall,
89/// where it came from, where it waits, until it wanders, its model variant (0 men, 1 women).
90pub struct Nomad {
91    /// The template.
92    pub template: usize,
93    /// The character.
94    pub character: Character,
95    /// The state: 0 walking to the town hall, 1 waiting, 2 leaving.
96    pub state: i8,
97    /// The town hall.
98    pub town_hall: Option<usize>,
99    /// Where it came from.
100    pub spawn: [f32; 3],
101    /// Where it waits.
102    pub target: [f32; 3],
103    /// The time until it wanders.
104    pub timer: i64,
105    /// The model variant: 0 men, 1 women.
106    pub variant: usize,
107}
108
109impl Sim<'_, '_> {
110    fn immigration_desc(&self, e: usize) -> Option<&ImmigrationTemplate> {
111        self.site_templates[self.sites.get(&e)?.template]
112            .immigration
113            .as_ref()
114    }
115
116    fn immigration(&mut self, e: usize) -> Option<&mut Immigration> {
117        self.sites.get_mut(&e)?.immigration.as_mut()
118    }
119
120    /// The calendar's month (`seconds / 3600 × 12`, past 11 is 0).
121    fn calendar_month(&self) -> i32 {
122        let m = (self.calendar / 3600.0 * 12.0) as i32;
123        if 11 < m {
124            0
125        } else {
126            m
127        }
128    }
129
130    /// `FUN_14004ed50`: the town has its population and a placed entity of every required
131    /// template (the town manager's zones by template, `+0x160`).
132    fn immigration_wanted(&self, e: usize) -> bool {
133        let Some(d) = self.immigration_desc(e) else {
134            return false;
135        };
136        if self.population < d.population {
137            return false;
138        }
139        d.required.iter().all(|&t| {
140            self.sites.iter().any(|(&s, site)| {
141                !site.destroyed && self.placed[s].alive && self.placed[s].template == t
142            })
143        })
144    }
145
146    /// State 2 enter and update (`FUN_14004dbf0`, `FUN_14004db80`).
147    pub(crate) fn immigration_idle(&mut self, e: usize) {
148        if self.immigration_wanted(e) {
149            self.machine(e).request(0xf);
150        }
151    }
152
153    /// State 0xf enter (`FUN_14004db00`): `(+0x48 + RandFloat × +0x4c)` × 300 s.
154    pub(crate) fn immigration_wait(&mut self, e: usize) {
155        let Some(d) = self.immigration_desc(e).cloned() else {
156            return;
157        };
158        let f = self.rng.rand_float();
159        let t = ticks((f * d.wait.1 + d.wait.0) * PERIOD);
160        if let Some(i) = self.immigration(e) {
161            i.timer = t;
162        }
163    }
164
165    /// State 0xf update (`FUN_14004da30`): when the wait is over, in the season, a band comes
166    /// (0x10) or the town no longer qualifies (2).
167    pub(crate) fn immigration_waiting(&mut self, e: usize, dt: i64) {
168        let Some(d) = self.immigration_desc(e).cloned() else {
169            return;
170        };
171        let Some(i) = self.immigration(e) else { return };
172        i.timer -= dt;
173        let due = i.timer < 1;
174        let month = self.calendar_month();
175        if due && d.months.0 <= month && month <= d.months.1 {
176            let next = if self.immigration_wanted(e) { 0x10 } else { 2 };
177            self.machine(e).request(next);
178        }
179    }
180
181    /// State 0x10 enter (`FUN_14004d9f0`) and update (`FUN_14004d9d0`): a new band (again
182    /// while none could be placed).
183    pub(crate) fn immigration_call(&mut self, e: usize, enter: bool) {
184        if enter {
185            if let Some(i) = self.immigration(e) {
186                i.arrived = 0;
187                i.nomads.clear();
188            }
189        } else if !self.immigration(e).is_some_and(|i| i.nomads.is_empty()) {
190            return;
191        }
192        self.spawn_band(e);
193    }
194
195    /// `FUN_14004ebd0(x, y, target)`: up to 50 cells within the margin of `(x, y)` that are
196    /// walkable and either by water or in the target's region.
197    fn edge(&mut self, d: &ImmigrationTemplate, x: i32, y: i32, target: i32) -> Option<i32> {
198        let n = self.size as i32;
199        for _ in 0..50 {
200            let cx = (x + self.rng.rand_tol(d.margin)).clamp(0, n - 1);
201            let cy = (y + self.rng.rand_tol(d.margin)).clamp(0, n - 1);
202            let cell = cy * n + cx;
203            let a = 1u32 << (self.cells.types[cell as usize].0 & 0x1f);
204            if a & MASK == 0 {
205                continue;
206            }
207            let b = 1u32 << (self.cells.types[target as usize].0 & 0x1f);
208            if (a | b) & 0x1e0 != 0 {
209                return Some(cell);
210            }
211            let (ra, rb) = (self.regions[cell as usize], self.regions[target as usize]);
212            if ra != 0 && ra == rb {
213                return Some(cell);
214            }
215        }
216        None
217    }
218
219    /// `FUN_14004e540`: a band from a random map edge (ten tries at a reachable cell): `Rand(2 ×
220    /// empty family slots) + population × share`, at least two, each walking from near that
221    /// edge to one of the town hall's create points.
222    fn spawn_band(&mut self, e: usize) {
223        let Some(d) = self.immigration_desc(e).cloned() else {
224            return;
225        };
226        let n = self.size as i32;
227        let target = self.cell_of(self.use_point(e, 0).0);
228        let mut tries = 0;
229        let (x, y, start) = loop {
230            let side = self.rng.rand_below(4);
231            let (x, y) = if side < 2 {
232                let x = if side == 0 {
233                    d.margin
234                } else {
235                    n - d.margin - 1
236                };
237                (x, self.rng.rand_below(n as u32) as i32)
238            } else {
239                let x = self.rng.rand_below(n as u32) as i32;
240                (
241                    x,
242                    if side == 2 {
243                        d.margin
244                    } else {
245                        n - d.margin - 1
246                    },
247                )
248            };
249            if let Some(start) = self.edge(&d, x, y, target) {
250                break (x, y, start);
251            }
252            tries += 1;
253            if 9 < tries {
254                return;
255            }
256        };
257        let population = self.population;
258        let f = self.rng.rand_float();
259        let free: i32 = self
260            .workforce
261            .residences
262            .iter()
263            .filter_map(|r| self.homes.get(r))
264            .map(|h| h.families.iter().filter(|f| f.is_empty()).count() as i32)
265            .sum();
266        let mut count = self.rng.rand_below((free * 2) as u32) as i32
267            + (population as f32 * (f * (d.share.1 - d.share.0) + d.share.0)) as i32;
268        if count < 2 {
269            count = 2;
270        }
271        let points: usize = self
272            .interact_entities(e)
273            .iter()
274            .map(|&x| self.templates[self.placed[x].template].create_points.len())
275            .sum();
276        for _ in 0..count {
277            let cell = self.edge(&d, x, y, target).unwrap_or(start);
278            let k = self.rng.rand_below(points as u32) as usize;
279            let dest = self.create_point(e, k);
280            let ground = self.ground_at(cell);
281            if let Some(id) = self.add_nomad(d.nomad, e, ground, dest) {
282                if let Some(i) = self.immigration(e) {
283                    i.nomads.push(id);
284                }
285            }
286        }
287        if let Some(i) = self.immigration(e) {
288            i.arrived = 0;
289        }
290    }
291
292    /// `FUN_14004dc60`: the band leaves (message 1 to each).
293    pub(crate) fn send_band_away(&mut self, e: usize) {
294        let band = self
295            .immigration(e)
296            .map(|i| std::mem::take(&mut i.nomads))
297            .unwrap_or_default();
298        for id in band {
299            self.nomad_message(id, 1);
300        }
301        if let Some(i) = self.immigration(e) {
302            i.arrived = 0;
303        }
304    }
305
306    /// State 0x11 enter (`FUN_14004d810`): event 14 at severity 2.
307    pub(crate) fn band_arrived(&mut self, e: usize) {
308        self.site_events.push((ARRIVED, 2, e));
309    }
310
311    /// State 0x11 update (`FUN_14004d760`): from the leaving month the band goes.
312    pub(crate) fn band_waiting(&mut self, e: usize) {
313        let Some(d) = self.immigration_desc(e) else {
314            return;
315        };
316        if d.leave <= self.calendar_month() {
317            self.send_band_away(e);
318            self.machine(e).request(2);
319        }
320    }
321
322    /// The ImmigrationComponent's state messages: 6 a nomad arrived (in 0x10); 8 turned away (in
323    /// 0x11). Message 7 (taking them in) needs the citizens:
324    /// `crate::behaviour::agents::Agents::admit_band`.
325    ///
326    /// Original: `FUN_14004d950`, `FUN_14004d680`, `FUN_14004d6f0`.
327    pub fn immigration_message(&mut self, e: usize, msg: i32) {
328        if self.immigration(e).is_none() || self.machine(e).index < 0 {
329            return;
330        }
331        match (self.machine(e).state, msg) {
332            (0x10, 6) => {
333                let i = self.immigration(e).unwrap();
334                i.arrived += 1;
335                if i.arrived == i.nomads.len() as i32 {
336                    self.machine(e).request(0x11);
337                }
338            }
339            (0x11, 8) => {
340                self.send_band_away(e);
341                self.machine(e).request(2);
342            }
343            _ => {}
344        }
345    }
346
347    // +0x60; +0x64
348    /// The visitors' disease risk (the larger of the town's and, for the longer of the town's and
349    /// months) and the band (each nomad and where it stands) for the citizens to be made. `None`
350    /// unless the band is waiting (0x11).
351    ///
352    /// Original: `FUN_14004ddb0` (town side).
353    pub fn take_band(&mut self, e: usize) -> Option<Vec<(usize, [f32; 3])>> {
354        if self.machine(e).index < 0 || self.machine(e).state != 0x11 {
355            return None;
356        }
357        let d = self.immigration_desc(e)?.clone();
358        let band = self.immigration(e)?.nomads.clone();
359        if self.visitors.0 < d.risk {
360            self.visitors.0 = d.risk;
361        }
362        let time = ticks(d.risk_months as f32 * PERIOD);
363        if self.visitors.1 < time {
364            self.visitors.1 = time;
365        }
366        Some(
367            band.iter()
368                .filter_map(|&id| Some((id, self.wildlife.nomads.get(&id)?.character.position)))
369                .collect(),
370        )
371    }
372
373    /// After the citizens are made: each nomad is gone (message 0) and the town hall goes back
374    /// to 2.
375    pub fn band_taken(&mut self, e: usize) {
376        let band = self
377            .immigration(e)
378            .map(|i| std::mem::take(&mut i.nomads))
379            .unwrap_or_default();
380        for id in band {
381            self.nomad_message(id, 0);
382        }
383        if let Some(i) = self.immigration(e) {
384            i.arrived = 0;
385        }
386        self.machine(e).request(2);
387    }
388}