Skip to main content

unbanished_game/behaviour/agents/update/
animals.rs

1//! Moving the animals and telling them about hunters.
2
3use super::*;
4
5impl Agents {
6    /// The wild animals' character update: animate, run the actions, turn and move.
7    ///
8    /// Deviation: the entity manager runs these updates in the order of a tree keyed by the
9    /// entity's address; the port takes them in the order they were made, which a growing heap
10    /// usually gives too.
11    ///
12    /// Original: `FUN_14010e990`; the order comes from `FUN_1400c9560`, `FUN_1400c82b0` and the
13    /// tree at manager `+0x68` (`FUN_1400c90a0`).
14    pub fn move_animals(
15        &mut self,
16        wildlife: &mut crate::nature::wildlife::Wildlife,
17        cells: &Cells,
18        terrain: &HeightGrid,
19        rng: &mut Random,
20        materials: &[RawMaterial],
21        dt: f32,
22    ) {
23        self.sync_map(cells);
24        let mut animating = Vec::new();
25        let mut storages: Vec<Storage> = Vec::new();
26        let ids: Vec<usize> = wildlife.animals.keys().copied().collect();
27        for a in ids {
28            let (template, variant) = {
29                let animal = &wildlife.animals[&a];
30                if animal.dying {
31                    continue;
32                }
33                (animal.template, animal.variant)
34            };
35            let Some(group) = wildlife.groups.get(&(template, variant)).cloned() else {
36                continue;
37            };
38            let animal = wildlife.animals.get_mut(&a).unwrap();
39            let mut messages = Vec::new();
40            let (mut carried, mut tool_uses, mut shown_tool) = (Storage::default(), 0, -1);
41            let (mut accident, mut accident_timer) = (None, 0);
42            let mut world = World {
43                size: cells.size,
44                types: &cells.types,
45                objects: &cells.objects,
46                occupants: &cells.occupants,
47                flags: &cells.flags,
48                roads: &cells.road_kind,
49                floors: &cells.floors,
50                regions: &self.regions,
51                terrain,
52                pathfinder: &mut self.pathfinder,
53                rng,
54                messages: &mut messages,
55                used: &mut Vec::new(),
56                materials,
57                storages: &mut storages,
58                carried: &mut carried,
59                tool_uses: &mut tool_uses,
60                storage_search: None,
61                pushes: Vec::new(),
62                shown_tool: &mut shown_tool,
63                animating: &mut animating,
64                accident: &mut accident,
65                accident_timer: &mut accident_timer,
66                accident_odds: None,
67            };
68            let position = animal.character.position;
69            let fired = animal.character.animate(&group, dt);
70            self.sounds.fire(&fired, position, world.rng);
71            animal.character.update(&mut world, &group, dt);
72            let ch = &animal.character;
73            wildlife
74                .tree
75                .place(ch.tree_slot, ch.position, ch.desc.radius);
76            wildlife.tree.set_direction(ch.tree_slot, ch.direction);
77        }
78        // The trader boats' CharacterComponent.
79        let ids: Vec<usize> = wildlife.boats.keys().copied().collect();
80        for id in ids {
81            let b = &wildlife.boats[&id];
82            let Some(group) = wildlife.groups.get(&(b.template, 0)).cloned() else {
83                continue;
84            };
85            let boat = wildlife.boats.get_mut(&id).unwrap();
86            let mut messages = Vec::new();
87            let (mut carried, mut tool_uses, mut shown_tool) = (Storage::default(), 0, -1);
88            let (mut accident, mut accident_timer) = (None, 0);
89            let mut world = World {
90                size: cells.size,
91                types: &cells.types,
92                objects: &cells.objects,
93                occupants: &cells.occupants,
94                flags: &cells.flags,
95                roads: &cells.road_kind,
96                floors: &cells.floors,
97                regions: &self.regions,
98                terrain,
99                pathfinder: &mut self.pathfinder,
100                rng,
101                messages: &mut messages,
102                used: &mut Vec::new(),
103                materials,
104                storages: &mut storages,
105                carried: &mut carried,
106                tool_uses: &mut tool_uses,
107                storage_search: None,
108                pushes: Vec::new(),
109                shown_tool: &mut shown_tool,
110                animating: &mut animating,
111                accident: &mut accident,
112                accident_timer: &mut accident_timer,
113                accident_odds: None,
114            };
115            let position = boat.character.position;
116            let fired = boat.character.animate(&group, dt);
117            self.sounds.fire(&fired, position, world.rng);
118            boat.character.update(&mut world, &group, dt);
119            let ch = &boat.character;
120            wildlife
121                .tree
122                .place(ch.tree_slot, ch.position, ch.desc.radius);
123            wildlife.tree.set_direction(ch.tree_slot, ch.direction);
124        }
125        // The nomads' CharacterComponent.
126        let ids: Vec<usize> = wildlife.nomads.keys().copied().collect();
127        for id in ids {
128            let n = &wildlife.nomads[&id];
129            let Some(group) = wildlife.groups.get(&(n.template, n.variant)).cloned() else {
130                continue;
131            };
132            let nomad = wildlife.nomads.get_mut(&id).unwrap();
133            let mut messages = Vec::new();
134            let (mut carried, mut tool_uses, mut shown_tool) = (Storage::default(), 0, -1);
135            let (mut accident, mut accident_timer) = (None, 0);
136            let mut world = World {
137                size: cells.size,
138                types: &cells.types,
139                objects: &cells.objects,
140                occupants: &cells.occupants,
141                flags: &cells.flags,
142                roads: &cells.road_kind,
143                floors: &cells.floors,
144                regions: &self.regions,
145                terrain,
146                pathfinder: &mut self.pathfinder,
147                rng,
148                messages: &mut messages,
149                used: &mut Vec::new(),
150                materials,
151                storages: &mut storages,
152                carried: &mut carried,
153                tool_uses: &mut tool_uses,
154                storage_search: None,
155                pushes: Vec::new(),
156                shown_tool: &mut shown_tool,
157                animating: &mut animating,
158                accident: &mut accident,
159                accident_timer: &mut accident_timer,
160                accident_odds: None,
161            };
162            let position = nomad.character.position;
163            let fired = nomad.character.animate(&group, dt);
164            self.sounds.fire(&fired, position, world.rng);
165            nomad.character.update(&mut world, &group, dt);
166            let ch = &nomad.character;
167            wildlife
168                .tree
169                .place(ch.tree_slot, ch.position, ch.desc.radius);
170            wildlife.tree.set_direction(ch.tree_slot, ch.direction);
171        }
172    }
173
174    /// `HuntAnimal`'s notify (`FUN_1400cd2b0`): once the lodge has gathered its hunting time
175    /// (`FUN_140127f50`), the nearest wild animal within 8 (`FUN_140097730`), not already
176    /// taken, next to a cell the hunter can reach, is taken (`FUN_1400c1370` without clearing:
177    /// walk there, shoot 4 s, remove it, leave its raw materials where it stood), and its herd
178    /// moves on (`FUN_140127810`).
179    pub(in crate::behaviour::agents) fn hunt_notify(
180        &mut self,
181        i: usize,
182        env: &mut Env,
183        groups: &[Option<&AnimationGroup>],
184    ) {
185        let Some(group) = groups.get(i).copied().flatten() else {
186            return;
187        };
188        let Some((lodge, done)) = self.characters[i].stack.hunt_watch() else {
189            return;
190        };
191        if *done {
192            return;
193        }
194        let Some(site) = env.construction.sites.get(&lodge) else {
195            return;
196        };
197        let Some(d) = env.construction.templates[site.template].hunt else {
198            return;
199        };
200        if site.hunt_time.unwrap_or(0) < ticks(d.time * 300.0) {
201            return;
202        }
203        let pos = self.characters[i].position;
204        // `FUN_140097730`: the nearest character with a WildAnimalComponent
205        // (`DAT_1401d0000`; livestock have none) within 8 of the hunter, the first of equals
206        // in the characters' tree's order, which finds nothing while the hunter stands more
207        // than 9 from height 0. Whether it is hunted already is asked after.
208        let animals = &env.wildlife.animals;
209        let best = env
210            .wildlife
211            .tree
212            .nearest(pos, 8.0, |who| match who {
213                crate::behaviour::character_tree::Who::Animal(a) => {
214                    animals.get(&a).is_some_and(|x| x.livestock.is_none())
215                }
216                _ => false,
217            })
218            .and_then(|who| match who {
219                crate::behaviour::character_tree::Who::Animal(a) => Some(a),
220                _ => None,
221            });
222        let Some(a) = best else { return };
223        let animal = &env.wildlife.animals[&a];
224        if animal.flags & crate::nature::wildlife::HUNTED != 0 {
225            return;
226        }
227        let n = env.cells.size as i32;
228        let cell_of = |p: [f32; 3]| {
229            let half = (n >> 1) as f32;
230            let x = ((p[0] + half) as i32).clamp(0, n - 1);
231            let y = ((p[1] + half) as i32).clamp(0, n - 1);
232            n * y + x
233        };
234        let (here, at) = (cell_of(pos), cell_of(animal.character.position));
235        let Some(nb) = crate::pathfind::nearest_neighbour(
236            env.cells.size,
237            &env.cells.types,
238            at,
239            here,
240            WALKABLE,
241        ) else {
242            return;
243        };
244        let town = TownView {
245            size: env.cells.size,
246            types: &env.cells.types,
247            regions: &self.regions,
248            occupants: &env.cells.occupants,
249            objects: &env.cells.objects,
250            floors: &env.cells.floors,
251            entities: &[],
252            happiness: &[],
253        };
254        if !town.reachable(WALKABLE, nb, here) {
255            return;
256        }
257        if let Some((_, done)) = self.characters[i].stack.hunt_watch() {
258            *done = true;
259        }
260        let materials = env
261            .wildlife
262            .animal_kinds
263            .get(&animal.template)
264            .map(|k| k.materials.clone())
265            .unwrap_or_default();
266        let herd = animal.herd;
267        let batch = self.states[i].carried.capacity;
268        let workplace = self.states[i].workplace;
269        let mut duration = ticks(4.0);
270        if self.states[i].tool_uses < 1 {
271            duration = ticks(crate::scheduler::seconds(duration) * self.rules.no_tool_factor);
272        }
273        let target = crate::town::floor_ground(&env.cells.floors, env.cells.size, env.terrain, nb);
274        let walk = MoveTo::new(target, 1, 0, WALKABLE, 0, -1.0, env.rng);
275        let ch = &mut self.characters[i];
276        let mut stack = std::mem::take(&mut ch.stack);
277        for &m in &materials {
278            stack.push(
279                ch,
280                group,
281                Action::CreateRawMaterial {
282                    template: m,
283                    cell: at,
284                    batch,
285                    workplace,
286                    factor: 1.0,
287                },
288            );
289        }
290        stack.push(ch, group, Action::RemoveAnimal { entity: a });
291        stack.push(
292            ch,
293            group,
294            Action::PerformWork {
295                facing: -1000.0,
296                anim: 0xb,
297                duration,
298                elapsed: 0,
299                consume: true,
300            },
301        );
302        stack.push(ch, group, Action::move_to(walk));
303        ch.stack = stack;
304        // `FUN_14010c730`, then the herd's new target.
305        let mut scheduler = crate::scheduler::EntityScheduler::default();
306        let mut wild = crate::nature::wildlife::Wild {
307            wildlife: env.wildlife,
308            placed: env.placed,
309            templates: env.templates,
310            cells: env.cells,
311            terrain: env.terrain,
312            rng: env.rng,
313            // Taking an animal creates no entity.
314            scheduler: &mut scheduler,
315        };
316        wild.hunted(a);
317        if let Some(h) = herd {
318            wild.retarget(h);
319        }
320        if let Some(t) = env
321            .construction
322            .sites
323            .get_mut(&lodge)
324            .and_then(|s| s.hunt_time.as_mut())
325        {
326            *t = 0;
327        }
328    }
329}