Skip to main content

unbanished_game/behaviour/agents/
update.rs

1//! The agents' iteration: characters, animals and hunt messages.
2
3mod animals;
4
5use super::*;
6
7impl Agents {
8    /// The bucket visits in `visits` split into the placed entities' (sites, piles) and the
9    /// citizens' (from `EXTRA`, as citizen indices), each in visiting order.
10    pub fn split_visits(visits: &[(usize, i64)]) -> (Vec<(usize, i64)>, Vec<(usize, i64)>) {
11        let (extra, foreign) = (crate::scheduler::EXTRA, crate::scheduler::FOREIGN);
12        let sites = visits.iter().copied().filter(|&(v, _)| v < extra).collect();
13        let citizens = visits
14            .iter()
15            .filter(|&&(v, _)| (extra..foreign).contains(&v))
16            .map(|&(v, e)| (v - extra, e))
17            .collect();
18        (sites, citizens)
19    }
20
21    /// The citizens' part of an iteration's every-iteration phase (bit `0x04`): the town step,
22    /// the job icons, every citizen's character (animation, actions, movement), then the sites'
23    /// state machines, nomads, boats and tornadoes. `groups[i]` is citizen `i`'s animation group
24    /// (`None` for the dead); `newborn` makes a child, with its random draws.
25    ///
26    /// Original: `FUN_1400c9560` (the bit-`0x04` set).
27    pub fn every_iteration(
28        &mut self,
29        citizens: &mut Vec<Citizen>,
30        env: &mut Env,
31        groups: &[Option<&AnimationGroup>],
32        dt: f32,
33        newborn: &mut dyn FnMut(&mut Random, &Citizen, bool) -> Citizen,
34    ) {
35        self.sync_map(env.cells);
36        // The town step (`FUN_140091780`): the population, and the visitors' disease risk
37        // running out.
38        {
39            let c = &mut *env.construction;
40            c.population = self.registry.len() as i32;
41            c.visitors.1 -= ticks(dt);
42            if c.visitors.1 < 0 {
43                c.visitors = (0.0, 0);
44            }
45            self.town_disease = c.visitors.0;
46        }
47        // `FUN_140118340`'s job icon (bit 3): no workplace for a profession that needs one.
48        let professions = env.construction.professions.clone();
49        for state in &mut self.states {
50            let anywhere = if professions.list.is_empty() {
51                self.rules.profession_allows_idle
52            } else {
53                professions.works_anywhere(state.profession)
54            };
55            crate::people::status::set_icon(
56                &mut state.status,
57                3,
58                !anywhere && state.workplace.is_none(),
59                false,
60            );
61        }
62        self.sectors.age_cache(ticks(dt));
63        let mut entities = entity_views(env.placed, env.templates, env.construction);
64        let mut animating = crate::town::animating(env.placed, env.templates);
65        let adult = self.adults(citizens);
66        // The citizens' CharacterComponents in the characters' tree: the dead leave it
67        // (`FUN_14010ee50`), the new join it (`FUN_14010ee90`), in index order.
68        // Births, bands and deaths join and leave it on the spot (`join_tree`, `remove`); this
69        // catches the start's citizens and any made elsewhere.
70        for i in 0..self.characters.len() {
71            let alive = groups.get(i).copied().flatten().is_some()
72                && citizens.get(i).is_some_and(|c| c.alive);
73            let ch = &mut self.characters[i];
74            if !alive && 0 <= ch.tree_slot {
75                env.wildlife.tree.remove(ch.tree_slot);
76                ch.tree_slot = -1;
77            }
78        }
79        for i in 0..self.characters.len() {
80            let alive = groups.get(i).copied().flatten().is_some()
81                && citizens.get(i).is_some_and(|c| c.alive);
82            let ch = &mut self.characters[i];
83            if alive && ch.tree_slot < 0 {
84                ch.tree_slot = env.wildlife.tree.insert(
85                    crate::behaviour::character_tree::Who::Citizen(i),
86                    ch.position,
87                    ch.desc.radius,
88                );
89            }
90        }
91        for i in 0..self.characters.len() {
92            let Some(group) = groups[i] else { continue };
93            // The citizen's ModelComponent comes before its CharacterComponent in the entity's
94            // components, and the entity manager runs them together (bit 0x04): the mesh update
95            // (FUN_140129e30, MeshInstance::Update) advances the clip and draws for its sound
96            // events, then the character runs.
97            {
98                let ch = &mut self.characters[i];
99                let position = ch.position;
100                let fired = ch.animate(group, dt);
101                self.sounds.fire(&fired, position, env.rng);
102            }
103            let mut messages = Vec::new();
104            let mut used = Vec::new();
105            {
106                let state = &mut self.states[i];
107                // The current job's work (`+0x30`) and its profession's accident odds.
108                let accident_odds = (0 <= state.job)
109                    .then(|| env.construction.jobs.works.get(&state.job))
110                    .flatten()
111                    .and_then(|w| {
112                        let p = env.construction.professions.list.get(w.profession)?;
113                        Some((w.profession, p.accident.0, p.accident.1))
114                    });
115                // `Town::FindMaterialStorage` for a redirected drop-off.
116                let town = crate::behaviour::activities::TownView {
117                    size: env.cells.size,
118                    types: &env.cells.types,
119                    regions: &self.regions,
120                    occupants: &env.cells.occupants,
121                    objects: &env.cells.objects,
122                    floors: &env.cells.floors,
123                    entities: &entities,
124                    happiness: &env.construction.happiness,
125                };
126                let (size, terrain, sites, materials) =
127                    (env.cells.size, env.terrain, env.sites, env.materials);
128                let floors = &env.cells.floors;
129                let sectors = &mut self.sectors;
130                let mut search = |storages: &[Storage],
131                                  rng: &mut Random,
132                                  m: usize,
133                                  n: i32,
134                                  cell: i32|
135                 -> Option<(usize, [f32; 3])> {
136                    let ground =
137                        move |cell: i32| crate::town::floor_ground(floors, size, terrain, cell);
138                    let mut geometry = crate::behaviour::activities::StorageGeometry {
139                        town: &town,
140                        sectors: &mut *sectors,
141                        ground: &ground,
142                    };
143                    crate::work::stock::find_material_storage(
144                        sites,
145                        storages,
146                        materials,
147                        m,
148                        n,
149                        true,
150                        cell,
151                        None,
152                        &mut geometry,
153                        rng,
154                    )
155                    .map(|f| (f.storage, f.target))
156                };
157                let mut world = World {
158                    size: env.cells.size,
159                    types: &env.cells.types,
160                    objects: &env.cells.objects,
161                    occupants: &env.cells.occupants,
162                    flags: &env.cells.flags,
163                    roads: &env.cells.road_kind,
164                    floors: &env.cells.floors,
165                    regions: &self.regions,
166                    terrain: env.terrain,
167                    pathfinder: &mut self.pathfinder,
168                    rng: env.rng,
169                    messages: &mut messages,
170                    used: &mut used,
171                    materials: env.materials,
172                    storages: env.storages,
173                    storage_search: Some(&mut search),
174                    pushes: Vec::new(),
175                    carried: &mut state.carried,
176                    tool_uses: &mut state.tool_uses,
177                    shown_tool: &mut state.shown_tool,
178                    animating: &mut animating,
179                    accident: &mut state.accident,
180                    accident_timer: &mut state.accident_timer,
181                    accident_odds,
182                };
183                self.characters[i].update(&mut world, group, dt);
184                // `FUN_14010e990` ends by placing it in the tree again (`FUN_140019070`).
185                let ch = &self.characters[i];
186                env.wildlife
187                    .tree
188                    .place(ch.tree_slot, ch.position, ch.desc.radius);
189                env.wildlife.tree.set_direction(ch.tree_slot, ch.direction);
190            }
191            for (m, n) in used {
192                if let Some(slot) = crate::work::produce::production_group(env.materials[m].flags) {
193                    env.construction.counters.used[slot] += n;
194                }
195            }
196            citizens[i].position = self.characters[i].position;
197            self.deliver(i, messages, citizens, env, groups, &adult, &mut entities);
198            self.characters[i].stack.end_on_empty();
199        }
200        // The sites' state machines, nomads, boats and tornadoes (bit 0x04).
201        {
202            let (mut sim, jobs) = self.sim(citizens, env, groups, &adult, &entities);
203            sim.update_sites_every(jobs, ticks(dt));
204            sim.update_nomads(ticks(dt));
205            sim.update_boats();
206            sim.update_tornadoes(jobs, ticks(dt));
207            jobs.drain(&mut sim);
208        }
209        // The tornadoes' victims (`FUN_14011c2a0(citizen, 5)` from `FUN_140058d20`).
210        for c in std::mem::take(&mut env.construction.tornado_kills) {
211            if !citizens[c].alive {
212                continue;
213            }
214            let mut born = Vec::new();
215            self.with_people(citizens, env, &entities, newborn, &mut born, |people| {
216                people.die(c, crate::people::life::reason::TORNADO, None);
217            });
218        }
219    }
220
221    /// Bucket 3's visits (sites and piles), in visiting order, each with the time since its last
222    /// visit, entity by entity: blight, fire, the state machine's scheduled update (with a
223    /// residence's storage and hearth), hunt, attendance, and a pile's age. `dt` is the
224    /// iteration's time.
225    ///
226    /// Original: `FUN_1400c9560` (bucket 3).
227    pub fn visit_sites(
228        &mut self,
229        citizens: &mut [Citizen],
230        env: &mut Env,
231        groups: &[Option<&AnimationGroup>],
232        dt: f32,
233        site_visits: &[(usize, i64)],
234    ) {
235        let entities = entity_views(env.placed, env.templates, env.construction);
236        let adult = self.adults(citizens);
237        // Entity by entity, each visited entity's scheduled components in its template's order:
238        // DiseaseComponent and FireComponent come before the StateMachineComponent (a
239        // residence's state-2 work runs inside it), HuntComponent and AttendanceComponent after
240        // it; a pile has its RawMaterialComponent. Each system passes over entities it does not
241        // own.
242        for &visit in site_visits {
243            let one = [visit];
244            let (e, elapsed) = visit;
245            {
246                let (mut sim, jobs) = self.sim(citizens, env, groups, &adult, &entities);
247                sim.update_blight(&one);
248                sim.update_fires(jobs, &one);
249                sim.update_sites_visits(jobs, ticks(dt), &one);
250                // The residence's state-2 update (`FUN_14012ee40`): the ClearStorage work, then
251                // the fire.
252                sim.residence_clear_storage(jobs, &one);
253                jobs.drain(&mut sim);
254            }
255            {
256                let c = &mut *env.construction;
257                if let Some(home) = c.homes.get_mut(&e) {
258                    crate::people::life::update_home(
259                        home,
260                        env.storages,
261                        env.materials,
262                        env.temperature,
263                        elapsed,
264                        &mut c.counters,
265                    );
266                }
267            }
268            {
269                let (mut sim, jobs) = self.sim(citizens, env, groups, &adult, &entities);
270                sim.update_hunts(&one);
271                sim.update_attendance(&one);
272                sim.age_piles(jobs, &one);
273                jobs.drain(&mut sim);
274            }
275        }
276    }
277
278    /// Bucket 1's visits (the scheduler's values: citizens from `EXTRA`, nomads by entity), in
279    /// visiting order, each with the time since its last visit: a citizen's character notify,
280    /// CitizenComponent, then CitizenAIComponent; a nomad's character notify.
281    ///
282    /// Original: `FUN_1400c9560` (bucket 1).
283    pub fn visit_citizens(
284        &mut self,
285        citizens: &mut Vec<Citizen>,
286        env: &mut Env,
287        groups: &[Option<&AnimationGroup>],
288        visits: &[(usize, i64)],
289        newborn: &mut dyn FnMut(&mut Random, &Citizen, bool) -> Citizen,
290    ) {
291        let mut entities = entity_views(env.placed, env.templates, env.construction);
292        let adult = self.adults(citizens);
293        let (extra, foreign) = (crate::scheduler::EXTRA, crate::scheduler::FOREIGN);
294        // Bucket 1 in its visiting order, each with the time since its last visit
295        // (`FUN_1400c9560`).
296        for &(v, elapsed) in visits {
297            if v < extra {
298                // A nomad's CharacterComponent notify (`FUN_14010e950`): MoveTo's follow check
299                // (`FUN_1400cde40`). Its other components have no scheduled update.
300                if let Some(nomad) = env.wildlife.nomads.get_mut(&v) {
301                    let following = env.wildlife.tree.follows(nomad.character.tree_slot);
302                    nomad.character.stack.notify_moves(following);
303                }
304                continue;
305            }
306            if v >= foreign {
307                continue;
308            }
309            let i = v - extra;
310            if i >= self.ais.len()
311                || groups.get(i).copied().flatten().is_none()
312                || !citizens[i].alive
313            {
314                continue;
315            }
316            // CharacterComponent's scheduled update (`FUN_14010e950`): the running chain's
317            // notify, a hunter's `HuntAnimal`.
318            refresh_views(&mut entities, env);
319            self.hunt_notify(i, env, groups);
320            let following = env.wildlife.tree.follows(self.characters[i].tree_slot);
321            self.characters[i].stack.notify_moves(following);
322            // CitizenComponent before CitizenAIComponent (the template's component order); a
323            // citizen queued for deletion stops there (entity flag `0x400`).
324            let born = self.live(i, citizens, env, &entities, elapsed, newborn);
325            for c in born {
326                let mut ch = Character::new(self.desc, citizens[c].position, CHILD_SCALE);
327                ch.yaw = self.characters[i].yaw;
328                self.characters.push(ch);
329                self.ais.push(CitizenAi::default());
330                self.states[c].carried = self.carried.clone();
331                // The child's entity activates as it is made (`FUN_14010ee90`).
332                self.join_tree(c, env);
333            }
334            if self.dying.iter().any(|&(d, _)| d == i) {
335                continue;
336            }
337            refresh_views(&mut entities, env);
338            self.think(i, citizens, env, groups, &adult, &entities, elapsed);
339        }
340    }
341
342    /// The end of an iteration, after every bucket: destroyed sites leave, the burials' tombstones
343    /// are placed, and the queued citizens are deleted (each component's remove slot).
344    ///
345    /// Original: `FUN_1400c9560` (its deletions).
346    pub fn finish(
347        &mut self,
348        citizens: &mut Vec<Citizen>,
349        env: &mut Env,
350        groups: &[Option<&AnimationGroup>],
351    ) {
352        let entities = entity_views(env.placed, env.templates, env.construction);
353        let adult = self.adults(citizens);
354        {
355            let (mut sim, jobs) = self.sim(citizens, env, groups, &adult, &entities);
356            sim.remove_destroyed_sites(jobs);
357            sim.place_burials();
358            jobs.drain(&mut sim);
359        }
360        // The entity manager deletes the queued entities (each component's remove slot);
361        // removals can queue more (orphaned children).
362        let mut k = 0;
363        while k < self.dying.len() {
364            let (c, _) = self.dying[k];
365            self.remove(c, citizens, env, groups, &entities);
366            k += 1;
367        }
368        self.dying.clear();
369        for (c, s) in citizens.iter_mut().zip(&self.states) {
370            c.school = s.school;
371        }
372    }
373}