Skip to main content

unbanished_game/disasters/
blight.rs

1//! Blight: DiseaseComponent on crop fields, orchards and pastures. See docs/FARMING.md "Blight".
2//!
3//! In its season a field may catch it, more likely when a cell grew the same thing last time. While
4//! sick it kills a crop, tree or animal now and then, and passes to fields nearby growing the same
5//! thing, until it runs its course or nothing is left.
6// vtable 0x14015f3b0
7
8use unbanished_formats::game::DiseaseDescription;
9
10use crate::nature::wildlife::HUNTED;
11use crate::scheduler::ticks;
12use crate::town::Sim;
13
14/// `DAT_140178934`.
15const PERIOD: f32 = 300.0;
16/// Event type 12: a field or pasture caught a disease.
17const CAUGHT: i32 = 0xc;
18// Game +0xd0
19/// `Game` bit 5: blight is off.
20pub const NO_BLIGHT: u32 = 0x20;
21
22// +0x28; +0x30; +0x38; +0x40; +0x48; +0x50; set up by FUN_1400495b0.
23/// The blight of a field, orchard or pasture: the time to the next check, the time left (sick while
24/// it is above zero), the time to the next death and to the next spread, whether it is on a
25/// pasture, and what grew when it last ended.
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub struct Blight {
28    /// The time to the next check.
29    pub check: i64,
30    /// The time left; sick while above zero.
31    pub left: i64,
32    /// The time to the next death.
33    pub kill: i64,
34    /// The time to the next spread.
35    pub spread: i64,
36    /// Whether it is on a pasture.
37    pub pasture: bool,
38    /// What grew when it last ended.
39    pub last: Option<usize>,
40}
41
42impl Sim<'_, '_> {
43    fn blight_desc(&self, e: usize) -> Option<DiseaseDescription> {
44        self.site_templates[self.sites.get(&e)?.template].disease
45    }
46
47    fn blight(&mut self, e: usize) -> Option<&mut Blight> {
48        self.sites.get_mut(&e)?.disease.as_mut()
49    }
50
51    /// `FUN_1400a50d0(map, rect, out, 0)`: the objects on the entity's cells, by rows.
52    fn objects_in(&self, e: usize) -> Vec<usize> {
53        let n = self.size as i32;
54        let (x, y) = self.placed[e].cell;
55        let (w, h) = self.placed[e].footprint;
56        let mut out = Vec::new();
57        for cy in y..y + h {
58            for cx in x..x + w {
59                if let Some(o) = self.cells.objects[(cy * n + cx) as usize] {
60                    out.push(o);
61                }
62            }
63        }
64        out
65    }
66
67    fn is_resource(&self, o: usize) -> bool {
68        self.placed[o].alive && self.templates[self.placed[o].template].natural.is_some()
69    }
70
71    /// `FUN_1400488e0`: what grows there: the pasture's kind; else the first natural resource
72    /// on its cells, or, with nothing on them, the field's crop or the orchard's tree.
73    fn grown(&self, e: usize) -> Option<usize> {
74        if let Some(p) = self.wildlife.pastures.get(&e) {
75            return p.kind;
76        }
77        let objects = self.objects_in(e);
78        if objects.is_empty() {
79            let site = self.sites.get(&e)?;
80            if let Some(f) = &site.crop_field {
81                return f.crop;
82            }
83            return site.orchard.as_ref().and_then(|o| o.tree);
84        }
85        objects
86            .into_iter()
87            .find(|&o| self.is_resource(o))
88            .map(|o| self.placed[o].template)
89    }
90
91    /// `FUN_140048b10`: nothing left to fall sick (an empty pasture, no natural resource on
92    /// the cells).
93    fn nothing_to_blight(&self, e: usize) -> bool {
94        if let Some(p) = self.wildlife.pastures.get(&e) {
95            return p.livestock.is_empty();
96        }
97        !self.objects_in(e).into_iter().any(|o| self.is_resource(o))
98    }
99
100    /// `FUN_140048d00`: a built field with something growing falls sick (event 12 at severity
101    /// 3, with the toolbar name). Its particles follow `left` in the app (docs/PARTICLES.md).
102    fn catch_blight(&mut self, e: usize) {
103        if self.nothing_to_blight(e) {
104            return;
105        }
106        // The state machine's pending state, else its state (`+0x52`, `+0x50`), past 1.
107        let state = self.sites.get(&e).map_or(0, |s| {
108            if s.machine.pending < 0 {
109                s.machine.state
110            } else {
111                s.machine.pending
112            }
113        });
114        if state <= 1 {
115            return;
116        }
117        let Some(d) = self.blight_desc(e) else { return };
118        self.site_events.push((CAUGHT, 3, e));
119        if let Some(b) = self.blight(e) {
120            b.left = ticks(d.duration * PERIOD);
121            b.kill = 0;
122            b.spread = 0;
123        }
124    }
125
126    /// `FUN_140048c80`: it is over; what grows now is remembered.
127    fn end_blight(&mut self, e: usize) {
128        let last = self.grown(e);
129        if let Some(b) = self.blight(e) {
130            b.check = 0;
131            b.left = 0;
132            b.kill = 0;
133            b.spread = 0;
134            b.last = last;
135        }
136    }
137
138    /// DiseaseComponent's scheduled update of every site that has one. A sick site counts down,
139    /// kills now and then, and spreads; a healthy one checks whether it falls sick.
140    ///
141    /// Original: `FUN_1400494f0`, and `FUN_1400491a0` for a sick site.
142    pub fn update_blight(&mut self, visits: &[(usize, i64)]) {
143        for &(e, dt) in visits {
144            if !self.sites.get(&e).is_some_and(|s| s.disease.is_some()) {
145                continue;
146            }
147            let Some(d) = self.blight_desc(e) else {
148                continue;
149            };
150            let Some(left) = self.blight(e).map(|b| b.left) else {
151                continue;
152            };
153            if left < 1 {
154                self.blight_chance(e, &d, dt);
155                continue;
156            }
157            let b = self.blight(e).unwrap();
158            b.left -= dt;
159            b.kill += dt;
160            b.spread += dt;
161            if b.left < 0 || self.nothing_to_blight(e) {
162                self.end_blight(e);
163                continue;
164            }
165            let period = ticks(d.kill * PERIOD);
166            while 0 < period && period < self.blight(e).map_or(0, |b| b.kill) {
167                self.blight(e).unwrap().kill -= period;
168                if self.blight(e).is_some_and(|b| b.pasture) {
169                    self.blight_animal(e);
170                } else {
171                    self.blight_crop(e);
172                }
173            }
174            let period = ticks(d.spread * PERIOD);
175            while 0 < period && period < self.blight(e).map_or(0, |b| b.spread) {
176                self.blight(e).unwrap().spread -= period;
177                self.spread_blight(e, &d);
178            }
179        }
180    }
181
182    /// `FUN_140048f70`: in its months, a check every `check` × 300 s: odds of one in
183    /// `12 / check × odds`, or `odds_same` when a cell last grew what grew here.
184    /// Off with `Game +0xd0` bit 5 (no disasters, or the debug flag).
185    fn blight_chance(&mut self, e: usize, d: &DiseaseDescription, dt: i64) {
186        if self.game_flags & NO_BLIGHT != 0 {
187            return;
188        }
189        let mut month = (self.calendar / 3600.0 * 12.0) as i32;
190        if 11 < month {
191            month = 0;
192        }
193        if month < d.months.0 || d.months.1 < month {
194            return;
195        }
196        let period = ticks(d.check * PERIOD);
197        let Some(b) = self.blight(e) else { return };
198        b.check += dt;
199        let last = b.last;
200        while 0 < period && period < self.blight(e).map_or(0, |b| b.check) {
201            self.blight(e).unwrap().check -= period;
202            // `FUN_1400a5030`: a cell's last growth (`+0x10`) is what grew when it last ended.
203            let n = self.size as i32;
204            let (x, y) = self.placed[e].cell;
205            let (w, h) = self.placed[e].footprint;
206            let same = (x..x + w).any(|cx| {
207                (y..y + h).any(|cy| self.cells.previous_template[(cy * n + cx) as usize] == last)
208            });
209            let odds = if same { d.odds_same } else { d.odds };
210            let chance = 1.0 / ((12.0 / d.check) * odds);
211            if self.rng.rand_float() < chance {
212                self.catch_blight(e);
213            }
214        }
215    }
216
217    /// `FUN_1400486d0`: up to 50 draws for an animal no one has taken; it dies.
218    fn blight_animal(&mut self, e: usize) {
219        let Some(herd) = self.wildlife.pastures.get(&e).map(|p| p.livestock.clone()) else {
220            return;
221        };
222        if herd.is_empty() {
223            return;
224        }
225        for _ in 0..50 {
226            let a = herd[self.rng.rand_below(herd.len() as u32) as usize];
227            let Some(animal) = self.wildlife.animals.get(&a) else {
228                continue;
229            };
230            if animal.flags & HUNTED == 0 {
231                // Already going (entity flag `0x400`): nothing more.
232                if !animal.dying {
233                    self.wildlife.kill(a);
234                }
235                return;
236            }
237        }
238    }
239
240    /// `FUN_1400484a0`: up to 50 draws among the objects for a natural resource no one is
241    /// removing; it withers (no growth, no pile, removal with clip 2 when it has one).
242    fn blight_crop(&mut self, e: usize) {
243        let objects = self.objects_in(e);
244        if objects.is_empty() {
245            return;
246        }
247        for _ in 0..50 {
248            let o = objects[self.rng.rand_below(objects.len() as u32) as usize];
249            if self.is_resource(o) && !self.claimed.contains(&o) {
250                self.placed[o].growth = 0.0;
251                self.keep_piles.insert(o, false);
252                self.placed[o].removal_requested = true;
253                self.animate_resource(o, 2);
254                *self.models_dirty = true;
255                return;
256            }
257        }
258    }
259
260    /// The spread: a random cell within `radius` of the centre (the x offset drawn first); the
261    /// field or pasture there, growing the same thing, falls sick.
262    ///
263    /// Original: `FUN_1400491a0` (its spread loop).
264    fn spread_blight(&mut self, e: usize, d: &DiseaseDescription) {
265        let n = self.size as i32;
266        let (x, y) = self.placed[e].cell;
267        let (w, h) = self.placed[e].footprint;
268        let centre = ((h >> 1) + y) * n + (w >> 1) + x;
269        let cx = (centre % n + self.rng.rand_tol(d.radius)).max(0);
270        let cy = (centre / n + self.rng.rand_tol(d.radius)).max(0);
271        let (cx, cy) = (cx.min(n - 1), cy.min(n - 1));
272        let i = (cy * n + cx) as usize;
273        let Some(other) = self.cells.occupants[i].or(self.cells.objects[i]) else {
274            return;
275        };
276        if other == e || self.sites.get(&other).is_none_or(|s| s.disease.is_none()) {
277            return;
278        }
279        if self.grown(other) == self.grown(e) {
280            self.catch_blight(other);
281        }
282    }
283}