ghast-client 0.5.5

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.12.2: the client's pistons (block events, moving blocks and the player among them).

use super::*;

impl Sim12 {
    /// `block_action`: a piston's extend / retract runs the client's piston (the 1.12 client
    /// lets the block at the position handle it).
    pub(super) fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_12_2::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.block_id & 4095) as u8,
            p.byte1,
            p.byte2,
            &mut self.piston_edits,
        );
        self.apply_piston_edits();
        Ok(())
    }

    /// The player's tick while blocks move (kept out of the plain tick's code): the extended
    /// tick's state and the entity boxes it collides with, then the moving blocks. Entity pushes
    /// and rocket boosts are not applied in these ticks.
    #[cold]
    #[inline(never)]
    pub(super) fn step_pistons(&mut self, pose: &Pose, controls: Controls, using_item: bool) {
        if let Some(r) = &mut self.rec {
            r.note_once("moving pistons not representable");
        }
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        let solids: &[ghast_physics::math::Aabb] =
            match (self.near.as_deref_mut(), self.entities.as_ref()) {
                (Some(n), Some(t)) if !n.idle() => {
                    n.solids(t, &self.world, &self.player);
                    &n.solids
                }
                _ => &[],
            };
        // The player's half: the moving blocks tick after every entity
        // ([`Sim12::tick_piston_phase`], from `tick_entities`).
        ghast_physics::v1_12::tick_player_among_pistons(
            &mut self.player,
            &mut self.ext,
            &input,
            &self.world,
            &ghast_physics::v1_12::Options::default(),
            solids,
            &self.pistons,
            &mut self.packets,
        );
    }

    /// The block-entity half of the client tick (`World.tickEntities` after every entity): the
    /// moving blocks advance and push the player and the other entities the client follows
    /// (it 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_12 as phys;
        if self.ride.is_some() {
            self.tick_piston_blocks();
            return;
        }
        // (search order, where it is kept, entity)
        type Other = ((i32, i32, i32, u64, u8), Kept, phys::PistonEntity);
        let mut others: Vec<Other> = Vec::new();
        let mut ghosts: Vec<ghast_physics::math::Aabb> = Vec::new();
        let mut player_key = None;
        let mut unmodelled = false;
        if let (Some(n), Some(t)) = (self.near.as_deref(), self.entities.as_ref()) {
            // The destroyed boats still in their chunks' lists.
            ghosts.extend(n.ghosts.iter().filter(|g| !g.cart).map(|g| g.bb));
            player_key = n.me.map(|(s, q)| (s[0], s[2], s[1], q, 0));
            for (k, c) in n.list.iter().enumerate() {
                let Some(e) = t.get(c.id) else { continue };
                if !Near12::present(t, &self.world, c) {
                    // Riders and carriers are not followed here.
                    unmodelled |= e.vehicle().is_some() && self.pistons.touches(&c.bb);
                    continue;
                }
                let name = match c.class {
                    Class12::Player => "player",
                    Class12::Boat => "boat",
                    Class12::Cart => "minecart",
                    _ => match e.entity_type() {
                        t @ ghast_entity::EntityType::LegacyMob(_) => {
                            ghast_entity::v1_12::info(t).map_or("", |i| i.name)
                        }
                        _ => "",
                    },
                };
                let living = !matches!(c.class, Class12::Boat | Class12::Cart);
                let alive = ghast_entity::v1_12::health(e).is_none_or(|h| h > 0.0);
                let spectator = c.class == Class12::Player && t.tab_game_mode(&e.uuid()) == Some(3);
                let pe = phys::PistonEntity {
                    bb: c.bb,
                    pos: c.at,
                    on_ground: c.on_ground,
                    in_web: c.in_web,
                    step_height: phys::step_height(name, living),
                    moved: !spectator,
                    collidable: matches!(c.class, Class12::Boat)
                        || (c.class == Class12::Shulker && alive),
                    pushable: !spectator
                        && phys::blocks_boat(
                            name,
                            living,
                            alive,
                            phys::entity_climbing(&self.world, c.at, c.bb.min_y),
                            !e.passengers().is_empty(),
                        ),
                    hits_pushable: phys::hits_pushable(name),
                    section: c.section,
                    carry: c.carry,
                };
                others.push((
                    (c.section[0], c.section[2], c.section[1], c.list_seq, 0),
                    Kept::Near(k),
                    pe,
                ));
            }
            // The entities a piston moves on the client that the near-entity model does not
            // hold: armor stands and bats (players, mobs, boats, minecarts and shulkers are
            // there); the solid objects it moves too (TNT, end crystals, falling blocks,
            // fireballs) are not followed.
            for e in t.iter() {
                use ghast_entity::EntityType as T;
                let name = match e.entity_type() {
                    T::LegacyObject(78) => "armor_stand",
                    ty @ T::LegacyMob(_)
                        if ghast_entity::v1_12::info(ty).is_some_and(|i| i.name == "bat") =>
                    {
                        "bat"
                    }
                    T::LegacyObject(50 | 51 | 63 | 70) => {
                        if let Some(b) = e.drawn_bounding_box() {
                            let bb =
                                ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
                            unmodelled |= self.pistons.touches(&bb);
                        }
                        continue;
                    }
                    _ => continue,
                };
                let (Some(b), Some(o)) = (e.drawn_bounding_box(), e.search_order()) else {
                    continue;
                };
                let bb = ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
                if e.vehicle().is_some() || !e.passengers().is_empty() {
                    unmodelled |= self.pistons.touches(&bb);
                    continue;
                }
                let section = [o.0, o.2, o.1];
                // Its place in its section's list among the near-entity model's entries: after
                // those that entered the list before it.
                let after = n
                    .list
                    .iter()
                    .filter(|c| {
                        c.section == section
                            && t.get(c.id)
                                .and_then(ghast_entity::Entity::search_order)
                                .is_some_and(|q| q.3 < o.3)
                    })
                    .map(|c| c.list_seq)
                    .max()
                    .unwrap_or(0);
                let carry = self
                    .piston_carry
                    .iter()
                    .find(|c| c.0 == e.id())
                    .map_or_else(Default::default, |c| c.1);
                let pe = phys::PistonEntity {
                    bb,
                    pos: e.drawn_position(),
                    on_ground: e.drawn_on_ground(),
                    in_web: e.drawn_in_web(),
                    step_height: phys::step_height(name, true),
                    moved: true,
                    collidable: false,
                    pushable: false,
                    hits_pushable: false,
                    section,
                    carry,
                };
                others.push((
                    (section[0], section[2], section[1], after, 1),
                    Kept::Extra(e.id()),
                    pe,
                ));
            }
        }
        others.sort_by_key(|c| c.0);
        let rank = player_key.map_or(others.len(), |o| others.iter().filter(|c| c.0 < o).count());
        let mut list: Vec<phys::PistonEntity> = others.iter().map(|c| c.2).collect();
        let f = |v: f64| (v.floor() as i32) >> 4;
        let p = self.player.pos;
        let place = phys::PlayerPlace {
            rank,
            section: [f(p[0]), f(p[1]).clamp(0, 15), f(p[2])],
        };
        self.piston_edits.clear();
        self.pistons.tick_after_entities_among(
            &mut self.player,
            &mut self.ext,
            &self.world,
            &ghosts,
            &mut list,
            place,
            self.piston_time,
            &mut self.piston_edits,
        );
        self.apply_piston_edits();
        // The client's own moves of its entity copies, which the crosshair picks there too.
        if let Some(n) = self.near.as_deref_mut() {
            for ((_, kept, before), after) in others.iter().zip(&list) {
                let k = match *kept {
                    Kept::Near(k) => k,
                    Kept::Extra(id) => {
                        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 != before
                            && let Some(t) = self.entities.as_mut()
                        {
                            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,
                                after.in_web,
                            );
                        }
                        continue;
                    }
                };
                let c = &mut n.list[k];
                c.on_ground = after.on_ground;
                c.in_web = after.in_web;
                c.carry = after.carry;
                if after.bb != before.bb || after.pos != before.pos {
                    c.bb = after.bb;
                    c.at = after.pos;
                    if c.class == Class12::Shulker && c.attached {
                        // Its tick puts it back on its attached block.
                        c.pushed = true;
                    } else {
                        c.pos = after.pos;
                    }
                }
                if (after.bb != before.bb
                    || after.pos != before.pos
                    || after.on_ground != before.on_ground
                    || after.in_web != before.in_web)
                    && let Some(t) = self.entities.as_mut()
                {
                    let b = after.bb;
                    t.client_pushed(
                        c.id,
                        after.pos,
                        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                        after.on_ground,
                        after.in_web,
                    );
                }
            }
        }
        if unmodelled {
            self.piston_uncertain_at = Some(self.player.ticks_alive);
        }
        sync_pose_12(pose, &self.player);
    }

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

    piston_bookkeeping!(
        moving: |s| s.block().id() == ghast_physics::v1_12::MOVING_PISTON,
        wire_id: raw
    );
}