ghast-entity 0.5.8

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
//! Hanging entities (paintings, item frames, leash knots): where the client puts them and their
//! box, both from the block they hang on and their facing (`AbstractDecorationEntity
//! .updateAttachmentPosition`), not from a size table.

use crate::entity::{Entity, EntityType};

/// 1.8 – 1.12 `Direction.fromHorizontal`: south, west, north, east as `(x, z)` offsets.
const HORIZONTAL: [(i32, i32); 4] = [(0, 1), (-1, 0), (0, -1), (1, 0)];

/// `Direction.fromHorizontal`: any int, `abs(dir % 4)` (a painting's data keeps its motive above
/// bit 8, a multiple of 4).
pub(crate) fn horizontal(dir: i32) -> usize {
    (dir % 4).unsigned_abs() as usize
}

/// 1.8 / 1.12 painting motives by title: width and height in pixels (`PaintingEntity.PaintingMotive`).
const MOTIVES_1_8: [(&str, u8, u8); 26] = [
    ("Kebab", 16, 16),
    ("Aztec", 16, 16),
    ("Alban", 16, 16),
    ("Aztec2", 16, 16),
    ("Bomb", 16, 16),
    ("Plant", 16, 16),
    ("Wasteland", 16, 16),
    ("Pool", 32, 16),
    ("Courbet", 32, 16),
    ("Sea", 32, 16),
    ("Sunset", 32, 16),
    ("Creebet", 32, 16),
    ("Wanderer", 16, 32),
    ("Graham", 16, 32),
    ("Match", 32, 32),
    ("Bust", 32, 32),
    ("Stage", 32, 32),
    ("Void", 32, 32),
    ("SkullAndRoses", 32, 32),
    ("Wither", 32, 32),
    ("Fighters", 64, 32),
    ("Pointer", 64, 64),
    ("Pigscene", 64, 64),
    ("BurningSkull", 64, 64),
    ("Skeleton", 64, 48),
    ("DonkeyKong", 64, 48),
];

/// A 1.8 / 1.12 painting title's size as the painting's data keeps it above the direction byte (bits
/// 8 – 15: width / 16 in the high nibble, height / 16 in the low one). An unknown title keeps the client's default motive (Kebab).
pub(crate) fn motive_1_8(title: &[u8]) -> u8 {
    let (_, w, h) = MOTIVES_1_8
        .iter()
        .find(|(n, _, _)| n.as_bytes() == title)
        .copied()
        .unwrap_or(MOTIVES_1_8[0]);
    (w / 16) << 4 | (h / 16)
}

/// 1.16.5 painting motive size by registry id (the same 26 motives in the same order).
pub(crate) fn motive_1_16(id: i32) -> u8 {
    let (_, w, h) = MOTIVES_1_8
        .get(usize::try_from(id).unwrap_or(0))
        .copied()
        .unwrap_or(MOTIVES_1_8[0]);
    (w / 16) << 4 | (h / 16)
}

/// 1.16.5 registry ids: painting, item frame, leash knot.
const PAINTING_1_16: u16 = 55;
const ITEM_FRAME_1_16: u16 = 38;
const LEASH_KNOT_1_16: u16 = 40;

/// The kinds of hanging entity.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Painting,
    ItemFrame,
    LeashKnot,
}

/// The kind of a tracked hanging entity (by version).
fn kind(e: &Entity) -> Option<Kind> {
    use crate::entity::Era;
    let legacy = matches!(e.era, Era::V1_8 | Era::V1_12);
    match e.ty {
        EntityType::Painting if legacy => Some(Kind::Painting),
        EntityType::LegacyObject(71) if legacy => Some(Kind::ItemFrame),
        EntityType::LegacyObject(77) if legacy => Some(Kind::LeashKnot),
        EntityType::Registry(PAINTING_1_16) if e.era == Era::V1_16 => Some(Kind::Painting),
        EntityType::Registry(ITEM_FRAME_1_16) if e.era == Era::V1_16 => Some(Kind::ItemFrame),
        EntityType::Registry(LEASH_KNOT_1_16) if e.era == Era::V1_16 => Some(Kind::LeashKnot),
        _ => None,
    }
}

/// `(width, height)` in pixels of a painting or item frame (`getWidth` / `getHeight`), from
/// the type alone (at spawn the entity's era is not set yet).
fn size(e: &Entity) -> Option<(i32, i32)> {
    match e.ty {
        EntityType::Painting | EntityType::Registry(PAINTING_1_16) => {
            let m = (e.data >> 8) & 0xff;
            Some(((m >> 4) * 16, (m & 15) * 16))
        }
        EntityType::LegacyObject(71) | EntityType::Registry(ITEM_FRAME_1_16) => Some((12, 12)),
        _ => None,
    }
}

/// 1.16 `Direction.byId`: down, up, north, south, west, east as `(x, y, z)` offsets.
const BY_ID: [(i32, i32, i32); 6] = [
    (0, -1, 0),
    (0, 1, 0),
    (0, 0, -1),
    (0, 0, 1),
    (-1, 0, 0),
    (1, 0, 0),
];

/// 1.16 `Direction.byId`: any int, `abs(id % 6)`.
fn by_id(dir: i32) -> (i32, i32, i32) {
    BY_ID[(dir % 6).unsigned_abs() as usize]
}

/// 1.16 `ItemFrameEntity.updateAttachmentPosition`: the frame on block `b` facing `dir`
/// (`Direction.byId`, up and down too).
pub(crate) fn frame_1_16(b: [i32; 3], dir: i32) -> [f64; 3] {
    let (ox, oy, oz) = by_id(dir);
    [
        f64::from(b[0]) + 0.5 - f64::from(ox) * 0.46875,
        f64::from(b[1]) + 0.5 - f64::from(oy) * 0.46875,
        f64::from(b[2]) + 0.5 - f64::from(oz) * 0.46875,
    ]
}

/// `updateAttachmentPosition` on 1.8 / 1.12: the position of a painting or item frame hanging on
/// block `b` facing `dir` (horizontal index), `None` for other entities.
pub(crate) fn attach_1_8(e: &Entity, b: [i32; 3], dir: i32) -> Option<[f64; 3]> {
    let (w, h) = size(e)?;
    let (ox, oz) = HORIZONTAL[horizontal(dir)];
    // rotateYCounterclockwise: south -> east, west -> south, north -> west, east -> north.
    let (cx, cz) = (oz, -ox);
    let half = |n: i32| if n % 32 == 0 { 0.5 } else { 0.0 };
    let mut d = f64::from(b[0]) + 0.5;
    let mut y = f64::from(b[1]) + 0.5;
    let mut f = f64::from(b[2]) + 0.5;
    d -= f64::from(ox) * 0.46875;
    f -= f64::from(oz) * 0.46875;
    y += half(h);
    d += half(w) * f64::from(cx);
    f += half(w) * f64::from(cz);
    Some([d, y, f])
}

/// `true` for a 1.8 – 1.16.5 painting, item frame or leash knot.
#[inline]
pub(crate) fn is_hanging(e: &Entity) -> bool {
    kind(e).is_some()
}

/// `true` for a painting (its position packets never turn it).
pub(crate) fn is_painting(e: &Entity) -> bool {
    kind(e) == Some(Kind::Painting)
}

/// `BlockPos(double, double, double)`: each coordinate floored.
fn block_of(p: [f64; 3]) -> [i32; 3] {
    p.map(|c| c.floor() as i32)
}

/// The block a painting hangs on, from its position: `updateAttachmentPosition` undone (every
/// offset is a multiple of 1/32, so the subtraction is exact).
/// 1.8 also puts a painting on its block's corner (all coordinates whole; a hanging position
/// never is: it sits 1/32 off the block face).
fn painting_block(e: &Entity, p: [f64; 3]) -> [i32; 3] {
    if p.iter().all(|c| c.fract() == 0.0) {
        return block_of(p);
    }
    let Some(at) = attach_1_8(e, [0, 0, 0], e.data) else {
        return block_of(p);
    };
    // `at` is the position on block (0, 0, 0): its offsets from that block.
    block_of([p[0] - at[0], p[1] - at[1], p[2] - at[2]])
}

/// 1.8 `AbstractDecorationEntity.updatePosition(t)`: the entity stands at `t` itself; only a new
/// block re-hangs it (an item frame or painting: position and box from the block and facing; a
/// leash knot has no facing and never does). `block` is the block it hung on.
fn update_position_1_8(e: &mut Entity, block: [i32; 3], t: [f64; 3]) {
    let to = block_of(t);
    e.pos = t;
    if to != block
        && kind(e) != Some(Kind::LeashKnot)
        && let Some(p) = attach_1_8(e, to, e.data)
    {
        e.pos = p;
    }
}

/// `updateTrackedPositionAndAngles` of a hanging entity, to tracked position `t`
/// (`AbstractDecorationEntity.setPosition` / `updatePosition`): an item frame hangs on the block
/// of `t`, a leash knot sits in its centre (its box stays where the knot spawned: only its
/// constructor builds one), a painting moves its block by the floored distance from its
/// position to `t` (`PaintingEntity.updateTrackedPositionAndAngles`). 1.8 differs: see
/// [`update_position_1_8`].
pub(crate) fn tracked_move(e: &mut Entity, t: [f64; 3]) {
    if e.era == crate::entity::Era::V1_8 {
        let block = match kind(e) {
            Some(Kind::Painting) => painting_block(e, e.pos),
            Some(_) => block_of(e.pos),
            None => return,
        };
        if kind(e) == Some(Kind::LeashKnot)
            && block_of(t) != block
            && e.links.as_ref().is_none_or(|l| l.knot_block.is_none())
        {
            e.links_mut().knot_block = Some(block);
        }
        let t = if kind(e) == Some(Kind::Painting) {
            // `pos.add(t - position)`, then `updatePosition` at that block's corner.
            let d = [t[0] - e.pos[0], t[1] - e.pos[1], t[2] - e.pos[2]];
            let n = if d == [0.0; 3] {
                block
            } else {
                [
                    (f64::from(block[0]) + d[0]).floor() as i32,
                    (f64::from(block[1]) + d[1]).floor() as i32,
                    (f64::from(block[2]) + d[2]).floor() as i32,
                ]
            };
            n.map(f64::from)
        } else {
            t
        };
        update_position_1_8(e, block, t);
        return;
    }
    match kind(e) {
        Some(Kind::ItemFrame) if e.era == crate::entity::Era::V1_16 => {
            e.pos = frame_1_16(block_of(t), e.data);
        }
        Some(Kind::ItemFrame) => {
            if let Some(p) = attach_1_8(e, block_of(t), e.data) {
                e.pos = p;
            }
        }
        Some(Kind::LeashKnot) => {
            let (from, to) = (block_of(e.pos), block_of(t));
            if from != to && e.links.as_ref().is_none_or(|l| l.knot_block.is_none()) {
                e.links_mut().knot_block = Some(from);
            }
            e.pos = knot_1_8(to);
        }
        Some(Kind::Painting) => {
            let b = painting_block(e, e.pos);
            let n = [
                (f64::from(b[0]) + (t[0] - e.pos[0])).floor() as i32,
                (f64::from(b[1]) + (t[1] - e.pos[1])).floor() as i32,
                (f64::from(b[2]) + (t[2] - e.pos[2])).floor() as i32,
            ];
            if let Some(p) = attach_1_8(e, n, e.data) {
                e.pos = p;
            }
        }
        None => {}
    }
}

/// 1.8 / 1.12 `LeashKnotEntity(world, pos)`: the knot sits at the block's centre.
pub(crate) fn knot_1_8(b: [i32; 3]) -> [f64; 3] {
    [
        f64::from(b[0]) + 0.5,
        f64::from(b[1]) + 0.5,
        f64::from(b[2]) + 0.5,
    ]
}

/// The box of a hanging entity at position `p` (`None` for other entities).
pub(crate) fn hanging_box(e: &Entity, p: [f64; 3]) -> Option<[f64; 6]> {
    let k = kind(e)?;
    // 1.8: the entity may stand off its hanging position (`update_position_1_8`); the box stays
    // the one its block gave it.
    let p = match k {
        _ if e.era != crate::entity::Era::V1_8 => p,
        Kind::LeashKnot => knot_1_8(block_of(p)),
        Kind::ItemFrame => attach_1_8(e, block_of(p), e.data)?,
        Kind::Painting => attach_1_8(e, painting_block(e, p), e.data)?,
    };
    let [d, y, f] = p;
    if k == Kind::ItemFrame && e.era == crate::entity::Era::V1_16 {
        // One pixel thick along the facing's axis (any of the six).
        let (ox, oy, _) = by_id(e.data);
        let (mut h, mut i, mut j) = (12.0_f64, 12.0_f64, 12.0_f64);
        if ox != 0 {
            h = 1.0;
        } else if oy != 0 {
            i = 1.0;
        } else {
            j = 1.0;
        }
        let (h, i, j) = (h / 32.0, i / 32.0, j / 32.0);
        return Some([d - h, y - i, f - j, d + h, y + i, f + j]);
    }
    if k == Kind::LeashKnot {
        let [d, y, f] = match e.links.as_ref().and_then(|l| l.knot_block) {
            // A knot moved to another block keeps its spawn block's box.
            Some(b) => knot_1_8(b),
            None => p,
        };
        return Some([
            d - 0.1875,
            y - 0.25 + 0.125,
            f - 0.1875,
            d + 0.1875,
            y + 0.25 + 0.125,
            f + 0.1875,
        ]);
    }
    let (w, h) = size(e)?;
    let (ox, _) = HORIZONTAL[horizontal(e.data)];
    let (mut j, k, mut l) = (f64::from(w), f64::from(h), f64::from(w));
    // One pixel thick along the facing axis.
    if ox == 0 {
        l = 1.0;
    } else {
        j = 1.0;
    }
    j /= 32.0;
    let k = k / 32.0;
    l /= 32.0;
    Some([d - j, y - k, f - l, d + j, y + k, f + l])
}

/// `getTargetingMargin` of a hanging entity: 1.8 0.1 (`Entity`), item frames 0; 1.12 and
/// 1.16 0.
pub(crate) fn margin(e: &Entity) -> Option<f32> {
    let k = kind(e)?;
    Some(
        if e.era == crate::entity::Era::V1_8 && k != Kind::ItemFrame {
            0.1
        } else {
            0.0
        },
    )
}