Skip to main content

unbanished_game/behaviour/
ai.rs

1//! CitizenAIComponent: choosing what a citizen does next. See docs/CITIZEN-AI.md.
2//!
3//! Original: `FUN_140115040`.
4mod qsort;
5pub use qsort::{crt_qsort, crt_qsort_by, crt_qsort_less};
6
7// vtable 0x140168890
8
9use crate::random::Random;
10use crate::scheduler::{seconds, ticks};
11
12/// Activities.
13///
14/// Original: `FUN_1401146c0`.
15pub mod activity {
16    /// Eat.
17    pub const EAT: u32 = 0;
18    /// Get warm.
19    pub const WARM: u32 = 1;
20    /// Emergency work, for example fighting a fire.
21    pub const EMERGENCY: u32 = 2;
22    /// Fetch clothing.
23    pub const CLOTHING: u32 = 3;
24    /// Fetch herbs.
25    pub const HERBS: u32 = 4;
26    /// Visit the doctor.
27    pub const DOCTOR: u32 = 5;
28    /// Stock the home with food.
29    pub const HOME_FOOD: u32 = 6;
30    /// Stock the home with firewood.
31    pub const HOME_FUEL: u32 = 7;
32    /// Fetch a tool.
33    pub const TOOL: u32 = 8;
34    /// Work.
35    pub const WORK: u32 = 9;
36    /// Go to school.
37    pub const SCHOOL: u32 = 10;
38    /// A child plays near its guardian.
39    pub const PLAY: u32 = 11;
40    /// Loiter near a building, then wait.
41    pub const IDLE: u32 = 12;
42    /// Drop off what the citizen carries.
43    pub const DROP_OFF: u32 = 13;
44    /// Eat, when very hungry.
45    pub const EAT_URGENT: u32 = 14;
46    /// Get warm, when very cold.
47    pub const WARM_URGENT: u32 = 15;
48    // FUN_140114c70 (the carried storage's size), FUN_140114d60 (the model).
49    /// Not an activity: `run` is asked to refresh the citizen before the normal choice (the
50    /// carried storage's size from the profession, and the model).
51    pub const REFRESH: u32 = u32::MAX;
52}
53use activity::*;
54
55/// `DAT_1401788fc`, `DAT_140178934`, `DAT_140178954`: loiter timers (seconds).
56const LOITER_UNHAPPY: f32 = 75.0;
57const LOITER_SAD: f32 = 300.0;
58const LOITER_ANYWAY: f32 = 1800.0;
59/// `DAT_140178934`: carrying inventory this long raises drop-off priority.
60const CARRY_LONG: f32 = 300.0;
61
62/// The citizen values candidate building reads (`D` = CitizenDescription).
63#[derive(Debug, Clone, Copy, Default)]
64pub struct CitizenView {
65    // +0x68; +0x228
66    /// Whether it has a disease.
67    pub sick: bool,
68    /// Whether a doctor is assigned.
69    pub doctor: bool,
70    // +0x44; +0x48; +0x50; +0x54; +0x80
71    /// The hunger.
72    pub hunger: f32,
73    /// The cold.
74    pub cold: f32,
75    /// The health.
76    pub health: f32,
77    /// Bit 9 of the health events: herbs are not wanted (*inferred*).
78    pub health_flag: bool,
79    /// The happiness.
80    pub happiness: f32,
81    // +0x3c; +0x208; +0x238; +0x1e4; +0xac
82    /// The age.
83    pub age: f32,
84    /// Whether it attends school.
85    pub school: bool,
86    /// Whether it has a home.
87    pub home: bool,
88    /// The clothing level.
89    pub clothing: i32,
90    /// The uses left on its tool.
91    pub tool: i32,
92    // +0x22
93    /// Map byte set at home, work or here.
94    ///
95    /// Original: `FUN_14011b0b0`.
96    pub emergency: bool,
97    /// The home has food.
98    ///
99    /// Original: `FUN_14011abb0`, `FUN_14011acc0`.
100    pub home_food: bool,
101    /// The home has firewood.
102    pub home_fuel: bool,
103    // +0x250; +0xb0
104    /// The spouse's supply errand: 1 food, 2 firewood.
105    pub spouse_activity: Option<u32>,
106    /// Carried inventory count.
107    ///
108    /// Original: `FUN_14011b2b0`.
109    pub carrying: i32,
110}
111
112/// The CitizenDescription thresholds candidate building reads.
113#[derive(Debug, Clone, Copy, Default)]
114pub struct Thresholds {
115    // +0x44
116    /// The age at which a citizen is an adult.
117    pub adult_age: f32,
118    // +0x74
119    /// The health below which a citizen looks for herbs.
120    pub health_low: f32,
121    // +0xb4
122    /// The happiness below which a citizen gets restless after `LOITER_SAD` seconds.
123    pub happy_low: f32,
124    // +0xb8
125    /// The happiness below which a citizen gets restless after `LOITER_UNHAPPY` seconds.
126    pub happy_unhappy: f32,
127    // +0xc8
128    /// The hunger above which a citizen eats.
129    pub hungry: f32,
130    // +0xcc
131    /// The hunger above which a citizen eats at once.
132    pub hungry_urgent: f32,
133    // +0xe8
134    /// The cold above which a citizen warms up.
135    pub cold: f32,
136    // +0xec
137    /// The cold above which a citizen warms up at once.
138    pub cold_urgent: f32,
139}
140
141/// One candidate (12-byte entries: activity, priority, unused).
142pub type Candidate = (u32, i32);
143
144/// A citizen's AI: the cooldown of each activity, the current and queued activity, and the urgent
145/// flags.
146#[derive(Debug, Clone)]
147pub struct CitizenAi {
148    // +0x28; +0x2c
149    /// The current activity.
150    pub current: u32,
151    /// The queued activity, if any.
152    pub queued: Option<u32>,
153    // +0x30 / +0x31
154    /// Eating urgently.
155    pub eating: bool,
156    /// Warming up urgently.
157    pub warming: bool,
158    // +0x40..+0xb8
159    /// Per-activity cooldowns (ticks).
160    pub cooldowns: [i64; 16],
161    // +0xc0; +0xc8
162    /// The time since the citizen last loitered.
163    pub since_loiter: i64,
164    /// How long the citizen has carried goods (reset while it carries nothing).
165    pub carrying_time: i64,
166}
167
168impl Default for CitizenAi {
169    fn default() -> Self {
170        CitizenAi {
171            current: IDLE,
172            queued: None,
173            eating: false,
174            warming: false,
175            cooldowns: [0; 16],
176            since_loiter: 0,
177            carrying_time: 0,
178        }
179    }
180}
181
182/// Candidate activities in push order, and whether the list is shuffled and sorted (the doctor-only
183/// and urgent-only lists return before that).
184///
185/// Original: `FUN_140113170`.
186pub fn candidates(
187    ai: &CitizenAi,
188    c: &CitizenView,
189    d: &Thresholds,
190    urgent_only: bool,
191) -> (Vec<Candidate>, bool) {
192    let (list, early) = candidate_list(ai, c, d, urgent_only);
193    (list, !early)
194}
195
196fn candidate_list(
197    ai: &CitizenAi,
198    c: &CitizenView,
199    d: &Thresholds,
200    urgent_only: bool,
201) -> (Vec<Candidate>, bool) {
202    let mut out = Vec::new();
203    if c.sick && c.doctor {
204        out.push((DOCTOR, 6));
205        return (out, true);
206    }
207    if c.hunger > d.hungry_urgent {
208        out.push((EAT_URGENT, 7));
209    }
210    if c.cold > d.cold_urgent {
211        out.push((WARM_URGENT, 7));
212    }
213    if c.hunger > d.hungry {
214        out.push((EAT, 6));
215    }
216    if c.cold > d.cold {
217        out.push((WARM, 6));
218    }
219    if !c.sick {
220        if c.emergency {
221            out.push((EMERGENCY, 7));
222        }
223        if c.clothing == 0 {
224            out.push((CLOTHING, 3));
225        }
226        if c.health < d.health_low && !c.health_flag {
227            out.push((HERBS, 3));
228        }
229    } else {
230        out.push((DOCTOR, 6));
231    }
232    if urgent_only {
233        return (out, true);
234    }
235    let loiter = seconds(ai.since_loiter);
236    let restless = (c.happiness < d.happy_unhappy && loiter > LOITER_UNHAPPY)
237        || (c.happiness < d.happy_low && loiter > LOITER_SAD)
238        || loiter > LOITER_ANYWAY;
239    out.push((IDLE, if restless { 2 } else { 0 }));
240    if c.age < d.adult_age || c.school {
241        if !c.school {
242            if !c.sick {
243                out.push((PLAY, 0));
244            }
245            if !c.home_food {
246                out.push((HOME_FOOD, 4));
247            }
248            if c.home_fuel {
249                return (out, false);
250            }
251            out.push((HOME_FUEL, 4));
252        } else if !c.sick {
253            out.push((SCHOOL, 2));
254        }
255        return (out, false);
256    }
257    if c.home {
258        if !c.home_food && c.spouse_activity != Some(1) {
259            out.push((HOME_FOOD, if c.hunger > d.hungry_urgent { 6 } else { 4 }));
260        }
261        if !c.home_fuel && c.spouse_activity != Some(2) {
262            out.push((HOME_FUEL, if c.cold > d.cold_urgent { 6 } else { 4 }));
263        }
264    }
265    if c.sick {
266        return (out, false);
267    }
268    if c.tool < 1 {
269        out.push((TOOL, 5));
270    }
271    out.push((WORK, 2));
272    if c.carrying >= 1 {
273        let long = ticks(CARRY_LONG) < ai.carrying_time;
274        out.push((DROP_OFF, if long { 3 } else { 1 }));
275    }
276    (out, false)
277}
278
279/// Swap each position with `Rand(count)`, then sort.
280///
281/// Original: `FUN_140113170` (tail).
282pub fn shuffle_and_sort(list: &mut [Candidate], rng: &mut Random) {
283    let n = list.len() as u32;
284    for i in 0..list.len() {
285        let j = rng.rand_below(n) as usize;
286        if j != i {
287            list.swap(i, j);
288        }
289    }
290    if list.len() > 1 {
291        crt_qsort(list);
292    }
293}
294
295/// `value <= limit` as a `comiss` with `jbe` (or a `ja` not taken) decides it: true for a NaN.
296#[allow(clippy::neg_cmp_op_on_partial_ord)]
297fn at_most(value: f32, limit: f32) -> bool {
298    !(limit < value)
299}
300
301impl CitizenAi {
302    /// Count cooldowns down, advance the loiter and carry clocks.
303    ///
304    /// Original: `FUN_1401148b0` (timers).
305    pub fn tick(&mut self, dt: i64, carrying: i32) {
306        for c in &mut self.cooldowns {
307            *c = (*c - dt).max(0);
308        }
309        self.since_loiter += dt;
310        self.carrying_time += dt;
311        if carrying == 0 {
312            self.carrying_time = 0;
313        }
314    }
315
316    /// Whether this update's hunger branch is taken: urgently hungry, no urgent activity running or
317    /// current, and the urgent meal's cooldown out after this update's `dt`. The caller then eats
318    /// from the home's storage first when it holds food ([`CitizenAi::update`]'s `home_meal`).
319    ///
320    /// Original: `FUN_1401148b0`.
321    pub fn hunger_branch(&self, dt: i64, view: &CitizenView, d: &Thresholds) -> bool {
322        let urgent_running = (self.eating && self.current == EAT_URGENT)
323            || (self.warming && self.current == WARM_URGENT);
324        let in_urgent = self.current == EAT_URGENT || self.current == WARM_URGENT;
325        let cooldown = (self.cooldowns[EAT_URGENT as usize] - dt).max(0);
326        // jbe at 0x140114a1b: a NaN hunger is not urgent.
327        !(at_most(view.hunger, d.hungry_urgent) || urgent_running || in_urgent || cooldown > 0)
328    }
329
330    // +0x60 >= 0
331    /// The scheduled update. `busy` is the character's "has actions" test; `run` dispatches an
332    /// activity (see [`CitizenAi::choose`]). `home_meal` is the citizen's hunger after eating from
333    /// the home's storage, when [`CitizenAi::hunger_branch`] held and the home had food: the urgent
334    /// choice is then made only if the citizen is still urgently hungry. Before the normal choice,
335    /// `run` is asked for [`activity::REFRESH`] (the carried storage's size and the model).
336    ///
337    /// Original: `FUN_14011a7b0`, `FUN_140114c70`, `FUN_140114d60`, `FUN_1401148b0`.
338    #[allow(clippy::too_many_arguments)]
339    pub fn update(
340        &mut self,
341        dt: i64,
342        view: &CitizenView,
343        d: &Thresholds,
344        rng: &mut Random,
345        home_meal: Option<f32>,
346        busy: impl Fn() -> bool,
347        mut run: impl FnMut(&mut CitizenAi, u32, &mut Random) -> bool,
348    ) {
349        self.tick(dt, view.carrying);
350        let urgent_running = (self.eating && self.current == EAT_URGENT)
351            || (self.warming && self.current == WARM_URGENT);
352        let in_urgent = self.current == EAT_URGENT || self.current == WARM_URGENT;
353        // jbe at 0x140114a1b: a NaN hunger is not urgent.
354        if at_most(view.hunger, d.hungry_urgent)
355            || urgent_running
356            || in_urgent
357            || self.cooldowns[EAT_URGENT as usize] > 0
358        {
359            // ja at 0x140114b49: a NaN hunger ends the urgent meal.
360            if self.eating && at_most(view.hunger, d.hungry_urgent) {
361                self.eating = false;
362            }
363        } else {
364            // `FUN_14011a7b0` ate from the home's storage first; still urgently hungry?
365            let hunger = home_meal.unwrap_or(view.hunger);
366            if d.hungry_urgent < hunger {
367                let fed = CitizenView { hunger, ..*view };
368                self.choose(&fed, d, true, rng, &mut run);
369                self.eating = self.current == EAT_URGENT;
370            }
371        }
372        // The rest reads the citizen's hunger as it is now, after any meal at home.
373        let fed = CitizenView {
374            hunger: home_meal.unwrap_or(view.hunger),
375            ..*view
376        };
377        let view = &fed;
378        // `bVar4` is computed once, before the hunger choice.
379        let in_urgent = self.current == EAT_URGENT || self.current == WARM_URGENT;
380        // jbe at 0x140114b75: a NaN cold is not urgent.
381        if at_most(view.cold, d.cold_urgent)
382            || urgent_running
383            || in_urgent
384            || self.cooldowns[WARM_URGENT as usize] > 0
385        {
386            // ja at 0x140114bce: a NaN cold ends the urgent warming.
387            if self.warming && at_most(view.cold, d.cold_urgent) {
388                self.warming = false;
389            }
390        } else {
391            self.choose(view, d, true, rng, &mut run);
392            self.warming = self.current == WARM_URGENT;
393        }
394        if !self.eating && !self.warming && view.emergency && self.current != EMERGENCY {
395            self.choose(view, d, true, rng, &mut run);
396        }
397        if busy() {
398            return;
399        }
400        // `FUN_140114c70` and `FUN_140114d60`, then the normal choice.
401        run(self, REFRESH, rng);
402        self.choose(view, d, false, rng, &mut run);
403    }
404
405    /// Run the queued activity, or try candidates in order until `run` leaves the character busy.
406    /// `run(activity)` is the dispatcher and returns whether the character now has actions queued.
407    ///
408    /// Original: `FUN_1401146c0`, `FUN_140113060`.
409    pub fn choose(
410        &mut self,
411        view: &CitizenView,
412        d: &Thresholds,
413        urgent_only: bool,
414        rng: &mut Random,
415        mut run: impl FnMut(&mut CitizenAi, u32, &mut Random) -> bool,
416    ) {
417        if let Some(q) = self.queued {
418            if self.dispatch(q, &mut run, rng) {
419                self.current = q;
420                self.queued = None;
421                return;
422            }
423        }
424        let (mut list, shuffle) = candidates(self, view, d, urgent_only);
425        if shuffle {
426            shuffle_and_sort(&mut list, rng);
427        }
428        for (activity, _) in list {
429            if self.dispatch(activity, &mut run, rng) {
430                self.current = activity;
431                break;
432            }
433        }
434    }
435
436    /// `FUN_1401146c0`: only activities whose cooldown has expired run.
437    fn dispatch(
438        &mut self,
439        activity: u32,
440        run: &mut impl FnMut(&mut CitizenAi, u32, &mut Random) -> bool,
441        rng: &mut Random,
442    ) -> bool {
443        if self.cooldowns[activity as usize] >= 1 {
444            return false;
445        }
446        run(self, activity, rng)
447    }
448}
449
450#[cfg(test)]
451mod tests;