ghast-client 0.5.3

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

use super::*;

impl ModernSim {
    /// `block_action`: a piston's block event runs the client's piston (the block at the
    /// position handles it; the client's shape updates of its writes are in the edits).
    #[cold]
    #[inline(never)]
    pub(super) fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        let p: cb::BlockAction = raw.decode_as()?;
        self.piston_edits.clear();
        let level = self.player.level;
        self.pistons.block_event(
            &self.world,
            &level,
            [p.location.x, p.location.y, p.location.z],
            p.byte1,
            p.byte2,
            &mut self.piston_edits,
        );
        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 level holds (the client moves its
    /// copies itself; they interpolate on toward the server's positions from there).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_piston_phase(&mut self, pose: &mut Pose) {
        use super::pistons as pm;
        if self.riding.is_some() {
            // The vehicle and the player on it are pushed too: not modelled here.
            let p = self.player.bb;
            if self.pistons.touches(&p) {
                self.piston_uncertain_at = Some(self.player.age);
            }
            self.piston_edits.clear();
            let level = self.player.level;
            self.pistons.tick_blocks(
                &self.world,
                &level,
                self.game_time(),
                &mut self.piston_edits,
            );
            if self.pistons.take_unmodelled() {
                self.piston_uncertain_at = Some(self.player.age);
            }
            self.apply_piston_edits();
            return;
        }
        // (search order: section, then entry; id, the entity)
        type Key = ((i32, u64), (u64, u64));
        let mut others: Vec<(Key, i32, pm::PistonEntity)> = Vec::new();
        let mut unmodelled = false;
        // The boat we left: its client copy is ours (with or without the tracker: the player
        // collides with it and it pushes the player either way), not moved here.
        if let Some(k) = self.parked.as_ref() {
            unmodelled |= self.pistons.touches(&aabb(k.bb));
        }
        if let Some(t) = self.entities.as_ref() {
            let me = self.own.id;
            for e in t.iter() {
                let id = e.id();
                if id == me {
                    continue;
                }
                let Some((pos, b)) = entity_box(e) else {
                    continue;
                };
                let bb = aabb(b);
                if self.parked.as_ref().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(ty) = super::entity::entity_type(e) else {
                    continue;
                };
                let player = e.is_player();
                let facts = if player {
                    Some(pm::EntityFacts {
                        step_height: 0.6,
                        ignored: false,
                        pushable: true,
                        collidable: false,
                        attached: false,
                        living: true,
                    })
                } else {
                    pm::entity_facts(ty.name)
                };
                let Some(f) = facts else {
                    continue;
                };
                let alive = super::entity::alive(e);
                let spectator = t.is_spectator(e);
                // ArmorStand: a marker is ignored (flags byte 0x10).
                let marker = ty.name == "armor_stand"
                    && ty
                        .flags_meta
                        .and_then(|k| e.metadata().byte(k))
                        .is_some_and(|fl| fl & 0x10 != 0);
                if e.vehicle().is_some() || !e.passengers().is_empty() {
                    // Riders and their vehicles move together: not modelled.
                    unmodelled |= self.pistons.touches(&bb);
                }
                let climbing = f.living
                    && modern::on_climbable::<Rules, _>(
                        &{
                            let mut q = modern::PlayerState::new(pos, 0.0, 0.0);
                            q.level = self.player.level;
                            q
                        },
                        &self.world,
                    );
                let w = f64::from(e.size().map_or(0.0, |s| s.0) / 2.0);
                let h = f64::from(e.size().map_or(0.0, |s| s.1));
                let shulker = ty.name == "shulker";
                let local = if shulker {
                    ghast_physics::math::Aabb::new(-0.5, 0.0, -0.5, 0.5, 1.0, 0.5)
                } else {
                    ghast_physics::math::Aabb::new(-w, 0.0, -w, w, h, w)
                };
                let carry = self
                    .piston_carry
                    .iter()
                    .find(|c| c.0 == id)
                    .map_or_else(Default::default, |c| c.1);
                let vehicle = ty.name.ends_with("_boat")
                    || ty.name.ends_with("_raft")
                    || ty.name.ends_with("minecart");
                let pe = pm::PistonEntity {
                    bb,
                    pos,
                    local,
                    snaps: shulker && e.vehicle().is_none(),
                    on_ground: e.on_ground(),
                    supported_by: None,
                    step_height: f.step_height,
                    moved: !spectator && !f.ignored && !marker && !f.attached,
                    normal: !f.ignored && !marker,
                    collidable: alive && f.collidable,
                    pushable: f.pushable && alive && !spectator && !climbing,
                    hits_pushable: vehicle,
                    carry,
                    resectioned: false,
                };
                let sec = section_order(pos);
                let entry = self
                    .section_moves
                    .iter()
                    .find(|m| m.0 == id && m.1 == sec)
                    .map_or((t.tick_seq(id).unwrap_or(u64::MAX), 0), |m| m.2);
                others.push(((sec, entry), id, pe));
            }
        }
        // getEntities walks sections by x, then z / y, each in the order its entities entered
        // it (taken here as the order they started ticking; the player when it entered its
        // section).
        others.sort_by_key(|c| c.0);
        let me = (
            section_order(self.player.pos),
            self.player_section.map_or((0, 0), |s| s.1),
        );
        let rank = others.iter().filter(|c| c.0 < me).count();
        let mut list: Vec<pm::PistonEntity> = others.iter().map(|c| c.2).collect();
        let around = modern::Surroundings::new();
        self.piston_edits.clear();
        let view = self.world.view(
            self.player.pos[0].floor() as i32,
            self.player.pos[2].floor() as i32,
        );
        let time = self.game_time();
        self.pistons.tick_after_entities_among(
            &mut self.player,
            &mut self.ext,
            &around,
            &mut list,
            pm::PlayerPlace { rank },
            &view,
            time,
            &mut self.piston_edits,
        );
        // The client's own moves of its entity copies.
        if let Some(t) = self.entities.as_mut() {
            for ((_, id, 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.pos != before.pos || after.on_ground != before.on_ground {
                    t.client_pushed(*id, after.pos, after.on_ground);
                    let sec = section_order(after.pos);
                    if after.resectioned {
                        self.section_moves_n += 1;
                        let at = (t.next_tick_seq(), self.section_moves_n);
                        self.section_moves.retain(|m| m.0 != *id);
                        self.section_moves.push((*id, sec, at));
                    }
                }
            }
            if self.piston_carry.len() > 64 {
                self.piston_carry.retain(|c| t.get(c.0).is_some());
            }
            if self.section_moves.len() > 64 {
                self.section_moves.retain(|m| {
                    t.get(m.0)
                        .is_some_and(|e| section_order(e.position()) == m.1)
                });
            }
        }
        // The player's own section after the pushes (re-entered when a push took it out, even
        // back into the same one).
        let left = self.pistons.take_player_resectioned();
        if let (Some((s, _)), Some(t)) = (self.player_section, self.entities.as_ref()) {
            let k = section_order(self.player.pos);
            if k != s || left {
                self.section_moves_n += 1;
                self.player_section = Some((k, (t.next_tick_seq(), self.section_moves_n)));
            }
        }
        if unmodelled | self.pistons.take_unmodelled() {
            self.piston_uncertain_at = Some(self.player.age);
        }
        self.apply_piston_edits();
        if <Rules as modern::Rules>::SEND_AFTER_ENTITIES && std::mem::take(&mut self.piston_step) {
            // 26.3 Minecraft.tick: LocalPlayer.sendChanges after tickBlockEntities, with the
            // pose the moving blocks left.
            self.packets.clear();
            super::pistons::send_after_pistons(&mut self.player, &mut self.packets);
            if self.force_step != ForceStepPosition::Off {
                force_modern_position(&mut self.packets, &mut self.player, self.force_step);
            }
            self.send_due = true;
        }
        sync_pose_26(pose, &self.player);
    }

    /// With entity tracking: the player's entity section and when it entered it (sections list
    /// their entities in the order they entered them).
    #[inline(never)]
    pub(super) fn track_player_section(&mut self) {
        let Some(t) = self.entities.as_ref() else {
            return;
        };
        let k = section_order(self.player.pos);
        match self.player_section {
            None => self.player_section = Some((k, (0, 0))),
            Some((s, _)) if s != k => {
                self.section_moves_n += 1;
                self.player_section = Some((k, (t.next_tick_seq(), self.section_moves_n)));
            }
            _ => {}
        }
    }

    /// The game time of this tick's block-entity phase (after the player's tick).
    pub(super) fn game_time(&self) -> i64 {
        let (t, age) = self.piston_clock;
        t.wrapping_add(i64::from(self.player.age.wrapping_sub(age).wrapping_sub(1)))
    }

    /// The player's step while blocks move: its tick among the moving blocks' shapes (the
    /// moving blocks tick after every entity, [`ModernSim::tick_piston_phase`]).
    #[cold]
    #[inline(never)]
    pub(super) fn step_among_pistons(
        &mut self,
        pose: &mut Pose,
        input: &ghast_physics::TickInput,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    ) {
        if self.entities.is_some() || self.parked.is_some() {
            collect_colliders(
                self.entities.as_ref(),
                self.parked.as_ref(),
                &self.player,
                None,
                &mut self.around.boxes,
                &mut Vec::new(),
                &self.own.mounts,
            );
        } else {
            self.around.boxes.clear();
        }
        let p = &mut self.player;
        let view = self
            .world
            .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        self.around.player_ticked = true;
        let around = modern::Surroundings::new().with_entities(&self.around.boxes);
        super::pistons::tick_player_among_pistons(
            p,
            &mut self.ext,
            &around,
            input,
            &view,
            &self.pistons,
            &mut self.packets,
        );
        // 26.3: the packets come after the block-entity phase (`send_changes`)
        self.piston_step = <Rules as modern::Rules>::SEND_AFTER_ENTITIES;
        self.ext_active = self.ext_wanted();
        if self.force_step != ForceStepPosition::Off {
            force_modern_position(&mut self.packets, &mut self.player, self.force_step);
        }
        if self.rec.is_some() {
            self.record_tick(input, Some("moving pistons not representable"));
        }
        push_packets(&self.packets, entity_id, out);
        sync_pose_26(pose, &self.player);
    }

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