Skip to main content

ob_engine/
voxel.rs

1//! KVX voxel models (Ken Silverman's format) used by Blood for 3D items and decorations.
2//!
3//! Layout of the first (full-detail) mip level:
4//! `i32 numbytes, xsiz, ysiz, zsiz, xpivot, ypivot, zpivot` (pivots in 8.8 fixed point),
5//! `i32 xoffset[xsiz+1]`, `u16 xyoffset[xsiz][ysiz+1]`, then per column a list of slabs
6//! `{u8 ztop, u8 zleng, u8 cull, u8 colors[zleng]}`. Offsets are relative to the start of
7//! the `xoffset` table. The file ends with a 768-byte palette (ignored: colours are indices
8//! into the game palette).
9
10pub const EMPTY: u8 = 255;
11
12#[derive(Debug, Clone)]
13pub struct Voxel {
14    pub xs: usize,
15    pub ys: usize,
16    pub zs: usize,
17    pub pivot: (f64, f64, f64),
18    /// Dense grid, index `(x * ys + y) * zs + z`; `EMPTY` where no voxel.
19    pub data: Vec<u8>,
20}
21
22impl Voxel {
23    pub fn parse(b: &[u8]) -> Option<Voxel> {
24        let rd = |o: usize| -> Option<i32> { Some(i32::from_le_bytes(b.get(o..o + 4)?.try_into().ok()?)) };
25        let numbytes = rd(0)? as usize;
26        let (xs, ys, zs) = (rd(4)? as usize, rd(8)? as usize, rd(12)? as usize);
27        if xs == 0 || ys == 0 || zs == 0 || xs > 256 || ys > 256 || zs > 256 {
28            return None;
29        }
30        let pivot = (rd(16)? as f64 / 256.0, rd(20)? as f64 / 256.0, rd(24)? as f64 / 256.0);
31        let base = 28;
32        if numbytes + 4 > b.len() {
33            return None;
34        }
35        let xoff: Vec<usize> = (0..=xs)
36            .map(|i| rd(base + i * 4).map(|v| v as usize))
37            .collect::<Option<_>>()?;
38        let xyo = base + (xs + 1) * 4;
39        let mut data = vec![EMPTY; xs * ys * zs];
40        for x in 0..xs {
41            let col_base = base + xoff[x];
42            let row = |y: usize| -> Option<usize> {
43                let o = xyo + (x * (ys + 1) + y) * 2;
44                Some(u16::from_le_bytes(b.get(o..o + 2)?.try_into().ok()?) as usize)
45            };
46            for y in 0..ys {
47                let (start, end) = (col_base + row(y)?, col_base + row(y + 1)?);
48                let mut p = start;
49                while p + 3 <= end && end <= b.len() {
50                    let ztop = b[p] as usize;
51                    let zlen = b[p + 1] as usize;
52                    p += 3;
53                    for k in 0..zlen {
54                        let z = ztop + k;
55                        if z < zs && p + k < b.len() {
56                            data[(x * ys + y) * zs + z] = b[p + k];
57                        }
58                    }
59                    p += zlen;
60                }
61            }
62        }
63        Some(Voxel {
64            xs,
65            ys,
66            zs,
67            pivot,
68            data,
69        })
70    }
71
72    #[inline]
73    pub fn at(&self, x: i32, y: i32, z: i32) -> u8 {
74        if x < 0 || y < 0 || z < 0 || x as usize >= self.xs || y as usize >= self.ys || z as usize >= self.zs {
75            return EMPTY;
76        }
77        self.data[(x as usize * self.ys + y as usize) * self.zs + z as usize]
78    }
79
80    /// Casts a ray in model space (units = voxels). Returns `(t, colour)` of the first
81    /// solid voxel, where `t` is the ray parameter.
82    pub fn cast(&self, o: [f64; 3], d: [f64; 3]) -> Option<(f64, u8)> {
83        let size = [self.xs as f64, self.ys as f64, self.zs as f64];
84        // Slab intersection with the model box.
85        let (mut t0, mut t1) = (0.0f64, f64::INFINITY);
86        for a in 0..3 {
87            if d[a].abs() < 1e-12 {
88                if o[a] < 0.0 || o[a] > size[a] {
89                    return None;
90                }
91            } else {
92                let (mut ta, mut tb) = ((0.0 - o[a]) / d[a], (size[a] - o[a]) / d[a]);
93                if ta > tb {
94                    std::mem::swap(&mut ta, &mut tb);
95                }
96                t0 = t0.max(ta);
97                t1 = t1.min(tb);
98            }
99        }
100        if t0 > t1 {
101            return None;
102        }
103        // 3D DDA from the entry point.
104        let t = t0 + 1e-6;
105        let p = [o[0] + d[0] * t, o[1] + d[1] * t, o[2] + d[2] * t];
106        let mut cell = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
107        let mut step = [0i32; 3];
108        let mut tmax = [f64::INFINITY; 3];
109        let mut tdelta = [f64::INFINITY; 3];
110        for a in 0..3 {
111            if d[a] > 0.0 {
112                step[a] = 1;
113                tmax[a] = t + ((cell[a] + 1) as f64 - p[a]) / d[a];
114                tdelta[a] = 1.0 / d[a];
115            } else if d[a] < 0.0 {
116                step[a] = -1;
117                tmax[a] = t + (cell[a] as f64 - p[a]) / d[a];
118                tdelta[a] = -1.0 / d[a];
119            }
120        }
121        let mut tc = t;
122        for _ in 0..(self.xs + self.ys + self.zs + 3) {
123            let c = self.at(cell[0], cell[1], cell[2]);
124            if c != EMPTY {
125                return Some((tc, c));
126            }
127            let a = if tmax[0] < tmax[1] {
128                if tmax[0] < tmax[2] {
129                    0
130                } else {
131                    2
132                }
133            } else if tmax[1] < tmax[2] {
134                1
135            } else {
136                2
137            };
138            if tmax[a] > t1 {
139                return None;
140            }
141            tc = tmax[a];
142            cell[a] += step[a];
143            tmax[a] += tdelta[a];
144        }
145        None
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    /// 2x1x3 model: column (0,0) has voxels z=1..2 colour 7; column (1,0) empty.
154    fn sample() -> Vec<u8> {
155        let (xs, ys, zs) = (2i32, 1i32, 3i32);
156        let mut cols: Vec<u8> = Vec::new();
157        cols.extend_from_slice(&[1, 2, 0, 7, 7]); // slab for x=0,y=0
158        let xoff_tab = (xs as usize + 1) * 4;
159        let xy_tab = xs as usize * (ys as usize + 1) * 2;
160        let start = (xoff_tab + xy_tab) as i32;
161        let mut b = Vec::new();
162        let numbytes = 24 + xoff_tab + xy_tab + cols.len();
163        for v in [numbytes as i32, xs, ys, zs, 256, 128, 3 * 256] {
164            b.extend_from_slice(&v.to_le_bytes());
165        }
166        for v in [start, start + 5, start + 5] {
167            b.extend_from_slice(&v.to_le_bytes());
168        }
169        for v in [0u16, 5, 0, 0] {
170            b.extend_from_slice(&v.to_le_bytes());
171        }
172        b.extend_from_slice(&cols);
173        b.extend_from_slice(&[0u8; 768]);
174        b
175    }
176
177    #[test]
178    fn parse_and_cast() {
179        let v = Voxel::parse(&sample()).unwrap();
180        assert_eq!((v.xs, v.ys, v.zs), (2, 1, 3));
181        assert_eq!(v.pivot, (1.0, 0.5, 3.0));
182        assert_eq!(v.at(0, 0, 1), 7);
183        assert_eq!(v.at(0, 0, 0), EMPTY);
184        assert_eq!(v.at(1, 0, 1), EMPTY);
185        // Ray along +x at z=1.5 from x=-1 hits voxel (0,0,1) at t=1.
186        let (t, c) = v.cast([-1.0, 0.5, 1.5], [1.0, 0.0, 0.0]).unwrap();
187        assert!((t - 1.0).abs() < 1e-5 && c == 7, "{t}");
188        // Ray along +x at z=0.5 misses (empty row).
189        assert!(v.cast([-1.0, 0.5, 0.5], [1.0, 0.0, 0.0]).is_none());
190        // Ray from the -x side going -x never enters.
191        assert!(v.cast([-1.0, 0.5, 1.5], [-1.0, 0.0, 0.0]).is_none());
192    }
193}