Skip to main content

unbanished_game/production/
quarry.rs

1//! Quarries and mines: the pit deepens as it is worked. See docs/QUARRY.md.
2//!
3//! - Entity event 4 (the build's end): the pit is dug to the description's shallow floor.
4//! - Its message, which each produced batch sends from the ConsumeProduce sequence (the
5//!   description's component type): the pit is dug to `lerp(shallow, deep, produced / lifetime)`,
6//!   then every cell of the map rectangle whose terrain is steep at any of four points (normal `z <
7//!   0.85`) becomes the quarry's (type 5, object the quarry).
8//!
9//! A dig: every vertex of the pit's picking mesh, placed by the model's transform,
10//! sets the height under it to the vertex's height, no lower than the floor. The DecalComponent is
11//! re-added around each dig (the port's decals follow the terrain).
12//!
13//! Original: `QuarryComponent`: `FUN_14010cad0`, `FUN_140055a50`, `FUN_1400554e0`, `FUN_1400c4440`;
14//! the dig is `FUN_140055320`.
15// vtable 0x1401605b0; slot +0x60; slot +0x78; +0x38
16
17use std::sync::Arc;
18
19use crate::crt::truncate;
20use crate::nature::seeding::{Cells, Placed};
21use crate::terrain::{CellType, HeightGrid};
22
23/// A resolved `QuarryDescription`.
24#[derive(Debug, Clone, PartialEq)]
25pub struct QuarryTemplate {
26    // +0x28, +0x2c
27    /// The floor when built.
28    pub shallow: f32,
29    /// The floor at the end of production.
30    pub deep: f32,
31    // +0x20
32    /// The pit's picking mesh vertices (model space).
33    pub vertices: Arc<Vec<[f32; 3]>>,
34}
35
36/// `DAT_140178930`.
37const HEIGHT_SCALE: f32 = 256.0;
38/// The cell type a steep quarry cell becomes.
39pub const QUARRY_CELL: CellType = CellType(5);
40
41/// The pit under the quarry `p`, no lower than `floor`. `size` is the map's cells per side.
42///
43/// Original: `FUN_140055320`.
44pub fn dig(heights: &mut [i16], width: usize, q: &QuarryTemplate, p: &Placed, floor: f32) -> bool {
45    let half = ((width - 1) >> 1) as f32;
46    let model = crate::math::Transform::of_model(p.yaw, p.position);
47    let mut changed = false;
48    for &v in q.vertices.iter() {
49        // The entity transform (`+0x148`) times the vertex.
50        let [x, y, z] = model.apply(v);
51        // jbe at 0x14005543c: raised to the floor; a NaN stays (`f32::max` would give the floor).
52        let z = z + 0.0;
53        let z = if floor > z { floor } else { z };
54        // cvttss2si at 0x140055469 and 0x14005546e: a NaN cell is i32::MIN, off the map.
55        let (gx, gy) = (truncate(x + 0.25 + half), truncate(y + 0.25 + half));
56        if gx < 0 || gy < 0 || width as i32 <= gx || width as i32 <= gy {
57            continue;
58        }
59        // cvttss2si at 0x140055455, low 16 bits stored.
60        let h = truncate(z * HEIGHT_SCALE) as i16;
61        let cell = &mut heights[gy as usize * width + gx as usize];
62        changed |= *cell != h;
63        *cell = h;
64    }
65    changed
66}
67
68/// The message's second half: the quarry's steep cells become its own.
69///
70/// Original: `FUN_1400554e0`.
71pub fn claim_steep_cells(cells: &mut Cells, terrain: &HeightGrid, entity: usize, p: &Placed) {
72    let n = cells.size as i32;
73    let half = (n >> 1) as f32 - 0.5;
74    let (x0, y0) = p.cell;
75    let (w, h) = p.footprint;
76    for y in y0..y0 + h {
77        for x in x0..x0 + w {
78            if x < 0 || y < 0 || n <= x || n <= y {
79                continue;
80            }
81            let (cx, cy) = (x as f32 - half, y as f32 - half);
82            for (dx, dy) in [(-0.25, -0.25), (-0.25, 0.25), (0.25, -0.25), (0.25, 0.25)] {
83                // The cell centre's ground (`FUN_1400a48b0` keeps x and y) a quarter on, the
84                // terrain cell under it cast from 100 above, at most 200 (`FUN_1400afef0`);
85                // no hit leaves the normal zero, which claims the cell.
86                let normal = terrain.normal_below(cx + dx, cy + dy, 100.0, 200.0);
87                if normal[2] < 0.85 {
88                    let i = (y * n + x) as usize;
89                    cells.set_type(i, QUARRY_CELL);
90                    cells.objects[i] = Some(entity);
91                }
92            }
93        }
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    fn placed() -> Placed {
102        Placed {
103            template: 0,
104            bucket: 0,
105            cell: (2, 2),
106            footprint: (4, 4),
107            position: [0.0, 0.0, 0.0],
108            yaw: 0.0,
109            variant: 0,
110            mesh: 0,
111            growth: 0.0,
112            growth_state: None,
113            spawn_state: None,
114            alive: true,
115            removal_requested: false,
116            animation: None,
117            scale: [1.0; 4],
118        }
119    }
120
121    /// The pit follows the mesh down to the floor; a deeper floor lets it follow further,
122    /// and the cells over its sides become the quarry's.
123    #[test]
124    fn the_pit_deepens_to_its_floor_and_claims_steep_cells() {
125        let q = QuarryTemplate {
126            shallow: -1.0,
127            deep: -3.0,
128            vertices: Arc::new(vec![[0.0, 0.0, -5.0], [1.0, 0.0, -0.5], [2.0, 0.0, 0.0]]),
129        };
130        let width = 17;
131        let mut heights = vec![0i16; width * width];
132        let p = placed();
133        assert!(dig(&mut heights, width, &q, &p, q.shallow));
134        let at = |h: &[i16], x: usize| h[8 * width + 8 + x];
135        assert_eq!(
136            (at(&heights, 0), at(&heights, 1), at(&heights, 2)),
137            (-256, -128, 0)
138        );
139        assert!(dig(&mut heights, width, &q, &p, q.deep));
140        assert_eq!(at(&heights, 0), -768);
141        let mut cells = Cells::new(8, vec![CellType::GROUND; 64]);
142        let grid = HeightGrid {
143            width,
144            heights: &heights,
145        };
146        claim_steep_cells(&mut cells, &grid, 7, &p);
147        let n = 8;
148        let claimed: Vec<usize> = (0..n * n)
149            .filter(|&i| cells.types[i] == QUARRY_CELL)
150            .collect();
151        assert!(!claimed.is_empty());
152        assert!(claimed.iter().all(|&i| cells.objects[i] == Some(7)));
153    }
154}