ghast-physics 0.4.10

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9 first), verified bit for bit against the real game
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! 1.16.5 block facts and collision shapes for the movement code, from `ghast-data`'s tables
//! of vanilla's exact voxel grids (generated from the oracle's dump).

use ghast_data::v1_16_5::{Block, BlockState, Material, Property, Side, VoxelClass, VoxelShapeRef};
use ghast_data::{FluidKind, PhysicsFlags};

use crate::math::Aabb;
use crate::voxel::{Points, VoxelShape};
use crate::world::BlockView;

/// A `ghast-data` voxel table entry as a [`VoxelShape`].
fn voxel(r: &'static VoxelShapeRef) -> VoxelShape<'static> {
    let axis = |n: u8, pts: &'static [f64]| match r.class {
        VoxelClass::Simple => Points::Fractional(u32::from(n)),
        VoxelClass::Array => Points::Explicit(pts),
    };
    VoxelShape {
        axes: [
            axis(r.sizes[0], r.xs),
            axis(r.sizes[1], r.ys),
            axis(r.sizes[2], r.zs),
        ],
        cells: r.cells,
    }
}

/// Per-state collision summary for the hot cell loop (one byte per state, built once from the
/// `ghast-data` tables; constant data like the sine table).
pub(crate) mod class {
    /// The collision shape has filled cells (always set for context / position dependent shapes).
    pub const NONEMPTY: u8 = 1;
    /// The shape is vanilla's shared full cube (`BlockCollisionSpliterator` fast path).
    pub const FULL_CUBE: u8 = 2;
    /// `exceedsCube()`.
    pub const EXCEEDS: u8 = 4;
    /// Moving piston (collides even at the cuboid's two-edge cells).
    pub const MOVING_PISTON: u8 = 8;
}

static CLASS: std::sync::LazyLock<Box<[u8]>> = std::sync::LazyLock::new(|| {
    (0..ghast_data::v1_16_5::STATE_COUNT as u16)
        .map(|id| {
            let Some(s) = BlockState::from_id(id) else {
                return 0;
            };
            let special = s.block() == Block::SCAFFOLDING || s.block() == Block::BAMBOO;
            let mut c = 0;
            if special || !s.voxel_shape().empty {
                c |= class::NONEMPTY;
            }
            if !special && s.full_cube_identity() {
                c |= class::FULL_CUBE;
            }
            if s.exceeds_cube() {
                c |= class::EXCEEDS;
            }
            if s.block() == Block::MOVING_PISTON {
                c |= class::MOVING_PISTON;
            }
            c
        })
        .collect()
});

/// The collision summary byte of a state (see [`class`]).
#[inline]
pub(crate) fn collision_class(s: BlockState) -> u8 {
    CLASS.get(s.id() as usize).copied().unwrap_or(0)
}

/// What a block's collision may depend on from the colliding player.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ShapeCtx {
    /// The entity's feet Y when the context was made.
    pub min_y: f64,
    /// Sneaking (vanilla `isDescending`).
    pub descending: bool,
}

/// A block's collision shape at a position.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Shape {
    /// No collision.
    Empty,
    /// A grid shape (the full cube is `VoxelShape::FULL_CUBE`).
    Grid {
        shape: VoxelShape<'static>,
        /// `true` for vanilla's shared full-cube instance (collision fast path).
        full_cube: bool,
    },
}

/// Which scaffolding variant applies: 0 = full (stable) shape, 1 = bottom slab, 2 = none.
fn scaffolding_variant(s: BlockState, y: i32, ctx: Option<&ShapeCtx>) -> usize {
    // Vanilla `isAbove(shape, pos, true)`: feet above the shape's top (minus 1e-5); a context-free
    // query counts as above. The bottom test uses a cube shifted one block down (top 0.0).
    let above = |top: f64| ctx.is_none_or(|c| c.min_y > f64::from(y) + top - f64::from(1.0e-5f32));
    let descending = ctx.is_some_and(|c| c.descending);
    if above(1.0) && !descending {
        return 0;
    }
    let bottom = s.get(Property::Bottom) == Some("true");
    let distance0 = s.get(Property::Distance) == Some("0");
    if !distance0 && bottom && above(0.0) {
        1
    } else {
        2
    }
}

/// The collision shape's boxes (vanilla `getBoundingBoxes` order), block-local.
pub(crate) fn collision_boxes(s: BlockState, y: i32, ctx: Option<&ShapeCtx>) -> &'static [Aabb] {
    if let Some(sc) = s.scaffolding_shapes() {
        return match scaffolding_variant(s, y, ctx) {
            0 => sc.stable,
            1 => sc.bottom,
            _ => &[],
        };
    }
    s.shape()
}

/// Bamboo's collision box before its per-position offset (6.5/16 .. 9.5/16, full height; an
/// `ArrayVoxelShape` because 13/32 needs more than vanilla's 3-bit simple-shape resolution).
static BAMBOO_XZ: [f64; 2] = [0.40625, 0.59375];
static BAMBOO_Y: [f64; 2] = [0.0, 1.0];

/// Vanilla's per-position horizontal model offset (`getModelOffset`, offset type XZ).
fn model_offset_xz(x: i32, z: i32) -> (f64, f64) {
    let mut l = i64::from(x.wrapping_mul(3_129_871)) ^ i64::from(z).wrapping_mul(116_129_781);
    l = l
        .wrapping_mul(l)
        .wrapping_mul(42_317_861)
        .wrapping_add(l.wrapping_mul(11));
    let l = l >> 16;
    let f = |bits: i64| (f64::from((bits & 15) as f32 / 15.0) - 0.5) * 0.5;
    (f(l), f(l >> 8))
}

/// Bamboo's collision box at `(x, z)` with its model offset, block-local (the shifted shape's
/// `getBoundingBoxes`: each boundary is `point + offset`).
pub(crate) fn bamboo_box(x: i32, z: i32) -> Aabb {
    let (ox, oz) = model_offset_xz(x, z);
    Aabb::new(
        BAMBOO_XZ[0] + ox,
        BAMBOO_Y[0],
        BAMBOO_XZ[0] + oz,
        BAMBOO_XZ[1] + ox,
        BAMBOO_Y[1],
        BAMBOO_XZ[1] + oz,
    )
}

/// The collision shape of a state at `(x, y, z)` for a player context.
pub(crate) fn collision_shape(
    s: BlockState,
    x: i32,
    y: i32,
    z: i32,
    ctx: Option<&ShapeCtx>,
) -> Shape {
    if s.block() == Block::BAMBOO {
        let (ox, oz) = model_offset_xz(x, z);
        return Shape::Grid {
            shape: VoxelShape {
                axes: [
                    Points::Shifted(&BAMBOO_XZ, ox),
                    Points::Shifted(&BAMBOO_Y, 0.0),
                    Points::Shifted(&BAMBOO_XZ, oz),
                ],
                cells: &[1],
            },
            full_cube: false,
        };
    }
    let r = match s.scaffolding_shapes() {
        Some(sc) => match scaffolding_variant(s, y, ctx) {
            0 => sc.stable_voxel,
            1 => sc.bottom_voxel,
            _ => return Shape::Empty,
        },
        None => s.voxel_shape(),
    };
    if r.empty {
        return Shape::Empty;
    }
    Shape::Grid {
        shape: voxel(r),
        full_cube: s.scaffolding_shapes().is_none() && s.full_cube_identity(),
    }
}

/// `BlockState.exceedsCube()`.
#[inline]
pub(crate) fn exceeds_cube(s: BlockState) -> bool {
    s.exceeds_cube()
}

/// `BlockState.shouldSuffocate`.
#[inline]
pub(crate) fn should_suffocate(s: BlockState) -> bool {
    s.should_suffocate()
}

/// `Material.blocksMovement()`.
#[inline]
pub(crate) fn blocks_movement(s: BlockState) -> bool {
    s.material_blocks_movement()
}

/// `isSideSolidFullSquare` for a horizontal side, given as the unit offset `(dx, dz)`.
#[inline]
pub(crate) fn side_solid(s: BlockState, dx: i32, dz: i32) -> bool {
    let side = match (dx, dz) {
        (0, -1) => Side::North,
        (1, 0) => Side::East,
        (0, 1) => Side::South,
        _ => Side::West,
    };
    s.side_solid_full_square(side)
}

/// Ice material (`ice`, `frosted_ice`).
pub(crate) fn is_ice_material(s: BlockState) -> bool {
    s.block().material() == Material::Ice
}

/// A liquid in a block state: kind, vanilla fluid amount `1..=8`, falling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FluidAt {
    pub kind: FluidKind,
    pub amount: u8,
    pub falling: bool,
}

/// The fluid state of a block state (vanilla `getFluidState`).
#[inline]
pub(crate) fn fluid(s: BlockState) -> Option<FluidAt> {
    s.fluid().map(|f| FluidAt {
        kind: f.kind,
        amount: f.amount(),
        falling: f.falling(),
    })
}

#[inline]
pub(crate) fn flags(s: BlockState) -> PhysicsFlags {
    s.block().physics().flags
}

/// Ground friction.
#[inline]
pub(crate) fn slipperiness(s: BlockState) -> f32 {
    s.block().physics().slipperiness
}

/// Horizontal velocity multiplier (soul sand, honey: 0.4).
#[inline]
pub(crate) fn velocity_multiplier(s: BlockState) -> f32 {
    s.block().physics().velocity_multiplier()
}

/// Jump velocity multiplier (honey: 0.5).
#[inline]
pub(crate) fn jump_multiplier(s: BlockState) -> f32 {
    s.block().physics().jump_factor
}

/// Vanilla's block range: y in `0..256`, |x|, |z| below 30,000,000.
#[inline]
pub(crate) fn is_valid_pos(x: i32, y: i32, z: i32) -> bool {
    (-30_000_000..30_000_000).contains(&x)
        && (-30_000_000..30_000_000).contains(&z)
        && (0..256).contains(&y)
}

/// `World.getBlockState`: void air outside the valid range.
#[inline]
pub(crate) fn state_at<W: BlockView<State = BlockState>>(
    w: &W,
    x: i32,
    y: i32,
    z: i32,
) -> BlockState {
    if is_valid_pos(x, y, z) {
        w.block(x, y, z)
    } else {
        Block::VOID_AIR.default_state()
    }
}

/// `true` when the state is a bed of any colour.
#[inline]
pub(crate) fn is_bed(s: BlockState) -> bool {
    (Block::WHITE_BED.id()..=Block::BLACK_BED.id()).contains(&s.block().id())
}

/// `true` for a climbable position: the climbable tag, or an open trapdoor above a ladder that
/// faces the same way.
pub(crate) fn is_climbable_at<W: BlockView<State = BlockState>>(
    w: &W,
    x: i32,
    y: i32,
    z: i32,
) -> bool {
    let s = state_at(w, x, y, z);
    let f = flags(s);
    if f.contains(PhysicsFlags::CLIMBABLE) {
        return true;
    }
    if f.contains(PhysicsFlags::TRAPDOOR) && s.get(Property::Open) == Some("true") {
        let below = state_at(w, x, y - 1, z);
        return below.block() == Block::LADDER
            && below.get(Property::Facing) == s.get(Property::Facing);
    }
    false
}

/// The entity-dependent part of a 1.16.5 block collision query (vanilla `EntityShapeContext`
/// as the collision shapes read it).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct CollisionContext {
    /// `entity.getY()` when the context was made (scaffolding's "above" tests).
    pub feet_y: f64,
    /// `isDescending()`: a sneaking player.
    pub descending: bool,
}

impl CollisionContext {
    /// The context of an entity with its feet at `feet_y`, sneaking or not.
    #[must_use]
    pub fn new(feet_y: f64, descending: bool) -> CollisionContext {
        CollisionContext { feet_y, descending }
    }
}

/// `Entity.collidesWithStateAtPos(pos, state)`: the collision shape of `state` at block `pos`
/// for the entity's context (scaffolding) and with the block's model offset (bamboo) overlaps
/// `bb` (`[min_x, min_y, min_z, max_x, max_y, max_z]`; `VoxelShapes.matchesAnywhere(…, AND)`:
/// an overlap that survives its 1e-7 point merging). The client uses it when the server's answer to a dig action
/// restores a block and moves the player back (`processPlayerActionResponse`).
#[must_use]
pub fn state_collides(
    state: BlockState,
    pos: [i32; 3],
    bb: [f64; 6],
    ctx: &CollisionContext,
) -> bool {
    let [x, y, z] = pos;
    let c = ShapeCtx {
        min_y: ctx.feet_y,
        descending: ctx.descending,
    };
    let q = Aabb::new(bb[0], bb[1], bb[2], bb[3], bb[4], bb[5]);
    let hits = |b: &Aabb| boxes_match(b, &q);
    if state.block() == Block::BAMBOO {
        return hits(&bamboo_box(x, z).at(x, y, z));
    }
    collision_boxes(state, y, Some(&c))
        .iter()
        .any(|b| hits(&b.at(x, y, z)))
}

/// One axis of `VoxelShapes.matchesAnywhere(a, b, AND)` for two single boxes: the merged point
/// list of `SimplePairList` (points within 1e-7 of the last kept one collapse) has a cell inside
/// both intervals. `DisjointPairList` when one ends more than 1e-7 before the other starts.
// The NaN start (`d`) must compare false, as vanilla's negated comparison does.
#[allow(clippy::neg_cmp_op_on_partial_ord)]
fn axis_overlaps(a0: f64, a1: f64, b0: f64, b1: f64) -> bool {
    if a1 < b0 - 1.0e-7 || b1 < a0 - 1.0e-7 {
        return false;
    }
    let first = [a0, a1];
    let second = [b0, b1];
    let (mut i, mut j) = (0usize, 0usize);
    let mut d = f64::NAN;
    // (min index, max index) of each kept point.
    let mut cells: [(i32, i32); 4] = [(0, 0); 4];
    let mut n = 0usize;
    loop {
        let bl = i < 2;
        let bl2 = j < 2;
        if !bl && !bl2 {
            break;
        }
        let bl3 = bl && (!bl2 || first[i] < second[j] + 1.0e-7);
        let e = if bl3 {
            i += 1;
            first[i - 1]
        } else {
            j += 1;
            second[j - 1]
        };
        // AND: neither "first only" nor "second only" points are kept.
        if (i != 0 && bl || bl3) && (j != 0 && bl2 || !bl3) {
            if !(d >= e - 1.0e-7) {
                cells[n] = (i as i32 - 1, j as i32 - 1);
                n += 1;
                d = e;
            } else if n > 0 {
                cells[n - 1] = (i as i32 - 1, j as i32 - 1);
            }
        }
    }
    // Cell k spans kept points k..k+1 and lies in segment cells[k] of each list.
    (0..n.saturating_sub(1)).any(|k| cells[k] == (0, 0))
}

/// `VoxelShapes.matchesAnywhere(a, b, AND)` of two single boxes.
pub(crate) fn boxes_match(a: &Aabb, b: &Aabb) -> bool {
    axis_overlaps(a.min_x, a.max_x, b.min_x, b.max_x)
        && axis_overlaps(a.min_y, a.max_y, b.min_y, b.max_y)
        && axis_overlaps(a.min_z, a.max_z, b.min_z, b.max_z)
}