Skip to main content

ghast_physics/modern/
mod.rs

1//! The modern client player movement (26.1 and later), one core generic over a [`Rules`] row.
2//!
3//! Same calling convention as the older version modules: state, input and world view in; new
4//! state and the tick's movement packets out. Pure and deterministic. A version is a type implementing
5//! [`Rules`] (its data tables and constants); the core is monomorphised per version, with no
6//! run-time version branch.
7//!
8//! | rule set | version | status |
9//! |---|---|---|
10//! | [`V26_1`] | 26.1 (protocol 775) | bit-exact against the vanilla oracle |
11//! | [`V26_2`] | 26.2 (protocol 776) | bit-exact against the vanilla oracle (26.1 + collision restitution) |
12//! | [`V26_3`] | 26.3 (protocol 777) | bit-exact against the vanilla oracle for player movement, boats, minecarts and pistons (26.2 + the rule items marked 26.3 on [`Rules`]) |
13//!
14//! Unloaded chunks are handled exactly as the 26.1 client does: gravity stays normal (the client
15//! reports every chunk as present), collision skips unloaded chunks, and the fluid sweep sees no
16//! fluid when a chunk around the box is unloaded. The caller is responsible for not ticking the
17//! player before its level is loaded (26.1's `player_loaded` gate: the client freezes the player
18//! until the chunks around it have arrived); the project rule "never treat unloaded chunks as air"
19//! is enforced there, one layer up.
20//!
21//! Other moving entities: [`projectile`] (thrown items, arrows, fireballs, wind charges, the
22//! fishing bobber), [`drop`](mod@drop) (item entities, experience orbs, primed TNT, falling blocks) and
23//! [`launch`] (the launch velocities of thrown and shot projectiles and dropped items), each on
24//! the server's and a client's side.
25//!
26//! Pistons: [`piston`] (moving blocks, their shapes and pushes). Not modelled (see the crate
27//! README): other block entities. Known gap: an opening shulker box's collision reaches past its cube (its lid moves
28//! with the block entity); the tables have the closed box, and the client push-out probe relies on
29//! every suffocating large shape staying inside its cube (pinned by the `ghast-data` test
30//! `suffocating_large_shapes_stay_in_their_cube`).
31
32mod attr;
33mod boat;
34mod body;
35mod border;
36pub(crate) mod collide;
37pub mod drop;
38mod entity;
39mod ext;
40mod fluid;
41mod inside;
42mod jdk_math;
43pub mod launch;
44mod load;
45pub(crate) mod math;
46mod mount;
47mod moving;
48pub mod piston;
49mod piston_facts;
50mod piston_shapes;
51mod player;
52pub mod projectile;
53mod rules;
54#[cfg(feature = "v26_3")]
55mod sturdy_facts;
56
57pub use attr::{
58    Attribute, MAX_MODIFIERS, Modifier, ModifierId, SPRINT_AMOUNT, identifier_hash,
59    java_string_hash, sprinting_id,
60};
61pub use boat::{Boat, BoatKind, BoatStatus, Seat, tick_boat, tick_passenger};
62pub use body::Side;
63pub use border::BorderState;
64pub use entity::{
65    PushKind, Pusher, Surroundings, collides_26_1, push_by, push_by_pair, push_kind_26_1,
66    section_query_reaches,
67};
68pub use ext::{MAX_ROCKETS, MovementAttributes, PlayerExt};
69pub use load::LoadGate;
70pub use mount::{Mount, MountKind, happy_ghast_collides, tick_mount};
71pub use player::{
72    AttributeKind, Attributes, ClientInput, ClientOptions, CollisionContext, Dimensions, Effects,
73    LevelInfo, PlayerState, Pose, SentState, UseEffects, in_water_or_rain, no_block_collision,
74    on_climbable, on_climbable_ext, riptide, state_collides, tick, tick_ext, tick_in,
75};
76pub use rules::Rules;
77#[cfg(feature = "v26_1")]
78pub use rules::V26_1;
79#[cfg(feature = "v26_2")]
80pub use rules::V26_2;
81#[cfg(feature = "v26_3")]
82pub use rules::V26_3;
83
84use crate::input::{Packets, TickInput};
85use crate::world::BlockView;
86
87/// Options of the modern rule sets (none yet).
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
89pub struct Options {}
90
91#[cfg(feature = "v26_1")]
92impl crate::Ruleset for V26_1 {
93    type BlockState = ghast_data::v26_1::BlockState;
94    type Player = PlayerState;
95    type Options = Options;
96
97    #[inline]
98    fn tick_with<W: BlockView<State = Self::BlockState>>(
99        player: &mut PlayerState,
100        input: &TickInput,
101        world: &W,
102        _options: &Options,
103        out: &mut Packets,
104    ) {
105        tick::<V26_1, W>(player, input, world, out);
106    }
107}
108
109#[cfg(feature = "v26_2")]
110impl crate::Ruleset for V26_2 {
111    type BlockState = ghast_data::v26_2::BlockState;
112    type Player = PlayerState;
113    type Options = Options;
114
115    #[inline]
116    fn tick_with<W: BlockView<State = Self::BlockState>>(
117        player: &mut PlayerState,
118        input: &TickInput,
119        world: &W,
120        _options: &Options,
121        out: &mut Packets,
122    ) {
123        tick::<V26_2, W>(player, input, world, out);
124    }
125}
126
127#[cfg(feature = "v26_3")]
128impl crate::Ruleset for V26_3 {
129    type BlockState = ghast_data::v26_3::BlockState;
130    type Player = PlayerState;
131    type Options = Options;
132
133    #[inline]
134    fn tick_with<W: BlockView<State = Self::BlockState>>(
135        player: &mut PlayerState,
136        input: &TickInput,
137        world: &W,
138        _options: &Options,
139        out: &mut Packets,
140    ) {
141        tick::<V26_3, W>(player, input, world, out);
142    }
143}
144
145/// A [`crate::MemoryWorld`]-like in-memory world for modern versions (build height `-64..320`).
146#[cfg(feature = "v26_1")]
147pub type MemoryWorld26 = ModernMemoryWorld<ghast_data::v26_1::BlockState>;
148
149/// [`MemoryWorld26`] over 26.2 block states.
150#[cfg(feature = "v26_2")]
151pub type MemoryWorld262 = ModernMemoryWorld<ghast_data::v26_2::BlockState>;
152
153/// [`MemoryWorld26`] over 26.3 block states.
154#[cfg(feature = "v26_3")]
155pub type MemoryWorld263 = ModernMemoryWorld<ghast_data::v26_3::BlockState>;
156
157/// An in-memory world with a configurable build height: explicitly loaded chunk columns,
158/// everything else unloaded. For tests, benches and offline planning.
159#[derive(Clone, Debug)]
160pub struct ModernMemoryWorld<S> {
161    /// Decoded states (decoding happens when a block is stored, not when it is read).
162    columns: std::collections::HashMap<(i32, i32), Box<[S]>>,
163    loaded_rects: Vec<[i32; 4]>,
164    decode: fn(u16) -> S,
165    air: S,
166    min_y: i32,
167    height: i32,
168    border: crate::WorldBorder,
169}
170
171impl<S: Copy> ModernMemoryWorld<S> {
172    /// An empty world; `decode` turns a stored raw value into a state (raw 0 must be air).
173    #[must_use]
174    pub fn new(decode: fn(u16) -> S, min_y: i32, height: i32) -> Self {
175        ModernMemoryWorld {
176            columns: std::collections::HashMap::new(),
177            loaded_rects: Vec::new(),
178            decode,
179            air: decode(0),
180            min_y,
181            height,
182            border: crate::WorldBorder::default(),
183        }
184    }
185
186    /// Lowest block Y of the build height.
187    #[must_use]
188    pub fn min_y(&self) -> i32 {
189        self.min_y
190    }
191
192    /// Number of block rows of the build height.
193    #[must_use]
194    pub fn height(&self) -> i32 {
195        self.height
196    }
197
198    /// Marks the inclusive chunk rectangle `[cx0, cz0] ..= [cx1, cz1]` as loaded.
199    pub fn load_chunks(&mut self, cx0: i32, cz0: i32, cx1: i32, cz1: i32) {
200        self.loaded_rects.push([cx0, cz0, cx1, cz1]);
201    }
202
203    /// Sets the world border.
204    pub fn set_border(&mut self, b: crate::WorldBorder) {
205        self.border = b;
206    }
207
208    /// Stores a raw block value (positions outside the build height are ignored).
209    pub fn set_raw(&mut self, x: i32, y: i32, z: i32, raw: u16) {
210        if y < self.min_y || y >= self.min_y + self.height {
211            return;
212        }
213        let len = (16 * 16 * self.height) as usize;
214        let air = self.air;
215        let state = (self.decode)(raw);
216        let col = self
217            .columns
218            .entry((x >> 4, z >> 4))
219            .or_insert_with(|| vec![air; len].into_boxed_slice());
220        col[Self::index(x, y - self.min_y, z)] = state;
221    }
222
223    /// Fills the inclusive box with a raw value.
224    pub fn fill_raw(&mut self, from: [i32; 3], to: [i32; 3], raw: u16) {
225        for x in from[0]..=to[0] {
226            for z in from[2]..=to[2] {
227                for y in from[1]..=to[1] {
228                    self.set_raw(x, y, z, raw);
229                }
230            }
231        }
232    }
233
234    #[inline]
235    fn index(x: i32, ry: i32, z: i32) -> usize {
236        ((ry as usize) << 8) | (((z & 15) as usize) << 4) | ((x & 15) as usize)
237    }
238
239    #[inline]
240    fn loaded(&self, cx: i32, cz: i32) -> bool {
241        self.loaded_rects
242            .iter()
243            .any(|r| cx >= r[0] && cx <= r[2] && cz >= r[1] && cz <= r[3])
244    }
245}
246
247impl<S: Copy> BlockView for ModernMemoryWorld<S> {
248    type State = S;
249
250    #[inline]
251    fn block(&self, x: i32, y: i32, z: i32) -> S {
252        let (cx, cz) = (x >> 4, z >> 4);
253        let ry = y - self.min_y;
254        if ry < 0 || ry >= self.height || !self.loaded(cx, cz) {
255            return self.air;
256        }
257        match self.columns.get(&(cx, cz)) {
258            Some(col) => col[Self::index(x, ry, z)],
259            None => self.air,
260        }
261    }
262
263    #[inline]
264    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
265        self.loaded(chunk_x, chunk_z)
266    }
267
268    fn world_border(&self) -> crate::WorldBorder {
269        self.border
270    }
271}
272
273/// An empty 26.3 world (overworld build height); unknown ids decode to air.
274#[cfg(feature = "v26_3")]
275#[must_use]
276pub fn memory_world_26_3() -> MemoryWorld263 {
277    ModernMemoryWorld::new(
278        |raw| {
279            ghast_data::v26_3::BlockState::from_id(raw)
280                .unwrap_or(ghast_data::v26_3::BlockState::AIR)
281        },
282        -64,
283        384,
284    )
285}
286
287/// An empty 26.2 world (overworld build height); unknown ids decode to air.
288#[cfg(feature = "v26_2")]
289#[must_use]
290pub fn memory_world_26_2() -> MemoryWorld262 {
291    ModernMemoryWorld::new(
292        |raw| {
293            ghast_data::v26_2::BlockState::from_id(raw)
294                .unwrap_or(ghast_data::v26_2::BlockState::AIR)
295        },
296        -64,
297        384,
298    )
299}
300
301/// An empty 26.1 world (overworld build height); unknown ids decode to air.
302#[cfg(feature = "v26_1")]
303#[must_use]
304pub fn memory_world_26_1() -> MemoryWorld26 {
305    ModernMemoryWorld::new(
306        |raw| {
307            ghast_data::v26_1::BlockState::from_id(raw)
308                .unwrap_or(ghast_data::v26_1::BlockState::AIR)
309        },
310        -64,
311        384,
312    )
313}