unbanished_game/people/life.rs
1//! The lives of citizens and their homes: needs, age, death, health, happiness, disease, homes,
2//! partners and births. See [Citizens](https://tanepiper.github.io/unbanished/topics/citizens),
3//! docs/CITIZEN-NEEDS-AND-HOUSEHOLDS.md and docs/CITIZEN-LIFE.md.
4//!
5//! The citizen description is kept as a table by offset, so the port reads the same values as
6//! the original.
7//!
8//! Deviations: the entity references the original keeps (home, partner, guardian, dependents)
9//! are citizen and entity indices; the dependents' ring is a vector in ring order.
10//!
11//! Original: `CitizenComponent` (vtable `0x1401689a0`), `ResidenceComponent` (vtable
12//! `0x14016a6a0`); disease spread `FUN_140117940`.
13mod update;
14
15mod death;
16mod health;
17mod households;
18mod services;
19pub use health::{
20 happiness_after, health_after, home_bonus, immunity_after, outbreak_check, recovers,
21 spread_target,
22};
23pub use households::{update_home, warm_at};
24
25// The CitizenDescription is at citizen +0x288.
26
27use std::collections::BTreeMap;
28
29use unbanished_formats::game::{CitizenDescription, Disease, ResidenceDescription};
30
31use crate::behaviour::activities::TownView;
32use crate::behaviour::agents::CitizenState;
33use crate::pathfind::WALKABLE;
34use crate::people::citizens::Citizen;
35use crate::random::Random;
36use crate::scheduler::{seconds, ticks};
37use crate::work::stock::{RawMaterial, Storage};
38
39/// `DAT_140178934`: the game's "minute" (most description times are in these units).
40const MINUTE: f32 = 300.0;
41/// `DAT_14017895c`.
42const HOUR: f32 = 3600.0;
43
44/// The CitizenDescription values, by offset.
45#[derive(Debug, Clone, Default)]
46pub struct LifeRules {
47 fields: BTreeMap<u32, f32>,
48 ints: BTreeMap<u32, i32>,
49 // D+0x20; D+0x28; D+0x30
50 /// `D`, `D`, `D`: the teacher's, priest's and doctor's professions (the workplaces whose
51 /// attendance a citizen joins), as profession indices.
52 pub services: [Option<usize>; 3],
53}
54
55// D+0x20/+0x28/+0x30
56/// Which service an attendance search is for (`D/`).
57pub mod service {
58 /// A school.
59 pub const SCHOOL: usize = 0;
60 /// A chapel.
61 pub const CHAPEL: usize = 1;
62 /// A doctor.
63 pub const DOCTOR: usize = 2;
64}
65
66impl LifeRules {
67 /// The rules from the citizen description.
68 pub fn new(d: &CitizenDescription) -> LifeRules {
69 let mut r = LifeRules::default();
70 // Constructor values (`FUN_14011a340`) of the fields the resource does not store:
71 // illness length `+0x94` / `+0x98` and immunity `+0x9c`, in minutes.
72 for (o, v) in [(0x94, 1.0), (0x98, 0.5), (0x9c, 12.0)] {
73 r.fields.insert(o, v);
74 r.ints.insert(o, v as i32);
75 }
76 for &o in d.fields.keys() {
77 r.fields.insert(o, d.f(o));
78 r.ints.insert(o, d.i(o));
79 }
80 r
81 }
82
83 /// Rules from description values by offset, for tests and tools.
84 pub fn from_values(values: &[(u32, f32)]) -> LifeRules {
85 let mut r = LifeRules::default();
86 for &(o, v) in values {
87 r.fields.insert(o, v);
88 r.ints.insert(o, v as i32);
89 }
90 r
91 }
92
93 /// The float at `D + o`.
94 pub fn f(&self, o: u32) -> f32 {
95 self.fields.get(&o).copied().unwrap_or(0.0)
96 }
97
98 /// The integer at `D + o`.
99 pub fn i(&self, o: u32) -> i32 {
100 self.ints.get(&o).copied().unwrap_or(0)
101 }
102
103 /// The age at which a child becomes an adult.
104 pub fn adult_age(&self) -> f32 {
105 self.f(0x44)
106 }
107
108 /// `(D[0xd0] − D[0xcc]) · ½ + D[0xcc]`: hungry enough for the status icon and a health event.
109 pub fn hunger_warning(&self) -> f32 {
110 (self.f(0xd0) - self.f(0xcc)) * 0.5 + self.f(0xcc)
111 }
112
113 /// `(D[0xf0] − D[0xec]) · ¼ + D[0xec]`.
114 pub fn cold_warning(&self) -> f32 {
115 (self.f(0xf0) - self.f(0xec)) * 0.25 + self.f(0xec)
116 }
117}
118
119/// The causes of death and the life events, as the event log's types.
120///
121/// Original: the reasons of `FUN_14011c2a0`.
122pub mod reason {
123 /// Starved.
124 pub const STARVED: i32 = 0;
125 /// Froze.
126 pub const FROZE: i32 = 1;
127 /// Died of old age.
128 pub const OLD_AGE: i32 = 2;
129 /// Died of disease.
130 pub const DISEASE: i32 = 3;
131 /// A child whose single guardian died.
132 ///
133 /// Original: `FUN_140119170`.
134 pub const ORPHANED: i32 = 4;
135 /// Killed by a tornado.
136 ///
137 /// Original: `FUN_140058d20`.
138 pub const TORNADO: i32 = 5;
139 /// Died in childbirth.
140 pub const CHILDBIRTH: i32 = 6;
141 // +0x1f8
142 /// Citizen: an accident (fire, tornado) named by its description.
143 pub const ACCIDENT: i32 = 7;
144 /// Was born.
145 pub const BORN: i32 = 8;
146 /// Became an adult.
147 pub const ADULT: i32 = 9;
148 /// Became a student.
149 pub const STUDENT: i32 = 10;
150 /// A laborer took the dead citizen's profession.
151 ///
152 /// Original: `FUN_140119170`.
153 pub const REPLACED: i32 = 0xf;
154 /// No laborer took the dead citizen's profession.
155 pub const NOT_REPLACED: i32 = 0x10;
156}
157
158/// An event the citizens' update asks the log for.
159///
160/// Original: `FUN_140118fc0`.
161#[derive(Debug, Clone, PartialEq)]
162pub struct LifeEvent {
163 /// The event type.
164 pub kind: i32,
165 /// How important the event is.
166 pub severity: i32,
167 /// The citizen.
168 pub citizen: usize,
169 /// `@4`: a disease's or accident's name (string-table key and table).
170 pub extra: Option<(Option<String>, String)>,
171}
172
173/// ResidenceComponent: the family slots and the fire.
174#[derive(Debug, Clone, PartialEq)]
175pub struct Home {
176 /// The residence description.
177 pub desc: ResidenceDescription,
178 /// The site's StorageComponent.
179 pub storage: usize,
180 // +0x50
181 /// The residents of each family slot, sorted as the original sorts them.
182 ///
183 /// Original: sorted by `FUN_14012f2f0`.
184 pub families: Vec<Vec<usize>>,
185 // +0x48
186 /// Time the last firewood keeps burning.
187 pub fuel: i64,
188 /// The StatusIconComponent bits the residence sets: 6 no food, 7 no firewood.
189 pub status: u32,
190}
191
192impl Home {
193 /// A home with its description and its storage.
194 pub fn new(desc: ResidenceDescription, storage: usize) -> Home {
195 Home {
196 desc,
197 storage,
198 families: vec![Vec::new(); desc.families.max(1) as usize],
199 fuel: 0,
200 status: 0,
201 }
202 }
203
204 /// The number of residents.
205 ///
206 /// Original: `FUN_14012f4c0`.
207 pub fn occupants(&self) -> usize {
208 self.families.iter().map(Vec::len).sum()
209 }
210
211 // +0x24
212 /// Family `slot` has at least residents.
213 ///
214 /// Original: `FUN_14012f9c0`.
215 pub fn full(&self, slot: usize) -> bool {
216 self.families
217 .get(slot)
218 .is_some_and(|f| f.len() as i32 >= self.desc.family_size)
219 }
220
221 /// Warm enough outside, or the fire is burning.
222 ///
223 /// Original: `FUN_140130100`.
224 pub fn warm(&self, temperature: f32) -> bool {
225 self.desc.warm_temperature <= temperature || self.fuel > 0
226 }
227
228 /// The number of families with residents.
229 ///
230 /// Original: counted by `FUN_14011abb0` and `FUN_14011acc0`.
231 pub fn families_living(&self) -> i32 {
232 self.families.iter().filter(|f| !f.is_empty()).count() as i32
233 }
234}
235
236/// The units of a category in `storage` that nobody has reserved: food (bit 5) or firewood
237/// (bit 6).
238///
239/// Original: `FUN_14012fea0` (food), `FUN_14012ffd0` (firewood).
240pub fn stored(storage: &Storage, materials: &[RawMaterial], bit: u32) -> i32 {
241 storage
242 .items
243 .iter()
244 .filter(|i| materials[i.material].flags >> bit & 1 != 0)
245 .map(|i| i.count - i.reserved)
246 .sum()
247}
248
249/// `FUN_14012fbe0`'s sort (`FUN_14012f2f0`): citizens without a guardian first, then by sex.
250pub(crate) fn family_order(citizens: &[Citizen], a: usize, b: usize) -> std::cmp::Ordering {
251 let key = |c: usize| {
252 let c = &citizens[c];
253 (c.parent.is_some() as u32) << 12 | (c.male as u32) << 8
254 };
255 key(a).cmp(&key(b))
256}
257
258/// Everything one citizen's update touches.
259pub struct People<'a, 'b> {
260 /// The citizens.
261 pub citizens: &'a mut Vec<Citizen>,
262 /// The citizens' states.
263 pub states: &'a mut Vec<CitizenState>,
264 // +0xa0
265 /// The living citizens, in activation order.
266 pub registry: &'a mut Vec<usize>,
267 /// The homes, by entity.
268 pub homes: &'a mut BTreeMap<usize, Home>,
269 /// The citizen description's rules.
270 pub rules: &'a LifeRules,
271 /// A view of the town.
272 pub town: &'a TownView<'b>,
273 // +0x1c..+0x27
274 /// Map cells ([`crate::nature::seeding::Cells::layers`]).
275 pub layers: &'a [[u8; 12]],
276 /// The game's random numbers.
277 pub rng: &'a mut Random,
278 /// The environment's temperature.
279 pub temperature: f32,
280 /// The diseases.
281 pub diseases: &'a [Disease],
282 // +0x1a8
283 /// The extra disease risk that visitors bring (0 until they are ported).
284 pub town_disease: f32,
285 /// The town's storages.
286 pub storages: &'a mut [Storage],
287 /// The raw materials.
288 pub materials: &'a [RawMaterial],
289 /// The character's action stack is empty (`stack_top + 1 < 1`).
290 pub idle: &'a [bool],
291 /// The log events asked for.
292 pub events: &'a mut Vec<LifeEvent>,
293 /// Citizens whose entity was queued for deletion, with the reason.
294 ///
295 /// Original: `FUN_1400c8370`.
296 pub dying: &'a mut Vec<(usize, i32)>,
297 /// Makes a child of `mother`: name, sex, appearance and lifespan, with their random draws.
298 /// The caller of this closure adds it to `citizens`.
299 ///
300 /// Original: `FUN_14011c550`, called from `FUN_140117060`.
301 pub newborn: &'a mut dyn FnMut(&mut Random, &Citizen, bool) -> Citizen,
302 // (the flag is the child's sex, `true` male)
303 /// Children born this update (new citizen indices).
304 pub born: &'a mut Vec<usize>,
305 // +0x60
306 /// The AttendanceComponents, by entity.
307 pub attendance: &'a mut BTreeMap<usize, crate::work::construction::Attendance>,
308 /// The service buildings that people attend.
309 pub attendance_list: &'a [usize],
310 // +0x100; +0x20
311 /// The workplaces and residences.
312 pub workforce: &'a mut crate::work::professions::Workforce,
313 /// The professions.
314 pub professions: &'a crate::work::professions::Professions,
315 /// The sites (their works' priorities, a cemetery's graves).
316 pub sites: &'a BTreeMap<usize, crate::work::construction::Site>,
317 // +0x40
318 /// The town's cemeteries.
319 pub cemeteries: &'a [usize],
320 /// The tombstones standing, with the time each one stays.
321 pub tombstones: &'a BTreeMap<usize, i64>,
322 /// Burials decided this update (cemetery, grave cell, the tombstone's lifetime); the
323 /// tombstones follow.
324 pub burials: &'a mut Vec<(usize, i32, i64)>,
325 /// The site templates (a cemetery's tombstone description).
326 pub site_templates: &'a [crate::work::construction::SiteTemplate],
327 /// The path-rank cache.
328 pub sectors: &'a mut crate::sectors::SectorGraph,
329 /// The ground's heights.
330 pub terrain: &'a crate::terrain::HeightGrid<'b>,
331 // Game +0x88
332 /// The characters' tree (`Game`): a disease spreads to the citizens about the sick.
333 pub tree: &'a crate::behaviour::character_tree::CharacterTree,
334}
335
336impl People<'_, '_> {
337 fn cell(&self, c: usize) -> i32 {
338 self.town.cell_of(self.citizens[c].position)
339 }
340
341 fn dying(&self, c: usize) -> bool {
342 self.dying.iter().any(|&(d, _)| d == c)
343 }
344
345 /// `FUN_140118fc0`: a log entry naming the citizen and its role.
346 fn report(
347 &mut self,
348 c: usize,
349 kind: i32,
350 severity: i32,
351 extra: Option<(Option<String>, String)>,
352 ) {
353 self.events.push(LifeEvent {
354 kind,
355 severity,
356 citizen: c,
357 extra,
358 });
359 }
360
361 /// The home's entrance is reachable from the citizen's cell.
362 ///
363 /// Original: `FUN_14011ada0`.
364 pub fn reaches(&mut self, c: usize, entity: usize) -> bool {
365 let cell = self.cell(c);
366 self.town.can_reach(cell, entity, self.rng)
367 }
368}
369
370// +0xc
371/// Citizen message 2: eat from `storage` until the citizen is no longer hungry: one unit of food
372/// per point of hunger. Each kind of food is remembered (for variety) and counts as used.
373///
374/// Original: `FUN_14011a7b0`, `FUN_14008e460`.
375pub fn eat(
376 s: &mut CitizenState,
377 storage: &mut Storage,
378 materials: &[RawMaterial],
379 rng: &mut Random,
380 counters: &mut crate::work::tracker::StockCounters,
381) {
382 while 0.0 < s.hunger {
383 let Some(m) = storage.find_item(materials, 0, rng) else {
384 return;
385 };
386 s.flags |= 0x10000;
387 if !s.foods.contains(&m) {
388 s.foods.push(m);
389 }
390 storage.remove(m, 1);
391 let flags = materials[m].flags;
392 if let Some(slot) = crate::work::produce::production_group(flags) {
393 counters.used[slot] += 1;
394 }
395 if s.health_events & 8 == 0 {
396 s.health_events = s.health_events & 0xfffffe8f | 8;
397 }
398 for (bit, event) in [(0, 0x10), (1, 0x20), (2, 0x40), (4, 0x100)] {
399 if flags >> bit & 1 != 0 {
400 s.health_events |= event;
401 }
402 }
403 s.hunger -= 1.0;
404 if s.hunger < 0.0 {
405 s.hunger = 0.0;
406 return;
407 }
408 }
409}