Skip to main content

unbanished_game/people/life/
health.rs

1//! Health, happiness and disease: their update, an outbreak, infection, spreading and recovery.
2
3use super::*;
4
5impl People<'_, '_> {
6    /// Health from the last interval's events, at most the description's maximum. Not ported:
7    /// the debug flag that keeps every citizen's health full.
8    ///
9    /// Original: `FUN_140117e60`.
10    // Game +0xd0 bit 3
11    pub(super) fn health(&mut self, c: usize) {
12        let r = self.rules;
13        let age = self.citizens[c].age;
14        let at_school = self.states[c].school.is_some();
15        let s = &mut self.states[c];
16        s.health = health_after(
17            s.health_events,
18            s.health,
19            age,
20            r.adult_age(),
21            at_school,
22            r.f(0x70),
23        );
24        s.health_events = 0;
25    }
26
27    /// `FUN_140117fb0`: happiness from events, needs, food variety, the home's surroundings
28    /// and the chapel.
29    pub(super) fn happiness(&mut self, c: usize) {
30        let r = self.rules;
31        let home_bonus = self.states[c].home.map(|h| {
32            // The home entrance cell's layers 0..=4 that are nonzero, less layer 5 (the
33            // HappinessComponent radii, `FUN_1400a4e60`), at least 0.
34            let cell = self.town.entrance(h, self.rng);
35            let l = usize::try_from(cell)
36                .ok()
37                .and_then(|i| self.layers.get(i))
38                .copied()
39                .unwrap_or_default();
40            let shared = self.homes.get(&h).is_some_and(|h| h.families.len() > 1);
41            home_bonus(&l, shared)
42        });
43        let s = &mut self.states[c];
44        let foods = s.foods.len() as i32;
45        let (flags, happiness, field_84, priest) =
46            (s.flags, s.happiness, s.field_84, s.priest.is_some());
47        s.happiness = happiness_after(r, flags, happiness, field_84, foods, home_bonus, priest);
48    }
49}
50
51// Map cell +0x1c..+0x20 the five HappinessComponent layers, +0x21 the sixth (FUN_1400a4e60).
52/// The home's bonus to a citizen's happiness: how many of the entrance cell's first five
53/// happiness layers are set, less the sixth, at least 0; a quarter of that (rounded down) when the
54/// home holds more than one family.
55///
56/// Original: `FUN_140117fb0` (its home part).
57pub fn home_bonus(layers: &[u8], shared: bool) -> i32 {
58    let v = (layers[..5].iter().filter(|&&b| b != 0).count() as i32 - layers[5] as i32).max(0);
59    if shared {
60        v >> 2
61    } else {
62        v
63    }
64}
65
66// Citizen +0x80 happiness, +0x88 flags, +0x84, +0xa0 foods, +0x230 priest; D+0xa4 the maximum,
67// +0xa8 and +0xac the food variety, +0xb0 work for happiness.
68/// A citizen's happiness after its events: the events move it at once, then it steps half a
69/// point toward a target made of the needs met, the work, the food variety, the home's bonus and
70/// the chapel, scaled by an eighth of the maximum; it stays within 0 and the maximum.
71///
72/// Measured: `tools/emu/happiness.py` (the original on 2,000 cases).
73///
74/// Original: `FUN_140117fb0`.
75pub fn happiness_after(
76    r: &LifeRules,
77    flags: u32,
78    happiness: f32,
79    field_84: i32,
80    foods: i32,
81    home_bonus: Option<i32>,
82    priest: bool,
83) -> f32 {
84    {
85        let f = flags;
86        let mut h = happiness;
87        if f & 2 != 0 {
88            h -= 8.0;
89        }
90        if f & 0x40 != 0 {
91            h -= 2.0;
92        }
93        if f & 0x80 != 0 {
94            h -= 4.0;
95        }
96        if f & 8 != 0 {
97            h -= 1.0;
98        }
99        if f & 0x10 != 0 {
100            h -= 1.0;
101        }
102        for bit in [8, 9, 10, 11, 12, 13] {
103            if f >> bit & 1 != 0 {
104                h += 1.0;
105            }
106        }
107        if f >> 0x12 & 1 != 0 {
108            h += 0.5;
109        }
110        h = clamp_happiness(h, r.f(0xa4));
111        let mut target = 0.0;
112        if f & 4 == 0 {
113            target += 1.0;
114        }
115        if f & 0x20 == 0 {
116            target += 1.0;
117        }
118        if f & 1 == 0 {
119            target += 1.0;
120        }
121        if f >> 0x11 & 1 != 0 {
122            // Citizen `+0x84` against `_workForHappiness` (`+0xb0`, 10): nothing in 1.0.7
123            // writes `+0x84` (no store in the Application but the zeroed component), so the
124            // original gives the half point every time, as here.
125            target += if field_84 < r.i(0xb0) { 0.5 } else { 1.0 };
126        }
127        if f >> 0x10 & 1 != 0 {
128            if r.i(0xa8) < foods {
129                if r.i(0xac) <= foods {
130                    target += 1.0;
131                }
132            } else {
133                target -= 1.0;
134            }
135        }
136        if let Some(b) = home_bonus {
137            target += b as f32;
138        }
139        if priest {
140            target += 1.0;
141        }
142        let target = target * 0.125 * r.f(0xa4);
143        // The original's tests, in its order (a NaN target takes the step up).
144        if !(target <= h) {
145            h += 0.5;
146        } else if !(h <= target) {
147            // Through a double (`DAT_140178868` is 0.5 as a double).
148            h = (h as f64 - 0.5) as f32;
149        }
150        clamp_happiness(h, r.f(0xa4))
151    }
152}
153
154impl People<'_, '_> {
155    /// The citizen's disease update: the check for an outbreak when healthy
156    /// ([`outbreak_check`]), else the illness running its course and spreading; false when the
157    /// disease kills the citizen.
158    ///
159    /// Original: `FUN_140117ca0`.
160    pub(super) fn disease(&mut self, c: usize, dt: i64) -> bool {
161        let r = self.rules;
162        match self.states[c].disease {
163            None => {
164                let s = &mut self.states[c];
165                let health = s.health;
166                let falls_ill = outbreak_check(
167                    r,
168                    health,
169                    &mut s.immunity,
170                    &mut s.disease_clock,
171                    self.town_disease,
172                    dt,
173                    self.rng,
174                );
175                if falls_ill {
176                    self.outbreak(c);
177                }
178                true
179            }
180            Some(d) => {
181                let s = &mut self.states[c];
182                s.disease_left -= dt;
183                s.spread -= dt;
184                if s.spread < 1 {
185                    self.spread(c);
186                    let interval = self.diseases.get(d).map_or(0.0, |d| d.spread_interval);
187                    self.states[c].spread = ticks(interval * MINUTE);
188                }
189                if self.states[c].disease_left < 1 {
190                    return self.recover(c);
191                }
192                true
193            }
194        }
195    }
196
197    /// `FUN_140117af0`: unless someone is already sick, a disease picked by weight.
198    pub(super) fn outbreak(&mut self, c: usize) {
199        if self
200            .registry
201            .iter()
202            .any(|&i| self.states[i].disease.is_some())
203        {
204            return;
205        }
206        let mut total = 0.0;
207        let cumulative: Vec<f32> = self
208            .diseases
209            .iter()
210            .map(|d| {
211                total += d.weight;
212                total
213            })
214            .collect();
215        let x = self.rng.rand_float() * total;
216        let mut low = 0.0;
217        for (i, &high) in cumulative.iter().enumerate() {
218            if low <= x && x < high {
219                self.infect(c, i);
220                break;
221            }
222            low = high;
223        }
224    }
225
226    /// `FUN_14011c060`: catch disease `d` (not while immune, nor at work in a profession
227    /// with `+0x4d`, the doctor). The outbreak event asks AutoSlow through the event log.
228    pub(super) fn infect(&mut self, c: usize, d: usize) {
229        let s = &self.states[c];
230        if s.disease.is_some() || 0 < s.immunity {
231            return;
232        }
233        let at_work = s.workplace.is_some()
234            && self
235                .professions
236                .list
237                .get(s.profession)
238                .is_some_and(|p| p.immune_at_work);
239        if at_work {
240            return;
241        }
242        let first = !self
243            .registry
244            .iter()
245            .any(|&i| self.states[i].disease.is_some());
246        if first {
247            let extra = self
248                .diseases
249                .get(d)
250                .map(|d| (d.table.clone(), d.name.clone()));
251            self.report(c, 0xb, 3, extra);
252        }
253        let r = self.rules;
254        let x = self.rng.rand_float_tol();
255        let s = &mut self.states[c];
256        s.disease = Some(d);
257        s.sick = true;
258        s.disease_left = ticks((x * r.f(0x98) + r.f(0x94)) * MINUTE);
259        s.spread = ticks(self.diseases.get(d).map_or(0.0, |d| d.spread_interval) * MINUTE);
260        self.join_service(c, service::DOCTOR, None);
261    }
262
263    // Only one: after the call to FUN_14011c060 (0x140117aae) the loop exits.
264    /// With the disease's odds, the first other citizen within its radius of the sick one (in the
265    /// characters' tree's order) who is not sick is offered it. That citizen may still turn it
266    /// away (immune, or a doctor at work). Nobody further in the list is tried.
267    ///
268    /// Original: `FUN_140117940` (the tree query is `FUN_140097e60` with the CitizenComponent
269    /// type; the offer is `FUN_14011c060`).
270    pub(super) fn spread(&mut self, c: usize) {
271        let Some(d) = self.states[c].disease else {
272            return;
273        };
274        let Some(disease) = self.diseases.get(d).cloned() else {
275            return;
276        };
277        // The draw comes before the tree is asked.
278        let x = self.rng.rand_float();
279        if disease.spread_chance < x {
280            return;
281        }
282        let p = self.citizens[c].position;
283        let near: Vec<usize> = self
284            .tree
285            .within(p, disease.spread_radius, |w| {
286                matches!(w, crate::behaviour::character_tree::Who::Citizen(_))
287            })
288            .into_iter()
289            .filter_map(|w| match w {
290                crate::behaviour::character_tree::Who::Citizen(i) if i != c => Some(i),
291                _ => None,
292            })
293            .collect();
294        let listed: Vec<(bool, bool)> = near
295            .iter()
296            .map(|&i| {
297                (
298                    false,
299                    self.states.get(i).is_none_or(|s| s.disease.is_some()),
300                )
301            })
302            .collect();
303        if let Some(k) = spread_target(&listed) {
304            self.infect(near[k], d);
305        }
306    }
307
308    /// `FUN_140117880`: when the illness ends, recover (immune for `D[0x9c]` minutes) or die.
309    pub(super) fn recover(&mut self, c: usize) -> bool {
310        let r = self.rules;
311        let s = &self.states[c];
312        let recovery = s
313            .disease
314            .and_then(|d| self.diseases.get(d))
315            .map_or(1.0, |d| d.recovery);
316        let lives = recovers(r, recovery, s.doctor.is_some(), self.rng);
317        if lives {
318            let s = &mut self.states[c];
319            s.spread = 0;
320            s.immunity = immunity_after(r);
321            s.disease = None;
322            s.sick = false;
323        }
324        // `FUN_14011ae80`: leave the doctor.
325        self.leave_service(c, service::DOCTOR, false);
326        lives
327    }
328}
329
330// The weakness is 1 − health / D+0x70; the odds mix D+0x7c..+0x90 by it and by the town's disease.
331/// The disease check of a citizen with no disease: the immunity runs down by `dt`, and the odds
332/// come from the citizen's weakness and the town's disease. With odds of 0 or less the clock is
333/// cleared and nothing is drawn. Otherwise one `RandFloat` against the time on the clock over the
334/// odds' span, and the clock is cleared. True when the citizen falls ill (the caller starts the
335/// outbreak).
336///
337/// Measured: `tools/emu/disease_check.py` (2,000 cases; the original draws exactly when the
338/// odds are above 0).
339///
340/// Original: `FUN_140117ca0` (its first branch).
341pub fn outbreak_check(
342    r: &LifeRules,
343    health: f32,
344    immunity: &mut i64,
345    clock: &mut i64,
346    town_disease: f32,
347    dt: i64,
348    rng: &mut Random,
349) -> bool {
350    // CitizenComponent +0x70.
351    *immunity = (*immunity - dt).max(0);
352    let weak = 1.0 - health / r.f(0x70);
353    let a = (r.f(0x84) - r.f(0x7c)) * weak + r.f(0x7c);
354    let b = (r.f(0x88) - r.f(0x80)) * weak + r.f(0x80);
355    let a = (r.f(0x8c) - a) * town_disease + a;
356    let b = (r.f(0x90) - b) * town_disease + b;
357    // CitizenComponent +0x60: odds of 0 or less clear the clock and return before the draw.
358    if b <= 0.0 {
359        *clock = 0;
360        return false;
361    }
362    let elapsed = *clock;
363    *clock = 0;
364    let span = a * 12.0 * MINUTE * b;
365    rng.rand_float() < seconds(elapsed) / span
366}
367
368// Doctor: citizen +0x228; the doctor's factor is D+0x128; the disease's recovery is +0x40.
369/// Whether a citizen whose illness has ended recovers: one `RandFloat` drawn first, then the
370/// citizen lives when one over the disease's recovery, over the doctor's factor (1 without a
371/// doctor), is below it.
372///
373/// Measured: `tools/emu/recovery.py` (the original on 2,000 cases).
374///
375/// Original: `FUN_140117880`.
376// jb at 0x1401178d3: a NaN odds recovers.
377#[allow(clippy::neg_cmp_op_on_partial_ord)]
378pub fn recovers(r: &LifeRules, recovery: f32, doctor: bool, rng: &mut Random) -> bool {
379    let x = rng.rand_float();
380    let factor = if doctor { r.f(0x128) } else { 1.0 };
381    !(x <= 1.0 / recovery / factor)
382}
383
384// D+0x9c, written to citizen +0x70.
385/// The immunity a citizen has after recovering: `D[0x9c]` × 300 s.
386///
387/// Original: `FUN_140117880`.
388pub fn immunity_after(r: &LifeRules) -> i64 {
389    ticks(r.f(0x9c) * MINUTE)
390}
391
392/// Which of the citizens near a sick one is offered the disease, from the characters' tree's
393/// list in its order: each entry is (the sick citizen itself, has a disease). The first that is
394/// neither, or none. Only one is ever offered, even when it then turns the disease away.
395///
396/// Measured: `tools/emu/disease_spread.py` (the original on 2,000 lists).
397///
398/// Original: `FUN_140117940`.
399pub fn spread_target(listed: &[(bool, bool)]) -> Option<usize> {
400    listed.iter().position(|&(own, sick)| !own && !sick)
401}
402
403/// Happiness kept in `0..=max` the original's way: below 0 becomes 0 (negative zero and NaN stay),
404/// then above `max` becomes `max`.
405///
406/// Original: `FUN_140117fb0`.
407fn clamp_happiness(h: f32, max: f32) -> f32 {
408    let h = if h < 0.0 { 0.0 } else { h };
409    if max < h {
410        max
411    } else {
412        h
413    }
414}
415
416// Citizen +0x50 health, +0x54 the interval's events, +0x3c age, +0x208 school; D+0x44 adult
417// age, D+0x70 the maximum.
418/// A citizen's health after an interval's events: up 0.5 for a good interval, down for a poor
419/// one, down 1 for each of the two worst events, down 0.25 for an adult not at school with no
420/// work done; then no lower than 0 and no higher than the maximum.
421///
422/// Measured: `tools/emu/health.py` (the original on 2,000 cases, NaN ages and healths among
423/// them).
424///
425/// Original: `FUN_140117e60`.
426pub fn health_after(
427    e: u32,
428    health: f32,
429    age: f32,
430    adult_age: f32,
431    at_school: bool,
432    max: f32,
433) -> f32 {
434    let mut health = health;
435    let mut n = (e >> 8 & 1) + (e >> 6 & 1) + (e >> 5 & 1) + (e >> 4 & 1);
436    if e & 0x200 != 0 {
437        n += 1;
438    }
439    if e & 8 != 0 && e & 4 != 0 && 3 < n {
440        health += 0.5;
441    }
442    if e & 8 != 0 && e & 0x200 == 0 && n < 3 {
443        health -= 1.0 - n as f32 / 3.0;
444    }
445    if e & 1 != 0 {
446        health -= 1.0;
447    }
448    if e & 2 != 0 {
449        health -= 1.0;
450    }
451    if e & 4 == 0 && adult_age <= age && !at_school {
452        health -= 0.25;
453    }
454    if health < 0.0 {
455        health = 0.0;
456    }
457    // The original's `max < health` test (a NaN health stays, where `f32::min` would not).
458    if max < health {
459        health = max;
460    }
461    health
462}