Skip to main content

unbanished_game/nature/
wildlife.rs

1//! Wild animals: PopulationComponent, HerdComponent, AnimalComponent and WildAnimalComponent. See
2//! docs/WILDLIFE-POPULATION.md.
3//!
4//! A population divides the map into cells of `cell` map cells. Each cell holds a capacity, set by
5//! its habitat, and a count that regrows and spreads every 300 s. The map is also divided into herd
6//! blocks. Each block starts one herd of `min..max` animals on a random habitable cell of the
7//! block. A herd rests for a while, then moves to another habitable cell of its block, and regrows
8//! from time to time. Its animals wander within an area around their home, idle, grow up and die of
9//! old age.
10//!
11//! Livestock (LivestockComponent) are animals too. Until a pasture of their kind takes them they
12//! roam like wild ones and wait in the town's list; in a pasture they keep to its area, a breeding
13//! male has young, and products gather. See docs/FARMING.md "Pastures".
14//!
15//! Original: `0x140169ab0`, `0x140168530`, `0x14016af20`.
16mod animals;
17mod herds;
18mod livestock;
19mod population;
20use herds::{area_around, inside, nearest_ground};
21
22// vtable 0x1401604b0; vtable 0x140169fb0; +0x80
23
24use std::collections::BTreeMap;
25
26use unbanished_formats::game::{
27    AnimalDescription, CharacterDescription, HerdDescription, PopulationDescription,
28};
29use unbanished_formats::types::AnimationGroup;
30
31use crate::behaviour::animation::AnimationStack;
32use crate::behaviour::character::{Action, Character, MoveTo};
33use crate::nature::seeding::{Cells, Placed, Template};
34use crate::random::Random;
35use crate::scheduler::{seconds, ticks, EntityScheduler};
36use crate::terrain::{CellType, HeightGrid};
37
38// +0x20
39/// AnimalComponent flag: a hunter has it.
40///
41/// Original: `FUN_14010c730`.
42pub const HUNTED: u32 = 0x100000;
43// +0x20
44/// AnimalComponent flag: wild.
45///
46/// Original: `FUN_14010c8d0`.
47pub const WILD: u32 = 0x400000;
48// +0x20
49/// AnimalComponent flag: young are due; the pasture's update has them born.
50///
51/// Original: `FUN_14010b8f0`, `FUN_14012c840`.
52pub const BIRTH: u32 = 0x200000;
53// +0x20
54/// AnimalComponent flag: may breed (a rancher's visit marks a random animal of the pasture).
55///
56/// Original: `FUN_14012cbf0`.
57pub const BREEDER: u32 = 0x800000;
58/// The animal walk mask (`3999`).
59const ANIMAL_WALK: u32 = 0xf9f;
60/// `DAT_140178934`.
61const PERIOD: f32 = 300.0;
62
63/// A population template's description and herd template (index into the placed-object
64/// templates).
65#[derive(Debug, Clone)]
66pub struct PopulationKind {
67    /// The population description.
68    pub desc: PopulationDescription,
69    /// The herd template it spawns, if any.
70    pub herd: Option<usize>,
71}
72
73/// The settings of a kind of herd.
74#[derive(Debug, Clone)]
75pub struct HerdKind {
76    /// The herd description.
77    pub desc: HerdDescription,
78    /// The animal template.
79    pub animal: usize,
80}
81
82/// The settings of a kind of animal.
83#[derive(Debug, Clone)]
84pub struct AnimalKind {
85    /// The animal description.
86    pub desc: AnimalDescription,
87    /// The raw-material (pile) templates a hunted animal leaves.
88    pub materials: Vec<usize>,
89    /// The character description: speeds and turning.
90    pub character: CharacterDescription,
91}
92
93/// A livestock template's LivestockDescription, resolved: the product's pile template, every
94/// `interval` × 300 s, and the stock slot.
95#[derive(Debug, Clone, Default, PartialEq)]
96pub struct LivestockKind {
97    /// The raw-material template it produces, if any.
98    pub product: Option<usize>,
99    /// The time between products, in seconds.
100    pub interval: f32,
101    /// The stock slot its product counts towards.
102    pub group: i32,
103}
104
105// +0x28; +0x30
106/// LivestockComponent: the pasture (entity), towards the next product.
107#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
108pub struct Livestock {
109    /// The pasture, if any.
110    pub pasture: Option<usize>,
111    /// The time towards the next product.
112    pub timer: i64,
113}
114
115// +0x28; +0x30; +0x40; +0x44
116/// PastureComponent's livestock side: the kind (animal template), its animals in joining order, the
117/// most it keeps (the window's slider), products gathered; with the MapComponent's area (x, y,
118/// width, height).
119#[derive(Debug, Clone, Default, PartialEq)]
120pub struct Pasture {
121    /// The animal template it keeps, if any.
122    pub kind: Option<usize>,
123    /// Its animals.
124    pub livestock: Vec<usize>,
125    /// The most animals it keeps.
126    pub limit: i32,
127    /// The amount produced that is not yet in piles.
128    pub produced: i32,
129    /// The area (x, y, width, height).
130    pub area: [i16; 4],
131}
132
133/// PopulationComponent.
134#[derive(Debug, Clone, PartialEq)]
135pub struct Population {
136    /// The entity.
137    pub entity: usize,
138    /// The template.
139    pub template: usize,
140    // +0x30
141    /// Cells per row.
142    pub width: i32,
143    // +0x38
144    /// Capacity, count and next count per cell.
145    pub cells: Vec<[i32; 3]>,
146    // +0x48
147    /// Herd blocks per row.
148    pub herd_width: i32,
149    // +0x60
150    /// Towards the next 300 s step.
151    pub clock: i64,
152    // +0x68
153    /// The next cell to recount.
154    pub cursor: i32,
155}
156
157/// HerdComponent.
158#[derive(Debug, Clone, PartialEq)]
159pub struct Herd {
160    /// The entity.
161    pub entity: usize,
162    /// The template.
163    pub template: usize,
164    // +0x28, +0x30
165    /// The population.
166    pub population: usize,
167    /// The herd's block in the population.
168    pub index: i32,
169    // +0x38
170    /// The animals (entities), in joining order.
171    pub animals: Vec<usize>,
172    // +0x48
173    /// Moving to the target (else resting).
174    pub moving: bool,
175    // +0x4c
176    /// The target map cell (−1 none).
177    pub target: i32,
178    // +0x50; +0x58
179    /// The rest time left.
180    pub rest: i64,
181    /// The time towards the next regrowth.
182    pub regrow: i64,
183}
184
185/// AnimalComponent and WildAnimalComponent, with the animal's CharacterComponent.
186pub struct Animal {
187    /// The template.
188    pub template: usize,
189    /// The character: position and movement.
190    pub character: Character,
191    // +0x28
192    /// WildAnimalComponent: the herd (index into [`Wildlife::herds`]).
193    pub herd: Option<usize>,
194    // +0x20
195    /// Component flags ([`HUNTED`], [`WILD`]).
196    pub flags: u32,
197    // +0x28
198    /// The home cell.
199    pub home: i32,
200    // +0x30
201    /// Until the next decision.
202    pub timer: i64,
203    // +0x38..+0x3e
204    /// The area it keeps to (x, y, width, height).
205    pub area: [i16; 4],
206    // +0x40
207    /// Male (the second mesh, antlers).
208    pub male: bool,
209    // +0x44, +0x48
210    /// The age in years.
211    pub age: f32,
212    /// The lifespan in years.
213    pub life: f32,
214    // +0x50
215    /// Until a breeding male's young (livestock only).
216    pub breed: i64,
217    /// LivestockComponent.
218    pub livestock: Option<Livestock>,
219    /// The model variant.
220    pub variant: usize,
221    /// The mesh.
222    pub mesh: usize,
223    /// Model scale.
224    ///
225    /// Original: `FUN_14010c7f0`.
226    pub scale: f32,
227    /// Queued for removal (entity flag `0x400`).
228    ///
229    /// Original: `FUN_1400c8370`.
230    pub dying: bool,
231}
232
233/// What a scheduled entity is.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235enum Kind {
236    Population(usize),
237    Herd(usize),
238    Animal,
239}
240
241/// The wildlife of a town.
242#[derive(Default)]
243pub struct Wildlife {
244    // Game +0x88
245    /// The characters' spatial tree (`Game`): citizens, animals, boats and nomads.
246    pub tree: crate::behaviour::character_tree::CharacterTree,
247    /// The animal populations.
248    pub populations: Vec<Population>,
249    /// The herds.
250    pub herds: Vec<Herd>,
251    /// Animals by entity.
252    pub animals: BTreeMap<usize, Animal>,
253    /// Templates by placed-object template index.
254    pub population_kinds: BTreeMap<usize, PopulationKind>,
255    /// The herd templates, by placed-object template index.
256    pub herd_kinds: BTreeMap<usize, HerdKind>,
257    /// The animal templates, by placed-object template index.
258    pub animal_kinds: BTreeMap<usize, AnimalKind>,
259    /// Animation groups by animal template and model variant.
260    pub groups: BTreeMap<(usize, usize), std::sync::Arc<AnimationGroup>>,
261    /// Entities queued for removal, in order.
262    pub dying: Vec<usize>,
263    kinds: BTreeMap<usize, Kind>,
264    /// LivestockDescriptions by animal template.
265    pub livestock_kinds: BTreeMap<usize, LivestockKind>,
266    // +0x80
267    /// The town's livestock without a pasture, in order.
268    pub unassigned: Vec<usize>,
269    // +0x90
270    /// The pastures, by entity.
271    pub pastures: BTreeMap<usize, Pasture>,
272    /// The town's list of pastures.
273    pub pasture_list: Vec<usize>,
274    /// The nomads, by entity.
275    pub nomads: BTreeMap<usize, crate::people::immigration::Nomad>,
276    /// The nomad templates, by template.
277    pub nomad_kinds: BTreeMap<usize, crate::people::immigration::NomadKind>,
278    /// The trader boats, by entity.
279    pub boats: BTreeMap<usize, crate::commerce::boat::Boat>,
280    /// The boat templates, by template.
281    pub boat_kinds: BTreeMap<usize, crate::commerce::boat::BoatKind>,
282}
283
284/// The town state wildlife reads and writes.
285pub struct Wild<'a, 't> {
286    /// The animals.
287    pub wildlife: &'a mut Wildlife,
288    /// The placed objects.
289    pub placed: &'a mut Vec<Placed>,
290    /// The object templates.
291    pub templates: &'a [Template],
292    /// The gameplay map.
293    pub cells: &'a Cells,
294    /// The ground's heights.
295    pub terrain: &'a HeightGrid<'t>,
296    /// The game's random numbers.
297    pub rng: &'a mut Random,
298    /// The entity scheduler.
299    pub scheduler: &'a mut EntityScheduler<usize>,
300}
301
302impl Wildlife {
303    /// A saved PopulationComponent; returns its index.
304    ///
305    /// Original: `FUN_140054e00`.
306    pub fn restore_population(&mut self, p: Population) -> usize {
307        let index = self.populations.len();
308        self.kinds.insert(p.entity, Kind::Population(index));
309        self.populations.push(p);
310        index
311    }
312
313    /// A saved HerdComponent; returns its index.
314    ///
315    /// Original: `FUN_140127460`.
316    pub fn restore_herd(&mut self, h: Herd) -> usize {
317        let index = self.herds.len();
318        self.kinds.insert(h.entity, Kind::Herd(index));
319        self.herds.push(h);
320        index
321    }
322
323    /// Restore an animal from a save: its animal component, its wild animal component, its
324    /// character and its livestock component.
325    ///
326    /// Original: `FUN_14010c310` (the animal component).
327    pub fn restore_animal(&mut self, entity: usize, a: Animal) {
328        self.kinds.insert(entity, Kind::Animal);
329        self.animals.insert(entity, a);
330    }
331
332    /// An animal dies (killed by a hunter, of old age, or in a herd without a habitat): it is
333    /// queued for removal and leaves its herd.
334    ///
335    /// Original: `FUN_1400c8370` on the animal.
336    pub fn kill(&mut self, a: usize) {
337        let Some(animal) = self.animals.get_mut(&a) else {
338            return;
339        };
340        if animal.dying {
341            return;
342        }
343        animal.dying = true;
344        if let Some(h) = animal.herd.take() {
345            self.herds[h].animals.retain(|&x| x != a);
346        }
347        // LivestockComponent's removal slot (`FUN_1401290d0`).
348        if let Some(l) = animal.livestock {
349            match l.pasture {
350                None => self.unassigned.retain(|&x| x != a),
351                Some(p) => {
352                    if let Some(p) = self.pastures.get_mut(&p) {
353                        p.livestock.retain(|&x| x != a);
354                    }
355                }
356            }
357        }
358        self.dying.push(a);
359    }
360
361    /// The animals a pasture has room for, its area over the kind's space per animal (none without
362    /// a kind).
363    ///
364    /// Original: `FUN_14012da40`.
365    pub fn capacity(&self, p: usize) -> i32 {
366        let Some(pasture) = self.pastures.get(&p) else {
367            return 0;
368        };
369        let Some(kind) = pasture.kind else { return 0 };
370        let space = self.animal_kinds.get(&kind).map_or(0, |k| k.desc.space);
371        let area = pasture.area[2] as i32 * pasture.area[3] as i32;
372        // Deviation: a zero space would divide by zero in the original.
373        if space == 0 {
374            return 0;
375        }
376        area / space
377    }
378
379    /// The animation group of an animal.
380    pub fn group(&self, a: &Animal) -> Option<&AnimationGroup> {
381        self.groups.get(&(a.template, a.variant)).map(|g| &**g)
382    }
383}
384
385impl Wild<'_, '_> {
386    fn n(&self) -> i32 {
387        self.cells.size as i32
388    }
389
390    fn cell_of(&self, p: [f32; 3]) -> i32 {
391        let n = self.n();
392        let half = (n >> 1) as f32;
393        let x = ((p[0] + half) as i32).clamp(0, n - 1);
394        let y = ((p[1] + half) as i32).clamp(0, n - 1);
395        n * y + x
396    }
397
398    fn ground(&self, cell: i32) -> [f32; 3] {
399        crate::town::floor_ground(&self.cells.floors, self.cells.size, self.terrain, cell)
400    }
401
402    fn kill(&mut self, a: usize) {
403        self.wildlife.kill(a);
404    }
405}