Skip to main content

ghast_physics/
world.rs

1//! What the physics needs to know about the world, and a simple in-memory implementation.
2
3use std::collections::HashMap;
4
5/// Read access to the blocks around a player, implemented by the world crate.
6///
7/// The physics only calls [`BlockView::block`] for valid positions: `|x|, |z| < 30_000_000` and
8/// `0 <= y < 256` (vanilla returns air outside that range without asking the chunk). The
9/// implementation must
10///
11/// - return the state **as vanilla decodes it** from chunk data: for 1.8 that is
12///   `BlockState::from_raw_vanilla` (unknown ids and unregistered metas read as air);
13/// - return air for positions in columns that are not loaded (vanilla's client uses an empty chunk
14///   there — never "solid", never an error).
15pub trait BlockView {
16    /// Block state type of the protocol version (`ghast_data::v1_8::BlockState` for 1.8).
17    type State: Copy;
18
19    /// The block state at a valid position (air when the column is not loaded).
20    fn block(&self, x: i32, y: i32, z: i32) -> Self::State;
21
22    /// `true` when the chunk column `(chunk_x, chunk_z)` has been received from the server.
23    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool;
24
25    /// The current world border (default: vanilla's initial border, centre 0, 0, size 6e7).
26    fn world_border(&self) -> WorldBorder {
27        WorldBorder::default()
28    }
29}
30
31impl<W: BlockView + ?Sized> BlockView for &W {
32    type State = W::State;
33
34    #[inline]
35    fn block(&self, x: i32, y: i32, z: i32) -> Self::State {
36        (**self).block(x, y, z)
37    }
38
39    #[inline]
40    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
41        (**self).is_chunk_loaded(chunk_x, chunk_z)
42    }
43
44    #[inline]
45    fn world_border(&self) -> WorldBorder {
46        (**self).world_border()
47    }
48}
49
50/// The world border as the collision code sees it (centre and current diameter).
51///
52/// Vanilla clamps each bound to ±29,999,984 (`maxWorldBorderRadius`). The default (centre 0, 0,
53/// size 6e7) is what a client has before any border packet arrives.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct WorldBorder {
56    /// Centre X.
57    pub center_x: f64,
58    /// Centre Z.
59    pub center_z: f64,
60    /// Current diameter (a moving border is not modelled: pass its current size).
61    pub size: f64,
62}
63
64impl Default for WorldBorder {
65    fn default() -> Self {
66        WorldBorder {
67            center_x: 0.0,
68            center_z: 0.0,
69            size: 6.0e7,
70        }
71    }
72}
73
74/// Vanilla's clamp for each border bound.
75const MAX_BORDER_RADIUS: f64 = 29_999_984.0;
76
77impl WorldBorder {
78    /// West bound (minimum X).
79    #[must_use]
80    pub fn west(&self) -> f64 {
81        let v = self.center_x - self.size / 2.0;
82        if v < -MAX_BORDER_RADIUS {
83            -MAX_BORDER_RADIUS
84        } else {
85            v
86        }
87    }
88
89    /// East bound (maximum X).
90    #[must_use]
91    pub fn east(&self) -> f64 {
92        let v = self.center_x + self.size / 2.0;
93        if v > MAX_BORDER_RADIUS {
94            MAX_BORDER_RADIUS
95        } else {
96            v
97        }
98    }
99
100    /// North bound (minimum Z).
101    #[must_use]
102    pub fn north(&self) -> f64 {
103        let v = self.center_z - self.size / 2.0;
104        if v < -MAX_BORDER_RADIUS {
105            -MAX_BORDER_RADIUS
106        } else {
107            v
108        }
109    }
110
111    /// South bound (maximum Z).
112    #[must_use]
113    pub fn south(&self) -> f64 {
114        let v = self.center_z + self.size / 2.0;
115        if v > MAX_BORDER_RADIUS {
116            MAX_BORDER_RADIUS
117        } else {
118            v
119        }
120    }
121
122    /// `true` when the block column at `(x, z)` is (partly) inside the border.
123    #[must_use]
124    pub fn contains_block(&self, x: i32, z: i32) -> bool {
125        f64::from(x) + 1.0 > self.west()
126            && f64::from(x) < self.east()
127            && f64::from(z) + 1.0 > self.north()
128            && f64::from(z) < self.south()
129    }
130}
131
132/// Number of blocks in one 16×256×16 chunk column.
133const COLUMN_LEN: usize = 16 * 256 * 16;
134
135/// A small in-memory world: explicitly loaded chunk columns, everything else unloaded.
136///
137/// Meant for tests, benches and offline planning. Blocks are stored per column in a dense array
138/// of raw values (`u16`), so lookups are a hash of the column plus an index.
139#[derive(Clone, Debug)]
140pub struct MemoryWorld<S> {
141    columns: HashMap<(i32, i32), Box<[u16]>>,
142    loaded_rects: Vec<[i32; 4]>,
143    decode: fn(u16) -> S,
144}
145
146impl<S: Copy> MemoryWorld<S> {
147    /// An empty world where nothing is loaded. `decode` turns a stored raw value into a state
148    /// (for 1.8: `BlockState::from_raw_vanilla`); raw 0 must decode to air.
149    #[must_use]
150    pub fn new(decode: fn(u16) -> S) -> Self {
151        MemoryWorld {
152            columns: HashMap::new(),
153            loaded_rects: Vec::new(),
154            decode,
155        }
156    }
157
158    /// Marks the inclusive chunk rectangle `[cx0, cz0] ..= [cx1, cz1]` as loaded (air until
159    /// blocks are set).
160    pub fn load_chunks(&mut self, cx0: i32, cz0: i32, cx1: i32, cz1: i32) {
161        self.loaded_rects.push([cx0, cz0, cx1, cz1]);
162    }
163
164    /// Stores a raw block value. Positions outside `0..256` in Y are ignored. Setting a block in
165    /// a column that is not loaded stores it but it stays invisible until the column is loaded.
166    pub fn set_raw(&mut self, x: i32, y: i32, z: i32, raw: u16) {
167        if !(0..256).contains(&y) {
168            return;
169        }
170        let col = self
171            .columns
172            .entry((x >> 4, z >> 4))
173            .or_insert_with(|| vec![0u16; COLUMN_LEN].into_boxed_slice());
174        col[Self::index(x, y, z)] = raw;
175    }
176
177    /// Fills the inclusive box with a raw value.
178    pub fn fill_raw(&mut self, from: [i32; 3], to: [i32; 3], raw: u16) {
179        for x in from[0]..=to[0] {
180            for z in from[2]..=to[2] {
181                for y in from[1]..=to[1] {
182                    self.set_raw(x, y, z, raw);
183                }
184            }
185        }
186    }
187
188    #[inline]
189    fn index(x: i32, y: i32, z: i32) -> usize {
190        ((y as usize) << 8) | (((z & 15) as usize) << 4) | ((x & 15) as usize)
191    }
192
193    #[inline]
194    fn loaded(&self, cx: i32, cz: i32) -> bool {
195        self.loaded_rects
196            .iter()
197            .any(|r| cx >= r[0] && cx <= r[2] && cz >= r[1] && cz <= r[3])
198    }
199}
200
201impl<S: Copy> BlockView for MemoryWorld<S> {
202    type State = S;
203
204    #[inline]
205    fn block(&self, x: i32, y: i32, z: i32) -> S {
206        let decode = self.decode;
207        let (cx, cz) = (x >> 4, z >> 4);
208        if !self.loaded(cx, cz) {
209            return decode(0);
210        }
211        match self.columns.get(&(cx, cz)) {
212            Some(col) => decode(col[Self::index(x, y, z)]),
213            None => decode(0),
214        }
215    }
216
217    #[inline]
218    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
219        self.loaded(chunk_x, chunk_z)
220    }
221}
222
223/// Side of the per-tick block cache cube.
224#[cfg_attr(
225    not(any(
226        feature = "v1_8",
227        feature = "v1_12",
228        feature = "v1_16_5",
229        feature = "v26_1"
230    )),
231    allow(dead_code)
232)]
233const CACHE_SIDE: i32 = 8;
234
235/// A per-tick memo of block lookups in an 8×8×8 cube around the player.
236///
237/// One tick asks for the same few dozen positions many times (pose checks, push-out probes, the
238/// collision sweeps, step-up retries); the cache turns the repeats into an array read. Anything
239/// outside the cube goes straight to the world. Purely an optimisation: results are identical.
240#[cfg_attr(
241    not(any(
242        feature = "v1_8",
243        feature = "v1_12",
244        feature = "v1_16_5",
245        feature = "v26_1"
246    )),
247    allow(dead_code)
248)]
249pub(crate) struct TickCache<'w, W: BlockView> {
250    world: &'w W,
251    origin: [i32; 3],
252    /// Chunk-loaded answers for the 3×3 chunks around the origin's chunk (0 unknown, 1 no, 2 yes).
253    loaded: [std::cell::Cell<u8>; 9],
254    chunk: [i32; 2],
255    cells: [std::cell::Cell<Option<W::State>>; (CACHE_SIDE * CACHE_SIDE * CACHE_SIDE) as usize],
256}
257
258#[cfg_attr(
259    not(any(
260        feature = "v1_8",
261        feature = "v1_12",
262        feature = "v1_16_5",
263        feature = "v26_1"
264    )),
265    allow(dead_code)
266)]
267impl<'w, W: BlockView> TickCache<'w, W> {
268    /// A cache centred on block `(x, y, z)`.
269    pub(crate) fn new(world: &'w W, x: i32, y: i32, z: i32) -> Self {
270        let h = CACHE_SIDE / 2;
271        TickCache {
272            world,
273            origin: [x - h, y - h + 1, z - h],
274            loaded: [const { std::cell::Cell::new(0) }; 9],
275            chunk: [x >> 4, z >> 4],
276            cells: [const { std::cell::Cell::new(None) };
277                (CACHE_SIDE * CACHE_SIDE * CACHE_SIDE) as usize],
278        }
279    }
280}
281
282impl<W: BlockView> BlockView for TickCache<'_, W> {
283    type State = W::State;
284
285    // Always inlined: the hottest call of every tick. Left to the size heuristic, a world
286    // whose read path grows by a few match arms (shared sections) turned this into a call at
287    // the collision loops (engine bench: +11 % instructions per tick on 26.1).
288    #[inline(always)]
289    fn block(&self, x: i32, y: i32, z: i32) -> W::State {
290        let (dx, dy, dz) = (
291            x.wrapping_sub(self.origin[0]) as u32,
292            y.wrapping_sub(self.origin[1]) as u32,
293            z.wrapping_sub(self.origin[2]) as u32,
294        );
295        let side = CACHE_SIDE as u32;
296        if dx >= side || dy >= side || dz >= side {
297            return self.world.block(x, y, z);
298        }
299        let cell = &self.cells[((dy * side + dz) * side + dx) as usize];
300        match cell.get() {
301            Some(s) => s,
302            None => {
303                let s = self.world.block(x, y, z);
304                cell.set(Some(s));
305                s
306            }
307        }
308    }
309
310    #[inline]
311    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
312        let (dx, dz) = (
313            chunk_x.wrapping_sub(self.chunk[0]).wrapping_add(1) as u32,
314            chunk_z.wrapping_sub(self.chunk[1]).wrapping_add(1) as u32,
315        );
316        if dx >= 3 || dz >= 3 {
317            return self.world.is_chunk_loaded(chunk_x, chunk_z);
318        }
319        let cell = &self.loaded[(dz * 3 + dx) as usize];
320        match cell.get() {
321            0 => {
322                let l = self.world.is_chunk_loaded(chunk_x, chunk_z);
323                cell.set(if l { 2 } else { 1 });
324                l
325            }
326            v => v == 2,
327        }
328    }
329
330    #[inline]
331    fn world_border(&self) -> WorldBorder {
332        self.world.world_border()
333    }
334}