Skip to main content

unbanished_game/people/
needs.rs

1//! The citizen activities that meet needs: eating (activities 0 and 14), warming up (1 and 15) and
2//! stocking the home with food and firewood (6 and 7). See docs/CITIZEN-LIFE.md.
3//!
4//! Original: `FUN_140112250`, `FUN_140112790`, `FUN_140111160`, `FUN_1401108b0`.
5
6mod home;
7mod services;
8
9use std::collections::BTreeMap;
10
11use unbanished_formats::types::AnimationGroup;
12
13use crate::behaviour::activities::{StorageGeometry, TownView};
14use crate::behaviour::agents::CitizenState;
15use crate::behaviour::ai::CitizenAi;
16use crate::behaviour::character::{work_facing, Action, Character, Component, Message, MoveTo};
17use crate::pathfind::WALKABLE;
18use crate::people::life::{stored, Home, LifeRules};
19use crate::random::Random;
20use crate::scheduler::ticks;
21use crate::sectors::SectorGraph;
22use crate::terrain::HeightGrid;
23use crate::work::stock::{find_storage, RawMaterial, Storage, StorageSite};
24
25/// `DAT_140178890`: an activity that found nothing waits this long (both its slots).
26const RETRY: f32 = 3.75;
27/// `DAT_1401788fc`, `DAT_140178934`: home-stocking cooldowns are `D[0xd8]` times these.
28const STOCK_UNREACHABLE: f32 = 75.0;
29const STOCK_NOTHING: f32 = 300.0;
30
31/// What the activities read and change besides the citizen.
32pub struct Needs<'a, 'b> {
33    /// A view of the town.
34    pub town: &'a TownView<'b>,
35    /// The sector graph.
36    pub sectors: &'a mut SectorGraph,
37    /// The storage sites.
38    pub sites: &'a [StorageSite],
39    /// The town's storages.
40    pub storages: &'a mut [Storage],
41    /// The raw materials.
42    pub materials: &'a [RawMaterial],
43    /// The homes, by entity.
44    pub homes: &'a mut BTreeMap<usize, Home>,
45    // +0x20
46    /// The town's residences, in the order they were completed: the searches over residences keep
47    /// the first of equal ranks.
48    ///
49    /// Original: `FUN_140093840`, `FUN_140094140`.
50    pub residences: &'a [usize],
51    /// The environment's temperature.
52    pub temperature: f32,
53    /// The citizen description's rules.
54    pub life: &'a LifeRules,
55    // +0x50
56    /// The laborer profession's carry.
57    pub carry: i32,
58    /// The ground's heights.
59    pub terrain: &'a HeightGrid<'b>,
60    /// The map's size in cells.
61    pub size: usize,
62    /// The game's random numbers.
63    pub rng: &'a mut Random,
64    // +0x70
65    /// The town's HealerComponents.
66    pub healers: &'a [usize],
67    /// Every WorkPlaceComponent, by entity.
68    pub workplaces: &'a BTreeMap<usize, crate::work::professions::WorkPlace>,
69    /// The AttendanceComponents, by entity.
70    pub attendance: &'a mut BTreeMap<usize, crate::work::construction::Attendance>,
71    /// Every citizen (play follows the guardian).
72    pub citizens: &'a [crate::people::citizens::Citizen],
73    /// Set when the school activity found no place to sit: the caller leaves the school and
74    /// looks for another.
75    ///
76    /// Original: `FUN_14011af20(c, 1)`.
77    pub reschool: bool,
78}
79
80/// The citizen an activity runs for.
81pub struct Who<'a> {
82    /// The citizen's AI.
83    pub ai: &'a mut CitizenAi,
84    /// The citizen's character.
85    pub ch: &'a mut Character,
86    /// The citizen's state.
87    pub state: &'a mut CitizenState,
88    /// The citizen's animation group.
89    pub group: &'a AnimationGroup,
90}
91
92impl Needs<'_, '_> {
93    /// `Interact::PointPosition(entity, 0)`: the first use point, else the rectangle centre.
94    fn point(&self, entity: usize) -> [f32; 3] {
95        let e = &self.town.entities[entity];
96        if let Some(p) = e.use_points.first() {
97            return *p;
98        }
99        crate::town::floor_ground(
100            self.town.floors,
101            self.size,
102            self.terrain,
103            self.town.point_cell(entity),
104        )
105    }
106
107    /// `FUN_1400c7e70`'s source: the model position, else the rectangle centre.
108    fn centre(&self, entity: usize) -> [f32; 3] {
109        let e = &self.town.entities[entity];
110        if e.has_model {
111            e.position
112        } else {
113            crate::town::floor_ground(
114                self.town.floors,
115                self.size,
116                self.terrain,
117                self.town.point_cell(entity),
118            )
119        }
120    }
121
122    fn home_food(&self, home: usize) -> i32 {
123        self.homes
124            .get(&home)
125            .map_or(0, |h| stored(&self.storages[h.storage], self.materials, 5))
126    }
127
128    fn warm_home(&self, entity: usize) -> bool {
129        self.homes
130            .get(&entity)
131            .is_some_and(|h| h.warm(self.temperature))
132    }
133
134    /// The storage of `entity` (a home's, or a registered town storage's).
135    fn storage(&self, entity: usize) -> Option<usize> {
136        self.homes.get(&entity).map(|h| h.storage).or_else(|| {
137            self.sites
138                .iter()
139                .find(|s| s.entity == entity)
140                .map(|s| s.storage)
141        })
142    }
143
144    /// `FUN_140093200` over the town's storages for category `category` (0 food, 1 fuel).
145    fn search(
146        &mut self,
147        category: u32,
148        cell: i32,
149        home: Option<usize>,
150    ) -> Option<(usize, [f32; 3])> {
151        let home_cell = home.map_or(-1, |h| self.town.entrance(h, self.rng));
152        let (size, terrain) = (self.size, self.terrain);
153        let floors = self.town.floors;
154        let ground = move |c: i32| crate::town::floor_ground(floors, size, terrain, c);
155        let mut geometry = StorageGeometry {
156            town: self.town,
157            sectors: self.sectors,
158            ground: &ground,
159        };
160        let found = find_storage(
161            self.sites,
162            self.storages,
163            self.materials,
164            category,
165            cell,
166            home_cell,
167            &mut geometry,
168            self.rng,
169        )?;
170        Some((self.sites[found.site].entity, found.target))
171    }
172
173    /// `FUN_140093840`: for the urgently hungry, the nearest of the home, the town's markets
174    /// and storages, and the empty residences that hold food, each taking a strictly better
175    /// rank in that order.
176    /// - The home: its entrance (`FUN_14008d480`, the ground at the cell's centre), when
177    ///   reachable, at its path rank (`FUN_140008830`), if it holds food (`FUN_140094410`).
178    /// - The markets, then the storages, as `FUN_140093200` weighs them but without its stop
179    ///   at a market covering the home.
180    /// - Each residence nobody lives in (`FUN_140017ac0`): its point 0, whose path rank
181    ///   (`FUN_1400a4ce0`, else the map width plus the straight distance) must beat the best;
182    ///   then the cells must be connected and the residence must hold food, and that rank is
183    ///   taken.
184    fn urgent_search(&mut self, cell: i32, home: Option<usize>) -> Option<(usize, [f32; 3])> {
185        let mut best = i32::MAX;
186        let mut found = None;
187        let (size, terrain) = (self.size, self.terrain);
188        let floors = self.town.floors;
189        let ground_at = move |c: i32| crate::town::floor_ground(floors, size, terrain, c);
190        if let Some(h) = home {
191            let entrance = self.town.entrance(h, self.rng);
192            if entrance >= 0 && self.town.reachable(WALKABLE, cell, entrance) {
193                let rank = self.rank(entrance, cell);
194                let food = self
195                    .homes
196                    .get(&h)
197                    .and_then(|r| self.storages[r.storage].find_item(self.materials, 0, self.rng));
198                if food.is_some() {
199                    best = rank;
200                    found = Some((h, ground_at(entrance)));
201                }
202            }
203        }
204        let (rank, storage) = {
205            let mut geometry = StorageGeometry {
206                town: self.town,
207                sectors: self.sectors,
208                ground: &ground_at,
209            };
210            crate::work::stock::scan_storages(
211                self.sites,
212                self.storages,
213                self.materials,
214                0,
215                cell,
216                None,
217                best,
218                &mut geometry,
219                self.rng,
220            )
221        };
222        if let Some(m) = storage {
223            best = rank;
224            found = Some((self.sites[m.site].entity, m.target));
225        }
226        let residences: Vec<usize> = self.residences.to_vec();
227        for e in residences {
228            let Some(home) = self.homes.get(&e) else {
229                continue;
230            };
231            if home.occupants() > 0 {
232                continue;
233            }
234            let p = self.point(e);
235            let to = self.town.cell_of(p);
236            let rank = self.rank(to, cell);
237            if best <= rank || !self.town.reachable(WALKABLE, cell, to) {
238                continue;
239            }
240            let storage = self.homes[&e].storage;
241            if self.storages[storage]
242                .find_item(self.materials, 0, self.rng)
243                .is_some()
244                && rank >= 0
245            {
246                best = rank;
247                found = Some((e, p));
248            }
249        }
250        found
251    }
252
253    /// The action stack emptied and set to call the AI back when done.
254    fn begin(&mut self, who: &mut Who) -> crate::behaviour::character::ActionStack {
255        let mut stack = std::mem::take(&mut who.ch.stack);
256        stack.clear(who.ch, who.group, self.storages);
257        stack.set_on_empty(vec![Action::SendMessage(Message {
258            component: Component::CitizenAi,
259            message: 0,
260            entity: None,
261            a: 0,
262            b: 0,
263        })]);
264        stack
265    }
266}
267
268impl Needs<'_, '_> {
269    /// The path-rank distance from `a` to `b`.
270    fn rank(&mut self, a: i32, b: i32) -> i32 {
271        let (size, terrain) = (self.size, self.terrain);
272        let floors = self.town.floors;
273        let ground_at = move |c: i32| crate::town::floor_ground(floors, size, terrain, c);
274        let mut g = StorageGeometry {
275            town: self.town,
276            sectors: self.sectors,
277            ground: &ground_at,
278        };
279        crate::work::stock::StorageSearchMap::rank(&mut g, a, b)
280    }
281
282    /// `FUN_1401280b0` over an entity's use points: the nearest reachable from `cell`.
283    fn nearest_point(&mut self, e: usize, cell: i32) -> Option<[f32; 3]> {
284        let points = self.town.entities.get(e)?.use_points.clone();
285        let mut best = 0xffff;
286        let mut found = None;
287        for p in points {
288            let to = self.town.cell_of(p);
289            if !self.town.reachable(WALKABLE, cell, to) {
290                continue;
291            }
292            let rank = self.rank(cell, to);
293            if rank < best {
294                best = rank;
295                found = Some(p);
296            }
297        }
298        found
299    }
300
301    /// `FUN_1400c0960(…, message, seconds, true)`: walk to `target`, work (no facing), then
302    /// Citizen message `message`.
303    fn visit(&mut self, who: &mut Who, target: [f32; 3], message: i32, secs: f32) {
304        let mut stack = self.begin(who);
305        stack.push(
306            who.ch,
307            who.group,
308            Action::SendMessage(Message {
309                component: Component::Citizen,
310                message,
311                entity: None,
312                a: 0,
313                b: 0,
314            }),
315        );
316        stack.push(
317            who.ch,
318            who.group,
319            Action::PerformWork {
320                facing: -1000.0,
321                anim: 8,
322                duration: ticks(secs),
323                elapsed: 0,
324                consume: false,
325            },
326        );
327        let walk = MoveTo::new(target, 1, 0, WALKABLE, 0, -1.0, self.rng);
328        stack.push(who.ch, who.group, Action::move_to(walk));
329        who.ch.stack = stack;
330        who.state.health_events |= 4;
331        who.state.job = -1;
332        who.state.supply_activity = 0;
333    }
334
335    /// `FUN_1400c2f20`: rest at home (walk there, warm up, 5 s).
336    fn rest_at_home(&mut self, who: &mut Who, home: usize) {
337        let target = self.point(home);
338        let mut stack = self.begin(who);
339        stack.push(
340            who.ch,
341            who.group,
342            Action::PerformWork {
343                facing: -1000.0,
344                anim: 8,
345                duration: ticks(5.0),
346                elapsed: 0,
347                consume: false,
348            },
349        );
350        stack.push(who.ch, who.group, citizen_message(0, home));
351        let walk = MoveTo::new(target, 1, 0, WALKABLE, 0, -1.0, self.rng);
352        stack.push(who.ch, who.group, Action::move_to(walk));
353        who.ch.stack = stack;
354        who.state.job = -1;
355        who.state.health_events |= 4;
356        who.state.supply_activity = 0;
357    }
358}
359
360fn citizen_message(message: i32, entity: usize) -> Action {
361    Action::SendMessage(Message {
362        component: Component::Citizen,
363        message,
364        entity: Some(entity),
365        a: 0,
366        b: 0,
367    })
368}
369
370/// The home holds food for every living family (`D[0xc4]` per member of this citizen's family).
371///
372/// Original: `FUN_14011abb0`.
373pub fn home_has_food(
374    home: &Home,
375    slot: i32,
376    storages: &[Storage],
377    materials: &[RawMaterial],
378    life: &LifeRules,
379) -> bool {
380    let members = home.families.get(slot.max(0) as usize).map_or(0, Vec::len) as i32;
381    home.families_living() * members * life.f(0xc4) as i32
382        <= stored(&storages[home.storage], materials, 5)
383}
384
385/// `D[0xd4]` firewood per living family.
386///
387/// Original: `FUN_14011acc0`.
388pub fn home_has_fuel(
389    home: &Home,
390    storages: &[Storage],
391    materials: &[RawMaterial],
392    life: &LifeRules,
393) -> bool {
394    home.families_living() as f32 * life.f(0xd4)
395        <= stored(&storages[home.storage], materials, 6) as f32
396}