ghast-client 0.5.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! 1.16.5: the client's pistons (block events, moving blocks and the player among them).

use super::*;

impl Sim16 {
    /// `block_action`: a piston's block event runs the client's piston (the block at the
    /// position handles it).
    pub(super) fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_16_5::play::clientbound as cb;
        let p: cb::BlockAction = raw.decode_as()?;
        self.piston_edits.clear();
        self.pistons.block_event(
            &self.world,
            [p.location.x, p.location.y, p.location.z],
            p.byte1,
            p.byte2,
            &mut self.piston_edits,
        );
        // The client's shape updates of the writes are in the edits; a kind the model does not
        // cover is flagged.
        if self.pistons.take_unmodelled() {
            self.piston_uncertain_at = Some(self.player.age);
        }
        self.apply_piston_edits();
        Ok(())
    }

    /// The block-entity half of the client tick (after every entity): the moving blocks advance
    /// and push the player and the other entities the client world holds (the client moves its
    /// copies itself; they interpolate on toward the server's positions), whose piston moves
    /// collide with the solid entities as they are at that moment.
    #[cold]
    #[inline(never)]
    pub(super) fn tick_piston_phase(&mut self, pose: &mut Pose) {
        use ghast_physics::v1_16_5 as phys;
        // (search order, id, a shulker, the entity)
        type Other = (
            (i32, i32, i32, u32),
            i32,
            bool,
            ghast_physics::v1_16_5::PistonEntity,
        );
        let mut others: Vec<Other> = Vec::new();
        let mut player_order = None;
        let mut unmodelled = false;
        if let Some(t) = self.entities.as_ref() {
            let parked = self.parked;
            let me = t.self_id();
            player_order = me.and_then(|id| t.search_order(id));
            for e in t.iter() {
                let id = e.id();
                if Some(id) == me {
                    continue;
                }
                // `getOtherEntities` finds what the client world's sections hold.
                let Some(order) = t.search_order(id) else {
                    continue;
                };
                let (Some(pos), Some(b)) = view(t, parked, id) else {
                    continue;
                };
                let bb = aabb(b);
                if parked.is_some_and(|k| k.id == id) {
                    // The boat we left: its client copy is ours, not the tracker's.
                    unmodelled |= self.pistons.touches(&bb);
                    continue;
                }
                let Some(name) = type_name(e) else {
                    continue;
                };
                let player = e.entity_type() == ghast_entity::EntityType::Player;
                let living =
                    player || e.class() == ghast_entity::EntityClass::Mob || name == "armor_stand";
                let alive = t.client_alive(id);
                let spectator = t.is_spectator(e);
                let marker =
                    name == "armor_stand" && e.metadata().byte(14).is_some_and(|f| f & 0x10 != 0);
                // `HorseBaseEntity.isPushable`: not while ridden.
                let ridden_horse = (name.ends_with("horse")
                    || matches!(name, "donkey" | "mule" | "llama" | "trader_llama"))
                    && !e.passengers().is_empty();
                let pushable = alive
                    && !spectator
                    && !ridden_horse
                    && phys::pushable(name, living)
                    && !(living && phys::climbing_at(&self.world, pos));
                let carry = self
                    .piston_carry
                    .iter()
                    .find(|c| c.0 == id)
                    .map_or_else(Default::default, |c| c.1);
                let pe = phys::PistonEntity {
                    bb,
                    pos,
                    on_ground: t.client_on_ground(id).unwrap_or(false),
                    step_height: phys::step_height(name, living),
                    moved: !spectator && !marker,
                    collidable: alive && phys::collides(name),
                    pushable,
                    hits_pushable: phys::hits_pushable(name),
                    living,
                    section: [order.0, order.2, order.1],
                    carry,
                };
                others.push((order, id, name == "shulker", pe));
            }
        }
        others.sort_by_key(|c| c.0);
        let rank = player_order.map_or(others.len(), |o| others.iter().filter(|c| c.0 < o).count());
        let mut list: Vec<phys::PistonEntity> = others.iter().map(|c| c.3).collect();
        let around = phys::Surroundings::new();
        self.piston_edits.clear();
        self.pistons.tick_after_entities_among(
            &mut self.player,
            &mut self.ext,
            &around,
            &mut list,
            phys::PlayerPlace {
                rank,
                // Where its tick left it (`checkEntityChunkPos`).
                section: {
                    let f = |v: f64| ghast_physics::math::floor(v) >> 4;
                    let p = self.filed_pos;
                    [f(p[0]), f(p[1]).clamp(0, 15), f(p[2])]
                },
            },
            &self.world,
            self.piston_time,
            &mut self.piston_edits,
        );
        // The client's own moves of its entity copies.
        if let Some(t) = self.entities.as_mut() {
            for ((_, id, shulker, before), after) in others.iter().zip(&list) {
                if after.carry != before.carry {
                    match self.piston_carry.iter_mut().find(|c| c.0 == *id) {
                        Some(c) => c.1 = after.carry,
                        None => self.piston_carry.push((*id, after.carry)),
                    }
                }
                if after.bb != before.bb
                    || after.pos != before.pos
                    || after.on_ground != before.on_ground
                {
                    self.piston_moved_shulker |= *shulker && after.bb != before.bb;
                    let b = after.bb;
                    t.client_pushed(
                        *id,
                        after.pos,
                        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                        after.on_ground,
                    );
                }
            }
            if self.piston_carry.len() > 64 {
                self.piston_carry.retain(|c| t.get(c.0).is_some());
            }
        }
        // Not modelled: a client shape update of a kind the model does not cover; the boat we
        // left pushed by a piston.
        if unmodelled | self.pistons.take_unmodelled() {
            self.piston_uncertain_at = Some(self.player.age);
        }
        self.apply_piston_edits();
        sync_pose_16(pose, &self.player);
    }

    /// The moving blocks' tick while the player rides (they do not push it here).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_piston_blocks(&mut self) {
        self.piston_edits.clear();
        self.pistons
            .tick_blocks(&self.world, self.piston_time, &mut self.piston_edits);
        if self.pistons.take_unmodelled() {
            self.piston_uncertain_at = Some(self.player.age);
        }
        self.apply_piston_edits();
    }

    piston_bookkeeping!(
        moving: |s| s.block() == ghast_data::v1_16_5::Block::MOVING_PISTON,
        wire_id: id
    );
}