ghast-physics 0.5.6

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
//! Item entities, experience orbs, primed TNT and falling blocks of 1.8.9: `Entity.move` over the
//! block collision boxes, ground friction (slippery blocks), the water push, the inside-block
//! effects — each ticked as the server and as a client tick it, checked bit for bit against the
//! vanilla oracle (`tests/golden/1.8.9/projectiles.jsonl.gz`).
//!
//! An orb follows the nearest player within 8 blocks ([`tick_drop_near`]: the target search
//! every 20 + `id % 100` ticks of the orb's clock, the pull towards the player's eyes).
//!
//! Not modelled: merging, pickup, a TNT explosion (the entity is removed when the fuse runs
//! out), where a landing falling block places its block (the server removes the entity then;
//! the world is not changed here).
//!
//! What the sides do differently (all from the vanilla tick): only the server burns an item or
//! an orb with the fire ticks left after lava, removes an old item, and lands a falling block (or
//! removes one whose block is not at its start position). Both sides push items and orbs out of
//! blocks.

use ghast_data::v1_8::BlockState;

use super::blocks::{HistoryShapes, is_air, is_lava, slipperiness, state_at};
use super::body::{self, Body, Health, Water, nid};
use crate::math::{Aabb, floor};
use crate::nonliving::LegacyRandom;
pub use crate::nonliving::Side;
pub use crate::orb::OrbPlayer;
use crate::world::{BlockView, WorldBorder};

/// The kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DropKind {
    /// `item` (an item entity; gravity 0.04).
    Item,
    /// `experience_orb` (gravity 0.03).
    ExperienceOrb,
    /// `tnt` (primed TNT; gravity 0.04).
    PrimedTnt,
    /// `falling_block` (gravity 0.04).
    FallingBlock,
}

impl DropKind {
    /// The name used for the kind (the modern entity type id).
    #[must_use]
    pub const fn entity_name(self) -> &'static str {
        match self {
            DropKind::Item => "item",
            DropKind::ExperienceOrb => "experience_orb",
            DropKind::PrimedTnt => "tnt",
            DropKind::FallingBlock => "falling_block",
        }
    }

    /// The kind of a name (with or without the `minecraft:` namespace).
    #[must_use]
    pub fn from_entity_name(name: &str) -> Option<DropKind> {
        let name = name.strip_prefix("minecraft:").unwrap_or(name);
        [
            DropKind::Item,
            DropKind::ExperienceOrb,
            DropKind::PrimedTnt,
            DropKind::FallingBlock,
        ]
        .into_iter()
        .find(|k| k.entity_name() == name)
    }

    /// Box width and height.
    #[must_use]
    pub const fn dimensions(self) -> (f32, f32) {
        match self {
            DropKind::Item => (0.25, 0.25),
            DropKind::ExperienceOrb => (0.5, 0.5),
            DropKind::PrimedTnt | DropKind::FallingBlock => (0.98, 0.98),
        }
    }
}

/// The state of an item entity, orb, primed TNT or falling block.
#[derive(Clone, Debug)]
pub struct Drop {
    kind: DropKind,
    b: Body,
    id: i32,
    age: i32,
    fuse: i32,
    time: i32,
    block: BlockState,
    cleared: Option<[i32; 3]>,
    /// An orb's followed player, its clock (`renderTicks`) and last target search.
    target: Option<OrbPlayer>,
    clock: i32,
    last_search: i32,
}

impl Drop {
    /// An entity at `pos` moving by `vel` per tick, as freshly spawned (first update pending, not
    /// on the ground, entity id 0, random seed 0, a TNT fuse of 80, a falling block of sand).
    #[must_use]
    pub fn new(kind: DropKind, pos: [f64; 3], vel: [f64; 3]) -> Drop {
        let (w, h) = kind.dimensions();
        let mut b = Body::new(pos, vel, w, h);
        b.history = HistoryShapes::Constructor;
        b.health_model = match kind {
            DropKind::Item | DropKind::ExperienceOrb => Health::Five,
            _ => Health::None,
        };
        b.water = match kind {
            DropKind::Item => Water::Item,
            DropKind::ExperienceOrb => Water::Orb,
            _ => Water::Entity,
        };
        Drop {
            kind,
            b,
            id: 0,
            age: 0,
            fuse: 80,
            time: 0,
            block: ghast_data::v1_8::Block::SAND.default_state(),
            cleared: None,
            target: None,
            clock: 0,
            last_search: 0,
        }
    }

    /// The player an orb follows (its entity id), if any.
    #[must_use]
    pub fn following(&self) -> Option<i32> {
        self.target.map(|t| t.id)
    }

    /// The entity id.
    #[must_use]
    pub fn with_id(mut self, id: i32) -> Drop {
        self.id = id;
        self
    }

    /// The seed of the entity's random (the push out of blocks, the jumps in lava, the water
    /// splash).
    #[must_use]
    pub fn with_random_seed(mut self, seed: i64) -> Drop {
        self.b.rng = LegacyRandom::new(seed);
        self
    }

    /// The on-ground flag.
    #[must_use]
    pub fn with_on_ground(mut self, on_ground: bool) -> Drop {
        self.b.on_ground = on_ground;
        self
    }

    /// The fall distance.
    #[must_use]
    pub fn with_fall_distance(mut self, fall: f32) -> Drop {
        self.b.fall = fall;
        self
    }

    /// Accepted for the shape the version modules share: 1.8 has no no-gravity flag.
    #[must_use]
    pub fn with_no_gravity(self, _no_gravity: bool) -> Drop {
        self
    }

    /// Accepted for the shape the version modules share: no 1.8 item is fire-proof.
    #[must_use]
    pub fn with_fire_immune(self, _fire_immune: bool) -> Drop {
        self
    }

    /// A primed TNT's fuse in ticks.
    #[must_use]
    pub fn with_fuse(mut self, fuse: i32) -> Drop {
        self.fuse = fuse;
        self
    }

    /// A falling block's block state.
    #[must_use]
    pub fn with_block(mut self, block: BlockState) -> Drop {
        self.block = block;
        self
    }

    /// Which bounds the history-dependent blocks (anvils, chests) have (default: the
    /// constructor bounds of a fresh game, [`HistoryShapes::Constructor`]).
    #[must_use]
    pub fn with_history_shapes(mut self, history: HistoryShapes) -> Drop {
        self.b.history = history;
        self
    }

    /// Sets the position (`updatePosition`: the box is made there), keeping the rest of the
    /// state.
    pub fn set_pos(&mut self, pos: [f64; 3]) {
        self.b.set_position(pos);
    }

    /// A position packet on a client (`Entity.updateTrackedPositionAndAngles`): the entity moves
    /// there and is pushed up onto the highest block box its box (less 1/32 on each horizontal
    /// side) runs into.
    pub fn set_tracked_position<W: BlockView<State = BlockState>>(
        &mut self,
        pos: [f64; 3],
        world: &W,
    ) {
        body::tracked_position(&mut self.b, world, pos);
    }

    /// Sets the motion (also a client's velocity packet), keeping the rest of the state.
    pub fn set_vel(&mut self, vel: [f64; 3]) {
        self.b.vel = vel;
    }

    /// Sets the on-ground flag.
    pub fn set_on_ground(&mut self, on_ground: bool) {
        self.b.on_ground = on_ground;
    }

    /// The kind.
    #[must_use]
    pub fn kind(&self) -> DropKind {
        self.kind
    }

    /// Position.
    #[must_use]
    pub fn pos(&self) -> [f64; 3] {
        self.b.pos
    }

    /// Motion per tick.
    #[must_use]
    pub fn vel(&self) -> [f64; 3] {
        self.b.vel
    }

    /// The bounding box.
    #[must_use]
    pub fn bounding_box(&self) -> Aabb {
        self.b.bb
    }

    /// The on-ground flag.
    #[must_use]
    pub fn on_ground(&self) -> bool {
        self.b.on_ground
    }

    /// `isTouchingWater()` (an orb's never changes).
    #[must_use]
    pub fn in_water(&self) -> bool {
        self.b.in_water
    }

    /// The last move collided horizontally.
    #[must_use]
    pub fn horizontal_collision(&self) -> bool {
        self.b.hcol
    }

    /// The last move collided vertically.
    #[must_use]
    pub fn vertical_collision(&self) -> bool {
        self.b.vcol
    }

    /// The fall distance.
    #[must_use]
    pub fn fall_distance(&self) -> f32 {
        self.b.fall
    }

    /// An item's or orb's age in ticks.
    #[must_use]
    pub fn age(&self) -> i32 {
        self.age
    }

    /// A primed TNT's remaining fuse.
    #[must_use]
    pub fn fuse(&self) -> i32 {
        self.fuse
    }

    /// A falling block's ticks.
    #[must_use]
    pub fn time(&self) -> i32 {
        self.time
    }

    /// The falling block cleared its own block at this cell on its first tick.
    #[must_use]
    pub fn cleared_block(&self) -> Option<[i32; 3]> {
        self.cleared
    }

    /// The block hit of this tick's ray: none in 1.8 (kept for the shape the version modules
    /// share).
    #[must_use]
    pub fn last_hit(&self) -> Option<super::projectile::ProjectileHit> {
        None
    }

    /// An item was pushed out of a block this tick (`noClip`).
    #[must_use]
    pub fn no_physics(&self) -> bool {
        self.b.no_clip
    }

    /// The entity was removed (a fuse ran out, burnt up, landed, an age limit).
    #[must_use]
    pub fn removed(&self) -> bool {
        self.b.removed
    }

    /// At rest: on the ground and not moving.
    #[must_use]
    pub fn at_rest(&self) -> bool {
        let v = self.b.vel;
        self.b.on_ground && v[0] * v[0] + v[2] * v[2] < 1.0e-12 && v[1].abs() < 1.0e-12
    }
}

/// The world with one cell turned to air (the falling block's own start block).
struct Cleared<'a, W> {
    w: &'a W,
    cell: Option<[i32; 3]>,
}

impl<W: BlockView<State = BlockState>> BlockView for Cleared<'_, W> {
    type State = BlockState;

    #[inline]
    fn block(&self, x: i32, y: i32, z: i32) -> BlockState {
        if self.cell == Some([x, y, z]) {
            BlockState::AIR
        } else {
            self.w.block(x, y, z)
        }
    }

    #[inline]
    fn is_chunk_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        self.w.is_chunk_loaded(chunk_x, chunk_z)
    }

    #[inline]
    fn world_border(&self) -> WorldBorder {
        self.w.world_border()
    }
}

/// One tick (the world's entity update, then the kind's `tick`) with no player in the world. A
/// removed entity does not tick.
pub fn tick_drop<W: BlockView<State = BlockState>>(d: &mut Drop, side: Side, world: &W) {
    tick_drop_near(d, side, world, &[]);
}

/// [`tick_drop`] with the world's players as this tick reads them, in `World.playerEntities`
/// order (an orb follows the nearest one; see [`crate::orb`]).
pub fn tick_drop_near<W: BlockView<State = BlockState>>(
    d: &mut Drop,
    side: Side,
    world: &W,
    players: &[OrbPlayer],
) {
    if d.b.removed {
        return;
    }
    match d.kind {
        DropKind::Item => item(d, side, world),
        DropKind::ExperienceOrb => orb(d, side, world, players),
        DropKind::PrimedTnt => tnt(d, world),
        DropKind::FallingBlock => falling(d, side, world),
    }
    d.b.end_tick();
}

/// Ticks until the entity rests on the ground with no motion ([`Drop::at_rest`]), is removed, or
/// `max_ticks` ticks ran; returns the ticks run.
pub fn run_drop<W: BlockView<State = BlockState>>(
    d: &mut Drop,
    side: Side,
    world: &W,
    max_ticks: u32,
) -> u32 {
    for t in 1..=max_ticks {
        tick_drop(d, side, world);
        if d.b.removed || d.at_rest() {
            return t;
        }
    }
    max_ticks
}

/// The ground friction under the box (the block one under its bottom), times 0.98.
fn ground_friction<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> f32 {
    let s = state_at(w, floor(b.pos[0]), floor(b.bb.min_y) - 1, floor(b.pos[2]));
    slipperiness(s) * 0.98
}

/// Lava at the entity's block: a jump in a random direction and the fizz sound (five draws).
fn lava_hop(b: &mut Body) {
    b.vel[1] = f64::from(0.2f32);
    b.vel[0] = f64::from((b.rng.next_float() - b.rng.next_float()) * 0.2);
    b.vel[2] = f64::from((b.rng.next_float() - b.rng.next_float()) * 0.2);
    b.rng.next_float();
}

fn lava_here<W: BlockView<State = BlockState>>(b: &Body, w: &W) -> bool {
    let p = b.block_pos();
    is_lava(state_at(w, p[0], p[1], p[2]))
}

/// `ItemEntity.tick`.
fn item<W: BlockView<State = BlockState>>(d: &mut Drop, side: Side, w: &W) {
    let b = &mut d.b;
    b.start_tick();
    body::base_tick(b, w, side);
    b.old = b.pos;
    b.vel[1] -= f64::from(0.04f32);
    let (x, y, z) = (b.pos[0], (b.bb.min_y + b.bb.max_y) / 2.0, b.pos[2]);
    b.no_clip = body::push_out_of_blocks(b, w, x, y, z);
    let v = b.vel;
    body::entity_move(b, w, v);
    let moved = (0..3).any(|a| b.old[a] as i32 != b.pos[a] as i32);
    if (moved || b.age % 25 == 0) && lava_here(b, w) {
        lava_hop(b);
    }
    let g = if b.on_ground {
        ground_friction(b, w)
    } else {
        0.98
    };
    b.vel[0] *= f64::from(g);
    b.vel[1] *= f64::from(0.98f32);
    b.vel[2] *= f64::from(g);
    if b.on_ground {
        b.vel[1] *= -0.5;
    }
    if d.age != -32768 {
        d.age += 1;
    }
    body::update_water_state(b, w);
    if side == Side::Server && d.age >= 6000 {
        b.removed = true;
    }
}

/// `ExperienceOrbEntity.tick`.
fn orb<W: BlockView<State = BlockState>>(d: &mut Drop, side: Side, w: &W, players: &[OrbPlayer]) {
    let b = &mut d.b;
    b.start_tick();
    body::base_tick(b, w, side);
    b.old = b.pos;
    b.vel[1] -= f64::from(0.03f32);
    if lava_here(b, w) {
        lava_hop(b);
    }
    let (x, y, z) = (b.pos[0], (b.bb.min_y + b.bb.max_y) / 2.0, b.pos[2]);
    body::push_out_of_blocks(b, w, x, y, z);
    if let Some(t) = crate::orb::legacy_target(
        &mut d.target,
        &mut d.last_search,
        d.clock,
        d.id,
        players,
        b.pos,
    ) {
        crate::orb::legacy_pull(&mut b.vel, b.pos, &t, false);
    }
    let v = b.vel;
    body::entity_move(b, w, v);
    let g = if b.on_ground {
        ground_friction(b, w)
    } else {
        0.98
    };
    b.vel[0] *= f64::from(g);
    b.vel[1] *= f64::from(0.98f32);
    b.vel[2] *= f64::from(g);
    if b.on_ground {
        b.vel[1] *= f64::from(-0.9f32);
    }
    d.clock = d.clock.wrapping_add(1);
    d.age += 1;
    if d.age >= 6000 {
        b.removed = true;
    }
}

/// `TntEntity.tick` (no base tick: only the water update after the fuse).
fn tnt<W: BlockView<State = BlockState>>(d: &mut Drop, w: &W) {
    let b = &mut d.b;
    b.start_tick();
    b.vel[1] -= f64::from(0.04f32);
    let v = b.vel;
    body::entity_move(b, w, v);
    for v in &mut b.vel {
        *v *= f64::from(0.98f32);
    }
    if b.on_ground {
        b.vel[0] *= f64::from(0.7f32);
        b.vel[2] *= f64::from(0.7f32);
        b.vel[1] *= -0.5;
    }
    let fuse = d.fuse;
    d.fuse -= 1;
    if fuse <= 0 {
        b.removed = true;
    } else {
        body::update_water_state(b, w);
    }
}

/// `FallingBlockEntity.tick` (no base tick).
fn falling<W: BlockView<State = BlockState>>(d: &mut Drop, side: Side, world: &W) {
    let server = side == Side::Server;
    if is_air(d.block) {
        d.b.removed = true;
        return;
    }
    let b = &mut d.b;
    b.start_tick();
    let first = d.time == 0;
    d.time += 1;
    if first {
        let p = b.block_pos();
        if state_at(world, p[0], p[1], p[2]).block().id() == d.block.block().id() {
            d.cleared = Some(p);
        } else if server {
            b.removed = true;
            return;
        }
    }
    let w = &Cleared {
        w: world,
        cell: d.cleared,
    };
    b.vel[1] -= f64::from(0.04f32);
    let v = b.vel;
    body::entity_move(b, w, v);
    for v in &mut b.vel {
        *v *= f64::from(0.98f32);
    }
    if server {
        let p = b.block_pos();
        if b.on_ground {
            b.vel[0] *= f64::from(0.7f32);
            b.vel[2] *= f64::from(0.7f32);
            b.vel[1] *= -0.5;
            if state_at(w, p[0], p[1], p[2]).block().id() != nid::PISTON_EXTENSION {
                b.removed = true;
            }
        } else if (d.time > 100 && (p[1] < 1 || p[1] > 256)) || d.time > 600 {
            b.removed = true;
        }
    }
}