Skip to main content

ob_engine/
geom.rs

1//! Geometry helpers over Build-style sector/wall data.
2//!
3//! Conventions: x grows east, y grows south, z grows *down*. Angles use 2048 units
4//! per full turn, 0 = east, 512 = south. One xy unit equals 16 z units.
5
6use crate::map::{Plane, Sector, Wall};
7
8pub const ANGLE_UNITS: f64 = 2048.0;
9
10#[inline]
11pub fn ang_to_rad(a: f64) -> f64 {
12    a * std::f64::consts::TAU / ANGLE_UNITS
13}
14
15/// Linear plane equation `z = a + bx * x + by * y` for a (possibly sloped) sector plane.
16#[derive(Debug, Clone, Copy)]
17pub struct PlaneEq {
18    pub a: f64,
19    pub bx: f64,
20    pub by: f64,
21}
22
23impl PlaneEq {
24    #[inline]
25    pub fn z_at(&self, x: f64, y: f64) -> f64 {
26        self.a + self.bx * x + self.by * y
27    }
28}
29
30/// Sloped-plane flag in ceiling/floor stat.
31pub const STAT_SLOPED: u16 = 2;
32
33pub fn plane_eq(sector: &Sector, walls: &[Wall], plane: &Plane) -> PlaneEq {
34    let z0 = plane.z as f64;
35    if plane.stat & STAT_SLOPED == 0 || plane.heinum == 0 || sector.wallnum < 2 {
36        return PlaneEq {
37            a: z0,
38            bx: 0.0,
39            by: 0.0,
40        };
41    }
42    let w1 = &walls[sector.wallptr as usize];
43    let w2 = &walls[w1.point2 as usize];
44    let (x1, y1) = (w1.x as f64, w1.y as f64);
45    let dx = w2.x as f64 - x1;
46    let dy = w2.y as f64 - y1;
47    let len = (dx * dx + dy * dy).sqrt();
48    if len < 1e-9 {
49        return PlaneEq {
50            a: z0,
51            bx: 0.0,
52            by: 0.0,
53        };
54    }
55    // z = z0 + heinum/256 * (dx*(py-y1) - dy*(px-x1)) / len
56    let k = plane.heinum as f64 / (256.0 * len);
57    let bx = -dy * k;
58    let by = dx * k;
59    PlaneEq {
60        a: z0 - bx * x1 - by * y1,
61        bx,
62        by,
63    }
64}
65
66pub fn ceil_eq(sectors: &[Sector], walls: &[Wall], s: usize) -> PlaneEq {
67    plane_eq(&sectors[s], walls, &sectors[s].ceiling)
68}
69pub fn floor_eq(sectors: &[Sector], walls: &[Wall], s: usize) -> PlaneEq {
70    plane_eq(&sectors[s], walls, &sectors[s].floor)
71}
72
73/// Ceiling and floor z of sector `s` at point (x, y).
74pub fn zs_of_slope(sectors: &[Sector], walls: &[Wall], s: usize, x: f64, y: f64) -> (f64, f64) {
75    (
76        ceil_eq(sectors, walls, s).z_at(x, y),
77        floor_eq(sectors, walls, s).z_at(x, y),
78    )
79}
80
81/// Even-odd point-in-sector test (handles inner loops).
82pub fn inside_sector(sectors: &[Sector], walls: &[Wall], s: usize, x: f64, y: f64) -> bool {
83    let sec = &sectors[s];
84    let start = sec.wallptr as usize;
85    let end = start + sec.wallnum as usize;
86    let mut inside = false;
87    for i in start..end {
88        let w1 = &walls[i];
89        let w2 = &walls[w1.point2 as usize];
90        let (x1, y1, x2, y2) = (w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64);
91        if (y1 > y) != (y2 > y) {
92            let xi = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
93            if x < xi {
94                inside = !inside;
95            }
96        }
97    }
98    inside
99}
100
101/// Finds the sector containing (x, y), searching neighbours of `hint` first.
102pub fn update_sector(sectors: &[Sector], walls: &[Wall], x: f64, y: f64, hint: i32) -> i32 {
103    if hint >= 0 && (hint as usize) < sectors.len() {
104        let h = hint as usize;
105        if inside_sector(sectors, walls, h, x, y) {
106            return hint;
107        }
108        let sec = &sectors[h];
109        for i in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
110            let ns = walls[i].nextsector;
111            if ns >= 0 && inside_sector(sectors, walls, ns as usize, x, y) {
112                return ns as i32;
113            }
114        }
115    }
116    (0..sectors.len())
117        .find(|&s| inside_sector(sectors, walls, s, x, y))
118        .map_or(-1, |s| s as i32)
119}
120
121/// Like [`update_sector`] but also requires z to lie between ceiling and floor.
122pub fn update_sector_z(sectors: &[Sector], walls: &[Wall], x: f64, y: f64, z: f64, hint: i32) -> i32 {
123    let ok = |s: usize| {
124        if !inside_sector(sectors, walls, s, x, y) {
125            return false;
126        }
127        let (c, f) = zs_of_slope(sectors, walls, s, x, y);
128        z >= c && z <= f
129    };
130    if hint >= 0 && (hint as usize) < sectors.len() {
131        let h = hint as usize;
132        if ok(h) {
133            return hint;
134        }
135        let sec = &sectors[h];
136        for wall in &walls[sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize] {
137            let ns = wall.nextsector;
138            if ns >= 0 && ok(ns as usize) {
139                return ns as i32;
140            }
141        }
142    }
143    let s = update_sector(sectors, walls, x, y, hint);
144    if s >= 0 {
145        return s;
146    }
147    -1
148}
149
150/// Ray/segment intersection. Returns `(t, s)` where the hit point is `o + d*t`
151/// and `s` in `[0,1]` is the position along the segment `a -> b`.
152#[inline]
153#[allow(clippy::too_many_arguments)]
154pub fn ray_segment(ox: f64, oy: f64, dx: f64, dy: f64, ax: f64, ay: f64, bx: f64, by: f64) -> Option<(f64, f64)> {
155    let ex = bx - ax;
156    let ey = by - ay;
157    let den = dx * ey - dy * ex;
158    if den.abs() < 1e-12 {
159        return None;
160    }
161    let qx = ax - ox;
162    let qy = ay - oy;
163    let t = (qx * ey - qy * ex) / den;
164    let s = (qx * dy - qy * dx) / den;
165    if (-1e-9..=1.0 + 1e-9).contains(&s) {
166        Some((t, s.clamp(0.0, 1.0)))
167    } else {
168        None
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::map::{Sector, Wall};
176
177    pub fn square_sector() -> (Vec<Sector>, Vec<Wall>) {
178        let pts = [(0, 0), (1024, 0), (1024, 1024), (0, 1024)];
179        let walls: Vec<Wall> = pts
180            .iter()
181            .enumerate()
182            .map(|(i, &(x, y))| Wall {
183                x,
184                y,
185                point2: ((i + 1) % 4) as i16,
186                nextwall: -1,
187                nextsector: -1,
188                ..Default::default()
189            })
190            .collect();
191        let mut s = Sector {
192            wallptr: 0,
193            wallnum: 4,
194            ..Default::default()
195        };
196        s.ceiling.z = -8192;
197        s.floor.z = 0;
198        (vec![s], walls)
199    }
200
201    #[test]
202    fn inside_and_update() {
203        let (s, w) = square_sector();
204        assert!(inside_sector(&s, &w, 0, 512.0, 512.0));
205        assert!(!inside_sector(&s, &w, 0, 2000.0, 512.0));
206        assert_eq!(update_sector(&s, &w, 10.0, 10.0, -1), 0);
207    }
208
209    #[test]
210    fn slope_matches_build_formula() {
211        let (mut s, w) = square_sector();
212        s[0].floor.stat = STAT_SLOPED;
213        s[0].floor.heinum = 256; // 1 z unit per xy unit away from first wall
214        let (_, f) = zs_of_slope(&s, &w, 0, 100.0, 300.0);
215        // first wall runs along +x at y=0, so z grows with y
216        assert!((f - 300.0).abs() < 1e-6, "{f}");
217    }
218
219    #[test]
220    fn ray_hits_segment() {
221        let (t, s) = ray_segment(0.0, 0.0, 1.0, 0.0, 10.0, -5.0, 10.0, 5.0).unwrap();
222        assert!((t - 10.0).abs() < 1e-9 && (s - 0.5).abs() < 1e-9);
223    }
224}