Skip to main content

unbanished_game/nature/wildlife/
livestock.rs

1//! Livestock: roaming until a pasture takes them, penning, breeding and births, trade, release and burial.
2
3use super::*;
4
5impl Wild<'_, '_> {
6    /// LivestockComponent's scheduled update (`FUN_140129020`): in a pasture, an animal with a
7    /// product adds one to the pasture's count every `interval` × 300 s.
8    pub(super) fn update_livestock(&mut self, a: usize, dt: i64) {
9        let Some(animal) = self.wildlife.animals.get(&a) else {
10            return;
11        };
12        let Some(Livestock {
13            pasture: Some(p),
14            timer,
15        }) = animal.livestock
16        else {
17            return;
18        };
19        let Some(kind) = self.wildlife.livestock_kinds.get(&animal.template) else {
20            return;
21        };
22        if kind.product.is_none() {
23            return;
24        }
25        let period = ticks(kind.interval * PERIOD);
26        let mut timer = timer + dt;
27        let mut products = 0;
28        // Deviation: a zero interval would never leave the loop in the original.
29        while 0 < period && period < timer {
30            products += 1;
31            timer -= period;
32        }
33        if let Some(l) = self
34            .wildlife
35            .animals
36            .get_mut(&a)
37            .unwrap()
38            .livestock
39            .as_mut()
40        {
41            l.timer = timer;
42        }
43        if let Some(pasture) = self.wildlife.pastures.get_mut(&p) {
44            pasture.produced += products;
45        }
46    }
47
48    /// The animal joins pasture `to` (or the town's list) and leaves its old one; leaving a pasture
49    /// it turns wild, joining one it keeps to its area.
50    ///
51    /// Original: `FUN_140129190`.
52    pub fn assign(&mut self, a: usize, to: Option<usize>) {
53        let Some(l) = self.wildlife.animals.get(&a).and_then(|x| x.livestock) else {
54            return;
55        };
56        if l.pasture == to {
57            return;
58        }
59        match l.pasture {
60            None => self.wildlife.unassigned.retain(|&x| x != a),
61            Some(p) => {
62                if let Some(p) = self.wildlife.pastures.get_mut(&p) {
63                    p.livestock.retain(|&x| x != a);
64                }
65                self.turn_wild(a);
66            }
67        }
68        if let Some(l) = self
69            .wildlife
70            .animals
71            .get_mut(&a)
72            .and_then(|x| x.livestock.as_mut())
73        {
74            l.pasture = to;
75        }
76        match to {
77            Some(p) => {
78                if let Some(pasture) = self.wildlife.pastures.get_mut(&p) {
79                    pasture.livestock.push(a);
80                }
81                self.pen(a);
82            }
83            None => self.wildlife.unassigned.push(a),
84        }
85    }
86
87    /// `FUN_14010b3a0`: wild again, at home where it stands with an area around it, then the
88    /// scheduled update with no time.
89    pub(super) fn turn_wild(&mut self, a: usize) {
90        let n = self.n();
91        let Some(animal) = self.wildlife.animals.get(&a) else {
92            return;
93        };
94        let cell = self.cell_of(animal.character.position);
95        let size = self.wildlife.animal_kinds[&animal.template].desc.area;
96        let animal = self.wildlife.animals.get_mut(&a).unwrap();
97        animal.flags |= WILD;
98        animal.home = cell;
99        animal.area = area_around(n, cell, size);
100        self.update_animal(a, 0);
101    }
102
103    /// `FUN_140129570`: no longer wild, the animal keeps to its pasture's area.
104    pub(super) fn pen(&mut self, a: usize) {
105        let Some(p) = self
106            .wildlife
107            .animals
108            .get(&a)
109            .and_then(|x| x.livestock)
110            .and_then(|l| l.pasture)
111        else {
112            return;
113        };
114        let Some(area) = self.wildlife.pastures.get(&p).map(|x| x.area) else {
115            return;
116        };
117        let animal = self.wildlife.animals.get_mut(&a).unwrap();
118        animal.flags &= !WILD;
119        animal.area = area;
120    }
121
122    /// A pasture with room takes the waiting livestock of its kind, in the town list's order, until
123    /// full.
124    ///
125    /// Original: `FUN_14012c610`.
126    pub fn fill(&mut self, p: usize) {
127        if self.wildlife.unassigned.is_empty() {
128            return;
129        }
130        let cap = self.wildlife.capacity(p);
131        let Some(pasture) = self.wildlife.pastures.get(&p) else {
132            return;
133        };
134        if cap <= pasture.livestock.len() as i32 {
135            return;
136        }
137        let kind = pasture.kind;
138        let waiting: Vec<usize> = self
139            .wildlife
140            .unassigned
141            .iter()
142            .copied()
143            .filter(|a| Some(self.wildlife.animals[a].template) == kind)
144            .collect();
145        for a in waiting {
146            self.assign(a, Some(p));
147            if cap <= self.wildlife.pastures[&p].livestock.len() as i32 {
148                break;
149            }
150        }
151    }
152
153    /// Each animal with young due has them, while the pasture holds fewer than three over its room
154    /// (the animals born join the end of the list and are seen too). Born animals are registered by
155    /// the caller.
156    ///
157    /// Original: `FUN_14012c840`.
158    pub fn births(&mut self, p: usize) -> Vec<usize> {
159        let cap = self.wildlife.capacity(p);
160        let mut born = Vec::new();
161        let mut i = 0;
162        while i < self
163            .wildlife
164            .pastures
165            .get(&p)
166            .map_or(0, |x| x.livestock.len())
167        {
168            let a = self.wildlife.pastures[&p].livestock[i];
169            let animal = self.wildlife.animals.get_mut(&a).unwrap();
170            if animal.flags & BIRTH != 0 {
171                animal.flags &= !BIRTH;
172                if (self.wildlife.pastures[&p].livestock.len() as i32) < cap + 3 {
173                    born.extend(self.give_birth(p, Some(a), false));
174                }
175            }
176            i += 1;
177        }
178        born
179    }
180
181    /// A young animal of the pasture's kind next to its parent (or anywhere in the pasture, any age
182    /// under a year, without one); male more likely the more females there are. With `buckets` it
183    /// joins the entity manager's buckets here, else the caller's.
184    ///
185    /// Original: `FUN_14012db40`.
186    pub fn give_birth(&mut self, p: usize, parent: Option<usize>, buckets: bool) -> Option<usize> {
187        let pasture = self.wildlife.pastures.get(&p)?;
188        let kind = pasture.kind?;
189        let area = pasture.area;
190        let variant = self.pick_variant(kind)?;
191        let position = match parent.and_then(|a| self.wildlife.animals.get(&a)) {
192            Some(parent) => {
193                let q = parent.character.position;
194                let dy = self.rng.rand_float_tol();
195                let dx = self.rng.rand_float_tol();
196                [q[0] + dx, q[1] + dy, q[2]]
197            }
198            None => {
199                let n = self.n();
200                let rx = self.rng.rand_below(area[2] as u32) as i32;
201                let ry = self.rng.rand_below(area[3] as u32) as i32;
202                let dy = self.rng.rand_float_tol();
203                let dx = self.rng.rand_float_tol();
204                let cell = n * (area[1] as i32 + ry) + area[0] as i32 + rx;
205                let g = self.ground(cell);
206                [g[0] + dx, g[1] + dy, g[2]]
207            }
208        };
209        let herd = &self.wildlife.pastures[&p].livestock;
210        let females = herd
211            .iter()
212            .filter(|a| self.wildlife.animals.get(a).is_some_and(|x| !x.male))
213            .count();
214        let male = if herd.is_empty() {
215            true
216        } else {
217            let share = females as f32 / herd.len() as f32;
218            share > self.rng.rand_float()
219        };
220        let yaw = self.rng.rand_float_tol() * 180.0;
221        let a = self.insert_animal(kind, variant, position, yaw, male)?;
222        self.assign(a, Some(p));
223        let age = if parent.is_none() {
224            self.rng.rand_float()
225        } else {
226            0.0
227        };
228        self.wildlife.animals.get_mut(&a).unwrap().age = age;
229        self.rescale(a);
230        self.register_animal_in(a, buckets);
231        Some(a)
232    }
233
234    /// The starting livestock of a kind, `count` animals around `at` (`spread` either way), males
235    /// and females in turn from a random first; any age under a year. They wait, wild, for a
236    /// pasture.
237    ///
238    /// Original: `FUN_1400a5fe0`.
239    pub fn start_livestock(&mut self, template: usize, count: i32, at: [f32; 3], spread: f32) {
240        let mut male = self.rng.rand_below(2) == 0;
241        for _ in 0..count {
242            let Some(variant) = self.pick_variant(template) else {
243                return;
244            };
245            let dy = self.rng.rand_float_tol();
246            let dx = self.rng.rand_float_tol();
247            let (x, y) = (at[0] + dx * spread, at[1] + dy * spread);
248            // `at`'s height, as the original passes it: the CharacterComponent's first update
249            // stands it on the ground.
250            let position = [x, y, at[2]];
251            let yaw = self.rng.rand_float_tol() * 180.0;
252            let Some(a) = self.insert_animal(template, variant, position, yaw, male) else {
253                return;
254            };
255            male = !male;
256            self.wildlife.animals.get_mut(&a).unwrap().age = self.rng.rand_float();
257            self.rescale(a);
258            self.register_animal(a);
259        }
260    }
261
262    // +0x48
263    /// Livestock bought at a trading post, `count` animals at random between its first two create
264    /// points (`a`, `b`), males and females in turn from a random first, turned at random; not
265    /// wild, they keep to the cells between the points (`area`) until a pasture takes them. Each is
266    /// `RandFloat` × half its lifespan old (the lifespan is drawn when the entity is made). The
267    /// owner registers the entities.
268    ///
269    /// Original: `FUN_14005b640`.
270    pub fn trade_livestock(
271        &mut self,
272        template: usize,
273        count: i32,
274        a: [f32; 3],
275        b: [f32; 3],
276        area: [i16; 4],
277    ) {
278        let mut male = self.rng.rand_below(2) == 0;
279        for _ in 0..count {
280            let Some(variant) = self.pick_variant(template) else {
281                return;
282            };
283            let fy = self.rng.rand_float();
284            let fx = self.rng.rand_float();
285            let (x, y) = (a[0] + (b[0] - a[0]) * fx, a[1] + (b[1] - a[1]) * fy);
286            // `a`'s height, as the original passes it: the CharacterComponent's first update
287            // stands it on the ground.
288            let position = [x, y, a[2]];
289            let yaw = self.rng.rand_float_tol() * crate::nature::seeding::YAW_RANGE;
290            let Some(id) = self.insert_animal(template, variant, position, yaw, male) else {
291                return;
292            };
293            male = !male;
294            let animal = self.wildlife.animals.get_mut(&id).unwrap();
295            animal.flags &= !WILD;
296            animal.area = area;
297            let life = animal.life;
298            let f = self.rng.rand_float();
299            self.wildlife.animals.get_mut(&id).unwrap().age = f * life * 0.5;
300            self.rescale(id);
301            self.register_animal_in(id, false);
302        }
303    }
304
305    /// The pasture's message 0 (a rancher's visit): a random animal of it may breed.
306    ///
307    /// Original: `FUN_14012cbf0`.
308    pub fn mark_breeder(&mut self, p: usize) {
309        let Some(herd) = self.wildlife.pastures.get(&p).map(|x| x.livestock.clone()) else {
310            return;
311        };
312        if herd.is_empty() {
313            return;
314        }
315        let r = self.rng.rand_below(herd.len() as u32) as usize;
316        if let Some(animal) = self.wildlife.animals.get_mut(&herd[r]) {
317            animal.flags |= BREEDER;
318        }
319    }
320
321    /// A pasture is removed: every animal goes back to the town's list, last first, and the
322    /// pasture leaves the town's list.
323    ///
324    /// Original: `FUN_14012c310` (state 3) and `FUN_14012ccb0` (removal).
325    pub fn release(&mut self, p: usize) {
326        while let Some(a) = self
327            .wildlife
328            .pastures
329            .get(&p)
330            .and_then(|x| x.livestock.last().copied())
331        {
332            self.assign(a, None);
333        }
334        self.wildlife.pasture_list.retain(|&x| x != p);
335    }
336
337    /// The entity manager's removal of the queued animals (their components' removal slots).
338    pub fn bury(&mut self) -> bool {
339        let dying = std::mem::take(&mut self.wildlife.dying);
340        let changed = !dying.is_empty();
341        for a in dying {
342            if let Some(animal) = self.wildlife.animals.remove(&a) {
343                // CharacterComponent's end (`FUN_14010ee50`): out of the tree.
344                self.wildlife.tree.remove(animal.character.tree_slot);
345                if let Some(h) = animal.herd {
346                    self.wildlife.herds[h].animals.retain(|&x| x != a);
347                }
348            }
349            self.wildlife.kinds.remove(&a);
350            if let Some(p) = self.placed.get_mut(a) {
351                p.alive = false;
352            }
353            self.scheduler.remove(a);
354        }
355        changed
356    }
357}