Skip to main content

unbanished_terrain/
surface.rs

1//! Packed per-cell surface data, uploaded as the terrain's `size × size` image and kept at
2//! MapComponent.
3//!
4//! The image is BGRA8 (format 5), so in memory each texel is the bytes `[dirt, rock, light, snow]`
5//! and the terrain pixel shader (`TerrainMaterial_ps`, sampler `transitionMap`) reads them as `.z`,
6//! `.y`, `.x`, `.w`:
7//! - Dirt (`.z`, lerps grass → dirt): 255 below height -0.5, otherwise squared Perlin noise;
8//!   raised towards 255 above height 8.
9//! - Rock (`.y`, lerps → triplanar rock): from the cell normal's up component (0 when nearly flat,
10//!   255 when steep); raised towards 255 above height 7.
11//! - Light (`.x`, multiplies the ambient term): one minus the mean facing of a radius-10
12//!   neighbourhood, scaled by the smoothed normal's up component.
13//! - Snow (`.w`): left 0 here.
14//!
15//! Float operations follow the disassembly order so results are bit-exact.
16//!
17//! Original: `FUN_1400d4910`, `FUN_1400b1c50`.
18// +0x140
19
20use super::Generator;
21use unbanished_core::noise::PerlinNoise;
22
23const NOISE_SCALE: f32 = 0.25;
24const NOISE_OCTAVES: f32 = 4.0;
25const LOW: f32 = -0.5;
26const FLAT: f32 = 0.999;
27const STEEP: f32 = 0.85;
28/// `DAT_1401787f0`, the f32 difference `0.999 - 0.85`.
29const SLOPE_RANGE: f32 = FLAT - STEEP;
30const R_HEIGHT: f32 = 8.0;
31const G_HEIGHT: f32 = 7.0;
32const HEIGHT_RAMP: f32 = 3.0;
33const NORMAL_Z: f32 = 2.0;
34
35type Vec3 = [f32; 3];
36
37/// `Math::Vector3::Normalize`: multiply by `1 / length`; a zero vector is returned unchanged.
38fn normalize(v: Vec3) -> Vec3 {
39    let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
40    if len == 0.0 {
41        return v;
42    }
43    let inv = 1.0 / len;
44    [v[0] * inv, v[1] * inv, v[2] * inv]
45}
46
47fn dot(a: Vec3, b: Vec3) -> f32 {
48    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
49}
50
51/// `cvttss2si` to 64 bits, keeping the low byte. A NaN or a value out of range converts to
52/// `i64::MIN`, whose low byte is 0 (`as i64` would saturate to `i64::MAX`).
53fn byte(v: f32) -> u32 {
54    if v.is_nan() || v >= 9_223_372_036_854_775_808.0 || v < -9_223_372_036_854_775_808.0 {
55        return 0;
56    }
57    (v as i64 as u64 & 0xff) as u32
58}
59
60/// `clamp((h - from) / 3, 0, 1) * 255` as a byte.
61fn height_ramp(h: f32, from: f32) -> u32 {
62    // comiss order in the original keeps NaN, as `clamp` does.
63    let t = ((h - from) / HEIGHT_RAMP).clamp(0.0, 1.0);
64    byte(t * 255.0)
65}
66
67struct Cell {
68    pos: Vec3,
69    normal: Vec3,
70}
71
72impl Generator {
73    fn sample(&self, x: i32, y: i32) -> f32 {
74        let hi = self.size;
75        let x = x.clamp(0, hi);
76        let y = y.clamp(0, hi);
77        self.grid[(y * (hi + 1) + x) as usize]
78    }
79
80    /// `FUN_1400d4620`: the normal from central differences, with 2 as the up component.
81    fn cell_normal(&self, x: i32, y: i32) -> Vec3 {
82        let dx = self.sample(x + 1, y) - self.sample(x - 1, y);
83        let dy = self.sample(x, y + 1) - self.sample(x, y - 1);
84        normalize([-dx, -dy, NORMAL_Z])
85    }
86
87    /// Build the packed surface image (`dirt | rock << 8 | light << 16`). Consumes two random
88    /// values, so it must run after `run` exactly as the game does.
89    ///
90    /// Original: `FUN_1400d4910`.
91    pub fn surface_map(&mut self) -> Vec<u32> {
92        let seed_y = self.rng.rand_tol(0xffffff);
93        let seed_x = self.rng.rand_tol(0xffffff);
94        let noise = PerlinNoise::new(NOISE_SCALE, NOISE_OCTAVES, seed_x, seed_y);
95        let n = self.size;
96        let mut cells = Vec::with_capacity((n * n) as usize);
97        for y in 0..n {
98            for x in 0..n {
99                cells.push(Cell {
100                    pos: [x as f32, y as f32, self.sample(x, y)],
101                    normal: self.cell_normal(x, y),
102                });
103            }
104        }
105
106        // Each texel depends only on the finished cells (no Random), so the rows are computed
107        // on several threads (native); every row is written by one thread, in the same order of
108        // operations as one pass.
109        let mut out = vec![0u32; (n * n) as usize];
110        let mut rows: Vec<(i32, &mut [u32])> = out
111            .chunks_mut(n as usize)
112            .enumerate()
113            .map(|(y, row)| (y as i32, row))
114            .collect();
115        unbanished_formats::par::map_mut(&mut rows, |(y, row)| {
116            for x in 0..n {
117                row[x as usize] = surface_texel(&cells, &noise, n, x, *y);
118            }
119        });
120        out
121    }
122}
123
124/// One texel of `surface_map`: dirt from the noise below `LOW`, rock from the slope, both
125/// raised by height, then the light (occlusion over a radius of 10 cells times the smoothed
126/// normal's z).
127#[allow(clippy::neg_cmp_op_on_partial_ord)]
128fn surface_texel(cells: &[Cell], noise: &PerlinNoise, n: i32, x: i32, y: i32) -> u32 {
129    let c = &cells[(y * n + x) as usize];
130    let h = c.pos[2];
131    let up = c.normal[2];
132    // jbe at 0x1400d4b70: a NaN height takes the noise.
133    let mut r = if !(LOW > h) {
134        let v = noise.generate(x as f32 * NOISE_SCALE, y as f32 * NOISE_SCALE);
135        let v = v * 0.5 + 0.5;
136        byte(v * v * 255.0)
137    } else {
138        0xff
139    };
140    let mut g = if FLAT > up && up > STEEP {
141        byte((1.0 - (up - STEEP) / SLOPE_RANGE) * 255.0)
142    } else if STEEP >= up {
143        0xff
144    } else {
145        0
146    };
147    if h > R_HEIGHT {
148        r = r.max(height_ramp(h, R_HEIGHT));
149    }
150    if h > G_HEIGHT {
151        g = g.max(height_ramp(h, G_HEIGHT));
152    }
153    let mut occlusion = 0.0f32;
154    let mut count = 0.0f32;
155    let mut smooth = [0.0f32; 3];
156    // The original visits rows -10..=9 but columns -10..=10.
157    for dy in -10..10 {
158        let ny = y + dy;
159        if ny < 0 || ny >= n {
160            continue;
161        }
162        for dx in -10..=10 {
163            let nx = x + dx;
164            if nx < 0 || nx >= n || dx * dx + dy * dy > 100 {
165                continue;
166            }
167            let o = &cells[(ny * n + nx) as usize];
168            let dir = normalize([
169                o.pos[0] - c.pos[0],
170                o.pos[1] - c.pos[1],
171                o.pos[2] - c.pos[2],
172            ]);
173            let d = dot(c.normal, dir);
174            occlusion += if d > 0.0 { d } else { 0.0 };
175            count += 1.0;
176            if dx.abs() <= 1 && dy.abs() <= 1 {
177                for (s, n) in smooth.iter_mut().zip(o.normal) {
178                    *s += n;
179                }
180            }
181        }
182    }
183    let smooth = normalize(smooth);
184    let b = byte((1.0 - occlusion / count) * smooth[2] * 255.0);
185    ((g & 0xff) << 8 | (r & 0xff)) | b << 16
186}
187
188#[cfg(test)]
189mod tests {
190    use super::byte;
191
192    /// `cvttss2si` to 64 bits: a NaN or a value out of range gives `i64::MIN`, low byte 0.
193    #[test]
194    fn byte_keeps_the_low_byte_of_cvttss2si() {
195        assert_eq!(byte(255.9), 255);
196        assert_eq!(byte(256.0), 0);
197        assert_eq!(byte(f32::NAN), 0);
198        assert_eq!(byte(1e30), 0);
199        assert_eq!(byte(f32::INFINITY), 0);
200    }
201}