Skip to main content

unbanished_game/disasters/
tornado.rs

1//! Tornadoes: the environment forms one while it rains
2//! (`Environment::update`); it crosses the map along a jagged line, flattening crops and trees,
3//! wrecking buildings and killing animals and citizens near it. See docs/TORNADO.md.
4//!
5//! - Setup: two random cells at least apart (at most a hundred tries), a 129-point line between
6//!   them bent by midpoint displacement, the event "a tornado has touched down" (type 30, severity
7//!   3).
8//! - Update: when its particles are gone the entity goes; else it follows the line (within 3
9//!   cells of its point, the next point is 10 further), wrecks what is near or, at the end, stops
10//!   forming particles, and moves a second toward its point on the ground.
11//!
12//! Original: `TornadoComponent`: `FUN_140058f00`, `FUN_1400592e0`, `FUN_140058630`,
13//! `FUN_1400589a0`; following the line, `FUN_1400ac6b0`.
14// vtable 0x140160ba0; slot +0x20; +0x24; slot +0x40; +0x20
15
16use crate::random::Random;
17use crate::scheduler::seconds;
18use crate::terrain::HeightGrid;
19use crate::town::Sim;
20use crate::work::jobs::Jobs;
21
22/// TornadoDescription.
23///
24/// Original: `FUN_1400596f0`.
25#[derive(Debug, Clone, Copy, Default, PartialEq)]
26pub struct TornadoTemplate {
27    // +0x20
28    /// Cells a second.
29    pub speed: f32,
30    // +0x24
31    /// The ends' least distance in cells.
32    pub min_distance: i32,
33    // +0x28
34    /// The time between wrecking passes.
35    pub interval: i64,
36    // +0x30
37    /// The reach of a pass (cells, and the radius about the thrown point).
38    pub reach: i32,
39    // +0x34
40    /// How far from it a pass throws its point.
41    pub throw: i32,
42    // +0x20
43    /// The fade of particle slot 0: once the tornado stops forming particles, the slot's alpha
44    /// falls to 0 over this time and the particle system goes.
45    pub fade: i64,
46}
47
48/// The component's state.
49///
50/// Original: `FUN_1400594e0`.
51#[derive(Debug, Clone, PartialEq)]
52pub struct Tornado {
53    // +0x30; +0x40; +0x50
54    /// The point it heads for.
55    pub target: [f32; 3],
56    /// The line it follows.
57    pub path: Vec<[f32; 3]>,
58    /// The index of the point it heads for.
59    pub index: i32,
60    // +0x28
61    /// Until the next wrecking pass.
62    pub timer: i64,
63    // +0x58
64    /// Where it is.
65    pub position: [f32; 3],
66    /// Whether its particle slot is on.
67    ///
68    /// Original: `FUN_140054080(0)` fades it out.
69    pub emitting: bool,
70    // slot +0x10; +0x7c
71    /// The particle slot's alpha (system) and its rate per second: `1 / fade` from the start, `−1 /
72    /// fade` once it stops; `None` once the slot is gone.
73    ///
74    /// Original: `FUN_140053fc0`.
75    pub slot: Option<(f32, f32)>,
76}
77
78impl Tornado {
79    /// The particle component's update for the slot, which runs before the tornado's (the template
80    /// lists `particle` first): the alpha moves by `AsSeconds(dt) × rate`; above 1 it stays at 1
81    /// and stops, at 0 or below the slot goes.
82    ///
83    /// Original: `FUN_140053490`.
84    pub fn step_slot(&mut self, dt: i64) {
85        let Some((alpha, rate)) = &mut self.slot else {
86            return;
87        };
88        if *rate != 0.0 {
89            *alpha += seconds(dt) * *rate;
90            if 1.0 < *alpha {
91                *alpha = 1.0;
92                *rate = 0.0;
93                return;
94            }
95        }
96        // jbe at 0x140053793: an alpha of 0 or less, or NaN, ends the slot.
97        #[allow(clippy::neg_cmp_op_on_partial_ord)]
98        if !(0.0 < *alpha) {
99            self.slot = None;
100        }
101    }
102}
103
104/// `PATH`: the line's points (`0x81`).
105const POINTS: usize = 129;
106
107/// `Math::Vector3::Normalize` with the length.
108fn normalize(v: [f32; 3]) -> ([f32; 3], f32) {
109    crate::math::normalize3_len(v)
110}
111
112/// Bend a line by midpoint displacement: the point midway between `a` and `b` moves off the line,
113/// to its left, by a random amount up to a quarter of their distance; then each half is bent the
114/// same way.
115///
116/// Original: `FUN_1400592e0(path, a, b)`.
117pub fn displace(path: &mut [[f32; 3]], a: usize, b: usize, rng: &mut Random) {
118    let (p, q) = (path[a], path[b]);
119    let (d, length) = normalize([q[0] - p[0], q[1] - p[1], q[2] - p[2]]);
120    let mid = [
121        (p[0] + q[0]) * 0.5,
122        (p[1] + q[1]) * 0.5,
123        (p[2] + q[2]) * 0.5,
124    ];
125    let (side, _) = normalize([-d[1], d[0], 0.0]);
126    let m = (a + b) >> 1;
127    let r = rng.rand_float();
128    let s = length * 0.25;
129    path[m] = [
130        side[0] * s * r + mid[0],
131        side[1] * s * r + mid[1],
132        side[2] * s * r + mid[2],
133    ];
134    if 1 < m - a {
135        displace(path, a, m, rng);
136    }
137    if 1 < b - m {
138        displace(path, m, b, rng);
139    }
140}
141
142impl Tornado {
143    /// A new tornado on a map of `size` cells: its line across the map, and its event.
144    ///
145    /// Original: `FUN_140058f00`.
146    pub fn new(
147        t: &TornadoTemplate,
148        size: usize,
149        terrain: &HeightGrid,
150        floors: &crate::world::floor::Floors,
151        rng: &mut Random,
152    ) -> Tornado {
153        let n = size as u32;
154        let mut tries = 0;
155        let (mut x0, mut y0, mut x1, mut y1);
156        loop {
157            x0 = rng.rand_below(n) as i32;
158            y0 = rng.rand_below(n) as i32;
159            x1 = rng.rand_below(n) as i32;
160            y1 = rng.rand_below(n) as i32;
161            if 99 < tries {
162                break;
163            }
164            tries += 1;
165            let (dx, dy) = (x1 - x0, y1 - y0);
166            if t.min_distance * t.min_distance <= dx * dx + dy * dy {
167                break;
168            }
169        }
170        // `FUN_1400a48b0(.., 0)` at the cells' centres: a floor counts.
171        let ground =
172            |x: i32, y: i32| crate::town::floor_ground(floors, size, terrain, y * size as i32 + x);
173        let start = ground(x0, y0);
174        let end = ground(x1, y1);
175        let mut path = vec![[0.0; 3]; POINTS];
176        path[0] = [start[0], start[1], 0.0];
177        path[POINTS - 1] = [end[0], end[1], 0.0];
178        displace(&mut path, 0, POINTS - 1, rng);
179        Tornado {
180            target: path[0],
181            path,
182            index: 0,
183            timer: 0,
184            position: start,
185            emitting: true,
186            slot: Some((0.0, 1.0 / seconds(t.fade))),
187        }
188    }
189
190    /// Within 3 of its point, the next point at least 10 on; false past the end.
191    ///
192    /// Original: `FUN_1400ac6b0(state, position, 10, 3)`, `FUN_1400ac590`.
193    pub fn follow(&mut self) -> bool {
194        let p = [self.position[0], self.position[1], 0.0];
195        let (dx, dy) = (self.target[0] - p[0], self.target[1] - p[1]);
196        if (dx * dx + dy * dy).sqrt() < 3.0 {
197            let mut i = self.index;
198            loop {
199                i += 1;
200                if self.path.len() as i32 <= i {
201                    return false;
202                }
203                let q = self.path[i as usize];
204                let (dx, dy, dz) = (p[0] - q[0], p[1] - q[1], p[2]);
205                if 100.0 <= dx * dx + dy * dy + dz * dz {
206                    break;
207                }
208            }
209            self.index = i;
210            let q = self.path[i as usize];
211            self.target = [q[0], q[1], 0.0];
212        }
213        true
214    }
215
216    // +0x34
217    /// The point a wrecking pass throws: `RandFloatTol × 180°` about it, up to away (`RandFloat`).
218    ///
219    /// Original: `FUN_1400589a0`.
220    pub fn throw(&self, t: &TornadoTemplate, rng: &mut Random) -> [f32; 3] {
221        let angle = rng.rand_float_tol() * 180.0 * 0.017_453_292;
222        let r = rng.rand_float();
223        let reach = t.throw as f32;
224        let (sin, cos) = (crate::crt::sinf(angle), crate::crt::cosf(angle));
225        let v = [sin * reach, cos * reach, reach * 0.0];
226        [
227            v[0] * r + self.position[0],
228            v[1] * r + self.position[1],
229            v[2] * r + self.position[2],
230        ]
231    }
232}
233
234impl Sim<'_, '_> {
235    /// Every tornado's update for `dt` ticks.
236    ///
237    /// Original: `FUN_140058630`.
238    pub fn update_tornadoes(&mut self, jobs: &mut Jobs, dt: i64) {
239        let ids: Vec<usize> = self.tornadoes.keys().copied().collect();
240        for e in ids {
241            let Some(t) = self.templates[self.placed[e].template].tornado else {
242                continue;
243            };
244            let tornado = self.tornadoes.get_mut(&e).unwrap();
245            tornado.step_slot(dt);
246            // Its particle system is gone (the slot faded out): the entity goes
247            // (`FUN_1400c8370`).
248            if tornado.slot.is_none() {
249                self.tornadoes.remove(&e);
250                self.placed[e].alive = false;
251                *self.models_dirty = true;
252                continue;
253            }
254            let going = tornado.follow();
255            let (d, _) = normalize([
256                tornado.target[0] - tornado.position[0],
257                tornado.target[1] - tornado.position[1],
258                tornado.target[2] - tornado.position[2],
259            ]);
260            if !going {
261                // `FUN_140054080(0)`: the slot fades out at `−(1 / AsSeconds(fade))`.
262                tornado.emitting = false;
263                if let Some((_, rate)) = &mut tornado.slot {
264                    *rate = -(1.0 / seconds(t.fade));
265                }
266            } else {
267                self.wreck(jobs, e, &t, dt);
268            }
269            let tornado = self.tornadoes.get_mut(&e).unwrap();
270            let step = seconds(dt) * t.speed;
271            let p = [
272                d[0] * step + tornado.position[0],
273                d[1] * step + tornado.position[1],
274                d[2] * step + tornado.position[2],
275            ];
276            // `FUN_1400a48b0(…, skip floors)`.
277            let mut normal = [0.0; 3];
278            tornado.position = [p[0], p[1], self.terrain.ground(p[0], p[1], &mut normal)];
279            self.placed[e].position = tornado.position;
280        }
281    }
282
283    /// `FUN_1400589a0`: every `+0x28` a pass: a point thrown about the tornado, the natural
284    /// resource on its cell, every entity within `+0x30` of it (`FUN_140097e60`), then the
285    /// objects of every cell within `+0x30` of the tornado (`FUN_140058d20` each).
286    fn wreck(&mut self, jobs: &mut Jobs, e: usize, t: &TornadoTemplate, dt: i64) {
287        let tornado = self.tornadoes.get_mut(&e).unwrap();
288        tornado.timer -= dt;
289        if 0 < tornado.timer {
290            return;
291        }
292        tornado.timer += t.interval;
293        let point = tornado.throw(t, self.rng);
294        let position = tornado.position;
295        let n = self.size as i32;
296        let half = (n >> 1) as f32;
297        let cell = |p: [f32; 3]| {
298            let x = ((p[0] + half) as i32).clamp(0, n - 1);
299            let y = ((p[1] + half) as i32).clamp(0, n - 1);
300            (x, y)
301        };
302        let (x, y) = cell(point);
303        if let Some(o) = self.cells.objects[(y * n + x) as usize] {
304            if self.templates[self.placed[o].template].natural.is_some() {
305                self.hit(jobs, Hit::Entity(o));
306            }
307        }
308        // `FUN_140097e60` (type 0): the characters within the reach of the point, in the
309        // characters' tree's order. Only characters: the buildings and resources are reached
310        // by the cells about the tornado below. The tree's z bounds leave out everyone while
311        // the point stands more than the reach + 1 from height 0. A nomad or a boat has none
312        // of what `FUN_140058d20` acts on.
313        let hits: Vec<Hit> = self
314            .wildlife
315            .tree
316            .within(point, t.reach as f32, |_| true)
317            .into_iter()
318            .filter_map(|who| match who {
319                crate::behaviour::character_tree::Who::Citizen(c) => Some(Hit::Citizen(c)),
320                crate::behaviour::character_tree::Who::Animal(a) => Some(Hit::Entity(a)),
321                _ => None,
322            })
323            .collect();
324        for h in hits {
325            self.hit(jobs, h);
326        }
327        let (cx, cy) = cell(position);
328        for y in cy - t.reach..=cy + t.reach {
329            for x in cx - t.reach..=cx + t.reach {
330                if x < 0 || y < 0 || n <= x || n <= y {
331                    continue;
332                }
333                if let Some(o) = self.cells.objects[(y * n + x) as usize] {
334                    self.hit(jobs, Hit::Entity(o));
335                }
336            }
337        }
338    }
339
340    /// `FUN_140058d20`: a growing natural resource (a crop, a tree) not already falling loses
341    /// its growth and is removed; a building that burns (Build and Fire) and is not damaged
342    /// yet is wrecked to rubble; an animal goes (`FUN_1400c9ea0`); a citizen dies (code 5).
343    fn hit(&mut self, jobs: &mut Jobs, h: Hit) {
344        let e = match h {
345            Hit::Citizen(c) => {
346                if !self.tornado_kills.contains(&c) {
347                    self.tornado_kills.push(c);
348                }
349                return;
350            }
351            Hit::Entity(e) => e,
352        };
353        if !self.placed[e].alive {
354            return;
355        }
356        let template = &self.templates[self.placed[e].template];
357        if template.natural.is_some() && template.growth.is_some() {
358            if self.placed[e].animation.is_none() && !self.placed[e].removal_requested {
359                self.placed[e].growth = 0.0;
360                self.placed[e].removal_requested = true;
361                self.animate_resource(e, 2);
362                *self.models_dirty = true;
363            }
364            return;
365        }
366        let building = self
367            .sites
368            .get(&e)
369            .is_some_and(|s| s.fire.is_some() && !s.destroyed)
370            && self.has_build(e);
371        if building {
372            if !self.is_damaged(e) && self.damage(jobs, e, 0) {
373                self.to_rubble(jobs, e);
374            }
375            return;
376        }
377        if self.wildlife.animals.contains_key(&e) {
378            self.wildlife.kill(e);
379        }
380    }
381}
382
383#[derive(Debug, Clone, Copy)]
384enum Hit {
385    Entity(usize),
386    Citizen(usize),
387}