ghast-entity 0.5.7

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 entity packets, vanilla-exact positions, O(1) lookup
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
//! The 26.x entity types whose client box is not the centred dimensions box
//! (`ghast_data::modern::type_flags::NO_BOX`), and where the client puts them:
//!
//! - **Item frames, glow item frames, paintings** (`HangingEntity`): the client keeps the block the
//!   entity hangs on (`BlockAttachedEntity.pos`: the block containing the position a spawn or
//!   move gives) and builds the box from it, the facing (spawn data, then the direction entity
//!   data) and, for frames, whether a map is framed (a stack with a `map_id` component: a 1 x 1
//!   box instead of 0.75 x 0.75), for paintings the variant's size (an even size moves the box by
//!   half a block to the left of the facing and up). The entity's position is the box centre
//!   (`AABB.getCenter`); an item frame also resets its `VecDeltaCodec` base to it.
//! - **Leash knots**: on their block's centre, 0.375 above its bottom; the type's 0.375 x 0.5 box.
//! - **Shulkers**: snapped onto the block centre (bottom) unless riding; the box grows from the
//!   attach face by the lid's opening (`Shulker.getProgressAabb` with the physical peek of the
//!   peek amount the client animates in steps of 0.05 per tick towards the peek entity data, and
//!   the `minecraft:scale` value at the last box rebuild).
//! - **Interaction entities**: the width / height entity data as the dimensions.
//! - **Wind charges** (and the breeze's): the type's box lowered by 0.15.
//!
//! Only these types run any of this: the tracker calls in after testing the type's `NO_BOX`
//! flag. Their state lives in fields of the boxed modern state the other types use for
//! something else ([`State::target`] is unused by types without an interpolation, `slime_size`
//! by types without a size entry), so no entity grows.
//!
//! Proof: `tests/golden/<26.x>/entity_boxes.jsonl.gz` (oracle `EntityBoxDump`).

use crate::entity::Entity;
use crate::modern_state::{State, st};
use ghast_data::modern::{EntityTypeData, type_flags};

/// The types with their own box.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Kind {
    Frame,
    Painting,
    Knot,
    Shulker,
    Interaction,
    WindCharge,
}

/// The kind of a type with the `NO_BOX` flag (`None` for the others).
#[inline]
pub(crate) fn kind(td: Option<&EntityTypeData>) -> Option<Kind> {
    let t = td?;
    if t.flags & type_flags::NO_BOX == 0 {
        return None;
    }
    kind_of(t.name)
}

#[cold]
fn kind_of(name: &str) -> Option<Kind> {
    Some(match name {
        "item_frame" | "glow_item_frame" => Kind::Frame,
        "painting" => Kind::Painting,
        "leash_knot" => Kind::Knot,
        "shulker" => Kind::Shulker,
        "interaction" => Kind::Interaction,
        "wind_charge" | "breeze_wind_charge" => Kind::WindCharge,
        _ => return None,
    })
}

// ------------------------------------------------------------------------------- state layout
//
// Hanging entities (frames, paintings, knots): `target` = the block, `slime_size` = facing
// (3-D id, bits 0 - 2) | width << 8 | height << 16 (painting variant, blocks) | 1 << 24 (a frame
// holds a map).
// Shulkers: `target` = [scale at the last box rebuild, current peek amount, peek entity data],
// `slime_size` = attach face (3-D id).
// Interactions: `target` = [width, height, 0].

const MAP: i32 = 1 << 24;

fn facing(m: &State) -> usize {
    (m.slime_size & 7) as usize % 6
}

fn block(m: &State) -> [f64; 3] {
    m.target
}

/// `Direction.from3DDataValue`: down, up, north, south, west, east.
fn from_3d(v: i32) -> i32 {
    (v % 6).abs()
}

/// `(x, y, z)` unit vectors of the 3-D direction ids.
const STEP: [[i32; 3]; 6] = [
    [0, -1, 0],
    [0, 1, 0],
    [0, 0, -1],
    [0, 0, 1],
    [-1, 0, 0],
    [1, 0, 0],
];

/// `Direction.getCounterClockWise()` of a horizontal 3-D id (north -> west -> south -> east).
fn counter_clockwise(d: usize) -> usize {
    match d {
        2 => 4,
        4 => 3,
        3 => 5,
        5 => 2,
        other => other,
    }
}

/// `Direction.getOpposite()`.
fn opposite(d: usize) -> usize {
    d ^ 1
}

/// Java `Math.min(double, double)`.
fn jmin(a: f64, b: f64) -> f64 {
    if a.is_nan() {
        return a;
    }
    if a == 0.0 && b == 0.0 && b.is_sign_negative() {
        return b;
    }
    if a <= b { a } else { b }
}

/// Java `Math.max(double, double)`.
fn jmax(a: f64, b: f64) -> f64 {
    if a.is_nan() {
        return a;
    }
    if a == 0.0 && b == 0.0 && a.is_sign_negative() {
        return b;
    }
    if a >= b { a } else { b }
}

/// `new AABB(x1, y1, z1, x2, y2, z2)` (each axis ordered).
fn aabb(a: [f64; 3], b: [f64; 3]) -> [f64; 6] {
    [
        jmin(a[0], b[0]),
        jmin(a[1], b[1]),
        jmin(a[2], b[2]),
        jmax(a[0], b[0]),
        jmax(a[1], b[1]),
        jmax(a[2], b[2]),
    ]
}

/// `AABB.ofSize(centre, sx, sy, sz)`.
fn of_size(c: [f64; 3], s: [f64; 3]) -> [f64; 6] {
    aabb(
        [c[0] - s[0] / 2.0, c[1] - s[1] / 2.0, c[2] - s[2] / 2.0],
        [c[0] + s[0] / 2.0, c[1] + s[1] / 2.0, c[2] + s[2] / 2.0],
    )
}

/// `AABB.getCenter()` (`Mth.lerp(0.5, min, max)` per axis).
fn center(b: [f64; 6]) -> [f64; 3] {
    [
        b[0] + 0.5 * (b[3] - b[0]),
        b[1] + 0.5 * (b[4] - b[1]),
        b[2] + 0.5 * (b[5] - b[2]),
    ]
}

/// `Vec3.relative(direction, distance)`.
fn relative(p: [f64; 3], d: usize, len: f64) -> [f64; 3] {
    let s = STEP[d];
    [
        p[0] + len * f64::from(s[0]),
        p[1] + len * f64::from(s[1]),
        p[2] + len * f64::from(s[2]),
    ]
}

/// `Mth.floor(double)`.
fn floor(v: f64) -> i32 {
    let i = v as i32;
    if v < f64::from(i) { i - 1 } else { i }
}

/// `Mth.sin(double)` (26.x: the 65536-entry table, indexed through a `long`). One entry is
/// computed as the table computes it.
fn mth_sin(v: f64) -> f32 {
    let i = (v * 10_430.378_350_470_453) as i64 & 0xFFFF;
    (i as f64 * std::f64::consts::PI * 2.0 / 65536.0).sin() as f32
}

/// The box of a hanging entity on its block (`HangingEntity.calculateBoundingBox`).
fn hanging_box(e: &Entity, k: Kind) -> [f64; 6] {
    let m = &*e.m;
    let b = block(m);
    let d = facing(m);
    let wall = relative([b[0] + 0.5, b[1] + 0.5, b[2] + 0.5], d, -0.46875);
    let axis = STEP[d];
    if k == Kind::Frame {
        let s = if m.slime_size & MAP != 0 { 1.0 } else { 0.75 };
        let size = |a: i32| if a != 0 { 0.0625 } else { s };
        return of_size(wall, [size(axis[0]), size(axis[1]), size(axis[2])]);
    }
    let w = (m.slime_size >> 8) & 0xFF;
    let h = (m.slime_size >> 16) & 0xFF;
    let off = |n: i32| if n % 2 == 0 { 0.5 } else { 0.0 };
    let p = relative(wall, counter_clockwise(d), off(w));
    let p = relative(p, 1, off(h));
    let (w, h) = (f64::from(w), f64::from(h));
    of_size(
        p,
        [
            if axis[0] != 0 { 0.0625 } else { w },
            h,
            if axis[2] != 0 { 0.0625 } else { w },
        ],
    )
}

/// The client box of entity `e` of kind `k` at its position.
pub(crate) fn bounding_box(e: &Entity, k: Kind) -> Option<[f64; 6]> {
    let [x, y, z] = e.pos;
    let m = &*e.m;
    Some(match k {
        Kind::Frame | Kind::Painting => hanging_box(e, k),
        Kind::Knot => {
            let s = m.td?.size?.registered?;
            let hw = f64::from(s.0) / 2.0;
            let h = f64::from(s.1);
            aabb([x - hw, y, z - hw], [x + hw, y + h, z + hw])
        }
        Kind::WindCharge => {
            let s = m.td?.size?.registered?;
            let w = f64::from(s.0 / 2.0);
            let y0 = y - f64::from(0.15_f32);
            aabb([x - w, y0, z - w], [x + w, y0 + f64::from(s.1), z + w])
        }
        Kind::Interaction => {
            // EntityDimensions.scalable(width, height).makeBoundingBox.
            let w = f64::from(m.target[0] as f32 / 2.0);
            let h = f64::from(m.target[1] as f32);
            aabb([x - w, y, z - w], [x + w, y + h, z + w])
        }
        Kind::Shulker => {
            let size = m.target[0] as f32;
            let peek = m.target[1] as f32;
            let phys = 0.5_f32 - mth_sin(f64::from((0.5_f32 + peek) * std::f32::consts::PI)) * 0.5;
            let d = STEP[opposite(m.slime_size as usize % 6)];
            let s = f64::from(size);
            // getProgressDeltaAabb(size, direction, -1, phys, position).
            let mut lo = [-s * 0.5, 0.0, -s * 0.5];
            let mut hi = [s * 0.5, s, s * 0.5];
            let max = f64::from((-1.0_f32).max(phys));
            for i in 0..3 {
                let a = f64::from(d[i]) * max * s;
                if a < 0.0 {
                    lo[i] += a;
                } else if a > 0.0 {
                    hi[i] += a;
                }
            }
            let b = aabb(lo, hi);
            // contract(-step * (1 + min) * size) with min = -1: a zero (no change); then move.
            aabb(
                [b[0] + x, b[1] + y, b[2] + z],
                [b[3] + x, b[4] + y, b[5] + z],
            )
        }
    })
}

// ------------------------------------------------------------------------------- tracker hooks

/// Painting variants of a vanilla registry, `(width, height)` in blocks by network id (the
/// registry order a vanilla server syncs: by name; every 26.x version has these 51).
const PAINTINGS: [(u8, u8); 51] = [
    (1, 1), // alban
    (1, 1), // aztec
    (1, 1), // aztec2
    (3, 4), // backyard
    (2, 2), // baroque
    (1, 1), // bomb
    (3, 3), // bouquet
    (4, 4), // burning_skull
    (2, 2), // bust
    (3, 3), // cavebird
    (4, 2), // changing
    (3, 3), // cotan
    (2, 1), // courbet
    (2, 1), // creebet
    (3, 3), // dennis
    (4, 3), // donkey_kong
    (2, 2), // earth
    (3, 3), // endboss
    (3, 3), // fern
    (4, 2), // fighters
    (4, 2), // finding
    (2, 2), // fire
    (1, 2), // graham
    (2, 2), // humble
    (1, 1), // kebab
    (4, 2), // lowmist
    (2, 2), // match
    (1, 1), // meditative
    (4, 4), // orb
    (3, 3), // owlemons
    (4, 2), // passage
    (4, 4), // pigscene
    (1, 1), // plant
    (4, 4), // pointer
    (3, 4), // pond
    (2, 1), // pool
    (1, 2), // prairie_ride
    (2, 1), // sea
    (4, 3), // skeleton
    (2, 2), // skull_and_roses
    (2, 2), // stage
    (3, 3), // sunflowers
    (2, 1), // sunset
    (3, 3), // tides
    (4, 4), // unpacked
    (2, 2), // void
    (1, 2), // wanderer
    (1, 1), // wasteland
    (2, 2), // water
    (2, 2), // wind
    (2, 2), // wither
];

/// The size of a registered painting variant (`None`: an id the vanilla registry does not have).
pub(crate) fn painting_size(id: i32) -> Option<(u8, u8)> {
    PAINTINGS.get(usize::try_from(id).ok()?).copied()
}

/// What a metadata packet changed for these types.
#[derive(Default, Clone, Copy)]
pub(crate) struct Keys {
    /// Hanging entities: the direction entry (3-D id as sent).
    pub(crate) direction: Option<i32>,
    /// Frames: whether the new stack has a `map_id` component.
    pub(crate) map: Option<bool>,
    /// Paintings: the variant's size (`None` inside: an unknown registry id, kept).
    pub(crate) variant: Option<(u8, u8)>,
    /// Shulkers: the attach face and the peek byte.
    pub(crate) face: Option<i32>,
    pub(crate) peek: Option<i8>,
    /// Interactions: width and height.
    pub(crate) width: Option<f32>,
    pub(crate) height: Option<f32>,
}

impl Keys {
    pub(crate) fn any(&self) -> bool {
        self.direction.is_some()
            || self.map.is_some()
            || self.variant.is_some()
            || self.face.is_some()
            || self.peek.is_some()
            || self.width.is_some()
            || self.height.is_some()
    }
}

/// `BlockAttachedEntity.setPos` / `Shulker.setPos` after the tracker put the entity at the raw
/// position `e.pos` (a spawn, a move, a sync or teleport). `old`: the position before, for a
/// plain `setPos`; `None` at a spawn and through `Entity.snapTo` (`setPosRaw` runs first, so a
/// shulker sees no block change). Returns the new `VecDeltaCodec` base when the type resets it
/// (item frames).
#[cold]
#[inline(never)]
pub(crate) fn set_pos(e: &mut Entity, k: Kind, old: Option<[f64; 3]>) -> Option<[f64; 3]> {
    match k {
        Kind::Frame | Kind::Painting | Kind::Knot => {
            let p = e.pos;
            e.m.target = [
                f64::from(floor(p[0])),
                f64::from(floor(p[1])),
                f64::from(floor(p[2])),
            ];
            recalc(e, k)
        }
        Kind::Shulker => {
            shulker_set_pos(e, old);
            None
        }
        Kind::Interaction | Kind::WindCharge => None,
    }
}

/// The rotation `setDirection` gives a frame or painting: horizontal facings turn yRot to
/// `get2DDataValue * 90` (frames also xRot 0); a frame facing up / down gets xRot -90 / 90 and
/// yRot 0.
fn direction_rotation(e: &mut Entity, k: Kind) {
    let d = facing(&e.m);
    // get2DDataValue of the 3-D ids (south 0, west 1, north 2, east 3).
    let horizontal = [None, None, Some(2), Some(0), Some(1), Some(3)][d];
    match horizontal {
        Some(h) => {
            e.yaw = (h * 90) as f32;
            if k == Kind::Frame {
                e.pitch = 0.0;
            }
        }
        None if k == Kind::Frame => {
            e.pitch = if d == 1 { -90.0 } else { 90.0 };
            e.yaw = 0.0;
        }
        // Painting.setDirection refuses vertical facings (a server never sends one).
        None => {}
    }
}

/// `recalculateBoundingBox` of a hanging entity: the position becomes the box centre (knots: the
/// block centre, 0.375 up). Returns the item frame's new codec base.
fn recalc(e: &mut Entity, k: Kind) -> Option<[f64; 3]> {
    let b = block(&e.m);
    if k == Kind::Knot {
        e.pos = [b[0] + 0.5, b[1] + 0.375, b[2] + 0.5];
        return None;
    }
    let c = center(hanging_box(e, k));
    e.pos = c;
    (k == Kind::Frame).then_some(c)
}

fn shulker_set_pos(e: &mut Entity, old: Option<[f64; 3]>) {
    let raw = e.pos;
    if e.vehicle().is_none() {
        e.pos = [
            f64::from(floor(raw[0])) + 0.5,
            f64::from(floor(raw[1] + 0.5)),
            f64::from(floor(raw[2])) + 0.5,
        ];
    }
    // tickCount != 0 and a new block: the client zeroes its copy of the peek entry.
    let block = |p: [f64; 3]| [floor(p[0]), floor(p[1]), floor(p[2])];
    if let Some(o) = old
        && e.m.flag(st::TICKED)
        && block(o) != block(e.pos)
    {
        e.m.target[2] = 0.0;
    }
    e.m.target[0] = f64::from(e.m.scale);
}

/// A spawn of a type with its own box: its state, then `setPos` at the spawn position (`data`:
/// the spawn data, a hanging entity's facing). Returns the item frame's codec base.
#[cold]
#[inline(never)]
pub(crate) fn spawned(e: &mut Entity, k: Kind, data: i32) -> Option<[f64; 3]> {
    match k {
        Kind::Frame | Kind::Painting | Kind::Knot => {
            // Default variant: the registry's first (1 x 1 in vanilla).
            let (w, h) = PAINTINGS[0];
            e.m.slime_size = from_3d(data) | i32::from(w) << 8 | i32::from(h) << 16;
            if k == Kind::Knot {
                e.m.slime_size = 0;
            } else {
                // recreateFromPacket: setDirection(from3DDataValue(data)) after the snap
                // (Painting.snapTo ignores the packet's rotation).
                if k == Kind::Painting {
                    e.yaw = 0.0;
                    e.pitch = 0.0;
                }
                direction_rotation(e, k);
            }
        }
        Kind::Shulker => {
            e.m.slime_size = 0; // attach face: down
            e.m.target = [f64::from(e.m.scale), 0.0, 0.0];
        }
        Kind::Interaction => e.m.target = [1.0, 1.0, 0.0],
        Kind::WindCharge => {}
    }
    set_pos(e, k, None)
}

/// A metadata packet of a type with its own box (`resize`: the pose or another size key
/// changed: `refreshDimensions`). Returns the item frame's new codec base.
#[cold]
#[inline(never)]
pub(crate) fn metadata(e: &mut Entity, k: Kind, keys: &Keys, resize: bool) -> Option<[f64; 3]> {
    match k {
        Kind::Frame | Kind::Painting => {
            let mut changed = false;
            if let Some(d) = keys.direction {
                e.m.slime_size = (e.m.slime_size & !7) | from_3d(d);
                direction_rotation(e, k);
                changed = true;
            }
            if let Some(m) = keys.map {
                e.m.slime_size = (e.m.slime_size & !MAP) | if m { MAP } else { 0 };
                changed = true;
            }
            if let Some((w, h)) = keys.variant {
                e.m.slime_size =
                    (e.m.slime_size & !0x00FF_FF00) | i32::from(w) << 8 | i32::from(h) << 16;
                changed = true;
            }
            if changed {
                return recalc(e, k);
            }
        }
        Kind::Shulker => {
            if let Some(p) = keys.peek {
                e.m.target[2] = f64::from(p);
            }
            if let Some(f) = keys.face {
                e.m.slime_size = from_3d(f);
            }
            // The face rebuilds the box; a pose change refreshes the dimensions (setPos again).
            if keys.face.is_some() || resize {
                shulker_set_pos(e, None);
            }
        }
        Kind::Interaction => {
            if let Some(w) = keys.width {
                e.m.target[0] = f64::from(w);
            }
            if let Some(h) = keys.height {
                e.m.target[1] = f64::from(h);
            }
        }
        Kind::Knot | Kind::WindCharge => {}
    }
    None
}

/// The shulker's part of its client tick (`Shulker.tick` after `LivingEntity.tick`): the peek
/// amount steps 0.05 towards the peek entry; a change rebuilds the box (`reapplyPosition`).
/// Returns whether it is still moving (the entity cannot settle).
#[cold]
#[inline(never)]
pub(crate) fn shulker_tick(e: &mut Entity) -> bool {
    e.m.set_flag(st::TICKED, true);
    let current = e.m.target[1] as f32;
    let target = e.m.target[2] as f32 * 0.01;
    if current == target {
        return false;
    }
    let next = if current > target {
        clamp_f(current - 0.05, target, 1.0)
    } else {
        clamp_f(current + 0.05, 0.0, target)
    };
    e.m.target[1] = f64::from(next);
    shulker_set_pos(e, None);
    true
}

/// `Mth.clamp(float, float, float)`: `value < min ? min : Math.min(value, max)`.
fn clamp_f(v: f32, lo: f32, hi: f32) -> f32 {
    if v < lo {
        lo
    } else if v.is_nan() || v <= hi {
        v
    } else {
        hi
    }
}

/// The scale changed and the dimensions were refreshed (`refreshDirtyAttributes`): a shulker
/// rebuilds its box with the new scale.
#[cold]
#[inline(never)]
pub(crate) fn rescaled(e: &mut Entity, k: Kind) {
    if k == Kind::Shulker {
        shulker_set_pos(e, None);
    }
}