Skip to main content

ghast_client/
engine.rs

1//! The deterministic client core: game state, the behaviour contract and the tick.
2//!
3//! No I/O and no clock here: the connection feeds decoded [`Inbound`] packets and the time
4//! in, and takes the [`Outbound`] packets out, so the tick order can be tested without a
5//! socket.
6//!
7//! # Tick model
8//!
9//! Mirrors 1.8.9 `MinecraftClient.tick` as recorded in vanilla-client packet traces (and is the same
10//! in 1.16.5):
11//!
12//! 1. inbound packets that arrived since the last tick have been applied (on arrival, like
13//!    vanilla's per-frame task queue; keep-alives, teleports and window confirms are
14//!    answered then);
15//! 2. [`Behavior::tick`] runs. Actions (`chat`, `select_slot`, `swing`, `respawn`, …) are
16//!    written immediately, in call order, before this tick's movement packet;
17//!    [`TickContext::set_aim`] / [`TickContext::set_controls`] only record intent;
18//! 3. held slot sync → rotation step (whole mouse counts) → movement step → sprint change →
19//!    sneak change → exactly one movement packet.
20//!
21//! The server therefore judges this tick's actions with the *previous* tick's sent pose
22//! ([`TickContext::sent`]).
23
24use std::panic::{AssertUnwindSafe, catch_unwind};
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27
28use crate::common::{
29    Abilities, ChatMessage, ClientSettings, Controls, GameMode, Health, Inbound, MovePacket,
30    Outbound, Pose, Vec3,
31};
32use crate::hands::{self, BlockHit, Buttons, DigFactors, Hands, HandsIo};
33use crate::interest::Interests;
34use crate::rotation::Rotation;
35use crate::sim::{Sim, WorldView};
36use crate::version::GameVersion;
37
38/// Pending chat messages kept for the behaviour; more are dropped (and counted) while the
39/// behaviour is not ticking.
40const MAX_PENDING_CHAT: usize = 512;
41
42/// A bot behaviour: the code that decides what the player does each tick.
43///
44/// Behaviours never see packets or versions: they read a [`TickContext`] and call its
45/// actions. A panic in a behaviour stops that behaviour (its [`Behavior::stop`] is called with
46/// `"panic"`) but not the connection: the player keeps standing and answering the server.
47pub trait Behavior {
48    /// Name for logs.
49    fn name(&self) -> &str {
50        "behavior"
51    }
52
53    /// Optional packet groups this behaviour needs. Read every tick; a change updates the
54    /// packet filter. Everything not asked for is dropped before it is decoded.
55    fn interests(&self) -> Interests {
56        Interests::NONE
57    }
58
59    /// Extra clientbound play packet ids (of `version`) to copy undecoded into
60    /// [`TickEvents::raw`], including packets the core consumes itself (the core's handling
61    /// does not change). Read every tick like [`Behavior::interests`]; a change updates the
62    /// packet filter. Decoding is the behaviour's job (`ghast::protocol::v1_8::play::clientbound`
63    /// / `v1_16_5`).
64    fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
65        let _ = version;
66        std::borrow::Cow::Borrowed(&[])
67    }
68
69    /// Called on the first tick the player is in the world, before that tick's
70    /// [`Behavior::tick`] (both see the same events).
71    fn start(&mut self, ctx: &mut TickContext<'_>) {
72        let _ = ctx;
73    }
74
75    /// Called every tick while the player is in the world and the server is answering.
76    fn tick(&mut self, ctx: &mut TickContext<'_>);
77
78    /// Whether the behaviour still wants ticks. Once it returns `false` the behaviour is done:
79    /// it is not ticked again (the player keeps standing and answering the server) and
80    /// [`Behavior::stop`] still runs when the session ends. Read after every start / tick.
81    fn running(&self) -> bool {
82        true
83    }
84
85    /// Called once when the session ends (or the behaviour panicked).
86    fn stop(&mut self, reason: &str) {
87        let _ = reason;
88    }
89}
90
91/// A boxed behaviour is a behaviour (a runner can pick one from its config at run time).
92impl<B: Behavior + ?Sized> Behavior for Box<B> {
93    fn name(&self) -> &str {
94        (**self).name()
95    }
96    fn interests(&self) -> Interests {
97        (**self).interests()
98    }
99    fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
100        (**self).raw_packets(version)
101    }
102    fn start(&mut self, ctx: &mut TickContext<'_>) {
103        (**self).start(ctx);
104    }
105    fn tick(&mut self, ctx: &mut TickContext<'_>) {
106        (**self).tick(ctx);
107    }
108    fn running(&self) -> bool {
109        (**self).running()
110    }
111    fn stop(&mut self, reason: &str) {
112        (**self).stop(reason);
113    }
114}
115
116/// Why [`TickContext::click`] (or opening / closing a window) sent nothing.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum ClickRefused {
119    /// The player is turning: click only while still.
120    Turning,
121    /// The inventory refused it.
122    Inventory(ghast_inventory::ClickError),
123}
124
125impl std::fmt::Display for ClickRefused {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        match self {
128            ClickRefused::Turning => f.write_str("the player is turning"),
129            ClickRefused::Inventory(e) => write!(f, "{e}"),
130        }
131    }
132}
133
134impl std::error::Error for ClickRefused {}
135
136/// A click that was sent: match it with [`TickEvents::inventory`]'s `clicks` on a later tick
137/// (window id and action number, as the server's confirm carries them).
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub struct ClickTicket {
140    /// Window id the click was sent for.
141    pub window_id: i32,
142    /// Its action number.
143    pub action: i16,
144}
145
146impl ClickTicket {
147    /// Whether `r` is the result of this click.
148    #[must_use]
149    pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
150        r.window_id == self.window_id && r.action == self.action
151    }
152}
153
154/// A behaviour that does nothing (the player stands still).
155#[derive(Debug, Clone, Copy, Default)]
156pub struct Idle;
157
158impl Behavior for Idle {
159    fn name(&self) -> &str {
160        "idle"
161    }
162
163    fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
164}
165
166/// A clientbound play packet copied for the behaviour ([`Behavior::raw_packets`]).
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct RawInbound {
169    /// Packet id (version-specific).
170    pub id: i32,
171    /// The body after the id, undecoded (a cheap reference-counted copy).
172    pub body: bytes::Bytes,
173    /// When the frame was decoded from the socket (frames read together share it).
174    pub at: Instant,
175}
176
177/// A server teleport / correction (`position`) with the poses around it.
178#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct TeleportEvent {
180    /// The packet's values as received: absolute or relative per
181    /// [`crate::common::teleport_flags`] in `flags`.
182    pub teleport: crate::common::Teleport,
183    /// What the server had from us just before ([`TickContext::sent`] before the overwrite):
184    /// compare with [`TeleportEvent::after`] to see what the server moved / turned us by.
185    pub sent_before: Pose,
186    /// The client pose just before (it may be ahead of `sent_before` within a tick).
187    pub pose_before: Pose,
188    /// The pose after applying it (relative fields resolved).
189    pub after: Pose,
190}
191
192/// Most teleports kept between two behaviour ticks.
193const MAX_PENDING_TELEPORTS: usize = 64;
194
195/// Most raw packets kept between two behaviour ticks.
196const MAX_PENDING_RAW: usize = 4096;
197
198/// What happened since the behaviour's previous tick.
199#[derive(Debug, Clone, Default, PartialEq)]
200pub struct TickEvents {
201    /// Chat messages in arrival order (only with [`Interests::CHAT`]).
202    pub chat: Vec<ChatMessage>,
203    /// Chat messages dropped because too many piled up while the behaviour was not ticking.
204    pub chat_dropped: usize,
205    /// The server teleported / corrected the player.
206    pub teleported: bool,
207    /// Every teleport in arrival order, with the sent pose before it (at most 64 per tick).
208    pub teleports: Vec<TeleportEvent>,
209    /// A join game packet arrived (first join or a proxy server switch).
210    pub joined: bool,
211    /// The player respawned or changed dimension.
212    pub respawned: bool,
213    /// The player died (health reached 0).
214    pub died: bool,
215    /// Health, food or saturation changed.
216    pub health_changed: bool,
217    /// The game mode changed.
218    pub game_mode_changed: bool,
219    /// Inventory / window changes and click results (ghast-inventory).
220    pub inventory: ghast_inventory::Events,
221    /// Block changes in arrival order (only with [`Interests::BLOCK_UPDATES`]): position and
222    /// the version's raw block state (1.8 `id << 4 | meta`, 1.16 the global palette id).
223    /// The world already holds them when the behaviour ticks.
224    pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
225    /// Block changes dropped because too many piled up between two behaviour ticks.
226    pub block_updates_dropped: usize,
227    /// The packets asked for with [`Behavior::raw_packets`], in arrival order (kept while the
228    /// behaviour is on hold, like chat).
229    pub raw: Vec<RawInbound>,
230    /// Raw packets dropped because more than 4096 piled up between two behaviour ticks.
231    pub raw_dropped: usize,
232}
233
234impl TickEvents {
235    fn clear(&mut self) {
236        self.chat.clear();
237        self.chat_dropped = 0;
238        self.teleported = false;
239        self.teleports.clear();
240        self.joined = false;
241        self.respawned = false;
242        self.died = false;
243        self.health_changed = false;
244        self.game_mode_changed = false;
245        self.inventory = ghast_inventory::Events::default();
246        self.block_updates.clear();
247        self.block_updates_dropped = 0;
248        self.raw.clear();
249        self.raw_dropped = 0;
250    }
251}
252
253/// Tunables of the core.
254#[derive(Debug, Clone)]
255pub(crate) struct CoreOptions {
256    pub name: Arc<str>,
257    pub version: GameVersion,
258    pub settings: ClientSettings,
259    pub brand: Option<String>,
260    pub sensitivity: f32,
261    pub silent_hold: Duration,
262    pub inventory: ghast_inventory::Version,
263    /// Keep the look still on a tick that dug / placed when the turn would take the
264    /// crosshair off the clicked block (Grim RotationPlace re-checks with the next look).
265    pub hold_turn_on_action: bool,
266}
267
268/// Client state shared by the connection and the behaviour context.
269#[derive(Debug)]
270pub(crate) struct Core {
271    opts: CoreOptions,
272    tick: u64,
273    entity_id: i32,
274    joined: bool,
275    teleported_once: bool,
276    ready: bool,
277    pose: Pose,
278    sent: Pose,
279    rotation: Rotation,
280    aimed: bool,
281    controls: Controls,
282    health: Health,
283    dead: bool,
284    abilities: Abilities,
285    game_mode: GameMode,
286    held_slot: u8,
287    sent_slot: u8,
288    open_window: i32,
289    dimension: String,
290    respawn_screen: bool,
291    pending: TickEvents,
292    current: TickEvents,
293    out: Vec<Outbound>,
294    last_inbound: Option<Instant>,
295    silent: bool,
296    quit: Option<String>,
297    status: String,
298    hands: Hands,
299    buttons: Buttons,
300    /// Inventory and windows (ghast-inventory).
301    inv: ghast_inventory::Inventory,
302    /// The look changed in the last movement step (window clicks need a still player).
303    turned: bool,
304    /// Our active status effects: id → amplifier.
305    effects: std::collections::BTreeMap<i8, i8>,
306    /// Aqua affinity on the helmet (dig speed under water).
307    aqua_affinity: bool,
308    /// Blocks broken on the client this tick (predicted air).
309    broken_now: Vec<ghast_protocol::BlockPos>,
310    /// Flight wanted by the behaviour this tick ([`TickContext::set_flying`]).
311    want_flying: Option<bool>,
312    /// Turns held back because they would have moved the crosshair off a clicked block.
313    held_turns: u64,
314    /// Test hook: this tick's look, set instead of a rotation step.
315    #[cfg(test)]
316    forced_look: Option<(f32, f32)>,
317}
318
319/// Behaviour bookkeeping of the engine.
320#[derive(Debug, Default)]
321struct BehaviorState {
322    started: bool,
323    failed: bool,
324    /// The behaviour reported [`Behavior::running`] `false`.
325    done: bool,
326}
327
328/// The core plus the behaviour's lifecycle.
329#[derive(Debug)]
330pub(crate) struct Engine<S> {
331    pub core: Core,
332    pub sim: S,
333    state: BehaviorState,
334}
335
336impl Core {
337    fn new(opts: CoreOptions) -> Self {
338        let rotation = Rotation::new(opts.sensitivity);
339        let inv = ghast_inventory::Inventory::new(opts.inventory);
340        Core {
341            opts,
342            tick: 0,
343            entity_id: 0,
344            joined: false,
345            teleported_once: false,
346            ready: false,
347            pose: Pose::default(),
348            sent: Pose::default(),
349            rotation,
350            aimed: false,
351            controls: Controls::default(),
352            health: Health::default(),
353            dead: false,
354            abilities: Abilities::default(),
355            game_mode: GameMode::default(),
356            held_slot: 0,
357            sent_slot: 0,
358            open_window: 0,
359            dimension: String::new(),
360            respawn_screen: true,
361            pending: TickEvents::default(),
362            current: TickEvents::default(),
363            out: Vec::with_capacity(16),
364            last_inbound: None,
365            silent: false,
366            quit: None,
367            status: String::new(),
368            hands: Hands::default(),
369            buttons: Buttons::default(),
370            inv,
371            turned: false,
372            effects: std::collections::BTreeMap::new(),
373            aqua_affinity: false,
374            broken_now: Vec::new(),
375            want_flying: None,
376            held_turns: 0,
377            #[cfg(test)]
378            forced_look: None,
379        }
380    }
381
382    /// A new client player entity (join, respawn): `lastReported*` zero, nothing held down,
383    /// waiting for the server's position.
384    fn reset_player(&mut self, why: &str) {
385        self.teleported_once = false;
386        self.ready = false;
387        self.pose = Pose::default();
388        self.sent = Pose::default();
389        self.controls = Controls::default();
390        self.aimed = false;
391        self.open_window = 0;
392        self.dead = false;
393        self.hands.reset();
394        self.buttons = Buttons::default();
395        self.effects.clear();
396        log::debug!(
397            "[{}] t{} {why}: waiting for the server position",
398            self.opts.name,
399            self.tick
400        );
401    }
402
403    fn column_loaded(&self, world: &dyn WorldView) -> bool {
404        // BlockPos(posX, 0, posZ) floors the coordinates.
405        let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
406        let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
407        world.is_column_loaded(cx, cz)
408    }
409}
410
411/// The held stack's dig / use facts.
412fn held_item<W: Sim + ?Sized>(
413    inv: &ghast_inventory::Inventory,
414    sim: &W,
415) -> Option<hands::HeldItem> {
416    let s = inv.held()?;
417    let id = u16::try_from(s.id).ok()?;
418    let count = u8::try_from(s.count.clamp(0, 255)).unwrap_or(0);
419    Some(sim.held_item(id, count, efficiency(s)))
420}
421
422/// Whether rays hit the entity (`Entity.collides`): living entities, players,
423/// paintings and the solid objects (boats, minecarts, TNT, falling blocks, item frames, armor
424/// stands, leash knots, end crystals); not items, orbs, projectiles.
425fn collidable(e: &ghast_entity::Entity) -> bool {
426    use ghast_entity::{EntityClass, EntityType};
427    match e.class() {
428        EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
429        EntityClass::Item | EntityClass::ExperienceOrb => false,
430        EntityClass::Object => match e.entity_type() {
431            EntityType::LegacyObject(t) => matches!(t, 1 | 10 | 50 | 51 | 70 | 71 | 77 | 78),
432            EntityType::Registry(_) => {
433                ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
434                    matches!(
435                        i.name,
436                        "boat"
437                            | "tnt"
438                            | "end_crystal"
439                            | "falling_block"
440                            | "item_frame"
441                            | "leash_knot"
442                            | "armor_stand"
443                            | "shulker_bullet"
444                    ) || i.name.contains("minecart")
445                })
446            }
447            _ => false,
448        },
449    }
450}
451
452/// The entity under the crosshair from `eyes` along `look` (vanilla `GameRenderer.updateTargetedEntity`), if
453/// entities are tracked.
454fn entity_pick<W: WorldView + ?Sized>(
455    w: &W,
456    version: GameVersion,
457    eyes: Vec3,
458    look: Vec3,
459    block_distance: Option<f64>,
460) -> Option<hands::EntityHit> {
461    let ents = w.entities()?;
462    let riding = ents.me().and_then(ghast_entity::Entity::vehicle);
463    // 1.8 grows entity boxes by the 0.1 collision border; 1.9+ does not.
464    let border = if version == GameVersion::V1_8_9 {
465        0.1
466    } else {
467        0.0
468    };
469    let cands = ents
470        .within([eyes.x, eyes.y, eyes.z], 8.0)
471        .filter(|e| collidable(e))
472        .filter_map(|e| {
473            let p = e.position();
474            Some((e.id(), e.bounding_box()?, Vec3::new(p[0], p[1], p[2])))
475        });
476    hands::pick_entity(cands, eyes, look, block_distance, border, riding)
477}
478
479/// The off-hand stack's facts (1.9+).
480fn off_held_item<W: Sim + ?Sized>(
481    inv: &ghast_inventory::Inventory,
482    sim: &W,
483) -> Option<hands::HeldItem> {
484    let s = inv.offhand()?;
485    let id = u16::try_from(s.id).ok()?;
486    let count = u8::try_from(s.count.clamp(0, 255)).unwrap_or(0);
487    Some(sim.held_item(id, count, 0))
488}
489
490/// Efficiency level of a stack (see [`enchant_level`]).
491fn efficiency(s: &ghast_inventory::Stack) -> u8 {
492    enchant_level(s, 32, "minecraft:efficiency")
493}
494
495/// An enchantment level from the stack NBT: the 1.8 `ench` list with numeric ids, or the 1.13+
496/// `Enchantments` list with names. Parsed only when the stack has NBT.
497fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
498    use ghast_protocol::nbt::Tag;
499    let Some(root) = s.nbt.as_ref().and_then(|n| n.parse().ok().flatten()) else {
500        return 0;
501    };
502    let Some(c) = root.tag.as_compound() else {
503        return 0;
504    };
505    let num = |t: Option<&Tag>| match t {
506        Some(Tag::Short(v)) => i32::from(*v),
507        Some(Tag::Int(v)) => *v,
508        Some(Tag::Byte(v)) => i32::from(*v),
509        _ => -1,
510    };
511    for key in ["ench", "Enchantments"] {
512        if let Some(Tag::List(l)) = c.get(key) {
513            for e in l.items.iter().filter_map(Tag::as_compound) {
514                let hit = match e.get("id") {
515                    Some(Tag::String(n)) => n == name,
516                    other => num(other) == id_1_8,
517                };
518                if hit {
519                    return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
520                }
521            }
522        }
523    }
524    0
525}
526
527impl<S: Sim> Engine<S> {
528    pub(crate) fn new(opts: CoreOptions, sim: S) -> Self {
529        Engine {
530            core: Core::new(opts),
531            sim,
532            state: BehaviorState::default(),
533        }
534    }
535
536    /// Bytes arrived from the server (liveness for the silent-server guard).
537    pub(crate) fn note_inbound(&mut self, now: Instant) {
538        self.core.last_inbound = Some(now);
539    }
540
541    /// Time of the last inbound bytes.
542    pub(crate) fn last_inbound(&self) -> Option<Instant> {
543        self.core.last_inbound
544    }
545
546    /// The bot's name (for logs).
547    pub(crate) fn name(&self) -> &str {
548        &self.core.opts.name
549    }
550
551    /// Queues a raw packet copy for the behaviour's next tick.
552    pub(crate) fn push_raw(&mut self, p: RawInbound) {
553        let ev = &mut self.core.pending;
554        if ev.raw.len() < MAX_PENDING_RAW {
555            ev.raw.push(p);
556        } else {
557            ev.raw_dropped += 1;
558        }
559    }
560
561    /// The raw packet ids the behaviour wants (none once it failed or finished).
562    pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
563        if self.state.failed || self.state.done {
564            std::borrow::Cow::Borrowed(&[])
565        } else {
566            b.raw_packets(self.core.opts.version)
567        }
568    }
569
570    /// The inventory (the connection feeds it its packets).
571    pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
572        &mut self.core.inv
573    }
574
575    /// Outbound packets produced since the last call, in send order.
576    pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
577        &mut self.core.out
578    }
579
580    /// Set when the behaviour asked to disconnect.
581    pub(crate) fn quit_requested(&self) -> Option<&str> {
582        self.core.quit.as_deref()
583    }
584
585    pub(crate) fn core_name(&self) -> &str {
586        &self.core.opts.name
587    }
588
589    pub(crate) fn tick_count(&self) -> u64 {
590        self.core.tick
591    }
592
593    /// Applies one inbound packet (except disconnect and compression, which the connection
594    /// handles).
595    pub(crate) fn handle(&mut self, p: Inbound) {
596        let c = &mut self.core;
597        let sim = &mut self.sim;
598        match p {
599            Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
600            Inbound::JoinGame(j) => {
601                c.entity_id = j.entity_id;
602                c.game_mode = j.game_mode;
603                c.respawn_screen = j.respawn_screen;
604                // A join always creates a new client world (the world itself was cleared by
605                // the world packet routing).
606                c.dimension = j.dimension;
607                c.joined = true;
608                c.pending.joined = true;
609                c.health = Health::default();
610                c.abilities = Abilities::default();
611                c.reset_player("join game");
612                sim.reset_player();
613                sim.spectator(c.game_mode == GameMode::Spectator);
614                // ClientPlayNetworkHandler.onGameJoin: settings, then the brand.
615                c.out.push(Outbound::Settings(c.opts.settings.clone()));
616                if let Some(brand) = &c.opts.brand {
617                    c.out.push(Outbound::Brand(brand.clone()));
618                }
619                log::info!(
620                    "[{}] joined: entity {} {:?} dimension {}",
621                    c.opts.name,
622                    c.entity_id,
623                    c.game_mode,
624                    c.dimension
625                );
626            }
627            Inbound::Respawn {
628                dimension,
629                game_mode,
630            } => {
631                if dimension != c.dimension {
632                    c.dimension = dimension;
633                }
634                c.game_mode = game_mode;
635                c.pending.respawned = true;
636                c.reset_player("respawn");
637                sim.reset_player();
638                sim.spectator(c.game_mode == GameMode::Spectator);
639            }
640            Inbound::Teleport(t) => {
641                if c.teleported_once {
642                    log::debug!(
643                        "[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
644                         {:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
645                        c.opts.name,
646                        c.tick,
647                        t.x,
648                        t.y,
649                        t.z,
650                        t.yaw,
651                        t.pitch,
652                        t.flags,
653                        c.sent.pos.x,
654                        c.sent.pos.y,
655                        c.sent.pos.z,
656                        c.sent.yaw,
657                        c.sent.pitch,
658                        c.sent.on_ground
659                    );
660                }
661                let (sent_before, pose_before) = (c.sent, c.pose);
662                sim.teleport(&mut c.pose, &t);
663                if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
664                    c.pending.teleports.push(TeleportEvent {
665                        teleport: t,
666                        sent_before,
667                        pose_before,
668                        after: c.pose,
669                    });
670                }
671                if let Some(id) = t.teleport_id {
672                    c.out.push(Outbound::TeleportConfirm(id));
673                }
674                c.out.push(Outbound::Move(MovePacket::PositionLook {
675                    pos: c.pose.pos,
676                    yaw: c.pose.yaw,
677                    pitch: c.pose.pitch,
678                    on_ground: false,
679                }));
680                // The server now has this pose; vanilla's lastReported* are not touched.
681                c.sent = Pose {
682                    on_ground: false,
683                    ..c.pose
684                };
685                if !c.teleported_once {
686                    log::debug!(
687                        "[{}] t{} spawn position {:.3} {:.3} {:.3}",
688                        c.opts.name,
689                        c.tick,
690                        c.pose.pos.x,
691                        c.pose.pos.y,
692                        c.pose.pos.z
693                    );
694                }
695                c.teleported_once = true;
696                c.pending.teleported = true;
697            }
698            Inbound::Chat(m) => {
699                if c.pending.chat.len() < MAX_PENDING_CHAT {
700                    c.pending.chat.push(m);
701                } else {
702                    c.pending.chat_dropped += 1;
703                }
704            }
705            Inbound::Health(h) => {
706                let was_dead = c.dead;
707                c.health = h;
708                sim.food(h.food);
709                c.pending.health_changed = true;
710                if h.health <= 0.0 && !was_dead {
711                    c.dead = true;
712                    c.pending.died = true;
713                    log::info!("[{}] t{} died", c.opts.name, c.tick);
714                }
715            }
716            Inbound::Died { entity_id } => {
717                if entity_id == c.entity_id && !c.respawn_screen {
718                    // 1.16 immediate respawn: the client respawns without a death screen.
719                    c.out.push(Outbound::Respawn);
720                }
721            }
722            Inbound::Abilities(a) => {
723                c.abilities = a;
724                c.pose.flying = a.flying();
725                sim.abilities(a);
726            }
727            Inbound::HeldSlot(s) => {
728                if (0..9).contains(&s) {
729                    // Only the inventory's selection changes; the controller's copy does not,
730                    // so the next sync echoes it (as vanilla does).
731                    if c.held_slot != s as u8 {
732                        c.hands.stop_using();
733                    }
734                    c.held_slot = s as u8;
735                }
736            }
737            Inbound::GameState { reason, value } => match reason {
738                3 => {
739                    c.game_mode = GameMode::from_wire(value as u8);
740                    sim.spectator(c.game_mode == GameMode::Spectator);
741                    c.pending.game_mode_changed = true;
742                }
743                // 1.15+: "immediate respawn" gamerule (1 = no respawn screen).
744                11 if c.opts.version != GameVersion::V1_8_9 => c.respawn_screen = value == 0.0,
745                _ => {}
746            },
747            // Window confirms are answered by the inventory (exactly once).
748            Inbound::Transaction { .. } => {}
749            Inbound::OpenWindow(id) => c.open_window = id,
750            Inbound::CloseWindow(_) => c.open_window = 0,
751            Inbound::Velocity { entity_id, motion } => {
752                if entity_id == c.entity_id {
753                    sim.velocity(motion, false);
754                }
755            }
756            Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
757            Inbound::MovementSpeed {
758                entity_id,
759                base,
760                modifiers,
761            } => {
762                if entity_id == c.entity_id {
763                    log::debug!(
764                        "[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
765                        c.opts.name,
766                        c.tick
767                    );
768                    let mods: Vec<(u128, f64, u8)> = modifiers
769                        .iter()
770                        .map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
771                        .collect();
772                    sim.movement_speed(base, &mods);
773                }
774            }
775            Inbound::Effect {
776                entity_id,
777                id,
778                amplifier,
779            } => {
780                if entity_id == c.entity_id {
781                    c.effects.insert(id, amplifier);
782                    sim.status_effects(&c.effects);
783                }
784            }
785            Inbound::EffectRemoved { entity_id, id } => {
786                if entity_id == c.entity_id {
787                    c.effects.remove(&id);
788                    sim.status_effects(&c.effects);
789                }
790            }
791            Inbound::EntityStatus { entity_id, status } => {
792                // 9: the server finished our item use (eating, drinking).
793                if entity_id == c.entity_id && status == 9 {
794                    c.hands.stop_using();
795                }
796            }
797            Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
798        }
799    }
800
801    /// The interests of the behaviour (the packet filter follows them).
802    pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
803        if self.state.failed {
804            Interests::NONE
805        } else {
806            b.interests()
807        }
808    }
809
810    /// Ends the behaviour (session over).
811    pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
812        if self.state.started && !self.state.failed {
813            self.state.failed = true;
814            let name = self.core.opts.name.clone();
815            if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
816                log::error!("[{name}] behaviour {} panicked in stop", b.name());
817            }
818        }
819    }
820
821    /// One client tick at `now`.
822    pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
823        let c = &mut self.core;
824        c.tick += 1;
825        // Per-tick packet-order guard and click timeout of the inventory.
826        c.inv.tick();
827        let was_ready = c.ready;
828        c.ready = c.teleported_once && c.column_loaded(&self.sim);
829        if c.ready != was_ready {
830            if c.ready {
831                log::info!(
832                    "[{}] t{} in the world at {:.3} {:.3} {:.3}",
833                    c.opts.name,
834                    c.tick,
835                    c.pose.pos.x,
836                    c.pose.pos.y,
837                    c.pose.pos.z
838                );
839            } else {
840                log::debug!(
841                    "[{}] t{} player column not loaded: not ticking",
842                    c.opts.name,
843                    c.tick
844                );
845            }
846        }
847        if !c.ready {
848            // The client player does not tick outside a loaded column (1.16 vanilla; on 1.8
849            // the bot waits for its column as well).
850            return;
851        }
852
853        let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
854        let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
855        if silent != c.silent {
856            c.silent = silent;
857            if silent {
858                log::warn!(
859                    "[{}] t{} server silent for {} ms: behaviour on hold",
860                    c.opts.name,
861                    c.tick,
862                    silent_for.unwrap_or_default().as_millis()
863                );
864            } else {
865                log::info!(
866                    "[{}] t{} server answering again: behaviour resumes",
867                    c.opts.name,
868                    c.tick
869                );
870            }
871        }
872
873        if silent {
874            // Freeze: release the keys, keep only the vanilla movement packet.
875            c.controls = Controls::default();
876            c.aimed = false;
877        } else if !self.state.failed && !self.state.done {
878            std::mem::swap(&mut c.pending, &mut c.current);
879            c.pending.clear();
880            c.current.inventory = c.inv.drain_events();
881            c.current.block_updates_dropped =
882                self.sim.drain_block_updates(&mut c.current.block_updates);
883            if c.current.inventory.player_changed {
884                // Armour enchantments that change movement / digging.
885                let ench = |a: usize, id: i32, name: &str| {
886                    c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
887                };
888                let depth = ench(3, 8, "minecraft:depth_strider");
889                let soul = ench(3, -1, "minecraft:soul_speed");
890                c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
891                self.sim.boots(depth, soul);
892            }
893            let started = self.state.started;
894            self.state.started = true;
895            if !started {
896                c.rotation.reset(c.pose.yaw, c.pose.pitch);
897            }
898            let name = c.opts.name.clone();
899            let result = catch_unwind(AssertUnwindSafe(|| {
900                let held = held_item(&c.inv, &self.sim);
901                let mut ctx = TickContext {
902                    core: c,
903                    world: &self.sim,
904                    held,
905                };
906                if !started {
907                    b.start(&mut ctx);
908                }
909                b.tick(&mut ctx);
910                b.running()
911            }));
912            match result {
913                Ok(true) => {}
914                Ok(false) => {
915                    self.state.done = true;
916                    log::info!("[{name}] behaviour {} finished", b.name());
917                }
918                Err(_) => {
919                    log::error!("[{name}] behaviour {} panicked: stopped", b.name());
920                    self.stop(b, "panic");
921                }
922            }
923        }
924
925        let c = &mut self.core;
926        // ClientPlayerInteractionManager.tick (syncSelectedSlot) runs before the key
927        // processing: a held slot the server changed is echoed before any click.
928        if c.held_slot != c.sent_slot {
929            c.sent_slot = c.held_slot;
930            c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
931        }
932        // MinecraftClient.tick key processing (a GUI takes the mouse: buttons up).
933        {
934            // The screen as the inventory models it (vanilla: a window the client has no
935            // screen for opens none; a window the client closed is gone at once).
936            let gui = c.inv.gui_open();
937            let eye = if c.pose.sneaking {
938                c.opts.version.sneak_eye_height()
939            } else {
940                c.opts.version.eye_height()
941            };
942            let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
943            let sim = &self.sim;
944            let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
945            let look = hands::look_vector(c.pose.yaw, c.pose.pitch);
946            let target = hands::pick(&blocks, eyes, look, hands::REACH);
947            let entity = entity_pick(sim, c.opts.version, eyes, look, target.map(|t| t.distance));
948            let in_water = blocks(
949                eyes.x.floor() as i32,
950                eyes.y.floor() as i32,
951                eyes.z.floor() as i32,
952            )
953            .is_some_and(|b| b.water);
954            let held = held_item(&c.inv, sim);
955            let mut placed = false;
956            let first = c.out.len();
957            let mut io = HandsIo {
958                blocks: &blocks,
959                target,
960                held,
961                held_stack: c.inv.held().cloned(),
962                food: c.health.food,
963                modern: c.opts.version != GameVersion::V1_8_9,
964                off_held: off_held_item(&c.inv, sim),
965                off_stack: c.inv.offhand().cloned(),
966                entity,
967                factors: DigFactors {
968                    on_ground: c.pose.on_ground,
969                    in_water,
970                    aqua_affinity: c.aqua_affinity,
971                    haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
972                    fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
973                },
974                sneaking: c.pose.sneaking,
975                out: &mut c.out,
976                broken: &mut c.broken_now,
977                placed: &mut placed,
978            };
979            let (left, right) = (c.buttons.left && !gui, c.buttons.right && !gui);
980            c.hands.tick(left, right, &mut io);
981            // Other placements: the server's set_slot brings the new count of the held stack.
982            let _ = placed;
983            predict_planting(c, sim, first);
984        }
985        for p in c.broken_now.drain(..) {
986            self.sim.predict_air(p.x, p.y, p.z);
987        }
988        // ClientPlayerEntity.tickMovement: a flight toggle is told to the server before the move.
989        if let Some(f) = c.want_flying.take() {
990            let first = c.out.len();
991            self.sim.set_flying(f, &mut c.out);
992            if c.out.len() > first {
993                c.pose.flying = f;
994            } else if f && !c.pose.flying {
995                log::debug!(
996                    "[{}] t{} set_flying(true) refused: flight not allowed",
997                    c.opts.name,
998                    c.tick
999                );
1000            }
1001        }
1002        // Rotation runs only on ticks the behaviour aimed (budgets untouched otherwise).
1003        c.turned = false;
1004        #[cfg(test)]
1005        if let Some((yaw, pitch)) = c.forced_look.take() {
1006            c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1007            c.pose.yaw = yaw;
1008            c.pose.pitch = pitch;
1009            c.aimed = false;
1010        }
1011        if c.aimed {
1012            let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
1013            if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1014                // Grim RotationPlace re-checks a dig / place with the look of the movement
1015                // packet that follows it: keep the mouse still on the clicked block this tick.
1016                c.held_turns += 1;
1017            } else {
1018                c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1019                c.pose.yaw = yaw;
1020                c.pose.pitch = pitch;
1021            }
1022            c.aimed = false;
1023        }
1024        let first = c.out.len();
1025        let using = c.hands.using_item();
1026        self.sim
1027            .step(&mut c.pose, c.controls, using, c.entity_id, &mut c.out);
1028        for o in &c.out[first..] {
1029            let Outbound::Move(m) = o else { continue };
1030            match *m {
1031                MovePacket::Position { pos, .. } => c.sent.pos = pos,
1032                MovePacket::Look { yaw, pitch, .. } => {
1033                    c.sent.yaw = yaw;
1034                    c.sent.pitch = pitch;
1035                }
1036                MovePacket::PositionLook {
1037                    pos, yaw, pitch, ..
1038                } => {
1039                    c.sent.pos = pos;
1040                    c.sent.yaw = yaw;
1041                    c.sent.pitch = pitch;
1042                }
1043                MovePacket::Flying { .. } => {}
1044            }
1045            if matches!(
1046                m,
1047                MovePacket::Position { .. } | MovePacket::PositionLook { .. }
1048            ) {
1049                c.sent.motion = c.pose.motion;
1050            }
1051        }
1052        c.sent.on_ground = c.pose.on_ground;
1053        c.sent.sneaking = c.pose.sneaking;
1054        c.sent.sprinting = c.pose.sprinting;
1055        c.sent.flying = c.pose.flying;
1056    }
1057}
1058
1059#[cfg(test)]
1060impl Core {
1061    /// Test hook: the held slot as both the client and the server have it (no sync packet).
1062    pub(crate) fn test_set_slot(&mut self, slot: u8) {
1063        self.held_slot = slot;
1064        self.sent_slot = slot;
1065        self.inv.select(slot);
1066    }
1067
1068    /// Test hook: the pose and the sent pose.
1069    pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
1070        (&mut self.pose, &mut self.sent)
1071    }
1072
1073    /// Test hook: turns held back by the post-look check.
1074    pub(crate) fn test_held_turns(&self) -> u64 {
1075        self.held_turns
1076    }
1077}
1078
1079#[cfg(test)]
1080impl TickContext<'_> {
1081    /// Test hook: this tick's look without a rotation step.
1082    pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
1083        self.core.forced_look = Some((yaw, pitch));
1084    }
1085
1086    /// Test hook: the rotation controller (to predict a step).
1087    pub(crate) fn test_rotation(&self) -> Rotation {
1088        self.core.rotation
1089    }
1090}
1091
1092/// 1.8 `SeedItem.use` / `CropItem.use` on the client: planting on the top of
1093/// its soil with air above uses one item at once (the server's set_slot follows later; it
1094/// sends none when the count already agrees). Applied to the `block_place` packets written
1095/// from `first` on. Other placements wait for the server's set_slot: predicting them needs
1096/// vanilla's full placement rules, and a wrong prediction would never be corrected.
1097fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
1098    if c.opts.version != GameVersion::V1_8_9 || c.game_mode == GameMode::Creative {
1099        return;
1100    }
1101    let mut uses = 0u8;
1102    for o in &c.out[first..] {
1103        let Outbound::Place {
1104            pos,
1105            face: crate::common::Face::Up,
1106            held: Some(held),
1107            off_hand: false,
1108            ..
1109        } = o
1110        else {
1111            continue;
1112        };
1113        // Seed item → its soil (wheat, pumpkin, melon seeds, carrot, potato: farmland;
1114        // nether wart: soul sand).
1115        let soil = match held.id {
1116            295 | 361 | 362 | 391 | 392 => 60,
1117            372 => 88,
1118            _ => continue,
1119        };
1120        let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
1121        if held.count > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
1122            uses += 1;
1123        }
1124    }
1125    if uses > 0 {
1126        c.inv.consume_held(uses);
1127    }
1128}
1129
1130/// Whether the look `yaw`/`pitch` still points at every block dug or placed this tick (its
1131/// full cube, from the sent and the current feet, standing or sneaking eyes, with the old or the
1132/// new yaw) — the post-look check that keeps Grim's RotationPlace check satisfied.
1133fn post_look_ok(c: &Core, yaw: f32, pitch: f32) -> bool {
1134    let looks = [
1135        hands::look_vector(c.pose.yaw, pitch),
1136        hands::look_vector(yaw, pitch),
1137    ];
1138    let heights = [
1139        c.opts.version.eye_height(),
1140        c.opts.version.sneak_eye_height(),
1141    ];
1142    c.out
1143        .iter()
1144        .filter_map(|o| match o {
1145            Outbound::Dig {
1146                status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
1147                pos,
1148                ..
1149            }
1150            | Outbound::Place { pos, .. } => Some(*pos),
1151            _ => None,
1152        })
1153        .all(|t| {
1154            [c.sent.pos, c.pose.pos].iter().all(|o| {
1155                heights.iter().any(|h| {
1156                    let eyes = Vec3::new(o.x, o.y + *h, o.z);
1157                    looks
1158                        .iter()
1159                        .any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
1160                })
1161            })
1162        })
1163}
1164
1165/// Reach of the post-look check (6 blocks).
1166const ACTION_LOOK_REACH: f64 = 6.0;
1167
1168/// The behaviour's view of the client during one tick.
1169///
1170/// Reading is free; actions are written to the server in call order before this tick's
1171/// movement packet.
1172pub struct TickContext<'a> {
1173    core: &'a mut Core,
1174    world: &'a dyn WorldView,
1175    held: Option<hands::HeldItem>,
1176}
1177
1178impl std::fmt::Debug for TickContext<'_> {
1179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1180        f.debug_struct("TickContext")
1181            .field("tick", &self.core.tick)
1182            .field("pose", &self.core.pose)
1183            .finish_non_exhaustive()
1184    }
1185}
1186
1187impl TickContext<'_> {
1188    /// Ticks since the connection entered the play state.
1189    #[must_use]
1190    pub fn tick(&self) -> u64 {
1191        self.core.tick
1192    }
1193
1194    /// The protocol version of this connection.
1195    #[must_use]
1196    pub fn version(&self) -> GameVersion {
1197        self.core.opts.version
1198    }
1199
1200    /// The client pose now (start of the tick, before this tick's rotation and movement).
1201    #[must_use]
1202    pub fn pose(&self) -> &Pose {
1203        &self.core.pose
1204    }
1205
1206    /// The last pose written to the server: what it judges this tick's actions against.
1207    #[must_use]
1208    pub fn sent(&self) -> &Pose {
1209        &self.core.sent
1210    }
1211
1212    /// Eye position of `pose` (standing or sneaking eye height of this version).
1213    #[must_use]
1214    pub fn eyes(&self, pose: &Pose) -> Vec3 {
1215        let v = self.core.opts.version;
1216        pose.eyes(if pose.sneaking {
1217            v.sneak_eye_height()
1218        } else {
1219            v.eye_height()
1220        })
1221    }
1222
1223    /// The world (loaded chunk columns and their blocks).
1224    #[must_use]
1225    pub fn world(&self) -> &dyn WorldView {
1226        self.world
1227    }
1228
1229    /// What happened since the previous tick.
1230    #[must_use]
1231    pub fn events(&self) -> &TickEvents {
1232        &self.core.current
1233    }
1234
1235    /// Our entity id.
1236    #[must_use]
1237    pub fn entity_id(&self) -> i32 {
1238        self.core.entity_id
1239    }
1240
1241    /// Health, food and saturation.
1242    #[must_use]
1243    pub fn health(&self) -> Health {
1244        self.core.health
1245    }
1246
1247    /// The player is dead (waiting for [`TickContext::respawn`]).
1248    #[must_use]
1249    pub fn is_dead(&self) -> bool {
1250        self.core.dead
1251    }
1252
1253    /// Game mode.
1254    #[must_use]
1255    pub fn game_mode(&self) -> GameMode {
1256        self.core.game_mode
1257    }
1258
1259    /// Abilities as the server sent them.
1260    #[must_use]
1261    pub fn abilities(&self) -> Abilities {
1262        self.core.abilities
1263    }
1264
1265    /// The server allows flight.
1266    #[must_use]
1267    pub fn can_fly(&self) -> bool {
1268        self.core.abilities.may_fly()
1269    }
1270
1271    /// The selected hotbar slot (0 … 8).
1272    #[must_use]
1273    pub fn held_slot(&self) -> u8 {
1274        self.core.held_slot
1275    }
1276
1277    /// Id of the open container window, if the server opened one.
1278    #[must_use]
1279    pub fn open_window(&self) -> Option<i32> {
1280        (self.core.open_window != 0).then_some(self.core.open_window)
1281    }
1282
1283    /// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16).
1284    #[must_use]
1285    pub fn dimension(&self) -> &str {
1286        &self.core.dimension
1287    }
1288
1289    /// The movement controls recorded for this tick.
1290    #[must_use]
1291    pub fn controls(&self) -> Controls {
1292        self.core.controls
1293    }
1294
1295    /// The rotation target.
1296    #[must_use]
1297    pub fn aim(&self) -> (f32, f32) {
1298        self.core.rotation.target()
1299    }
1300
1301    // ---- actions: written now, before this tick's movement packet ----
1302
1303    /// Sends a chat line or command (truncated to the version's limit, 100 / 256 UTF-16
1304    /// units, like vanilla).
1305    pub fn chat(&mut self, text: impl Into<String>) {
1306        self.core.out.push(Outbound::Chat(text.into()));
1307    }
1308
1309    /// Asks the server to respawn the player. Only sent while dead; returns whether it was.
1310    pub fn respawn(&mut self) -> bool {
1311        if self.core.dead {
1312            self.core.out.push(Outbound::Respawn);
1313            true
1314        } else {
1315            false
1316        }
1317    }
1318
1319    /// Selects a hotbar slot (0 … 8); sends `held_item_slot` when it changes. Out-of-range
1320    /// slots are ignored.
1321    pub fn select_slot(&mut self, slot: u8) {
1322        if slot < 9 {
1323            if self.core.held_slot != slot {
1324                self.core.hands.stop_using();
1325                self.core.hands.ticks_since_swing = 0;
1326            }
1327            self.core.held_slot = slot;
1328            self.core.inv.select(slot);
1329            if self.core.sent_slot != slot {
1330                self.core.sent_slot = slot;
1331                self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
1332            }
1333        }
1334    }
1335
1336    /// Swings the arm (`arm_animation`).
1337    pub fn swing(&mut self) {
1338        self.core.out.push(Outbound::Swing);
1339    }
1340
1341    /// Ends the session after this tick's packets are written.
1342    pub fn disconnect(&mut self, reason: impl Into<String>) {
1343        self.core.quit = Some(reason.into());
1344    }
1345
1346    // ---- intent for this tick's movement step ----
1347
1348    /// Rotation target for this tick: the client turns toward it in whole mouse counts
1349    /// (at most 14° yaw / 10.5° pitch per tick). Call it every tick you want to turn.
1350    pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
1351        self.core.rotation.set_target(yaw, pitch);
1352        self.core.aimed = true;
1353    }
1354
1355    /// Movement keys from now on (kept until changed); the physics turns them into movement
1356    /// like vanilla's `Input` (sneaking scales walking by 0.3).
1357    pub fn set_controls(&mut self, controls: Controls) {
1358        self.core.controls = controls;
1359    }
1360
1361    /// The inventory: player slots, cursor, the open window, the pending click.
1362    #[must_use]
1363    pub fn inventory(&self) -> &ghast_inventory::Inventory {
1364        &self.core.inv
1365    }
1366
1367    /// Clicks in the open screen (`window_click`, written now). Refused (nothing sent) while
1368    /// the player is turning (the look changed in the last movement step or an aim is set for
1369    /// this tick: clicks only while still) or when the inventory refuses it (one click in
1370    /// flight, same-tick packet order, unpredictable result, …). The result arrives in
1371    /// [`TickEvents::inventory`] on a later tick.
1372    pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
1373        if self.core.turned || self.core.aimed {
1374            return Err(ClickRefused::Turning);
1375        }
1376        let o = self
1377            .core
1378            .inv
1379            .click(click)
1380            .map_err(ClickRefused::Inventory)?;
1381        let ticket = match &o {
1382            ghast_inventory::Outgoing::Click(p) => ClickTicket {
1383                window_id: i32::from(p.window_id),
1384                action: p.action,
1385            },
1386            _ => ClickTicket {
1387                window_id: -1,
1388                action: -1,
1389            },
1390        };
1391        self.core.out.push(Outbound::Inventory(o));
1392        Ok(ticket)
1393    }
1394
1395    /// Opens the player inventory GUI (1.8: the "open inventory" client command; 1.16: nothing
1396    /// is sent). Window 0 clicks need it open.
1397    pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
1398        if let Some(o) = self
1399            .core
1400            .inv
1401            .open_inventory()
1402            .map_err(ClickRefused::Inventory)?
1403        {
1404            self.core.out.push(Outbound::Inventory(o));
1405        }
1406        Ok(())
1407    }
1408
1409    /// Closes the open GUI (`close_window` with its id; 0 for the player inventory).
1410    pub fn close_window(&mut self) -> Result<(), ClickRefused> {
1411        let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
1412        self.core.out.push(Outbound::Inventory(o));
1413        // Vanilla closeHandledScreen: the container ends on the client too.
1414        self.core.open_window = 0;
1415        Ok(())
1416    }
1417
1418    /// Mouse buttons from now on (kept until changed; released by a join, a respawn or an
1419    /// open window). Left held mines what the crosshair is on, right held uses / places
1420    /// (vanilla's key processing, after the behaviour and before the movement packet).
1421    pub fn set_buttons(&mut self, buttons: Buttons) {
1422        self.core.buttons = buttons;
1423    }
1424
1425    /// The buttons held.
1426    #[must_use]
1427    pub fn buttons(&self) -> Buttons {
1428        self.core.buttons
1429    }
1430
1431    /// What the crosshair is on as the server judges it: the first block within reach 4.5
1432    /// along the **sent** look from the sent eyes.
1433    #[must_use]
1434    pub fn target(&self) -> Option<BlockHit> {
1435        let s = &self.core.sent;
1436        let v = self.core.opts.version;
1437        let eye = if s.sneaking {
1438            v.sneak_eye_height()
1439        } else {
1440            v.eye_height()
1441        };
1442        let world = self.world;
1443        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1444        hands::pick(
1445            &blocks,
1446            Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z),
1447            hands::look_vector(s.yaw, s.pitch),
1448            hands::REACH,
1449        )
1450    }
1451
1452    /// The tracked entities (behaviours that ask for [`Interests::ENTITIES`]).
1453    #[must_use]
1454    pub fn entities(&self) -> Option<&ghast_entity::Entities> {
1455        self.world.entities()
1456    }
1457
1458    /// The entity the crosshair is on as the server judges it (from the sent pose; vanilla's
1459    /// entity pick: reach 3, 1.8 boxes grown by 0.1, closer than the block hit).
1460    #[must_use]
1461    pub fn target_entity(&self) -> Option<hands::EntityHit> {
1462        let s = &self.core.sent;
1463        let v = self.core.opts.version;
1464        let eye = if s.sneaking {
1465            v.sneak_eye_height()
1466        } else {
1467            v.eye_height()
1468        };
1469        let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
1470        let look = hands::look_vector(s.yaw, s.pitch);
1471        let block = self.target().map(|t| t.distance);
1472        entity_pick(self.world, v, eyes, look, block)
1473    }
1474
1475    /// Attacks `entity` (`use_entity` attack and the arm swing in the version's order; 1.16
1476    /// resets the attack cooldown). Refused (`false`, nothing sent) unless the sent crosshair is
1477    /// on that entity.
1478    pub fn attack(&mut self, entity: i32) -> bool {
1479        if self.target_entity().is_none_or(|e| e.id != entity) {
1480            return false;
1481        }
1482        let world = self.world;
1483        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1484        let c = &mut *self.core;
1485        let modern = c.opts.version != GameVersion::V1_8_9;
1486        let mut placed = false;
1487        let mut io = HandsIo {
1488            blocks: &blocks,
1489            target: None,
1490            held: self.held,
1491            held_stack: None,
1492            food: c.health.food,
1493            modern,
1494            off_held: None,
1495            off_stack: None,
1496            entity: None,
1497            factors: DigFactors::default(),
1498            sneaking: c.pose.sneaking,
1499            out: &mut c.out,
1500            broken: &mut c.broken_now,
1501            placed: &mut placed,
1502        };
1503        if !modern {
1504            io.out.push(Outbound::Swing);
1505        }
1506        c.hands.attack(entity, &mut io);
1507        if modern {
1508            c.out.push(Outbound::Swing);
1509        }
1510        true
1511    }
1512
1513    /// 1.16 attack strength 0 … 1 for an attack speed (4.0 for an empty hand, swords 1.6,
1514    /// axes 0.8–1.0); 1.0 on 1.8 (no cooldown).
1515    #[must_use]
1516    pub fn attack_strength(&self, attack_speed: f64) -> f32 {
1517        if self.core.opts.version == GameVersion::V1_8_9 {
1518            1.0
1519        } else {
1520            self.core.hands.attack_strength(attack_speed)
1521        }
1522    }
1523
1524    /// The block being broken with the left button and its progress 0 … 1.
1525    #[must_use]
1526    pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
1527        self.core.hands.mining()
1528    }
1529
1530    /// Blocks broken so far (finish sent).
1531    #[must_use]
1532    pub fn broken(&self) -> u64 {
1533        self.core.hands.broken
1534    }
1535
1536    /// Using the held item (eating, blocking, drawing a bow): movement input is slowed.
1537    #[must_use]
1538    pub fn using_item(&self) -> bool {
1539        self.core.hands.using_item()
1540    }
1541
1542    /// Starts digging `pos` on `face` (`block_dig` start, then an arm swing), breaking it at
1543    /// once when it is instant for the held item. Refused (nothing sent, `false`) unless the
1544    /// crosshair from the sent pose is on exactly that block face.
1545    pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
1546        if !self
1547            .target()
1548            .is_some_and(|t| t.pos == pos && t.face == face)
1549        {
1550            return false;
1551        }
1552        let world = self.world;
1553        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1554        let c = &mut *self.core;
1555        let mut placed = false;
1556        let mut io = HandsIo {
1557            blocks: &blocks,
1558            target: None,
1559            held: self.held,
1560            held_stack: c.inv.held().cloned(),
1561            food: c.health.food,
1562            modern: c.opts.version != GameVersion::V1_8_9,
1563            off_held: None,
1564            off_stack: None,
1565            entity: None,
1566            factors: DigFactors {
1567                on_ground: c.pose.on_ground,
1568                in_water: false,
1569                aqua_affinity: c.aqua_affinity,
1570                haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
1571                fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
1572            },
1573            sneaking: c.pose.sneaking,
1574            out: &mut c.out,
1575            broken: &mut c.broken_now,
1576            placed: &mut placed,
1577        };
1578        c.hands.click_block(pos, face, &mut io);
1579        c.out.push(Outbound::Swing);
1580        true
1581    }
1582
1583    /// Right-clicks `support`'s `face` at the absolute point `hit` (`block_place`, then an arm
1584    /// swing): places the held block or activates the block. Refused (nothing sent, `false`)
1585    /// unless the crosshair from the sent pose is on exactly that block face.
1586    pub fn place(
1587        &mut self,
1588        support: ghast_protocol::BlockPos,
1589        face: crate::common::Face,
1590        hit: Vec3,
1591    ) -> bool {
1592        let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
1593            return false;
1594        };
1595        let world = self.world;
1596        let Some(b) = world.block_query(support.x, support.y, support.z) else {
1597            return false;
1598        };
1599        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
1600        let c = &mut *self.core;
1601        let mut placed = false;
1602        let first = c.out.len();
1603        let mut io = HandsIo {
1604            blocks: &blocks,
1605            target: None,
1606            held: self.held,
1607            held_stack: c.inv.held().cloned(),
1608            food: c.health.food,
1609            modern: c.opts.version != GameVersion::V1_8_9,
1610            off_held: None,
1611            off_stack: None,
1612            entity: None,
1613            factors: DigFactors::default(),
1614            sneaking: c.pose.sneaking,
1615            out: &mut c.out,
1616            broken: &mut c.broken_now,
1617            placed: &mut placed,
1618        };
1619        c.hands
1620            .right_click_block(BlockHit { hit, ..t }, &b, &mut io);
1621        let _ = placed;
1622        predict_planting(c, world, first);
1623        c.out.push(Outbound::Swing);
1624        true
1625    }
1626
1627    /// When the last inbound bytes arrived (a gap before a setback means lag).
1628    #[must_use]
1629    pub fn last_inbound(&self) -> Option<Instant> {
1630        self.core.last_inbound
1631    }
1632
1633    /// The yaw / pitch this tick's movement step will use, from this tick's
1634    /// [`TickContext::set_aim`] and the digs / places written so far (incl. the turn held by
1635    /// [`crate::Client::hold_turn_on_action`]). Computed on a copy: the rotation's carried
1636    /// budget does not change. Clicks of held buttons, which run after the behaviour, are not
1637    /// seen. Without an aim this tick: the current look.
1638    #[must_use]
1639    pub fn planned_look(&self) -> (f32, f32) {
1640        let c = &*self.core;
1641        let now = (c.pose.yaw, c.pose.pitch);
1642        #[cfg(test)]
1643        if let Some(l) = c.forced_look {
1644            return l;
1645        }
1646        if !c.aimed {
1647            return now;
1648        }
1649        let mut r = c.rotation;
1650        let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
1651        if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1652            now
1653        } else {
1654            (yaw, pitch)
1655        }
1656    }
1657
1658    /// Starts or stops creative-style flight: the `abilities` packet goes out before this
1659    /// tick's movement step, like a double-tapped jump (but without the jump). Starting needs
1660    /// the server's "may fly" ability; asking for the current state sends nothing.
1661    pub fn set_flying(&mut self, flying: bool) {
1662        self.core.want_flying = Some(flying);
1663    }
1664
1665    /// Turns held back so far because they would have taken the crosshair off a block dug or
1666    /// placed on the same tick (see [`crate::Client::hold_turn_on_action`]).
1667    #[must_use]
1668    pub fn held_turns(&self) -> u64 {
1669        self.core.held_turns
1670    }
1671
1672    /// Behaviour status line (logged when it changes).
1673    pub fn status(&mut self, text: &str) {
1674        if self.core.status != text {
1675            text.clone_into(&mut self.core.status);
1676            log::info!(
1677                "[{}] t{} status: {text}",
1678                self.core.opts.name,
1679                self.core.tick
1680            );
1681        }
1682    }
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687    use super::*;
1688    use crate::common::Teleport;
1689    use crate::common::{ChatPosition, EntityAction, JoinGame};
1690    use ghast_protocol::RawPacket;
1691
1692    fn opts(version: GameVersion) -> CoreOptions {
1693        CoreOptions {
1694            name: "test".into(),
1695            version,
1696            settings: ClientSettings::default(),
1697            brand: Some("vanilla".into()),
1698            sensitivity: 0.5,
1699            silent_hold: Duration::from_millis(1500),
1700            hold_turn_on_action: true,
1701            inventory: match version {
1702                GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
1703                _ => ghast_inventory::Version::V1_16_5,
1704            },
1705        }
1706    }
1707
1708    /// A 1.8.9 engine (physics) or a 1.16.5 one (stand-still mover).
1709    fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
1710        let sim: Box<dyn Sim> = match version {
1711            GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
1712            _ => Box::new(crate::sim::Sim16::new()),
1713        };
1714        Engine::new(opts(version), sim)
1715    }
1716
1717    /// Loads the column of chunk (x, z) the way the connection does.
1718    fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
1719        let raw = match e.core.opts.version {
1720            GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
1721            _ => crate::sim::test_chunks::v1_16_5(x, z),
1722        };
1723        e.sim.world_packet(&raw).unwrap();
1724    }
1725
1726    fn join(e: &mut Engine<Box<dyn Sim>>) {
1727        e.handle(Inbound::JoinGame(JoinGame {
1728            entity_id: 7,
1729            game_mode: GameMode::Survival,
1730            dimension: "0".into(),
1731            hardcore: false,
1732            dimension_nbt: None,
1733            respawn_screen: true,
1734        }));
1735        load(e, 0, 0);
1736        e.handle(Inbound::Teleport(Teleport {
1737            x: 8.5,
1738            y: 64.0,
1739            z: 8.5,
1740            yaw: 90.0,
1741            pitch: 0.0,
1742            flags: 0,
1743            teleport_id: None,
1744        }));
1745        e.outbound().clear();
1746    }
1747
1748    /// Records the tick's packets as names.
1749    fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
1750        let v = out
1751            .iter()
1752            .map(|o| match o {
1753                Outbound::Move(m) => m.trace_id(),
1754                Outbound::Chat(_) => "chat",
1755                Outbound::HeldSlot(_) => "held_slot",
1756                Outbound::Swing => "swing",
1757                Outbound::EntityAction { .. } => "entity_action",
1758                Outbound::KeepAlive(_) => "keep_alive",
1759                Outbound::Transaction { .. } => "transaction",
1760                Outbound::TeleportConfirm(_) => "teleport_confirm",
1761                Outbound::Respawn => "respawn",
1762                Outbound::Settings(_) => "settings",
1763                Outbound::Brand(_) => "brand",
1764                Outbound::Abilities { .. } => "abilities",
1765                Outbound::Dig { .. } => "block_dig",
1766                Outbound::Place { .. } | Outbound::UseItem { .. } => "block_place",
1767                Outbound::SwingOffHand => "swing_off",
1768                Outbound::UseEntity { .. } => "use_entity",
1769                Outbound::Inventory(_) => "inventory",
1770            })
1771            .collect();
1772        out.clear();
1773        v
1774    }
1775
1776    struct Script<F: FnMut(&mut TickContext<'_>)>(F);
1777    impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
1778        fn tick(&mut self, ctx: &mut TickContext<'_>) {
1779            (self.0)(ctx);
1780        }
1781    }
1782
1783    #[test]
1784    fn join_sends_settings_then_brand() {
1785        let mut e = engine(GameVersion::V1_8_9);
1786        e.handle(Inbound::JoinGame(JoinGame {
1787            entity_id: 1,
1788            game_mode: GameMode::Creative,
1789            dimension: "0".into(),
1790            hardcore: false,
1791            dimension_nbt: None,
1792            respawn_screen: true,
1793        }));
1794        assert_eq!(names(e.outbound()), ["settings", "brand"]);
1795    }
1796
1797    #[test]
1798    fn nothing_before_the_first_teleport() {
1799        let mut e = engine(GameVersion::V1_8_9);
1800        let mut b = Idle;
1801        let t0 = Instant::now();
1802        load(&mut e, 0, 0);
1803        e.outbound().clear();
1804        for i in 0..5 {
1805            e.tick(&mut b, t0 + Duration::from_millis(50 * i));
1806        }
1807        assert!(e.outbound().is_empty());
1808    }
1809
1810    #[test]
1811    fn teleport_reply_per_version() {
1812        let mut e = engine(GameVersion::V1_16_5);
1813        e.handle(Inbound::Teleport(Teleport {
1814            x: 1.0,
1815            y: 2.0,
1816            z: 3.0,
1817            yaw: 450.0,
1818            pitch: 100.0,
1819            flags: 0,
1820            teleport_id: Some(5),
1821        }));
1822        let out = std::mem::take(e.outbound());
1823        assert_eq!(out[0], Outbound::TeleportConfirm(5));
1824        match out[1] {
1825            Outbound::Move(MovePacket::PositionLook {
1826                yaw,
1827                pitch,
1828                on_ground,
1829                ..
1830            }) => {
1831                assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
1832            }
1833            ref o => panic!("unexpected {o:?}"),
1834        }
1835        let mut e = engine(GameVersion::V1_8_9);
1836        e.handle(Inbound::Teleport(Teleport {
1837            x: 1.0,
1838            y: 2.0,
1839            z: 3.0,
1840            yaw: 450.0,
1841            pitch: 100.0,
1842            flags: 0,
1843            teleport_id: None,
1844        }));
1845        let out = std::mem::take(e.outbound());
1846        assert_eq!(out.len(), 1);
1847        // 1.8 does not clamp the pitch.
1848        assert!(matches!(
1849            out[0],
1850            Outbound::Move(MovePacket::PositionLook {
1851                yaw: 90.0,
1852                pitch: 100.0,
1853                ..
1854            })
1855        ));
1856    }
1857
1858    #[test]
1859    fn actions_precede_the_single_movement_packet() {
1860        let mut e = engine(GameVersion::V1_8_9);
1861        join(&mut e);
1862        let t0 = Instant::now();
1863        e.note_inbound(t0);
1864        let mut b = Script(|ctx: &mut TickContext<'_>| {
1865            if ctx.tick() == 2 {
1866                ctx.select_slot(3);
1867                ctx.chat("hello");
1868                ctx.swing();
1869                ctx.set_controls(Controls {
1870                    sneak: true,
1871                    ..Controls::default()
1872                });
1873            }
1874        });
1875        e.tick(&mut b, t0);
1876        assert_eq!(names(e.outbound()), ["C06"]);
1877        e.tick(&mut b, t0);
1878        assert_eq!(
1879            names(e.outbound()),
1880            ["held_slot", "chat", "swing", "entity_action", "C03"]
1881        );
1882        for _ in 0..100 {
1883            e.tick(&mut b, t0);
1884            let n = names(e.outbound());
1885            assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
1886        }
1887    }
1888
1889    #[test]
1890    fn standing_bot_packets() {
1891        let mut e = engine(GameVersion::V1_8_9);
1892        join(&mut e);
1893        let mut b = Idle;
1894        let t0 = Instant::now();
1895        e.note_inbound(t0);
1896        // First tick: the position differs from the fresh player's lastReported (origin).
1897        e.tick(&mut b, t0);
1898        let out = std::mem::take(e.outbound());
1899        assert!(matches!(
1900            out[..],
1901            [Outbound::Move(MovePacket::PositionLook {
1902                on_ground: false,
1903                ..
1904            })]
1905        ));
1906        // Then flying (on ground) with a position refresh every 21st tick.
1907        let mut kinds = Vec::new();
1908        for _ in 0..42 {
1909            e.tick(&mut b, t0);
1910            kinds.extend(names(e.outbound()));
1911        }
1912        assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
1913        assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
1914        assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
1915        assert!(e.core.sent.on_ground);
1916    }
1917
1918    #[test]
1919    fn silent_server_freezes_behaviour() {
1920        let mut e = engine(GameVersion::V1_8_9);
1921        join(&mut e);
1922        let t0 = Instant::now();
1923        e.note_inbound(t0);
1924        let mut ticks = 0;
1925        let mut b = Script(|ctx: &mut TickContext<'_>| {
1926            ticks += 1;
1927            ctx.set_controls(Controls {
1928                sneak: true,
1929                ..Controls::default()
1930            });
1931        });
1932        e.tick(&mut b, t0 + Duration::from_millis(100));
1933        e.tick(&mut b, t0 + Duration::from_millis(1600));
1934        // Frozen: keys released, so the sneak stops; still one movement packet.
1935        let n = names(e.outbound());
1936        assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
1937        e.note_inbound(t0 + Duration::from_millis(1700));
1938        e.tick(&mut b, t0 + Duration::from_millis(1700));
1939        let _ = b;
1940        assert_eq!(ticks, 2);
1941    }
1942
1943    #[test]
1944    fn keepalive_answered_transactions_left_to_the_inventory() {
1945        let mut e = engine(GameVersion::V1_8_9);
1946        join(&mut e);
1947        e.handle(Inbound::KeepAlive(42));
1948        // The engine never answers confirms: the inventory does (exactly once), see the
1949        // fake-server test.
1950        e.handle(Inbound::Transaction {
1951            window_id: 0,
1952            action: -5,
1953            accepted: false,
1954        });
1955        assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
1956    }
1957
1958    #[test]
1959    fn panicking_behaviour_does_not_stop_the_tick() {
1960        let mut e = engine(GameVersion::V1_8_9);
1961        join(&mut e);
1962        let t0 = Instant::now();
1963        let mut b = Script(|ctx: &mut TickContext<'_>| {
1964            if ctx.tick() == 2 {
1965                panic!("boom");
1966            }
1967        });
1968        let hook = std::panic::take_hook();
1969        std::panic::set_hook(Box::new(|_| {}));
1970        for _ in 0..5 {
1971            e.tick(&mut b, t0);
1972        }
1973        std::panic::set_hook(hook);
1974        assert!(e.state.failed);
1975        assert_eq!(names(e.outbound()).len(), 5);
1976    }
1977
1978    #[test]
1979    fn chat_events_reach_the_behaviour_once() {
1980        let mut e = engine(GameVersion::V1_16_5);
1981        join(&mut e);
1982        e.handle(Inbound::Chat(ChatMessage {
1983            json: r#"{"text":"hi"}"#.into(),
1984            position: ChatPosition::System,
1985            sender: None,
1986        }));
1987        let mut seen = Vec::new();
1988        let mut b = Script(|ctx: &mut TickContext<'_>| {
1989            seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
1990        });
1991        let t0 = Instant::now();
1992        e.tick(&mut b, t0);
1993        e.tick(&mut b, t0);
1994        let _ = b;
1995        assert_eq!(seen, ["hi"]);
1996    }
1997
1998    #[test]
1999    fn immediate_respawn_1_16() {
2000        let mut e = engine(GameVersion::V1_16_5);
2001        join(&mut e);
2002        e.handle(Inbound::GameState {
2003            reason: 11,
2004            value: 1.0,
2005        });
2006        e.handle(Inbound::Died { entity_id: 7 });
2007        assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
2008    }
2009
2010    /// Left button on the floor: START, swings, FINISH, all before the tick's movement
2011    /// packet; the broken block is predicted air and the player falls into the hole.
2012    #[test]
2013    fn dig_with_the_left_button() {
2014        let mut e = engine(GameVersion::V1_8_9);
2015        join(&mut e);
2016        let t0 = Instant::now();
2017        e.note_inbound(t0);
2018        let mut b = Script(|ctx: &mut TickContext<'_>| {
2019            ctx.set_aim(90.0, 89.5);
2020            let down = ctx.target().is_some_and(|t| {
2021                t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
2022            });
2023            ctx.set_buttons(Buttons {
2024                left: down,
2025                right: false,
2026            });
2027        });
2028        let mut ticks = Vec::new();
2029        for _ in 0..200 {
2030            e.tick(&mut b, t0);
2031            let n = names(e.outbound());
2032            assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
2033            assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
2034            ticks.push(n);
2035        }
2036        let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
2037        assert_eq!(
2038            flat.iter().filter(|x| **x == "block_dig").count(),
2039            2,
2040            "start + finish"
2041        );
2042        assert!(e.core.hands.broken == 1);
2043        // Stone by hand: not harvestable, 1 / 1.5 / 100 per tick -> 151 damage ticks.
2044        let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
2045        let finish = ticks
2046            .iter()
2047            .rposition(|t| t.contains(&"block_dig"))
2048            .unwrap();
2049        assert_eq!(finish - start, 150);
2050        assert!(e.sim.block_query(8, 63, 8).unwrap().air);
2051        assert!(
2052            e.core.pose.pos.y < 64.0,
2053            "falls into the hole: {:?}",
2054            e.core.pose.pos
2055        );
2056    }
2057
2058    /// `place` is refused unless the sent look is on the face; then C08 + C0A before the
2059    /// movement packet.
2060    #[test]
2061    fn place_needs_the_sent_look() {
2062        let mut e = engine(GameVersion::V1_8_9);
2063        join(&mut e);
2064        let t0 = Instant::now();
2065        e.note_inbound(t0);
2066        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2067        let mut results = Vec::new();
2068        let mut b = Script(|ctx: &mut TickContext<'_>| {
2069            ctx.set_aim(90.0, 89.5);
2070            results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
2071        });
2072        // A stack of stone in the selected hotbar slot (window 0 slot 36).
2073        e.core
2074            .inv
2075            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2076        let mut placed_tick = None;
2077        for i in 0..20 {
2078            e.tick(&mut b, t0);
2079            let n = names(e.outbound());
2080            if n.contains(&"block_place") {
2081                assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
2082                placed_tick.get_or_insert(i);
2083            }
2084        }
2085        let _ = b;
2086        let first = results.iter().position(|r| *r).unwrap();
2087        assert!(first > 3, "refused while still turning");
2088        assert_eq!(placed_tick, Some(first));
2089        assert_eq!(e.core.inv.held().map(|s| s.id), Some(1));
2090    }
2091
2092    #[test]
2093    fn sneak_action_order() {
2094        let mut e = engine(GameVersion::V1_8_9);
2095        join(&mut e);
2096        let mut b = Script(|ctx: &mut TickContext<'_>| {
2097            ctx.set_controls(Controls {
2098                sneak: true,
2099                ..Controls::default()
2100            });
2101        });
2102        e.tick(&mut b, Instant::now());
2103        let out = std::mem::take(e.outbound());
2104        assert_eq!(
2105            out[0],
2106            Outbound::EntityAction {
2107                entity_id: 7,
2108                action: EntityAction::StartSneaking
2109            }
2110        );
2111        assert!(matches!(out[1], Outbound::Move(_)));
2112    }
2113
2114    /// Block changes reach the behaviour once, in arrival order, only when asked for.
2115    #[test]
2116    fn block_updates_per_version() {
2117        use ghast_protocol::BlockPos;
2118        for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2119            let mut e = engine(v);
2120            join(&mut e);
2121            e.sim.collect_block_updates(true);
2122            let t0 = Instant::now();
2123            e.note_inbound(t0);
2124            let raws = match v {
2125                GameVersion::V1_8_9 => {
2126                    use ghast_protocol::v1_8::play::clientbound as cb;
2127                    vec![
2128                        RawPacket::from_packet(&cb::BlockChange {
2129                            location: BlockPos::new(3, 63, 4),
2130                            r#type: 59 << 4 | 7,
2131                        })
2132                        .unwrap(),
2133                        RawPacket::from_packet(&cb::MultiBlockChange {
2134                            chunk_x: 0,
2135                            chunk_z: 0,
2136                            records: vec![cb::MultiBlockChangeRecords {
2137                                horizontal_pos: 5 << 4 | 6,
2138                                y: 62,
2139                                block_id: 60 << 4 | 7,
2140                            }],
2141                        })
2142                        .unwrap(),
2143                    ]
2144                }
2145                _ => {
2146                    use ghast_protocol::v1_16_5::play::clientbound as cb;
2147                    // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
2148                    let local = (5 << 8 | 6 << 4 | 14) as i64;
2149                    vec![
2150                        RawPacket::from_packet(&cb::BlockChange {
2151                            location: BlockPos::new(3, 63, 4),
2152                            r#type: 1,
2153                        })
2154                        .unwrap(),
2155                        RawPacket::from_packet(&cb::MultiBlockChange {
2156                            chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
2157                                x: 0,
2158                                z: 0,
2159                                y: 0xF_FFFF,
2160                            },
2161                            not_trust_edges: false,
2162                            records: vec![9 << 12 | local],
2163                        })
2164                        .unwrap(),
2165                    ]
2166                }
2167            };
2168            for raw in &raws {
2169                e.sim.world_packet(raw).unwrap();
2170            }
2171            let mut seen = Vec::new();
2172            let mut b = Script(|ctx: &mut TickContext<'_>| {
2173                seen.push(ctx.events().block_updates.clone());
2174            });
2175            e.tick(&mut b, t0);
2176            e.tick(&mut b, t0);
2177            let _ = b;
2178            let want = match v {
2179                GameVersion::V1_8_9 => vec![
2180                    (BlockPos::new(3, 63, 4), 59 << 4 | 7),
2181                    (BlockPos::new(5, 62, 6), 60 << 4 | 7),
2182                ],
2183                _ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
2184            };
2185            assert_eq!(seen, [want, Vec::new()], "{v:?}");
2186
2187            // Not collected when not asked for.
2188            e.sim.collect_block_updates(false);
2189            e.sim.world_packet(&raws[0]).unwrap();
2190            let mut n = usize::MAX;
2191            let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
2192            e.tick(&mut b, t0);
2193            let _ = b;
2194            assert_eq!(n, 0);
2195        }
2196    }
2197
2198    /// `set_flying` sends the abilities packet before the move, only when allowed and changed.
2199    #[test]
2200    fn set_flying_needs_may_fly() {
2201        for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2202            let mut e = engine(v);
2203            join(&mut e);
2204            let t0 = Instant::now();
2205            e.note_inbound(t0);
2206            // In the air (flight ends on landing, like vanilla).
2207            e.handle(Inbound::Teleport(Teleport {
2208                x: 8.5,
2209                y: 70.0,
2210                z: 8.5,
2211                yaw: 90.0,
2212                pitch: 0.0,
2213                flags: 0,
2214                teleport_id: Some(2),
2215            }));
2216            e.outbound().clear();
2217            let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
2218            e.tick(&mut b, t0);
2219            assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
2220            assert!(!e.core.pose.flying);
2221            e.handle(Inbound::Abilities(Abilities {
2222                flags: 4,
2223                ..Abilities::default()
2224            }));
2225            e.tick(&mut b, t0);
2226            let out = std::mem::take(e.outbound());
2227            assert_eq!(
2228                out[0],
2229                Outbound::Abilities {
2230                    flags: 6,
2231                    flying_speed: 0.05,
2232                    walking_speed: 0.1
2233                },
2234                "{v:?}"
2235            );
2236            assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
2237            assert!(e.core.pose.flying && e.core.sent.flying);
2238            // Already flying: nothing more.
2239            e.tick(&mut b, t0);
2240            assert!(!names(e.outbound()).contains(&"abilities"));
2241            let _ = b;
2242        }
2243    }
2244
2245    /// A behaviour that reports `running() == false` is not ticked again.
2246    #[test]
2247    fn finished_behaviour_is_not_ticked() {
2248        struct Three(std::rc::Rc<std::cell::Cell<u32>>);
2249        impl Behavior for Three {
2250            fn tick(&mut self, _ctx: &mut TickContext<'_>) {
2251                self.0.set(self.0.get() + 1);
2252            }
2253            fn running(&self) -> bool {
2254                self.0.get() < 3
2255            }
2256        }
2257        let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
2258        let mut e = engine(GameVersion::V1_8_9);
2259        join(&mut e);
2260        let t0 = Instant::now();
2261        e.note_inbound(t0);
2262        let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
2263        for _ in 0..10 {
2264            e.tick(&mut b, t0);
2265            // The player keeps sending its movement packet.
2266            let out = std::mem::take(e.outbound());
2267            assert!(
2268                out.iter().any(|o| matches!(o, Outbound::Move(_))),
2269                "{out:?}"
2270            );
2271        }
2272        assert_eq!(
2273            ticks.get(),
2274            3,
2275            "not ticked after running() == false (through the Box)"
2276        );
2277    }
2278
2279    /// A turn that would take the crosshair off a block placed this tick waits one tick.
2280    #[test]
2281    fn turn_held_on_a_place_tick() {
2282        let mut e = engine(GameVersion::V1_8_9);
2283        join(&mut e);
2284        let t0 = Instant::now();
2285        e.note_inbound(t0);
2286        e.core
2287            .inv
2288            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2289        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2290        let mut tick = 0;
2291        let mut placed_at = None;
2292        let mut pitches = Vec::new();
2293        let mut b = Script(|ctx: &mut TickContext<'_>| {
2294            tick += 1;
2295            if placed_at.is_none() {
2296                ctx.set_aim(90.0, 89.5);
2297                if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
2298                    placed_at = Some(tick);
2299                    // Look up on the same tick: held back.
2300                    ctx.set_aim(90.0, -60.0);
2301                }
2302            } else {
2303                ctx.set_aim(90.0, -60.0);
2304            }
2305            pitches.push(ctx.pose().pitch);
2306        });
2307        for _ in 0..30 {
2308            e.tick(&mut b, t0);
2309            e.outbound().clear();
2310        }
2311        let _ = b;
2312        let p = placed_at.expect("placed");
2313        assert_eq!(e.core.held_turns, 1);
2314        // Pose at the start of the tick after the place: still the place look.
2315        assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
2316        assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
2317    }
2318
2319    /// `click` returns the ticket its confirm carries.
2320    #[test]
2321    fn click_ticket_matches_the_confirm() {
2322        let mut e = engine(GameVersion::V1_8_9);
2323        join(&mut e);
2324        let t0 = Instant::now();
2325        e.note_inbound(t0);
2326        e.core
2327            .inv
2328            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2329        let mut ticket = None;
2330        let mut n = 0;
2331        let mut b = Script(|ctx: &mut TickContext<'_>| {
2332            n += 1;
2333            if n == 1 {
2334                ctx.open_inventory().unwrap();
2335            } else if ticket.is_none() {
2336                ticket = ctx
2337                    .click(ghast_inventory::Click::Pickup {
2338                        slot: 36,
2339                        right: false,
2340                    })
2341                    .ok();
2342            }
2343        });
2344        for _ in 0..3 {
2345            e.tick(&mut b, t0);
2346        }
2347        let _ = b;
2348        let t = ticket.expect("click sent");
2349        assert_eq!(t.window_id, 0);
2350        assert!(t.matches(&ghast_inventory::ClickResult {
2351            window_id: 0,
2352            action: t.action,
2353            outcome: ghast_inventory::ClickOutcome::Accepted,
2354        }));
2355    }
2356
2357    /// 1.8 planting uses the seed at once (vanilla `SeedItem.use` on the client); a
2358    /// stone block place waits for the server.
2359    #[test]
2360    fn planting_uses_the_seed_at_once() {
2361        use ghast_protocol::v1_8::play::clientbound as cb;
2362        for (soil, item, used) in [
2363            (60 << 4 | 7, 295, true),
2364            (1 << 4, 295, false),
2365            (60 << 4, 1, false),
2366        ] {
2367            let mut e = engine(GameVersion::V1_8_9);
2368            join(&mut e);
2369            let t0 = Instant::now();
2370            e.note_inbound(t0);
2371            let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2372            let raw = RawPacket::from_packet(&cb::BlockChange {
2373                location: floor,
2374                r#type: soil,
2375            })
2376            .unwrap();
2377            e.sim.world_packet(&raw).unwrap();
2378            e.core
2379                .inv
2380                .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
2381            let mut done = false;
2382            let mut b = Script(|ctx: &mut TickContext<'_>| {
2383                ctx.set_aim(90.0, 89.5);
2384                if !done {
2385                    done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
2386                }
2387            });
2388            let mut sent = None;
2389            for _ in 0..20 {
2390                e.tick(&mut b, t0);
2391                for o in e.outbound().drain(..) {
2392                    if let Outbound::Place { held, .. } = o {
2393                        sent = held.map(|h| h.count);
2394                    }
2395                }
2396            }
2397            let _ = b;
2398            assert_eq!(sent, Some(64), "the packet carries the stack before use");
2399            let left = e.core.inv.held().map(|s| s.count);
2400            assert_eq!(
2401                left,
2402                Some(if used { 63 } else { 64 }),
2403                "soil {soil} item {item}"
2404            );
2405        }
2406    }
2407
2408    /// `planned_look` is the look the movement step then uses: a plain turn, a turn held on a
2409    /// place tick, no aim; and it leaves the rotation's budget alone.
2410    #[test]
2411    fn planned_look_is_the_next_look() {
2412        let mut e = engine(GameVersion::V1_8_9);
2413        join(&mut e);
2414        let t0 = Instant::now();
2415        e.note_inbound(t0);
2416        e.core
2417            .inv
2418            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
2419        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
2420        let mut n = 0;
2421        let mut placed = false;
2422        let mut plans: Vec<(f32, f32)> = Vec::new();
2423        let mut b = Script(|ctx: &mut TickContext<'_>| {
2424            n += 1;
2425            if n % 5 == 0 {
2426                // No aim this tick: the current look.
2427            } else if !placed {
2428                ctx.set_aim(90.0, 89.5);
2429                if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
2430                    placed = true;
2431                    ctx.set_aim(90.0, -60.0);
2432                }
2433            } else {
2434                ctx.set_aim(150.0, -60.0);
2435            }
2436            // Asking twice changes nothing.
2437            let p = ctx.planned_look();
2438            assert_eq!(p, ctx.planned_look());
2439            plans.push(p);
2440        });
2441        let mut looks = Vec::new();
2442        for _ in 0..40 {
2443            e.tick(&mut b, t0);
2444            e.outbound().clear();
2445            looks.push((e.core.pose.yaw, e.core.pose.pitch));
2446        }
2447        let _ = b;
2448        assert!(placed);
2449        assert_eq!(e.core.test_held_turns(), 1);
2450        assert_eq!(plans, looks);
2451    }
2452
2453    /// A teleport event keeps the sent pose from before the overwrite, the raw values and the
2454    /// resolved pose.
2455    #[test]
2456    fn teleport_event_has_the_sent_pose_before() {
2457        for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2458            let mut e = engine(v);
2459            join(&mut e);
2460            let t0 = Instant::now();
2461            e.note_inbound(t0);
2462            let mut seen = Vec::new();
2463            let mut b = Script(|ctx: &mut TickContext<'_>| {
2464                seen.extend(ctx.events().teleports.iter().copied());
2465            });
2466            e.tick(&mut b, t0);
2467            let sent = e.core.sent;
2468            // Relative yaw +30, absolute position.
2469            let tp = Teleport {
2470                x: 10.5,
2471                y: 64.0,
2472                z: 8.5,
2473                yaw: 30.0,
2474                pitch: 0.0,
2475                flags: crate::common::teleport_flags::YAW,
2476                teleport_id: Some(9),
2477            };
2478            e.handle(Inbound::Teleport(tp));
2479            e.tick(&mut b, t0);
2480            e.tick(&mut b, t0);
2481            let _ = b;
2482            // The spawn position first (join), then ours, each once.
2483            assert_eq!(seen.len(), 2, "{v:?}");
2484            let ev = seen[1];
2485            assert_eq!(ev.teleport, tp);
2486            assert_eq!(ev.sent_before, sent);
2487            assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
2488            assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
2489        }
2490    }
2491
2492    /// A container the server opened and the behaviour closed (`close_window`) no longer
2493    /// holds the mouse: the left button digs again (both versions). While it is open the
2494    /// buttons are up.
2495    #[test]
2496    fn closed_window_frees_the_buttons() {
2497        for v in [GameVersion::V1_8_9, GameVersion::V1_16_5] {
2498            let mut e = engine(v);
2499            join(&mut e);
2500            let t0 = Instant::now();
2501            e.note_inbound(t0);
2502            if v == GameVersion::V1_16_5 {
2503                // The 1.16 test chunk is all air: put a stone floor under the player.
2504                use ghast_protocol::v1_16_5::play::clientbound as cb;
2505                let raw = RawPacket::from_packet(&cb::BlockChange {
2506                    location: ghast_protocol::BlockPos::new(8, 63, 8),
2507                    r#type: 1,
2508                })
2509                .unwrap();
2510                e.sim.world_packet(&raw).unwrap();
2511            }
2512            e.core.inv.on_open_window(
2513                5,
2514                Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
2515                "Vault".into(),
2516            );
2517            e.handle(Inbound::OpenWindow(5));
2518            // Something on the cursor: vanilla's client-side close drops it (the server
2519            // throws it out), so the client forgets it too.
2520            e.core
2521                .inv
2522                .on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
2523            let mut n = 0;
2524            let mut closed_at = None;
2525            let mut b = Script(|ctx: &mut TickContext<'_>| {
2526                n += 1;
2527                ctx.set_aim(90.0, 89.5);
2528                ctx.set_buttons(Buttons {
2529                    left: true,
2530                    right: false,
2531                });
2532                if n == 15 {
2533                    assert!(ctx.inventory().cursor().is_some());
2534                    ctx.close_window().unwrap();
2535                    assert_eq!(ctx.open_window(), None);
2536                    let inv = ctx.inventory();
2537                    assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
2538                    closed_at = Some(n);
2539                }
2540            });
2541            let mut first_dig = None;
2542            for i in 1..=30 {
2543                e.tick(&mut b, t0);
2544                let out = std::mem::take(e.outbound());
2545                if first_dig.is_none()
2546                    && out.iter().any(|o| {
2547                        matches!(
2548                            o,
2549                            Outbound::Dig {
2550                                status: crate::common::DigStatus::Start,
2551                                ..
2552                            }
2553                        )
2554                    })
2555                {
2556                    first_dig = Some(i);
2557                }
2558            }
2559            let _ = b;
2560            assert_eq!(closed_at, Some(15));
2561            let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
2562            // The hands run after the behaviour: the closing tick already digs.
2563            assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
2564        }
2565    }
2566}