Skip to main content

unbanished_game/disasters/
fire.rs

1//! Fire: FireComponent, its work FireWork, WellComponent and the town's water sources (`Game`:
2//! shore points, wells, per 8 × 8 block). See docs/FIRE.md.
3//!
4//! A building catches fire now and then (or from a burning neighbour), is damaged for half the burn
5//! (DestroyComponent), and marks the cells around it as an emergency: citizens there drop what they
6//! do and carry buckets from the nearest water to it. Enough buckets, or the burn running out, put
7//! it out; it is left as rubble.
8//!
9//! Original: `FUN_1400055e0`, `FUN_14005da70`.
10mod fighting;
11
12// vtable 0x14015f480; vtable 0x1401676c0; vtable 0x140160fb0; Game +0xf0; +0x130; +0xe0; +0x140
13
14use unbanished_formats::game::FireDescription;
15
16use crate::behaviour::character::{work_facing, Action, Component, Message, MoveTo};
17use crate::nature::seeding::Cells;
18use crate::scheduler::{seconds, ticks};
19use crate::town::Sim;
20use crate::work::jobs::{Jobs, Work, WorkKind};
21
22/// `DAT_140178934`.
23const PERIOD: f32 = 300.0;
24// +0x22; Map +0x9c
25/// The map layer counting fires over each cell (total `Map`).
26pub const LAYER: usize = 6;
27/// FireWork's registration mask (category 14, emergencies).
28const MASK: u32 = 0x4000;
29/// Event type 31: a building caught fire.
30const CAUGHT: i32 = 0x1f;
31// Game +0xd0
32/// `Game` bit 6: fires are off (no disasters).
33pub const NO_FIRES: u32 = 0x40;
34/// `Map::Reachable` mask of the water search.
35const WATER_MASK: u32 = 0xe07;
36/// `DAT_140178824`, `DAT_140178888`.
37const THROW: f32 = 0.75;
38const RUN: f32 = 3.5;
39
40// +0x28; +0x2c; +0x30; +0x38; +0x40
41/// FireComponent: buckets thrown, buckets at the last spread, burn left (burning while above zero),
42/// towards the next spread, towards the next ignition check.
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct Fire {
45    /// The buckets thrown.
46    pub buckets: i32,
47    /// The buckets at the last spread.
48    pub buckets_seen: i32,
49    /// The burn left; burning while above zero.
50    pub burn: i64,
51    /// The time towards the next spread.
52    pub spread: i64,
53    /// The time towards the next ignition check.
54    pub timer: i64,
55}
56
57/// The town's water sources.
58#[derive(Debug, Clone, Default)]
59pub struct Water {
60    // +0x130
61    /// (shore cell, water cell) pairs.
62    pub points: Vec<(i32, i32)>,
63    // +0xe0
64    /// WellComponents (a removed well leaves its slot empty).
65    pub wells: Vec<Option<usize>>,
66    // +0x140
67    /// Per 8 × 8 block, the point indices (wells as `-1 - i`).
68    pub blocks: Vec<Vec<i32>>,
69    /// Cells per map side.
70    pub size: i32,
71}
72
73impl Water {
74    /// Every ground cell (type 2) next to river or lake water (types 7, 8) is a point, with the
75    /// first such neighbour by rows.
76    ///
77    /// Original: `FUN_14008e050`, `FUN_1400a43f0` (scan).
78    pub fn new(cells: &Cells) -> Water {
79        let n = cells.size as i32;
80        let b = (n >> 3).max(0) as usize;
81        let mut water = Water {
82            blocks: vec![Vec::new(); b * b],
83            size: n,
84            ..Default::default()
85        };
86        for y in 0..n {
87            for x in 0..n {
88                let cell = y * n + x;
89                if cells.types[cell as usize].0 != 2 {
90                    continue;
91                }
92                'found: for dy in -1..=1 {
93                    for dx in -1..=1 {
94                        let (wx, wy) = (x + dx, y + dy);
95                        if wx < 0 || wy < 0 || n <= wx || n <= wy {
96                            continue;
97                        }
98                        let w = wy * n + wx;
99                        if (7..=8).contains(&cells.types[w as usize].0) {
100                            let i = water.points.len() as i32;
101                            water.points.push((cell, w));
102                            water.add_entry(x, y, i);
103                            break 'found;
104                        }
105                    }
106                }
107            }
108        }
109        water
110    }
111
112    fn block(&self, x: i32, y: i32) -> Option<usize> {
113        let b = self.size >> 3;
114        let (bx, by) = (x >> 3, y >> 3);
115        (0 <= bx && bx < b && 0 <= by && by < b).then_some((b * by + bx) as usize)
116    }
117
118    /// Add a value to the map layer at a cell.
119    ///
120    /// Original: `FUN_14008df50`.
121    pub fn add_entry(&mut self, x: i32, y: i32, v: i32) {
122        if let Some(k) = self.block(x, y) {
123            self.blocks[k].push(v);
124        }
125    }
126
127    /// `FUN_14008deb0`.
128    fn remove_entry(&mut self, x: i32, y: i32, v: i32) {
129        if let Some(k) = self.block(x, y) {
130            self.blocks[k].retain(|&e| e != v);
131        }
132    }
133
134    /// The first empty slot, else a new one, filed under the well's map cell.
135    ///
136    /// Original: `FUN_140097180`.
137    pub fn add_well(&mut self, e: usize, cell: (i32, i32)) {
138        let i = match self.wells.iter().position(Option::is_none) {
139            Some(i) => {
140                self.wells[i] = Some(e);
141                i
142            }
143            None => {
144                self.wells.push(Some(e));
145                self.wells.len() - 1
146            }
147        };
148        self.add_entry(cell.0, cell.1, -1 - i as i32);
149    }
150
151    /// Remove a well from the fire-fighting layer.
152    ///
153    /// Original: `FUN_140097070`.
154    pub fn remove_well(&mut self, e: usize, cell: (i32, i32)) {
155        if let Some(i) = self.wells.iter().position(|&w| w == Some(e)) {
156            self.remove_entry(cell.0, cell.1, -1 - i as i32);
157            self.wells[i] = None;
158        }
159    }
160}
161
162/// A fire's layer over the home's or the workplace's map-rectangle centre, or the citizen's own
163/// cell.
164///
165/// Original: `Citizen::HasEmergency`, `FUN_14011b0b0`.
166pub fn has_emergency(
167    cells: &Cells,
168    placed: &[crate::nature::seeding::Placed],
169    home: Option<usize>,
170    workplace: Option<usize>,
171    position: [f32; 3],
172) -> bool {
173    if cells.layer_totals[LAYER] < 1 {
174        return false;
175    }
176    let n = cells.size as i32;
177    for e in [home, workplace].into_iter().flatten() {
178        let p = &placed[e];
179        let cell = (p.cell.1 + (p.footprint.1 >> 1)) * n + p.cell.0 + (p.footprint.0 >> 1);
180        if cells.layers[cell as usize][LAYER] != 0 {
181            return true;
182        }
183    }
184    let half = (n >> 1) as f32;
185    let x = ((position[0] + half) as i32).clamp(0, n - 1);
186    let y = ((position[1] + half) as i32).clamp(0, n - 1);
187    cells.layers[(y * n + x) as usize][LAYER] != 0
188}
189
190impl Sim<'_, '_> {
191    fn fire_desc(&self, e: usize) -> Option<FireDescription> {
192        self.site_templates[self.sites.get(&e)?.template].fire
193    }
194
195    fn fire(&mut self, e: usize) -> Option<&mut Fire> {
196        self.sites.get_mut(&e)?.fire.as_mut()
197    }
198
199    /// FireComponent's scheduled update of every building that has one: not burning, the ignition
200    /// odds (unless fires are off); burning, the spread and the burn running out.
201    ///
202    /// Original: `FUN_140049910`.
203    pub fn update_fires(&mut self, jobs: &mut Jobs, visits: &[(usize, i64)]) {
204        for &(e, dt) in visits {
205            if !self
206                .sites
207                .get(&e)
208                .is_some_and(|s| s.fire.is_some() && !s.destroyed)
209            {
210                continue;
211            }
212            let Some(d) = self.fire_desc(e) else { continue };
213            let off = self.game_flags & NO_FIRES != 0;
214            let Some(f) = self.fire(e) else { continue };
215            if f.burn == 0 {
216                if off {
217                    continue;
218                }
219                f.timer += dt;
220                if self.odds(e, d.years, d.odds) {
221                    self.ignite(jobs, e);
222                }
223                continue;
224            }
225            f.burn -= dt;
226            f.spread -= dt;
227            if 0 < f.burn && f.spread < 1 {
228                self.spread_fire(jobs, e, &d);
229            }
230            if self.fire(e).is_some_and(|f| f.burn < 1) {
231                self.put_out(jobs, e);
232            }
233        }
234    }
235
236    /// `FUN_1400ae760(timer, [years, odds], rng)`: one in `years × 12 × 300 s × odds` per
237    /// second since the last check; the time restarts.
238    fn odds(&mut self, e: usize, years: f32, odds: f32) -> bool {
239        let mut timer = self.fire(e).unwrap().timer;
240        let happens = crate::chance::once_in_years(&mut timer, years, odds, self.rng);
241        self.fire(e).unwrap().timer = timer;
242        happens
243    }
244
245    // +0x17
246    /// A building neither damaged nor being torn down is damaged for half the burn; it burns, gets
247    /// its FireWork (prioritised), marks the emergency around it and, as the first fire, posts
248    /// event 31. The particles and the fire sound follow `burn` in the app (docs/PARTICLES.md,
249    /// `Ambience::drive_entities`). (AutoSlow, settings, comes from the event: `EventLog::add`.)
250    ///
251    /// Original: `FireComponent::Ignite`, `FUN_140049f70`.
252    pub fn ignite(&mut self, jobs: &mut Jobs, e: usize) {
253        if self.is_damaged(e) || self.is_demolishing(e) {
254            return;
255        }
256        let Some(d) = self.fire_desc(e) else { return };
257        let total = ticks(d.burn_months * PERIOD + d.burn);
258        if !self.damage(jobs, e, ticks(seconds(total) * 0.5)) {
259            return;
260        }
261        if let Some(f) = self.fire(e) {
262            f.burn = total;
263            f.spread = ticks(d.interval);
264            f.buckets = 0;
265            f.buckets_seen = 0;
266        }
267        let work = Work::new(
268            e,
269            self.rect_cell(e),
270            self.professions.laborer,
271            WorkKind::Fire(crate::production::herbalist::HerbalistWork::default()),
272        );
273        self.set_work(jobs, e, work, MASK, false);
274        let id = self.sites[&e].work_id;
275        jobs.prioritize(id);
276        if self.cells.layer_totals[LAYER] < 1 {
277            self.site_events.push((CAUGHT, 3, e));
278        }
279        self.mark_emergency(e, &d, 1);
280    }
281
282    /// `FUN_14004a320`: the fire layer over the map rectangle grown by the radius
283    /// (`FUN_1400a4f50`).
284    fn mark_emergency(&mut self, e: usize, d: &FireDescription, delta: i32) {
285        let (x, y) = self.placed[e].cell;
286        let (w, h) = self.placed[e].footprint;
287        let r = d.radius;
288        let n = self.size as i32;
289        for cy in y - r..=y + h - 1 + r {
290            for cx in x - r..=x + w - 1 + r {
291                if 0 <= cx && 0 <= cy && cx < n && cy < n {
292                    let v = &mut self.cells.layers[(cy * n + cx) as usize][LAYER];
293                    *v = (*v as i32 + delta) as u8;
294                }
295            }
296        }
297        self.cells.layer_totals[LAYER] += delta as i16;
298    }
299
300    /// It is rubble now; its work and emergency go; the particles fade and the fire sound stops
301    /// with `burn` at 0 (in the app).
302    ///
303    /// Original: `FireComponent::PutOut`, `FUN_140049e20`.
304    pub fn put_out(&mut self, jobs: &mut Jobs, e: usize) {
305        let Some(d) = self.fire_desc(e) else { return };
306        if let Some(f) = self.fire(e) {
307            f.burn = 0;
308            f.spread = 0;
309        }
310        self.to_rubble(jobs, e);
311        self.remove_work(jobs, e);
312        self.mark_emergency(e, &d, -1);
313    }
314
315    /// FireComponent's message slot: message 0, a bucket of water.
316    ///
317    /// Original: `FUN_1400499f0`.
318    pub fn fire_message(&mut self, jobs: &mut Jobs, e: usize, msg: i32) {
319        if msg != 0 {
320            return;
321        }
322        let Some(d) = self.fire_desc(e) else { return };
323        let Some(f) = self.fire(e) else { return };
324        f.buckets += 1;
325        f.burn -= ticks(d.interval * PERIOD / d.buckets as f32);
326        if f.burn < 1 || d.buckets <= f.buckets {
327            self.put_out(jobs, e);
328        }
329    }
330
331    /// `FUN_140049a90`: each spread interval due, a random cell within `min(w, h)` of the
332    /// rectangle; a building there with a FireComponent catches with its odds (halved in
333    /// rain, and halved again when more than a fifth of its buckets were thrown here since the
334    /// last spread).
335    fn spread_fire(&mut self, jobs: &mut Jobs, e: usize, d: &FireDescription) {
336        let n = self.size as i32;
337        let (x, y) = self.placed[e].cell;
338        let (w, h) = self.placed[e].footprint;
339        let m = w.min(h);
340        let x1 = (w - 1 + m + x).min(n - 1);
341        let y1 = (h - 1 + m + y).min(n - 1);
342        let x0 = (x - m).max(0);
343        let y0 = y - m;
344        loop {
345            let Some(f) = self.fire(e) else { return };
346            if 0 < f.spread {
347                break;
348            }
349            f.spread += ticks(d.interval * PERIOD);
350            let cx = self.rng.rand_range(x0, x1);
351            let cy = self.rng.rand_range(y0, y1);
352            let cell = cy * n + cx;
353            // Deviation: a cell above the map's first row (the rows' range is not clamped at 0)
354            // makes the original read outside the cell array; nothing burns there here.
355            let other = (0 <= cell && cell < n * n)
356                .then(|| self.cells.occupants[cell as usize])
357                .flatten();
358            if let Some(o) = other {
359                if let Some(od) = self.fire_desc(o) {
360                    let mut chance = od.spread;
361                    if self.precipitation {
362                        chance *= 0.5;
363                    }
364                    let f = self.fire(e).unwrap();
365                    if od.buckets / 5 < f.buckets - f.buckets_seen {
366                        chance *= 0.5;
367                    }
368                    if self.rng.rand_float() < chance {
369                        self.ignite(jobs, o);
370                    }
371                }
372            }
373            if self.fire(e).is_none_or(|f| f.burn <= 0) {
374                break;
375            }
376        }
377        if let Some(f) = self.fire(e) {
378            f.buckets_seen = f.buckets;
379        }
380    }
381}