ghast-physics 0.5.5

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! The generic non-living entity of 1.12.2: the parts of vanilla's `Entity` that projectiles,
//! item entities, experience orbs, primed TNT and falling blocks share — position and box,
//! `Entity.move` over collision boxes, landing, the inside-block effects, the water push, fire and
//! damage as far as they decide a removal, and the push out of blocks.
//!
//! Every side-dependent step reads a [`Side`]; no step reads the player's state (the player keeps
//! its own copies in `player.rs`).

use ghast_data::v1_12::BlockState;

use super::blocks::{
    BoxList, BoxSink, ShapeKind, add_collision_boxes, id, is_air, is_tall_support, shape_kind,
    state_at,
};
use super::fluid::{contains_lava, water_contact};
use crate::math::{Aabb, BoxOps, floor, sorted_box};
use crate::nonliving::{LegacyRandom, Side};
use crate::world::{BlockView, WorldBorder};

/// Block ids the non-living entities read.
pub(crate) mod nid {
    pub const FLOWING_LAVA: u8 = 10;
    pub const LAVA: u8 = 11;
    pub const FIRE: u8 = 51;
    pub const CACTUS: u8 = 81;
    pub const END_PORTAL_FRAME: u8 = 120;
    pub const CONCRETE_POWDER: u8 = 252;
}

/// How damage changes an entity (only what decides its removal is modelled).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Health {
    /// Damage changes nothing (projectiles, TNT, falling blocks).
    None,
    /// An item entity or an experience orb (5 health).
    Five,
}

/// How the entity answers `updateWaterState` (each kind's own override).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Water {
    /// `Entity`: the box less 0.4 at the bottom, shrunk by 0.001; splash, fall reset, fire out.
    Entity,
    /// `ItemEntity`: the whole box; splash; nothing else.
    Item,
    /// `ExperienceOrbEntity`: the push only (the water flag never changes).
    Orb,
}

/// The `Entity` fields the non-living 1.12.2 entities read and write.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Body {
    pub pos: [f64; 3],
    pub old: [f64; 3],
    /// `prevTickX/Y/Z`: the position when the world started the entity's update.
    pub tick_start: [f64; 3],
    pub vel: [f64; 3],
    pub bb: Aabb,
    pub width: f32,
    pub height: f32,
    pub yaw: f32,
    pub pitch: f32,
    pub yaw_o: f32,
    pub pitch_o: f32,
    pub on_ground: bool,
    pub hcol: bool,
    pub vcol: bool,
    pub fall: f32,
    pub in_web: bool,
    pub in_water: bool,
    pub first_update: bool,
    pub no_gravity: bool,
    pub no_clip: bool,
    pub removed: bool,
    /// `ticksAlive` (counted by the world before each tick).
    pub age: i32,
    pub fire_ticks: i32,
    pub health: i32,
    pub health_model: Health,
    pub water: Water,
    pub outside_border: bool,
    pub rng: LegacyRandom,
}

impl Body {
    pub(crate) fn new(pos: [f64; 3], vel: [f64; 3], width: f32, height: f32) -> Body {
        let mut b = Body {
            pos,
            old: pos,
            tick_start: pos,
            vel,
            bb: Aabb::FULL,
            width,
            height,
            yaw: 0.0,
            pitch: 0.0,
            yaw_o: 0.0,
            pitch_o: 0.0,
            on_ground: false,
            hcol: false,
            vcol: false,
            fall: 0.0,
            in_web: false,
            in_water: false,
            first_update: true,
            no_gravity: false,
            no_clip: false,
            removed: false,
            age: 0,
            fire_ticks: -1,
            health: 5,
            health_model: Health::None,
            water: Water::Entity,
            outside_border: false,
            rng: LegacyRandom::new(0),
        };
        b.set_position(pos);
        b
    }

    /// `Entity.updatePosition`: the position and the box made there.
    pub(crate) fn set_position(&mut self, p: [f64; 3]) {
        self.pos = p;
        let f = f64::from(self.width / 2.0);
        self.bb = sorted_box(
            p[0] - f,
            p[1],
            p[2] - f,
            p[0] + f,
            p[1] + f64::from(self.height),
            p[2] + f,
        );
    }

    /// `World.updateEntity` before the entity's own tick: previous position and rotation,
    /// `ticksAlive++`.
    pub(crate) fn start_tick(&mut self) {
        self.old = self.pos;
        self.tick_start = self.pos;
        self.yaw_o = self.yaw;
        self.pitch_o = self.pitch;
        self.age += 1;
    }

    /// `World.updateEntity` after the entity's own tick: a coordinate that is not finite goes
    /// back to where the update started (the box is left as it is), a rotation that is not
    /// finite to the previous one.
    pub(crate) fn end_tick(&mut self) {
        for a in 0..3 {
            if !self.pos[a].is_finite() {
                self.pos[a] = self.tick_start[a];
            }
        }
        if !self.pitch.is_finite() {
            self.pitch = self.pitch_o;
        }
        if !self.yaw.is_finite() {
            self.yaw = self.yaw_o;
        }
    }

    /// `new BlockPos(this)`.
    pub(crate) fn block_pos(&self) -> [i32; 3] {
        [floor(self.pos[0]), floor(self.pos[1]), floor(self.pos[2])]
    }

    /// `isOnFire()` (the burning flag a client could read is never set in the modelled ticks).
    fn on_fire(&self) -> bool {
        self.fire_ticks > 0
    }

    /// `damage(source, amount)` of the kinds whose health can run out.
    pub(crate) fn damage(&mut self, amount: i32) {
        if self.health_model == Health::Five {
            self.health -= amount;
            if self.health <= 0 {
                self.removed = true;
            }
        }
    }

    /// The splash of `onSwimmingStart` (sound pitch, then bubble and splash particles; floats).
    fn splash(&mut self) {
        self.rng.next_float();
        self.rng.next_float();
        let n = 1.0f32 + self.width * 20.0;
        let mut i = 0;
        while (i as f32) < n {
            self.rng.next_float();
            self.rng.next_float();
            self.rng.next_float();
            i += 1;
        }
        let mut i = 0;
        while (i as f32) < n {
            self.rng.next_float();
            self.rng.next_float();
            i += 1;
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Water, fire and the base tick

/// `updateWaterState` of the entity's kind (with the flow push of the water it touches).
pub(crate) fn update_water_state<W: BlockView<State = BlockState>>(b: &mut Body, w: &W) -> bool {
    let probe = match b.water {
        Water::Entity => {
            b.bb.grow(0.0, -f64::from(0.4f32), 0.0)
                .shrink(0.001, 0.001, 0.001)
        }
        Water::Item | Water::Orb => b.bb,
    };
    let (touching, flow) = water_contact(w, &probe);
    if touching && flow.length() > 0.0 {
        let f = flow.normalize();
        b.vel[0] += f.x * 0.014;
        b.vel[1] += f.y * 0.014;
        b.vel[2] += f.z * 0.014;
    }
    match b.water {
        Water::Orb => return touching,
        _ if touching => {
            if !b.in_water && !b.first_update {
                b.splash();
            }
            if b.water == Water::Entity {
                b.fall = 0.0;
                b.fire_ticks = 0;
            }
            b.in_water = true;
        }
        _ => b.in_water = false,
    }
    b.in_water
}

/// `isTouchingLava()`.
pub(crate) fn touching_lava<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> bool {
    contains_lava(
        w,
        &b.bb
            .grow(-f64::from(0.1f32), -f64::from(0.4f32), -f64::from(0.1f32)),
    )
}

/// `Entity.baseTick` of these entities: water, fire, lava (damage, fire, the fall distance
/// halved), the removal under the world, the end of the first update.
pub(crate) fn base_tick<W: BlockView<State = BlockState>>(b: &mut Body, w: &W, side: Side) {
    update_water_state(b, w);
    if side == Side::Client {
        b.fire_ticks = 0;
    } else if b.fire_ticks > 0 {
        if b.fire_ticks % 20 == 0 {
            b.damage(1);
        }
        b.fire_ticks -= 1;
    }
    if touching_lava(b, w) {
        b.damage(4);
        if b.fire_ticks < 300 {
            b.fire_ticks = 300;
        }
        b.fall *= 0.5;
    }
    if b.pos[1] < -64.0 {
        b.removed = true;
    }
    b.first_update = false;
}

// ---------------------------------------------------------------------------------------------
// Collision boxes

fn ceil(v: f64) -> i32 {
    let i = v as i32;
    if v > f64::from(i) { i + 1 } else { i }
}

const STONE: BlockState = ghast_data::v1_12::Block::STONE.default_state();

/// `World.getCollisionBoxes(entity, query)` with no other entities: the block boxes intersecting
/// `query` (one block wider on x / z without the four corner columns and the top layer of the
/// edge columns; outside the world border blocks collide like stone while the entity is inside).
/// With no entity (`b` is `None`) the border plays no part. Returns `false` at the first box when
/// `first` is set (`collidesWithAnyBlock`).
pub(crate) fn gather<W: BlockView<State = BlockState>>(
    b: Option<&mut Body>,
    w: &W,
    query: Aabb,
    out: &mut BoxList,
) {
    out.clear();
    let border: WorldBorder = w.world_border();
    let (x0, x1) = (floor(query.min_x) - 1, ceil(query.max_x) + 1);
    let (y0, y1) = (floor(query.min_y) - 1, ceil(query.max_y) + 1);
    let (z0, z1) = (floor(query.min_z) - 1, ceil(query.max_z) + 1);
    let (was_outside, inside) = match &b {
        Some(b) => {
            let m = if b.outside_border { 1.0 } else { -1.0 };
            let (wx, nz, ex, sz) = (
                border.west() + m,
                border.north() + m,
                border.east() - m,
                border.south() - m,
            );
            let (x, z) = (b.pos[0], b.pos[2]);
            (b.outside_border, x > wx && x < ex && z > nz && z < sz)
        }
        None => (false, false),
    };
    let entity = b.is_some();
    let mut visited = false;
    let mut sink = BoxSink { query, out };
    for x in x0..x1 {
        let edge_x = x == x0 || x == x1 - 1;
        for z in z0..z1 {
            let edge_z = z == z0 || z == z1 - 1;
            if edge_x && edge_z {
                continue;
            }
            let substitute = entity && inside && !border.contains_block(x, z);
            for y in y0..y1 {
                if (edge_x || edge_z) && y == y1 - 1 {
                    continue;
                }
                visited = true;
                let s = if substitute {
                    STONE
                } else {
                    state_at(w, x, y, z)
                };
                add_collision_boxes(w, x, y, z, s, &mut sink);
            }
        }
    }
    if let Some(b) = b
        && visited
    {
        if was_outside && inside {
            b.outside_border = false;
        } else if !was_outside && !inside {
            b.outside_border = true;
        }
    }
}

/// `World.collidesWithAnyBlock(box)`: any block box intersects it (no entity).
pub(crate) fn collides_any<W: BlockView<State = BlockState>>(w: &W, query: &Aabb) -> bool {
    let mut boxes = BoxList::new();
    gather(None, w, *query, &mut boxes);
    !boxes.is_empty()
}

/// The block's single collision box (`getCollisionBoundingBox`) as far as the non-living entities
/// read it: the bounding box of its collision boxes, fences, walls and gates cut at the block's
/// top, an end portal frame without its eye. `None` without one.
pub(crate) fn collision_bounds<W: BlockView<State = BlockState>>(
    w: &W,
    x: i32,
    y: i32,
    z: i32,
) -> Option<Aabb> {
    let s = state_at(w, x, y, z);
    let mut boxes = BoxList::new();
    let (fx, fy, fz) = (f64::from(x), f64::from(y), f64::from(z));
    let query = Aabb::new(fx - 1.0, fy - 1.0, fz - 1.0, fx + 2.0, fy + 3.0, fz + 2.0);
    let mut sink = BoxSink {
        query,
        out: &mut boxes,
    };
    add_collision_boxes(w, x, y, z, s, &mut sink);
    let list = boxes.as_slice();
    let first = *list.first()?;
    if s.block().id() == nid::END_PORTAL_FRAME {
        return Some(first);
    }
    let mut u = first;
    for b in &list[1..] {
        u = Aabb::new(
            u.min_x.min(b.min_x),
            u.min_y.min(b.min_y),
            u.min_z.min(b.min_z),
            u.max_x.max(b.max_x),
            u.max_y.max(b.max_y),
            u.max_z.max(b.max_z),
        );
    }
    if matches!(
        shape_kind(s.block().id()),
        ShapeKind::Fence | ShapeKind::Wall | ShapeKind::Gate
    ) && u.max_y > fy + 1.0
    {
        u.max_y = fy + 1.0;
    }
    Some(u)
}

/// `World.isBlockFullCube`-like test of `pushOutOfBlocks`: a collision box whose average edge is
/// at least 1.
fn full_box<W: BlockView<State = BlockState>>(w: &W, p: [i32; 3]) -> bool {
    collision_bounds(w, p[0], p[1], p[2]).is_some_and(|b| {
        ((b.max_x - b.min_x) + (b.max_y - b.min_y) + (b.max_z - b.min_z)) / 3.0 >= 1.0
    })
}

/// `Entity.pushOutOfBlocks(x, y, z)`: nothing unless a block box overlaps the entity; then the
/// nearest open side (west, east, north, south, up) and one random draw. Returns whether it
/// pushed.
pub(crate) fn push_out_of_blocks<W: BlockView<State = BlockState>>(
    b: &mut Body,
    w: &W,
    x: f64,
    y: f64,
    z: f64,
) -> bool {
    let p = [floor(x), floor(y), floor(z)];
    let (d, e, f) = (
        x - f64::from(p[0]),
        y - f64::from(p[1]),
        z - f64::from(p[2]),
    );
    if !collides_any(w, &b.bb) {
        return false;
    }
    // (axis, sign)
    let mut dir = (1usize, 1.0f32);
    let mut g = f64::MAX;
    let open = |o: [i32; 3]| !full_box(w, [p[0] + o[0], p[1] + o[1], p[2] + o[2]]);
    if open([-1, 0, 0]) && d < g {
        g = d;
        dir = (0, -1.0);
    }
    if open([1, 0, 0]) && 1.0 - d < g {
        g = 1.0 - d;
        dir = (0, 1.0);
    }
    if open([0, 0, -1]) && f < g {
        g = f;
        dir = (2, -1.0);
    }
    if open([0, 0, 1]) && 1.0 - f < g {
        g = 1.0 - f;
        dir = (2, 1.0);
    }
    if open([0, 1, 0]) && 1.0 - e < g {
        dir = (1, 1.0);
    }
    let h = b.rng.next_float() * 0.2 + 0.1;
    let v = f64::from(dir.1 * h);
    for (a, c) in b.vel.iter_mut().enumerate() {
        *c = if a == dir.0 { v } else { *c * 0.75 };
    }
    true
}

// ---------------------------------------------------------------------------------------------
// Entity.move

/// `Entity.move(SELF, ...)` of a non-living entity (no step-up, no sneaking).
pub(crate) fn entity_move<W: BlockView<State = BlockState>>(b: &mut Body, w: &W, m: [f64; 3]) {
    let [mut dx, mut dy, mut dz] = m;
    if b.no_clip {
        b.bb = b.bb.offset(dx, dy, dz);
        b.pos = [
            (b.bb.min_x + b.bb.max_x) / 2.0,
            b.bb.min_y,
            (b.bb.min_z + b.bb.max_z) / 2.0,
        ];
        return;
    }
    if b.in_web {
        b.in_web = false;
        dx *= 0.25;
        dy *= f64::from(0.05f32);
        dz *= 0.25;
        b.vel = [0.0; 3];
    }
    let (n, o, p) = (dx, dy, dz);
    let mut boxes = BoxList::new();
    let query = b.bb.stretch(dx, dy, dz);
    gather(Some(b), w, query, &mut boxes);
    let list = boxes.as_slice();
    let mut bb = b.bb;
    if dy != 0.0 {
        for c in list {
            dy = c.clip_y(&bb, dy);
        }
        bb = bb.offset(0.0, dy, 0.0);
    }
    if dx != 0.0 {
        for c in list {
            dx = c.clip_x(&bb, dx);
        }
        if dx != 0.0 {
            bb = bb.offset(dx, 0.0, 0.0);
        }
    }
    if dz != 0.0 {
        for c in list {
            dz = c.clip_z(&bb, dz);
        }
        if dz != 0.0 {
            bb = bb.offset(0.0, 0.0, dz);
        }
    }
    b.bb = bb;
    b.pos = [
        (bb.min_x + bb.max_x) / 2.0,
        bb.min_y,
        (bb.min_z + bb.max_z) / 2.0,
    ];
    b.hcol = n != dx || p != dz;
    b.vcol = o != dy;
    b.on_ground = b.vcol && o < 0.0;
    let lp = [
        floor(b.pos[0]),
        floor(b.pos[1] - f64::from(0.2f32)),
        floor(b.pos[2]),
    ];
    let mut landed = state_at(w, lp[0], lp[1], lp[2]);
    if is_air(landed) {
        let below = state_at(w, lp[0], lp[1] - 1, lp[2]);
        if is_tall_support(below) {
            landed = below;
        }
    }
    // fall: no block's onLandedUpon moves these entities.
    if b.on_ground {
        b.fall = 0.0;
    } else if dy < 0.0 {
        b.fall = (f64::from(b.fall) - dy) as f32;
    }
    if n != dx {
        b.vel[0] = 0.0;
    }
    if p != dz {
        b.vel[2] = 0.0;
    }
    let block = landed.block().id();
    if o != dy {
        // Block.onLanded: slime and beds bounce a non-living entity with 0.8 of the factor.
        match block {
            id::SLIME => {
                if b.vel[1] < 0.0 {
                    b.vel[1] = -b.vel[1] * 0.8;
                }
            }
            id::BED => {
                if b.vel[1] < 0.0 {
                    b.vel[1] = -b.vel[1] * f64::from(0.66f32) * 0.8;
                }
            }
            _ => b.vel[1] = 0.0,
        }
    }
    // None of these entities climbs (no step sounds, no `onSteppedOn`).
    check_block_collision(b, w);
    // Fire: a fire source in the box burns; out of it the burning ends; a wet burning entity is
    // put out (a sound).
    let wet = b.in_water;
    if fire_source_in(w, &b.bb.shrink(0.001, 0.001, 0.001)) {
        b.damage(1);
        if !wet {
            b.fire_ticks += 1;
            if b.fire_ticks == 0 && b.fire_ticks < 160 {
                b.fire_ticks = 160;
            }
        }
    } else if b.fire_ticks <= 0 {
        b.fire_ticks = -1;
    }
    if wet && b.on_fire() {
        b.rng.next_float();
        b.rng.next_float();
        b.fire_ticks = -1;
    }
}

/// Any fire or lava block in the box (`World.containsFireSource`).
fn fire_source_in<W: BlockView<State = BlockState>>(w: &W, bb: &Aabb) -> bool {
    let (x0, x1) = (floor(bb.min_x), ceil(bb.max_x));
    let (y0, y1) = (floor(bb.min_y), ceil(bb.max_y));
    let (z0, z1) = (floor(bb.min_z), ceil(bb.max_z));
    if !(y1 >= 0 && y0 < 256) {
        return false;
    }
    for x in x0..x1 {
        for y in y0..y1 {
            for z in z0..z1 {
                let id = state_at(w, x, y, z).block().id();
                if id == nid::FIRE || id == nid::FLOWING_LAVA || id == nid::LAVA {
                    return true;
                }
            }
        }
    }
    false
}

/// `Entity.checkBlockCollision`: every block the box (shrunk by 0.001) is in, its
/// `onEntityCollision` as far as it moves or damages these entities.
pub(crate) fn check_block_collision<W: BlockView<State = BlockState>>(b: &mut Body, w: &W) {
    let bb = b.bb;
    let (x0, y0, z0) = (
        floor(bb.min_x + 0.001),
        floor(bb.min_y + 0.001),
        floor(bb.min_z + 0.001),
    );
    let (x1, y1, z1) = (
        floor(bb.max_x - 0.001),
        floor(bb.max_y - 0.001),
        floor(bb.max_z - 0.001),
    );
    if !(y1 >= 0 && y0 < 256) {
        return;
    }
    for x in x0..=x1 {
        for y in y0..=y1 {
            for z in z0..=z1 {
                block_touch(b, state_at(w, x, y, z));
            }
        }
    }
}

/// One block's `onEntityCollision` for these entities: cobwebs slow the next move, soul sand
/// slows at once, cacti hurt.
pub(crate) fn block_touch(b: &mut Body, s: BlockState) {
    match s.block().id() {
        id::WEB => {
            b.in_web = true;
            b.fall = 0.0;
        }
        id::SOUL_SAND => {
            b.vel[0] *= 0.4;
            b.vel[2] *= 0.4;
        }
        nid::CACTUS => b.damage(1),
        _ => {}
    }
}