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::{Crosshair, PickQuery, Sim, WorldView};
36use crate::version::{Capabilities, 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 after every tick's movement step (also while the behaviour is on hold or has
86    /// finished), with a read-only view of what the server now has: the pose sent this tick,
87    /// the world, entities and inventory. For observers (a viewer, a recorder); it cannot act.
88    /// Default: nothing.
89    ///
90    /// ```
91    /// use ghast_client::{Behavior, TickContext, TickView};
92    ///
93    /// /// Logs where the server has the player, once a second.
94    /// struct Tracker;
95    ///
96    /// impl Behavior for Tracker {
97    ///     fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
98    ///
99    ///     fn after_tick(&mut self, view: &TickView<'_>) {
100    ///         if view.tick() % 20 == 0 {
101    ///             let p = view.sent();
102    ///             println!("{} {:?} in {}", view.tick(), p.pos, view.dimension());
103    ///         }
104    ///     }
105    /// }
106    /// ```
107    fn after_tick(&mut self, view: &TickView<'_>) {
108        let _ = view;
109    }
110
111    /// Called once when the session ends (or the behaviour panicked).
112    fn stop(&mut self, reason: &str) {
113        let _ = reason;
114    }
115
116    /// 26.1+: a dialog the server shows during the configuration state, before the player is in
117    /// the world (behaviours do not tick there). Called only with [`Interests::DIALOGS`]; the
118    /// client sends the returned answer at once, as vanilla would for that button (see
119    /// [`crate::dialog`]); `None` leaves the dialog open. A dialog the answer opens is offered
120    /// next. Play-state dialogs come through [`TickContext::dialog`] instead. Default: `None`.
121    fn configuration_dialog(
122        &mut self,
123        dialog: &crate::dialog::Dialog,
124    ) -> Option<crate::dialog::DialogAnswer> {
125        let _ = dialog;
126        None
127    }
128}
129
130/// A boxed behaviour is a behaviour (a runner can pick one from its config at run time).
131impl<B: Behavior + ?Sized> Behavior for Box<B> {
132    fn name(&self) -> &str {
133        (**self).name()
134    }
135    fn interests(&self) -> Interests {
136        (**self).interests()
137    }
138    fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
139        (**self).raw_packets(version)
140    }
141    fn start(&mut self, ctx: &mut TickContext<'_>) {
142        (**self).start(ctx);
143    }
144    fn tick(&mut self, ctx: &mut TickContext<'_>) {
145        (**self).tick(ctx);
146    }
147    fn running(&self) -> bool {
148        (**self).running()
149    }
150    fn after_tick(&mut self, view: &TickView<'_>) {
151        (**self).after_tick(view);
152    }
153    fn stop(&mut self, reason: &str) {
154        (**self).stop(reason);
155    }
156    fn configuration_dialog(
157        &mut self,
158        dialog: &crate::dialog::Dialog,
159    ) -> Option<crate::dialog::DialogAnswer> {
160        (**self).configuration_dialog(dialog)
161    }
162}
163
164/// Why [`TickContext::click`] (or opening / closing a window) sent nothing.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166#[non_exhaustive]
167pub enum ClickRefused {
168    /// The player is turning: click only while still.
169    Turning,
170    /// The inventory refused it.
171    Inventory(ghast_inventory::ClickError),
172}
173
174impl std::fmt::Display for ClickRefused {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            ClickRefused::Turning => f.write_str("the player is turning"),
178            ClickRefused::Inventory(e) => write!(f, "{e}"),
179        }
180    }
181}
182
183impl std::error::Error for ClickRefused {}
184
185/// A click that was sent: match it with [`TickEvents::inventory`]'s `clicks` on a later tick
186/// (window id and action number, as the server's confirm carries them).
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub struct ClickTicket {
189    /// Window id the click was sent for.
190    pub window_id: i32,
191    /// Its action number.
192    pub action: i16,
193}
194
195impl ClickTicket {
196    /// Whether `r` is the result of this click.
197    #[must_use]
198    pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
199        r.window_id == self.window_id && r.action == self.action
200    }
201}
202
203/// A behaviour that does nothing (the player stands still).
204#[derive(Debug, Clone, Copy, Default)]
205pub struct Idle;
206
207impl Behavior for Idle {
208    fn name(&self) -> &str {
209        "idle"
210    }
211
212    fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
213}
214
215/// A clientbound play packet copied for the behaviour ([`Behavior::raw_packets`]).
216#[derive(Debug, Clone, PartialEq, Eq)]
217#[non_exhaustive]
218pub struct RawInbound {
219    /// Packet id (version-specific).
220    pub id: i32,
221    /// The body after the id, undecoded (a cheap reference-counted copy).
222    pub body: bytes::Bytes,
223    /// When the frame was decoded from the socket (frames read together share it).
224    pub at: Instant,
225}
226
227/// A server teleport / correction (`position`) with the poses around it.
228#[derive(Debug, Clone, Copy, PartialEq)]
229#[non_exhaustive]
230pub struct TeleportEvent {
231    /// The packet's values as received: absolute or relative per
232    /// [`crate::common::teleport_flags`] in `flags`.
233    pub teleport: crate::common::Teleport,
234    /// What the server had from us just before ([`TickContext::sent`] before the overwrite):
235    /// compare with [`TeleportEvent::after`] to see what the server moved / turned us by.
236    pub sent_before: Pose,
237    /// The client pose just before (it may be ahead of `sent_before` within a tick).
238    pub pose_before: Pose,
239    /// The pose after applying it (relative fields resolved).
240    pub after: Pose,
241}
242
243/// Most teleports kept between two behaviour ticks.
244const MAX_PENDING_TELEPORTS: usize = 64;
245
246/// Most raw packets kept between two behaviour ticks.
247const MAX_PENDING_RAW: usize = 4096;
248/// Most dialog events kept between two behaviour ticks (the open dialog is always current).
249const MAX_PENDING_DIALOGS: usize = 64;
250
251/// What happened since the behaviour's previous tick.
252#[derive(Debug, Clone, Default, PartialEq)]
253#[non_exhaustive]
254pub struct TickEvents {
255    /// Chat messages in arrival order (only with [`Interests::CHAT`]).
256    pub chat: Vec<ChatMessage>,
257    /// Chat messages dropped because too many piled up while the behaviour was not ticking.
258    pub chat_dropped: usize,
259    /// The server teleported / corrected the player.
260    pub teleported: bool,
261    /// Every teleport in arrival order, with the sent pose before it (at most 64 per tick).
262    pub teleports: Vec<TeleportEvent>,
263    /// A join game packet arrived (first join or a proxy server switch).
264    pub joined: bool,
265    /// The player respawned or changed dimension.
266    pub respawned: bool,
267    /// The player died (health reached 0).
268    pub died: bool,
269    /// Health, food or saturation changed.
270    pub health_changed: bool,
271    /// The game mode changed.
272    pub game_mode_changed: bool,
273    /// Inventory / window changes and click results (ghast-inventory).
274    pub inventory: ghast_inventory::Events,
275    /// Block changes in arrival order (only with [`Interests::BLOCK_UPDATES`]): position and
276    /// the version's raw block state (1.8 `id << 4 | meta`, 1.16 the global palette id).
277    /// The world already holds them when the behaviour ticks.
278    pub block_updates: Vec<(ghast_protocol::BlockPos, u32)>,
279    /// Block changes dropped because too many piled up between two behaviour ticks.
280    pub block_updates_dropped: usize,
281    /// The packets asked for with [`Behavior::raw_packets`], in arrival order (kept while the
282    /// behaviour is on hold, like chat).
283    pub raw: Vec<RawInbound>,
284    /// Raw packets dropped because more than 4096 piled up between two behaviour ticks.
285    pub raw_dropped: usize,
286}
287
288impl TickEvents {
289    fn clear(&mut self) {
290        self.chat.clear();
291        self.chat_dropped = 0;
292        self.teleported = false;
293        self.teleports.clear();
294        self.joined = false;
295        self.respawned = false;
296        self.died = false;
297        self.health_changed = false;
298        self.game_mode_changed = false;
299        self.inventory = ghast_inventory::Events::default();
300        self.block_updates.clear();
301        self.block_updates_dropped = 0;
302        self.raw.clear();
303        self.raw_dropped = 0;
304    }
305}
306
307/// Tunables of the core.
308#[derive(Debug, Clone)]
309pub(crate) struct CoreOptions {
310    pub name: Arc<str>,
311    /// The version's capability row (the core asks it instead of comparing versions).
312    pub caps: &'static Capabilities,
313    pub settings: ClientSettings,
314    pub brand: Option<String>,
315    pub sensitivity: f32,
316    pub silent_hold: Duration,
317    pub inventory: ghast_inventory::Version,
318    /// Keep the look still on a tick that dug / placed when the turn would take the
319    /// crosshair off the clicked block (Grim RotationPlace re-checks with the next look).
320    pub hold_turn_on_action: bool,
321    /// Accept server resource packs the server requires (optional ones are declined).
322    pub accept_required_packs: bool,
323    /// Entities push the player (vanilla: on; off is the non-vanilla opt-in of
324    /// [`crate::Client::entity_push`]).
325    pub entity_push: bool,
326}
327
328/// Client state shared by the connection and the behaviour context.
329#[derive(Debug)]
330pub(crate) struct Core {
331    opts: CoreOptions,
332    tick: u64,
333    entity_id: i32,
334    joined: bool,
335    teleported_once: bool,
336    ready: bool,
337    pose: Pose,
338    sent: Pose,
339    rotation: Rotation,
340    aimed: bool,
341    controls: Controls,
342    health: Health,
343    dead: bool,
344    abilities: Abilities,
345    game_mode: GameMode,
346    held_slot: u8,
347    sent_slot: u8,
348    open_window: i32,
349    dimension: String,
350    respawn_screen: bool,
351    pending: TickEvents,
352    current: TickEvents,
353    out: Vec<Outbound>,
354    last_inbound: Option<Instant>,
355    silent: bool,
356    quit: Option<String>,
357    status: String,
358    hands: Hands,
359    buttons: Buttons,
360    /// Inventory and windows (ghast-inventory).
361    inv: ghast_inventory::Inventory,
362    /// The look changed in the last movement step (window clicks need a still player).
363    turned: bool,
364    /// Our active status effects: id → amplifier.
365    effects: std::collections::BTreeMap<i8, i8>,
366    /// Aqua affinity on the helmet (dig speed under water).
367    aqua_affinity: bool,
368    /// Blocks broken on the client this tick (predicted air).
369    broken_now: Vec<ghast_protocol::BlockPos>,
370    /// The crosshair pick's entity list (kept to reuse the allocation).
371    pick: PickList,
372    /// Flight wanted by the behaviour this tick ([`TickContext::set_flying`]).
373    want_flying: Option<bool>,
374    /// Turns held back because they would have moved the crosshair off a clicked block.
375    held_turns: u64,
376    /// Arm swings (main and off hand) written in finished ticks.
377    swings: u64,
378    /// 1.21.4+ level loading: the server said the level's chunks are coming (game event 13).
379    level_load_started: bool,
380    /// 1.21.4+: `player_loaded` was sent for the current level.
381    client_loaded: bool,
382    /// 1.19.3+ signed chat: a chat session is ready to be announced (`setKeyPair`).
383    chat_session_due: bool,
384    /// 1.21.4+: this tick sent `player_loaded` (no mouse turn on it).
385    gate_tick: bool,
386    /// Test hook: the level-load gate's "section compiled" / "timed out" inputs.
387    #[cfg(test)]
388    test_gate: Option<(bool, bool)>,
389    /// Ticks spent waiting for the level (vanilla lets the player in after 30 s).
390    load_wait: u32,
391    /// Consecutive ticks the 3x3 columns around the player have been loaded (vanilla compiles
392    /// the player's section only then, and sees it compiled a tick later at the earliest).
393    near_loaded: u8,
394    /// Time origin for nanosecond timestamps (chunk batch timing).
395    origin: Instant,
396    /// Entities push the player ([`TickContext::set_entity_push`]).
397    entity_push: bool,
398    /// The switch as the sim has it.
399    entity_push_sim: bool,
400    /// The dialog open now (26.1+ `show_dialog`).
401    dialog: Option<Arc<crate::dialog::Dialog>>,
402    /// Dialog events since the behaviour's last tick, and those of its current tick (kept out
403    /// of [`TickEvents`]: almost always empty, they cost nothing per tick this way).
404    dialogs_pending: Vec<crate::dialog::DialogEvent>,
405    dialogs: Vec<crate::dialog::DialogEvent>,
406    /// The wire's block-prediction sequence after the last packets written (1.19+).
407    sequence: Option<i32>,
408    /// Test hook: this tick's look, set instead of a rotation step.
409    #[cfg(test)]
410    forced_look: Option<(f32, f32)>,
411}
412
413/// Behaviour bookkeeping of the engine.
414#[derive(Debug, Default)]
415struct BehaviorState {
416    started: bool,
417    failed: bool,
418    /// The behaviour reported [`Behavior::running`] `false`.
419    done: bool,
420}
421
422/// The core plus the behaviour's lifecycle.
423#[derive(Debug)]
424pub(crate) struct Engine<S> {
425    pub core: Core,
426    pub sim: S,
427    state: BehaviorState,
428}
429
430impl Core {
431    fn new(opts: CoreOptions) -> Self {
432        let rotation = Rotation::new(opts.sensitivity);
433        // a version module exists only with its feature, which enables its inventory
434        let inv = ghast_inventory::Inventory::new(opts.inventory)
435            .expect("the version's feature enables its ghast-inventory feature");
436        let entity_push = opts.entity_push;
437        Core {
438            opts,
439            tick: 0,
440            entity_id: 0,
441            joined: false,
442            teleported_once: false,
443            ready: false,
444            pose: Pose::default(),
445            sent: Pose::default(),
446            rotation,
447            aimed: false,
448            controls: Controls::default(),
449            health: Health::default(),
450            dead: false,
451            abilities: Abilities::default(),
452            game_mode: GameMode::default(),
453            held_slot: 0,
454            sent_slot: 0,
455            open_window: 0,
456            dimension: String::new(),
457            respawn_screen: true,
458            pending: TickEvents::default(),
459            current: TickEvents::default(),
460            out: Vec::with_capacity(16),
461            last_inbound: None,
462            silent: false,
463            quit: None,
464            status: String::new(),
465            hands: Hands::default(),
466            buttons: Buttons::default(),
467            inv,
468            turned: false,
469            effects: std::collections::BTreeMap::new(),
470            aqua_affinity: false,
471            broken_now: Vec::new(),
472            pick: PickList::default(),
473            want_flying: None,
474            held_turns: 0,
475            swings: 0,
476            level_load_started: false,
477            client_loaded: false,
478            chat_session_due: false,
479            gate_tick: false,
480            #[cfg(test)]
481            test_gate: None,
482            load_wait: 0,
483            near_loaded: 0,
484            origin: Instant::now(),
485            entity_push,
486            entity_push_sim: entity_push,
487            dialog: None,
488            dialogs_pending: Vec::new(),
489            dialogs: Vec::new(),
490            sequence: None,
491            #[cfg(test)]
492            forced_look: None,
493        }
494    }
495
496    /// A new client player entity (join, respawn): `lastReported*` zero, nothing held down,
497    /// waiting for the server's position.
498    fn reset_player(&mut self, why: &str) {
499        self.teleported_once = false;
500        self.ready = false;
501        self.pose = Pose::default();
502        self.sent = Pose::default();
503        self.controls = Controls::default();
504        self.aimed = false;
505        self.open_window = 0;
506        self.dead = false;
507        self.hands.reset();
508        self.buttons = Buttons::default();
509        self.effects.clear();
510        // A new level waits for its chunks again (1.21.4+ LevelLoadTracker).
511        self.level_load_started = false;
512        self.client_loaded = false;
513        self.load_wait = 0;
514        self.near_loaded = 0;
515        log::debug!(
516            "[{}] t{} {why}: waiting for the server position",
517            self.opts.name,
518            self.tick
519        );
520    }
521
522    /// The last inbound time in nanoseconds from the core's origin.
523    fn now_nanos(&self) -> i64 {
524        self.last_inbound.map_or(0, |t| {
525            t.saturating_duration_since(self.origin).as_nanos() as i64
526        })
527    }
528
529    fn column_loaded(&self, world: &dyn WorldView) -> bool {
530        // BlockPos(posX, 0, posZ) floors the coordinates.
531        let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
532        let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
533        world.is_column_loaded(cx, cz)
534    }
535
536    /// The player's column and its 8 neighbours are loaded (`RenderSection.hasAllNeighbors`:
537    /// the condition for vanilla's first compile of the player's section).
538    fn neighbourhood_loaded(&self, world: &dyn WorldView) -> bool {
539        let cx = (self.pose.pos.x.floor() as i64 >> 4) as i32;
540        let cz = (self.pose.pos.z.floor() as i64 >> 4) as i32;
541        (-1..=1).all(|dx| (-1..=1).all(|dz| world.is_column_loaded(cx + dx, cz + dz)))
542    }
543}
544
545/// The held stack's dig / use facts.
546fn held_item<W: Sim + ?Sized>(
547    inv: &ghast_inventory::Inventory,
548    sim: &W,
549) -> Option<hands::HeldItem> {
550    let s = inv.held()?;
551    let id = u16::try_from(s.id()).ok()?;
552    let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
553    Some(sim.item_use_facts(s, false, sim.held_item(id, count, efficiency(s))))
554}
555
556/// Whether rays hit the entity (`Entity.collides`): living entities, players,
557/// paintings and the solid objects (boats, minecarts, TNT, falling blocks, item frames, armor
558/// stands, leash knots, end crystals); not items, orbs, projectiles.
559fn collidable(e: &ghast_entity::Entity) -> bool {
560    use ghast_entity::{EntityClass, EntityType};
561    match e.class() {
562        EntityClass::Player | EntityClass::Mob | EntityClass::Painting => true,
563        EntityClass::Item | EntityClass::ExperienceOrb => false,
564        EntityClass::Object => match e.entity_type() {
565            // 63: the large fireball (`EntityFireball.canBeCollidedWith`; small fireballs and
566            // wither skulls are not).
567            EntityType::LegacyObject(t) => {
568                matches!(t, 1 | 10 | 50 | 51 | 63 | 70 | 71 | 77 | 78)
569            }
570            #[cfg(feature = "v1_16_5")]
571            EntityType::Registry(_) => {
572                ghast_entity::v1_16_5::info(e.entity_type()).is_some_and(|i| {
573                    matches!(
574                        i.name,
575                        "boat"
576                            | "fireball"
577                            | "tnt"
578                            | "end_crystal"
579                            | "falling_block"
580                            | "item_frame"
581                            | "leash_knot"
582                            | "armor_stand"
583                            | "shulker_bullet"
584                    ) || i.name.contains("minecart")
585                })
586            }
587            _ => false,
588        },
589        // A class added for a newer version: not targetable until it is classified here.
590        _ => false,
591    }
592}
593
594/// 1.8 – 1.16.5: whether the crosshair pick can hit `e` (rays hit it, not a spectator) and its
595/// targeting margin from the type's size table.
596pub(crate) fn legacy_pick_margin(
597    ents: &ghast_entity::Entities,
598    e: &ghast_entity::Entity,
599) -> Option<f32> {
600    let spectator = e.is_player()
601        && ents
602            .player_info(&e.uuid())
603            .is_some_and(|p| p.game_mode == 3);
604    (collidable(e) && !spectator).then(|| e.targeting_margin())
605}
606
607/// The pickable entities near the eyes as the oracle-proven crosshair pick takes them, with
608/// each one's id and position alongside (empty without an entity tracker).
609#[derive(Debug, Default)]
610struct PickList {
611    entities: Vec<ghast_physics::pick::PickEntity>,
612    ids: Vec<(i32, Vec3)>,
613}
614
615impl PickList {
616    /// Fills the list: tracked entities within 16 blocks of `eyes` (vanilla's search box only
617    /// drops entities the ray cannot hit, so this radius loses none) that the version's pick can
618    /// hit ([`Sim::pick_margin`]), not ourselves.
619    fn fill(&mut self, w: &(impl Sim + ?Sized), caps: &Capabilities, eyes: Vec3) {
620        self.entities.clear();
621        self.ids.clear();
622        if let Some(ents) = w.entities() {
623            self.fill_from(w, ents, caps, eyes);
624        }
625    }
626
627    #[inline(never)]
628    fn fill_from(
629        &mut self,
630        w: &(impl Sim + ?Sized),
631        ents: &ghast_entity::Entities,
632        caps: &Capabilities,
633        eyes: Vec3,
634    ) {
635        use ghast_entity::Entity;
636        let me = ents.self_id();
637        let root = |mut id: i32| {
638            for _ in 0..16 {
639                match ents.get(id).and_then(Entity::vehicle) {
640                    Some(v) => id = v,
641                    None => break,
642                }
643            }
644            id
645        };
646        let riding = ents.me().and_then(Entity::vehicle);
647        let my_root = me.map(root);
648        for e in ents.within([eyes.x, eyes.y, eyes.z], 16.0) {
649            if Some(e.id()) == me {
650                continue;
651            }
652            let Some(pick_radius) = w.pick_margin(e) else {
653                continue;
654            };
655            let Some(b) = e.bounding_box() else {
656                continue;
657            };
658            // 1.8: the vehicle we sit on; 1.9+: anything with our root vehicle.
659            let same_root_vehicle = if caps.entity_pick_root_vehicle {
660                my_root.is_some_and(|r| root(e.id()) == r)
661            } else {
662                riding == Some(e.id())
663            };
664            self.entities.push(ghast_physics::pick::PickEntity {
665                bb: ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]),
666                pick_radius,
667                same_root_vehicle,
668            });
669            let p = e.position();
670            self.ids.push((e.id(), Vec3::new(p[0], p[1], p[2])));
671        }
672    }
673
674    /// The pick result as the hands take it: the block (none when an entity is in front or
675    /// beyond the 3-block limit) and the entity.
676    fn split(&self, t: Crosshair, eyes: Vec3) -> (Option<BlockHit>, Option<hands::EntityHit>) {
677        match t {
678            Crosshair::Block(b) => (b, None),
679            Crosshair::Entity { index, hit } => {
680                let (id, entity_pos) = self.ids[index];
681                let d = [hit.x - eyes.x, hit.y - eyes.y, hit.z - eyes.z];
682                let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
683                (
684                    None,
685                    Some(hands::EntityHit {
686                        id,
687                        hit,
688                        entity_pos,
689                        distance,
690                    }),
691                )
692            }
693        }
694    }
695}
696
697/// The player's box at `pos` for the pick's entity search (standing 0.6 x 1.8: the search
698/// box only filters out entities the ray cannot reach, so the pose's exact box is not needed).
699fn pick_box(pos: Vec3) -> ghast_physics::math::Aabb {
700    let h = f64::from(0.6f32 / 2.0);
701    ghast_physics::math::Aabb::new(
702        pos.x - h,
703        pos.y,
704        pos.z - h,
705        pos.x + h,
706        pos.y + f64::from(1.8f32),
707        pos.z + h,
708    )
709}
710
711/// The off-hand stack's facts (1.9+).
712fn off_held_item<W: Sim + ?Sized>(
713    inv: &ghast_inventory::Inventory,
714    sim: &W,
715) -> Option<hands::HeldItem> {
716    let s = inv.offhand()?;
717    let id = u16::try_from(s.id()).ok()?;
718    let count = u8::try_from(s.count().clamp(0, 255)).unwrap_or(0);
719    Some(sim.item_use_facts(s, true, sim.held_item(id, count, 0)))
720}
721
722/// Efficiency level of a stack (see [`enchant_level`]).
723fn efficiency(s: &ghast_inventory::Stack) -> u8 {
724    enchant_level(s, 32, "minecraft:efficiency")
725}
726
727/// An enchantment level from the stack NBT: the 1.8 `ench` list with numeric ids, or the 1.13+
728/// `Enchantments` list with names. Parsed only when the stack has NBT.
729fn enchant_level(s: &ghast_inventory::Stack, id_1_8: i32, name: &str) -> u8 {
730    use ghast_protocol::nbt::Tag;
731    let Some(root) = s.nbt().and_then(|n| n.parse().ok().flatten()) else {
732        return 0;
733    };
734    let Some(c) = root.tag.as_compound() else {
735        return 0;
736    };
737    let num = |t: Option<&Tag>| match t {
738        Some(Tag::Short(v)) => i32::from(*v),
739        Some(Tag::Int(v)) => *v,
740        Some(Tag::Byte(v)) => i32::from(*v),
741        _ => -1,
742    };
743    for key in ["ench", "Enchantments"] {
744        if let Some(Tag::List(l)) = c.get(key) {
745            for e in l.items.iter().filter_map(Tag::as_compound) {
746                let hit = match e.get("id") {
747                    Some(Tag::String(n)) => n == name,
748                    other => num(other) == id_1_8,
749                };
750                if hit {
751                    return u8::try_from(num(e.get("lvl")).clamp(0, 255)).unwrap_or(0);
752                }
753            }
754        }
755    }
756    0
757}
758
759impl<S: Sim> Engine<S> {
760    pub(crate) fn new(opts: CoreOptions, mut sim: S) -> Self {
761        sim.set_entity_push(opts.entity_push);
762        Engine {
763            core: Core::new(opts),
764            sim,
765            state: BehaviorState::default(),
766        }
767    }
768
769    /// A chat session was started in the wire layer: announce it on the next tick, from the
770    /// connection tick like vanilla (`ClientPacketListener.tick` → `setKeyPair`).
771    pub(crate) fn request_chat_session(&mut self) {
772        self.core.chat_session_due = true;
773    }
774
775    /// A join game arrived and no reconfiguration dropped the level since.
776    pub(crate) fn joined(&self) -> bool {
777        self.core.joined
778    }
779
780    /// Bytes arrived from the server (liveness for the silent-server guard).
781    pub(crate) fn note_inbound(&mut self, now: Instant) {
782        self.core.last_inbound = Some(now);
783    }
784
785    /// Time of the last inbound bytes.
786    pub(crate) fn last_inbound(&self) -> Option<Instant> {
787        self.core.last_inbound
788    }
789
790    /// The wire layer's prediction sequence after writing packets.
791    pub(crate) fn note_sequence(&mut self, sequence: Option<i32>) {
792        self.core.sequence = sequence;
793    }
794
795    /// The bot's name (for logs).
796    pub(crate) fn name(&self) -> &str {
797        &self.core.opts.name
798    }
799
800    /// Queues a raw packet copy for the behaviour's next tick.
801    pub(crate) fn push_raw(&mut self, p: RawInbound) {
802        let ev = &mut self.core.pending;
803        if ev.raw.len() < MAX_PENDING_RAW {
804            ev.raw.push(p);
805        } else {
806            ev.raw_dropped += 1;
807        }
808    }
809
810    /// The raw packet ids the behaviour wants (none once it failed or finished).
811    pub(crate) fn raw_packets<B: Behavior>(&self, b: &B) -> std::borrow::Cow<'static, [i32]> {
812        if self.state.failed || self.state.done {
813            std::borrow::Cow::Borrowed(&[])
814        } else {
815            b.raw_packets(self.core.opts.caps.version)
816        }
817    }
818
819    /// The inventory (the connection feeds it its packets).
820    pub(crate) fn inventory_mut(&mut self) -> &mut ghast_inventory::Inventory {
821        &mut self.core.inv
822    }
823
824    /// Outbound packets produced since the last call, in send order.
825    pub(crate) fn outbound(&mut self) -> &mut Vec<Outbound> {
826        &mut self.core.out
827    }
828
829    /// Set when the behaviour asked to disconnect.
830    pub(crate) fn quit_requested(&self) -> Option<&str> {
831        self.core.quit.as_deref()
832    }
833
834    pub(crate) fn core_name(&self) -> &str {
835        &self.core.opts.name
836    }
837
838    pub(crate) fn tick_count(&self) -> u64 {
839        self.core.tick
840    }
841
842    /// Applies one inbound packet (except disconnect and compression, which the connection
843    /// handles).
844    pub(crate) fn handle(&mut self, p: Inbound) {
845        let c = &mut self.core;
846        let sim = &mut self.sim;
847        match p {
848            Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
849            Inbound::JoinGame(j) => {
850                c.entity_id = j.entity_id;
851                // LocalPlayer's main arm comes from the client option.
852                sim.set_main_arm_left(c.opts.settings.main_hand == 0);
853                c.game_mode = j.game_mode;
854                c.respawn_screen = j.respawn_screen;
855                // A join always creates a new client world (the world itself was cleared by
856                // the world packet routing).
857                c.dimension = j.dimension;
858                c.joined = true;
859                c.pending.joined = true;
860                // The level's loading screen replaces any dialog.
861                c.dialog = None;
862                c.health = Health::default();
863                c.abilities = Abilities::default();
864                c.reset_player("join game");
865                sim.reset_player();
866                sim.spectator(c.game_mode == GameMode::Spectator);
867                // ClientPlayNetworkHandler.onGameJoin: settings, then the brand (1.20.2+ sends
868                // both in the configuration state instead).
869                if !c.opts.caps.configuration_state {
870                    c.out.push(Outbound::Settings(c.opts.settings.clone()));
871                    if let Some(brand) = &c.opts.brand {
872                        c.out.push(Outbound::Brand(brand.clone()));
873                    }
874                }
875                log::info!(
876                    "[{}] joined: entity {} {:?} dimension {}",
877                    c.opts.name,
878                    c.entity_id,
879                    c.game_mode,
880                    c.dimension
881                );
882            }
883            Inbound::Respawn {
884                dimension,
885                game_mode,
886                keep,
887            } => {
888                if dimension != c.dimension {
889                    c.dimension = dimension;
890                }
891                c.game_mode = game_mode;
892                c.pending.respawned = true;
893                c.reset_player("respawn");
894                sim.respawn_player(keep);
895                sim.spectator(c.game_mode == GameMode::Spectator);
896            }
897            Inbound::Teleport(t) => {
898                if c.teleported_once {
899                    log::debug!(
900                        "[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
901                         {:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
902                        c.opts.name,
903                        c.tick,
904                        t.x,
905                        t.y,
906                        t.z,
907                        t.yaw,
908                        t.pitch,
909                        t.flags,
910                        c.sent.pos.x,
911                        c.sent.pos.y,
912                        c.sent.pos.z,
913                        c.sent.yaw,
914                        c.sent.pitch,
915                        c.sent.on_ground
916                    );
917                }
918                let (sent_before, pose_before) = (c.sent, c.pose);
919                sim.teleport(&mut c.pose, &t);
920                if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
921                    c.pending.teleports.push(TeleportEvent {
922                        teleport: t,
923                        sent_before,
924                        pose_before,
925                        after: c.pose,
926                    });
927                }
928                if let Some(id) = t.teleport_id {
929                    c.out.push(Outbound::TeleportConfirm(id));
930                }
931                c.out.push(Outbound::Move(MovePacket::PositionLook {
932                    horizontal_collision: false,
933                    pos: c.pose.pos,
934                    yaw: c.pose.yaw,
935                    pitch: c.pose.pitch,
936                    on_ground: false,
937                }));
938                // The server now has this pose; vanilla's lastReported* are not touched.
939                c.sent = Pose {
940                    on_ground: false,
941                    ..c.pose
942                };
943                if !c.teleported_once {
944                    log::debug!(
945                        "[{}] t{} spawn position {:.3} {:.3} {:.3}",
946                        c.opts.name,
947                        c.tick,
948                        c.pose.pos.x,
949                        c.pose.pos.y,
950                        c.pose.pos.z
951                    );
952                }
953                c.teleported_once = true;
954                c.pending.teleported = true;
955            }
956            Inbound::Chat(m) => {
957                if c.pending.chat.len() < MAX_PENDING_CHAT {
958                    c.pending.chat.push(m);
959                } else {
960                    c.pending.chat_dropped += 1;
961                }
962            }
963            Inbound::Health(h) => {
964                let was_dead = c.dead;
965                c.health = h;
966                sim.food(h.food);
967                // isAlive(): a dead player does not wait for its section (26.1 load gate).
968                sim.player_alive(h.health > 0.0);
969                c.pending.health_changed = true;
970                if h.health <= 0.0 && !was_dead {
971                    c.dead = true;
972                    c.pending.died = true;
973                    log::info!("[{}] t{} died", c.opts.name, c.tick);
974                }
975            }
976            Inbound::Died { entity_id } => {
977                if entity_id == c.entity_id && !c.respawn_screen {
978                    // 1.16 immediate respawn: the client respawns without a death screen.
979                    c.out.push(Outbound::Respawn);
980                }
981            }
982            Inbound::Abilities(a) => {
983                c.abilities = a;
984                c.pose.flying = a.flying();
985                sim.abilities(a);
986            }
987            Inbound::HeldSlot(s) => {
988                if (0..9).contains(&s) {
989                    // Only the inventory's selection changes; the controller's copy does not,
990                    // so the next sync echoes it (as vanilla does).
991                    if c.held_slot != s as u8 {
992                        c.hands.stop_using();
993                    }
994                    c.held_slot = s as u8;
995                }
996            }
997            Inbound::GameState { reason, value } => match reason {
998                // Weather (the 26.1 riptide reads the rain).
999                1 | 2 | 7 => sim.weather(reason, value),
1000                3 => {
1001                    c.game_mode = GameMode::from_wire(value as u8);
1002                    sim.spectator(c.game_mode == GameMode::Spectator);
1003                    if c.game_mode == GameMode::Spectator {
1004                        // Spectators cannot use items (vanilla `useItem` passes).
1005                        c.hands.stop_using();
1006                    }
1007                    c.pending.game_mode_changed = true;
1008                }
1009                // 1.15+: "immediate respawn" gamerule (1 = no respawn screen).
1010                11 if c.opts.caps.immediate_respawn_rule => c.respawn_screen = value == 0.0,
1011                // 1.21.4+ LEVEL_CHUNKS_LOAD_START: the level's chunks are on their way.
1012                13 if c.opts.caps.player_loaded_gate => {
1013                    c.level_load_started = true;
1014                    sim.level_load_start();
1015                }
1016                _ => {}
1017            },
1018            // Window confirms are answered by the inventory (exactly once).
1019            Inbound::Transaction { .. } => {}
1020            Inbound::OpenWindow(id) => c.open_window = id,
1021            Inbound::CloseWindow(_) => c.open_window = 0,
1022            Inbound::Velocity { entity_id, motion } => {
1023                if entity_id == c.entity_id {
1024                    sim.velocity(motion, false);
1025                }
1026            }
1027            Inbound::ExplosionPush(motion) => sim.velocity(motion, true),
1028            Inbound::MovementSpeed {
1029                entity_id,
1030                base,
1031                modifiers,
1032            } => {
1033                if entity_id == c.entity_id {
1034                    log::debug!(
1035                        "[{}] t{} movement speed base {base:?} modifiers {modifiers:?}",
1036                        c.opts.name,
1037                        c.tick
1038                    );
1039                    let mods: Vec<(u128, f64, u8)> = modifiers
1040                        .iter()
1041                        .map(|&(id, amount, op)| (id.as_u128(), amount, op as u8))
1042                        .collect();
1043                    sim.movement_speed(base, &mods);
1044                }
1045            }
1046            Inbound::Effect {
1047                entity_id,
1048                id,
1049                amplifier,
1050            } => {
1051                if entity_id == c.entity_id {
1052                    c.effects.insert(id, amplifier);
1053                    sim.status_effects(&c.effects);
1054                }
1055            }
1056            Inbound::EffectRemoved { entity_id, id } => {
1057                if entity_id == c.entity_id {
1058                    c.effects.remove(&id);
1059                    sim.status_effects(&c.effects);
1060                }
1061            }
1062            Inbound::EntityStatus { entity_id, status } => {
1063                // 9: the server finished our item use (eating, drinking).
1064                if entity_id == c.entity_id && status == 9 {
1065                    c.hands.stop_using();
1066                }
1067            }
1068            Inbound::Attributes {
1069                entity_id,
1070                attributes,
1071            } => {
1072                if entity_id == c.entity_id {
1073                    sim.attributes(&attributes);
1074                }
1075            }
1076            Inbound::Ping(id) => c.out.push(Outbound::Pong(id)),
1077            Inbound::ChunkBatchStart => sim.chunk_batch_start(c.now_nanos()),
1078            Inbound::ChunkBatchFinished(size) => {
1079                let per_tick = sim.chunk_batch_finished(size, c.now_nanos());
1080                c.out.push(Outbound::ChunkBatchReceived(per_tick));
1081            }
1082            Inbound::StartConfiguration => {
1083                // Vanilla drops the level and the player until the next join.
1084                c.joined = false;
1085                c.dialog = None;
1086                c.reset_player("reconfiguration");
1087                sim.drop_level();
1088            }
1089            Inbound::ResourcePackPush { id, required } => {
1090                // A client that never shows the prompt: optional packs are declined; required
1091                // ones are accepted (and reported loaded) when allowed, as the server would
1092                // otherwise disconnect.
1093                if required && c.opts.accept_required_packs {
1094                    for result in [3, 4, 0] {
1095                        c.out.push(Outbound::ResourcePackStatus { id, result });
1096                    }
1097                } else {
1098                    c.out.push(Outbound::ResourcePackStatus { id, result: 1 });
1099                }
1100            }
1101            Inbound::CookieRequest(key) => {
1102                // The wire layer fills in a stored value.
1103                c.out.push(Outbound::CookieResponse { key, value: None });
1104            }
1105            Inbound::StoreCookie { .. } => {}
1106            // The session driver ends the session (or follows the transfer).
1107            Inbound::Transfer { .. } => {}
1108            Inbound::Rotate {
1109                yaw,
1110                pitch,
1111                relative_yaw,
1112                relative_pitch,
1113            } => {
1114                // ClientPacketListener.handleRotatePlayer: set (or add), answer with a look.
1115                let yaw = if relative_yaw { c.pose.yaw + yaw } else { yaw };
1116                let pitch = if relative_pitch {
1117                    c.pose.pitch + pitch
1118                } else {
1119                    pitch
1120                };
1121                c.pose.yaw = yaw;
1122                c.pose.pitch = pitch.clamp(-90.0, 90.0);
1123                c.rotation.reset(c.pose.yaw, c.pose.pitch);
1124                c.out.push(Outbound::LookAnswer {
1125                    yaw: c.pose.yaw,
1126                    pitch: c.pose.pitch,
1127                });
1128                c.sent.yaw = c.pose.yaw;
1129                c.sent.pitch = c.pose.pitch;
1130            }
1131            Inbound::ShowDialog(d) => {
1132                log::debug!("[{}] t{} dialog \"{}\"", c.opts.name, c.tick, d.title);
1133                c.dialog = Some(d.clone());
1134                if c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
1135                    c.dialogs_pending.push(crate::dialog::DialogEvent::Shown(d));
1136                }
1137            }
1138            Inbound::ClearDialog => {
1139                if c.dialog.take().is_some() && c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
1140                    c.dialogs_pending.push(crate::dialog::DialogEvent::Cleared);
1141                }
1142            }
1143            Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
1144        }
1145    }
1146
1147    /// The interests of the behaviour (the packet filter follows them).
1148    pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
1149        if self.state.failed {
1150            Interests::NONE
1151        } else {
1152            b.interests()
1153        }
1154    }
1155
1156    /// Ends the behaviour (session over).
1157    pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
1158        if self.state.started && !self.state.failed {
1159            self.state.failed = true;
1160            let name = self.core.opts.name.clone();
1161            if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
1162                log::error!("[{name}] behaviour {} panicked in stop", b.name());
1163            }
1164        }
1165    }
1166
1167    /// One client tick at `now` (dialog commands never parse: no command tree).
1168    #[cfg(test)]
1169    #[allow(dead_code, reason = "the engine tests need every version feature")]
1170    pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
1171        self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
1172    }
1173
1174    /// One client tick at `now`; `commands` checks a dialog's command like vanilla's
1175    /// `verifyCommand` (the wire layer's command tree).
1176    pub(crate) fn tick_with<B: Behavior>(
1177        &mut self,
1178        b: &mut B,
1179        now: Instant,
1180        commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
1181    ) {
1182        let c = &mut self.core;
1183        c.tick += 1;
1184        // Per-tick packet-order guard and click timeout of the inventory.
1185        c.inv.tick();
1186        let was_ready = c.ready;
1187        // 1.21.4+ (`LocalPlayer.tick` without the old `hasChunkAt` check): once the level
1188        // loaded, the player ticks in an unloaded column too (its blocks read as void air).
1189        c.ready = c.teleported_once
1190            && ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
1191        if c.ready != was_ready {
1192            if c.ready {
1193                log::info!(
1194                    "[{}] t{} in the world at {:.3} {:.3} {:.3}",
1195                    c.opts.name,
1196                    c.tick,
1197                    c.pose.pos.x,
1198                    c.pose.pos.y,
1199                    c.pose.pos.z
1200                );
1201            } else {
1202                log::debug!(
1203                    "[{}] t{} player column not loaded: not ticking",
1204                    c.opts.name,
1205                    c.tick
1206                );
1207            }
1208        }
1209        if c.chat_session_due && c.joined {
1210            // ClientPacketListener.tick: the key pair future finished → chat_session_update,
1211            // before the level-load check.
1212            c.chat_session_due = false;
1213            c.out.push(Outbound::ChatSessionUpdate);
1214        }
1215        if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
1216            // 1.21.4+ LevelLoadTracker: after the server's "chunks load start" the level is
1217            // ready once the player's section is compiled and visible
1218            // (`isSectionCompiledAndVisible`; spectators and dead players at once); after 30 s
1219            // it lets the player in anyway. The first compile needs the 3x3 columns around the
1220            // player (`hasAllNeighbors`) and happens in a frame after the tick that received
1221            // them, so the earliest ready tick is the next one (a nearby section has no
1222            // fade-in). `player_loaded` goes out from the connection tick, before the key
1223            // handling and the player tick.
1224            c.load_wait += 1;
1225            let near = c.neighbourhood_loaded(&self.sim);
1226            c.near_loaded = if near {
1227                c.near_loaded.saturating_add(1)
1228            } else {
1229                0
1230            };
1231            // The oracle-proven gate (ghast_physics::modern::LoadGate) decides (dead players,
1232            // spectators and feet outside the build height included); "section compiled" is
1233            // ours: the nine columns on two consecutive ticks.
1234            let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
1235            #[cfg(test)]
1236            let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
1237            if self.sim.load_gate_tick(compiled, timed_out) {
1238                c.client_loaded = true;
1239                c.gate_tick = true;
1240                c.out.push(Outbound::PlayerLoaded);
1241                log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
1242            }
1243        }
1244        if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
1245            // The client player does not tick outside a loaded column (1.16 vanilla; on 1.8
1246            // the bot waits for its column as well) nor before its level loaded (1.21.4+).
1247            if c.opts.caps.sends_tick_end && c.joined {
1248                c.out.push(Outbound::TickEnd);
1249            }
1250            // Behind the level-load gate only the player's entity tick counter runs.
1251            if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
1252                self.sim.tick_unloaded();
1253            }
1254            self.sim.tick_entities(&mut c.pose);
1255            return;
1256        }
1257
1258        let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
1259        let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
1260        if silent != c.silent {
1261            c.silent = silent;
1262            if silent {
1263                log::warn!(
1264                    "[{}] t{} server silent for {} ms: behaviour on hold",
1265                    c.opts.name,
1266                    c.tick,
1267                    silent_for.unwrap_or_default().as_millis()
1268                );
1269            } else {
1270                log::info!(
1271                    "[{}] t{} server answering again: behaviour resumes",
1272                    c.opts.name,
1273                    c.tick
1274                );
1275            }
1276        }
1277
1278        if silent {
1279            // Freeze: release the keys, keep only the vanilla movement packet.
1280            c.controls = Controls::default();
1281            c.aimed = false;
1282        } else if !self.state.failed && !self.state.done {
1283            std::mem::swap(&mut c.pending, &mut c.current);
1284            c.pending.clear();
1285            if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
1286                c.dialogs.clear();
1287                std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
1288            }
1289            c.current.inventory = c.inv.drain_events();
1290            c.current.block_updates_dropped =
1291                self.sim.drain_block_updates(&mut c.current.block_updates);
1292            if c.current.inventory.player_changed {
1293                // Armour enchantments that change movement / digging.
1294                let ench = |a: usize, id: i32, name: &str| {
1295                    c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
1296                };
1297                let depth = ench(3, 8, "minecraft:depth_strider");
1298                let soul = ench(3, -1, "minecraft:soul_speed");
1299                c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
1300                self.sim.boots(depth, soul);
1301                self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
1302            }
1303            let started = self.state.started;
1304            self.state.started = true;
1305            if !started {
1306                c.rotation.reset(c.pose.yaw, c.pose.pitch);
1307            }
1308            let name = c.opts.name.clone();
1309            let result = catch_unwind(AssertUnwindSafe(|| {
1310                let held = held_item(&c.inv, &self.sim);
1311                let mut ctx = TickContext {
1312                    core: c,
1313                    world: &self.sim,
1314                    held,
1315                    crosshair: std::cell::OnceCell::new(),
1316                    commands,
1317                };
1318                if !started {
1319                    b.start(&mut ctx);
1320                }
1321                b.tick(&mut ctx);
1322                b.running()
1323            }));
1324            match result {
1325                Ok(true) => {}
1326                Ok(false) => {
1327                    self.state.done = true;
1328                    log::info!("[{name}] behaviour {} finished", b.name());
1329                }
1330                Err(_) => {
1331                    log::error!("[{name}] behaviour {} panicked: stopped", b.name());
1332                    self.stop(b, "panic");
1333                }
1334            }
1335        }
1336
1337        let c = &mut self.core;
1338        // The behaviour may have switched entity pushes for this tick's entity ticks.
1339        if c.entity_push != c.entity_push_sim {
1340            c.entity_push_sim = c.entity_push;
1341            self.sim.set_entity_push(c.entity_push);
1342        }
1343        // ClientPlayerInteractionManager.tick (syncSelectedSlot) runs before the key
1344        // processing: a held slot the server changed is echoed before any click.
1345        if c.held_slot != c.sent_slot {
1346            c.sent_slot = c.held_slot;
1347            c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
1348        }
1349        // MinecraftClient.tick key processing (a GUI takes the mouse: buttons up).
1350        {
1351            // The screen as the inventory models it (vanilla: a window the client has no
1352            // screen for opens none; a window the client closed is gone at once).
1353            let gui = c.inv.gui_open();
1354            // 26.1: the riptide strength of the held tridents, while it can matter.
1355            if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
1356                self.sim.held_use_inputs(&mut c.inv);
1357            }
1358            let eye = if c.pose.sneaking {
1359                c.opts.caps.sneak_eye_height
1360            } else {
1361                c.opts.caps.eye_height
1362            };
1363            let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
1364            let sim = &self.sim;
1365            let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
1366            let look = hands::look_vector(c.pose.yaw, c.pose.pitch);
1367            let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
1368            let (left, right) = (c.buttons.left && !gui, c.buttons.right && !gui);
1369            // GameRenderer.updateTargetedEntity before the key handling: one oracle-proven
1370            // pick for the block and the entity. With both buttons up the hands never read it
1371            // (no click, and the dig is reset whatever the target), so it is only computed
1372            // when a button is down — here, at the vanilla pick point, from this state.
1373            let (target, entity) = if left || right {
1374                c.pick.fill(sim, c.opts.caps, eyes);
1375                let crosshair = sim.crosshair_target(&PickQuery {
1376                    eyes,
1377                    rotation: (c.pose.yaw, c.pose.pitch),
1378                    look,
1379                    held: held_id,
1380                    now: true,
1381                    creative: c.game_mode == GameMode::Creative,
1382                    player_bb: pick_box(c.pose.pos),
1383                    entities: &c.pick.entities,
1384                });
1385                c.pick.split(crosshair, eyes)
1386            } else {
1387                (None, None)
1388            };
1389            let in_water = blocks(
1390                eyes.x.floor() as i32,
1391                eyes.y.floor() as i32,
1392                eyes.z.floor() as i32,
1393            )
1394            .is_some_and(|b| b.water);
1395            let held = held_item(&c.inv, sim);
1396            let mut placed = false;
1397            let first = c.out.len();
1398            let mut io = HandsIo {
1399                blocks: &blocks,
1400                target,
1401                held,
1402                held_stack: c.inv.held().cloned(),
1403                food: c.health.food,
1404                modern: c.opts.caps.combat_1_9,
1405                off_held: off_held_item(&c.inv, sim),
1406                off_stack: c.inv.offhand().cloned(),
1407                entity,
1408                factors: DigFactors {
1409                    on_ground: c.pose.on_ground,
1410                    in_water,
1411                    aqua_affinity: c.aqua_affinity,
1412                    haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
1413                    fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
1414                },
1415                sneaking: c.pose.sneaking,
1416                out: &mut c.out,
1417                broken: &mut c.broken_now,
1418                placed: &mut placed,
1419                spectator: c.game_mode == GameMode::Spectator,
1420            };
1421            c.hands.tick(left, right, &mut io);
1422            // Other placements: the server's set_slot brings the new count of the held stack.
1423            let _ = placed;
1424            predict_planting(c, sim, first);
1425        }
1426        for p in c.broken_now.drain(..) {
1427            self.sim.predict_air(p.x, p.y, p.z);
1428        }
1429        // ClientPlayerEntity.tickMovement: a flight toggle is told to the server before the move.
1430        if let Some(f) = c.want_flying.take() {
1431            let first = c.out.len();
1432            self.sim.set_flying(f, &mut c.out);
1433            if c.out.len() > first {
1434                c.pose.flying = f;
1435            } else if f && !c.pose.flying {
1436                log::debug!(
1437                    "[{}] t{} set_flying(true) refused: flight not allowed",
1438                    c.opts.name,
1439                    c.tick
1440                );
1441            }
1442        }
1443        // Rotation runs only on ticks the behaviour aimed (budgets untouched otherwise).
1444        c.turned = false;
1445        #[cfg(test)]
1446        if let Some((yaw, pitch)) = c.forced_look.take() {
1447            c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1448            c.pose.yaw = yaw;
1449            c.pose.pitch = pitch;
1450            c.aimed = false;
1451        }
1452        // The gate tick keeps the look (the loading screen held the mouse); an aim set on it
1453        // turns from the next tick.
1454        let gate_tick = std::mem::take(&mut c.gate_tick);
1455        if c.aimed && !gate_tick {
1456            let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
1457            if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
1458                // Grim RotationPlace re-checks a dig / place with the look of the movement
1459                // packet that follows it: keep the mouse still on the clicked block this tick.
1460                c.held_turns += 1;
1461            } else {
1462                c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
1463                c.pose.yaw = yaw;
1464                c.pose.pitch = pitch;
1465            }
1466            c.aimed = false;
1467        }
1468        let first = c.out.len();
1469        // 26.1 per-tick inputs: updatingUsingItem, the glider (the other versions' sims do
1470        // nothing here).
1471        // 26.1 per-tick inputs, only when something can need them: a use, a release, a jump
1472        // press, attached rockets.
1473        if self.sim.modern_inputs()
1474            && (c.hands.using_item()
1475                || c.hands.released_use().is_some()
1476                || c.controls.jump
1477                || self.sim.pre_tick_wanted())
1478        {
1479            let pre = crate::sim::PreTick {
1480                using: c.hands.use_item(),
1481                released: c.hands.released_use(),
1482                controls: c.controls,
1483                look: (c.pose.yaw, c.pose.pitch),
1484            };
1485            if !self.sim.pre_tick(&c.inv, &pre) {
1486                c.hands.stop_using();
1487            }
1488        }
1489        let using = c.hands.using_item();
1490        self.sim
1491            .step(&mut c.pose, c.controls, using, c.entity_id, &mut c.out);
1492        // ClientLevel.tickEntities: after this tick's pick and key handling, and after the
1493        // player (the first entity in the client's tick list): the other entities' ticks see
1494        // the moved player and push it (26.1).
1495        self.sim.tick_entities(&mut c.pose);
1496        c.hands.count_use_tick();
1497        for o in &c.out[first..] {
1498            let Outbound::Move(m) = o else { continue };
1499            match *m {
1500                MovePacket::Position { pos, .. } => c.sent.pos = pos,
1501                MovePacket::Look { yaw, pitch, .. } => {
1502                    c.sent.yaw = yaw;
1503                    c.sent.pitch = pitch;
1504                }
1505                MovePacket::PositionLook {
1506                    pos, yaw, pitch, ..
1507                } => {
1508                    c.sent.pos = pos;
1509                    c.sent.yaw = yaw;
1510                    c.sent.pitch = pitch;
1511                }
1512                MovePacket::Flying { .. } => {}
1513            }
1514            if matches!(
1515                m,
1516                MovePacket::Position { .. } | MovePacket::PositionLook { .. }
1517            ) {
1518                c.sent.motion = c.pose.motion;
1519            }
1520        }
1521        c.sent.on_ground = c.pose.on_ground;
1522        c.sent.sneaking = c.pose.sneaking;
1523        c.sent.sprinting = c.pose.sprinting;
1524        c.sent.flying = c.pose.flying;
1525        c.swings += count_swings(&c.out);
1526        // Minecraft.tick ends with `tick_end` (1.21.2+), after the player's packets.
1527        if c.opts.caps.sends_tick_end {
1528            c.out.push(Outbound::TickEnd);
1529        }
1530
1531        if self.state.started && !self.state.failed {
1532            let name = c.opts.name.clone();
1533            let view = TickView {
1534                core: &self.core,
1535                world: &self.sim,
1536            };
1537            if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
1538                log::error!(
1539                    "[{name}] behaviour {} panicked in after_tick: stopped",
1540                    b.name()
1541                );
1542                self.stop(b, "panic");
1543            }
1544        }
1545    }
1546}
1547
1548/// Arm swings (main or off hand) in a packet list.
1549fn count_swings(out: &[Outbound]) -> u64 {
1550    out.iter()
1551        .filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
1552        .count() as u64
1553}
1554
1555/// A read-only view after the movement step ([`Behavior::after_tick`]).
1556pub struct TickView<'a> {
1557    core: &'a Core,
1558    world: &'a dyn WorldView,
1559}
1560
1561impl std::fmt::Debug for TickView<'_> {
1562    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1563        f.debug_struct("TickView")
1564            .field("tick", &self.core.tick)
1565            .field("sent", &self.core.sent)
1566            .finish_non_exhaustive()
1567    }
1568}
1569
1570impl TickView<'_> {
1571    /// Ticks since the session started.
1572    #[must_use]
1573    pub fn tick(&self) -> u64 {
1574        self.core.tick
1575    }
1576
1577    /// The protocol version.
1578    #[must_use]
1579    pub fn version(&self) -> GameVersion {
1580        self.core.opts.caps.version
1581    }
1582
1583    /// The client pose after this tick's movement step.
1584    #[must_use]
1585    pub fn pose(&self) -> &Pose {
1586        &self.core.pose
1587    }
1588
1589    /// What the server has after this tick's movement packet (position, look, flags).
1590    #[must_use]
1591    pub fn sent(&self) -> &Pose {
1592        &self.core.sent
1593    }
1594
1595    /// The world.
1596    #[must_use]
1597    pub fn world(&self) -> &dyn WorldView {
1598        self.world
1599    }
1600
1601    /// The tracked entities (with [`Interests::ENTITIES`]).
1602    #[must_use]
1603    pub fn entities(&self) -> Option<&ghast_entity::Entities> {
1604        self.world.entities()
1605    }
1606
1607    /// The inventory and the open window.
1608    #[must_use]
1609    pub fn inventory(&self) -> &ghast_inventory::Inventory {
1610        &self.core.inv
1611    }
1612
1613    /// What the behaviour saw this tick (the events of [`TickContext::events`]).
1614    #[must_use]
1615    pub fn events(&self) -> &TickEvents {
1616        &self.core.current
1617    }
1618
1619    /// Our entity id.
1620    #[must_use]
1621    pub fn entity_id(&self) -> i32 {
1622        self.core.entity_id
1623    }
1624
1625    /// Health, food and saturation.
1626    #[must_use]
1627    pub fn health(&self) -> Health {
1628        self.core.health
1629    }
1630
1631    /// Game mode.
1632    #[must_use]
1633    pub fn game_mode(&self) -> GameMode {
1634        self.core.game_mode
1635    }
1636
1637    /// The selected hotbar slot.
1638    #[must_use]
1639    pub fn held_slot(&self) -> u8 {
1640        self.core.held_slot
1641    }
1642
1643    /// The block being broken and its progress 0 … 1.
1644    #[must_use]
1645    pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
1646        self.core.hands.mining()
1647    }
1648
1649    /// Arm swings sent so far (see [`TickContext::swings`]).
1650    #[must_use]
1651    pub fn swings(&self) -> u64 {
1652        self.core.swings
1653    }
1654
1655    /// Blocks broken so far.
1656    #[must_use]
1657    pub fn broken(&self) -> u64 {
1658        self.core.hands.broken
1659    }
1660
1661    /// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16), as
1662    /// [`TickContext::dimension`].
1663    #[must_use]
1664    pub fn dimension(&self) -> &str {
1665        &self.core.dimension
1666    }
1667
1668    /// Using the held item (eating, blocking, drawing a bow): movement input is slowed. As
1669    /// [`TickContext::using_item`].
1670    #[must_use]
1671    pub fn using_item(&self) -> bool {
1672        self.core.hands.using_item()
1673    }
1674
1675    /// The serverbound packets of this tick in write order (its actions, the movement
1676    /// packet, `tick_end`), plus the answers to packets that arrived just before it; written
1677    /// to the socket right after [`Behavior::after_tick`]. A dig shows as
1678    /// [`Outbound::Dig`](crate::common::Outbound::Dig) with its status, block and face. The
1679    /// wire layer adds per-protocol details when it writes them (sequence numbers:
1680    /// [`TickView::prediction_sequence`]).
1681    #[must_use]
1682    pub fn outbound(&self) -> &[Outbound] {
1683        &self.core.out
1684    }
1685
1686    /// [`TickContext::prediction_sequence`] (before this tick's packets are written).
1687    #[must_use]
1688    pub fn prediction_sequence(&self) -> Option<i32> {
1689        self.core.sequence
1690    }
1691}
1692
1693#[cfg(all(test, feature = "v1_8"))]
1694impl Core {
1695    /// Test hook: the held slot as both the client and the server have it (no sync packet).
1696    pub(crate) fn test_set_slot(&mut self, slot: u8) {
1697        self.held_slot = slot;
1698        self.sent_slot = slot;
1699        self.inv.select(slot);
1700    }
1701
1702    /// Test hook: the pose and the sent pose.
1703    pub(crate) fn test_poses(&mut self) -> (&mut Pose, &mut Pose) {
1704        (&mut self.pose, &mut self.sent)
1705    }
1706
1707    /// Test hook: turns held back by the post-look check.
1708    pub(crate) fn test_held_turns(&self) -> u64 {
1709        self.held_turns
1710    }
1711}
1712
1713#[cfg(all(test, feature = "v1_8"))]
1714impl TickContext<'_> {
1715    /// Test hook: this tick's look without a rotation step.
1716    pub(crate) fn test_force_look(&mut self, yaw: f32, pitch: f32) {
1717        self.core.forced_look = Some((yaw, pitch));
1718    }
1719
1720    /// Test hook: the rotation controller (to predict a step).
1721    pub(crate) fn test_rotation(&self) -> Rotation {
1722        self.core.rotation
1723    }
1724}
1725
1726/// 1.8 `SeedItem.use` / `CropItem.use` on the client: planting on the top of
1727/// its soil with air above uses one item at once (the server's set_slot follows later; it
1728/// sends none when the count already agrees). Applied to the `block_place` packets written
1729/// from `first` on. Other placements wait for the server's set_slot: predicting them needs
1730/// vanilla's full placement rules, and a wrong prediction would never be corrected.
1731fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
1732    if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
1733        return;
1734    }
1735    let mut uses = 0u8;
1736    for o in &c.out[first..] {
1737        let Outbound::Place {
1738            pos,
1739            face: crate::common::Face::Up,
1740            held: Some(held),
1741            off_hand: false,
1742            ..
1743        } = o
1744        else {
1745            continue;
1746        };
1747        // Seed item → its soil (wheat, pumpkin, melon seeds, carrot, potato: farmland;
1748        // nether wart: soul sand).
1749        let soil = match held.id() {
1750            295 | 361 | 362 | 391 | 392 => 60,
1751            372 => 88,
1752            _ => continue,
1753        };
1754        let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
1755        if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
1756            uses += 1;
1757        }
1758    }
1759    if uses > 0 {
1760        c.inv.consume_held(uses);
1761    }
1762}
1763
1764/// Whether the look `yaw`/`pitch` still points at every block dug or placed this tick (its
1765/// full cube, from the sent and the current feet, standing or sneaking eyes, with the old or the
1766/// new yaw) — the post-look check that keeps Grim's RotationPlace check satisfied.
1767fn post_look_ok(c: &Core, yaw: f32, pitch: f32) -> bool {
1768    let looks = [
1769        hands::look_vector(c.pose.yaw, pitch),
1770        hands::look_vector(yaw, pitch),
1771    ];
1772    let heights = [c.opts.caps.eye_height, c.opts.caps.sneak_eye_height];
1773    c.out
1774        .iter()
1775        .filter_map(|o| match o {
1776            Outbound::Dig {
1777                status: crate::common::DigStatus::Start | crate::common::DigStatus::Finish,
1778                pos,
1779                ..
1780            }
1781            | Outbound::Place { pos, .. } => Some(*pos),
1782            _ => None,
1783        })
1784        .all(|t| {
1785            [c.sent.pos, c.pose.pos].iter().all(|o| {
1786                heights.iter().any(|h| {
1787                    let eyes = Vec3::new(o.x, o.y + *h, o.z);
1788                    looks
1789                        .iter()
1790                        .any(|l| hands::ray_hits_cube(eyes, *l, t, ACTION_LOOK_REACH))
1791                })
1792            })
1793        })
1794}
1795
1796/// Reach of the post-look check (6 blocks).
1797const ACTION_LOOK_REACH: f64 = 6.0;
1798
1799/// The behaviour's view of the client during one tick.
1800///
1801/// Reading is free; actions are written to the server in call order before this tick's
1802/// movement packet.
1803pub struct TickContext<'a> {
1804    core: &'a mut Core,
1805    world: &'a dyn Sim,
1806    held: Option<hands::HeldItem>,
1807    /// The sent-pose crosshair, picked on the first ask: nothing a behaviour does during its
1808    /// tick changes the sent pose, the game mode or the world.
1809    crosshair: std::cell::OnceCell<(Option<BlockHit>, Option<hands::EntityHit>)>,
1810    /// Vanilla's check of a dialog command (`verifyCommand`).
1811    commands: &'a dyn Fn(&str) -> crate::dialog::CommandCheck,
1812}
1813
1814impl std::fmt::Debug for TickContext<'_> {
1815    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1816        f.debug_struct("TickContext")
1817            .field("tick", &self.core.tick)
1818            .field("pose", &self.core.pose)
1819            .finish_non_exhaustive()
1820    }
1821}
1822
1823impl TickContext<'_> {
1824    /// Ticks since the connection entered the play state.
1825    #[must_use]
1826    pub fn tick(&self) -> u64 {
1827        self.core.tick
1828    }
1829
1830    /// The protocol version of this connection.
1831    #[must_use]
1832    pub fn version(&self) -> GameVersion {
1833        self.core.opts.caps.version
1834    }
1835
1836    /// The client pose now (start of the tick, before this tick's rotation and movement).
1837    #[must_use]
1838    pub fn pose(&self) -> &Pose {
1839        &self.core.pose
1840    }
1841
1842    /// The last pose written to the server: what it judges this tick's actions against.
1843    #[must_use]
1844    pub fn sent(&self) -> &Pose {
1845        &self.core.sent
1846    }
1847
1848    /// Eye position of `pose` (standing or sneaking eye height of this version).
1849    #[must_use]
1850    pub fn eyes(&self, pose: &Pose) -> Vec3 {
1851        let v = self.core.opts.caps;
1852        pose.eyes(if pose.sneaking {
1853            v.sneak_eye_height
1854        } else {
1855            v.eye_height
1856        })
1857    }
1858
1859    /// The world (loaded chunk columns and their blocks).
1860    #[must_use]
1861    pub fn world(&self) -> &dyn WorldView {
1862        self.world
1863    }
1864
1865    /// 26.1: the client player's complete movement state as the physics holds it now (start of
1866    /// the tick): the attributes the server sent (movement speed, step height, jump strength,
1867    /// scale, ...), effects, abilities and the level's build height. Clone it to simulate
1868    /// ahead with `ghast_physics::modern::tick`. `None` on the other versions.
1869    #[cfg(ghast_modern)]
1870    #[must_use]
1871    pub fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
1872        self.world.modern_player()
1873    }
1874
1875    /// What happened since the previous tick.
1876    #[must_use]
1877    pub fn events(&self) -> &TickEvents {
1878        &self.core.current
1879    }
1880
1881    /// Our entity id.
1882    #[must_use]
1883    pub fn entity_id(&self) -> i32 {
1884        self.core.entity_id
1885    }
1886
1887    /// Arm swings (main and off hand) written so far in the session: every `arm_animation`,
1888    /// whether from [`TickContext::swing`], an action (place, dig, attack) or the held buttons
1889    /// (digging swings every tick). Includes this tick's written so far.
1890    #[must_use]
1891    pub fn swings(&self) -> u64 {
1892        self.core.swings + count_swings(&self.core.out)
1893    }
1894
1895    /// Health, food and saturation.
1896    #[must_use]
1897    pub fn health(&self) -> Health {
1898        self.core.health
1899    }
1900
1901    /// The player is dead (waiting for [`TickContext::respawn`]).
1902    #[must_use]
1903    pub fn is_dead(&self) -> bool {
1904        self.core.dead
1905    }
1906
1907    /// Game mode.
1908    #[must_use]
1909    pub fn game_mode(&self) -> GameMode {
1910        self.core.game_mode
1911    }
1912
1913    /// Abilities as the server sent them.
1914    #[must_use]
1915    pub fn abilities(&self) -> Abilities {
1916        self.core.abilities
1917    }
1918
1919    /// The server allows flight.
1920    #[must_use]
1921    pub fn can_fly(&self) -> bool {
1922        self.core.abilities.may_fly()
1923    }
1924
1925    /// The selected hotbar slot (0 … 8).
1926    #[must_use]
1927    pub fn held_slot(&self) -> u8 {
1928        self.core.held_slot
1929    }
1930
1931    /// Id of the open container window, if the server opened one.
1932    #[must_use]
1933    pub fn open_window(&self) -> Option<i32> {
1934        (self.core.open_window != 0).then_some(self.core.open_window)
1935    }
1936
1937    /// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16).
1938    #[must_use]
1939    pub fn dimension(&self) -> &str {
1940        &self.core.dimension
1941    }
1942
1943    /// The movement controls recorded for this tick.
1944    #[must_use]
1945    pub fn controls(&self) -> Controls {
1946        self.core.controls
1947    }
1948
1949    /// The rotation target.
1950    #[must_use]
1951    pub fn aim(&self) -> (f32, f32) {
1952        self.core.rotation.target()
1953    }
1954
1955    // ---- actions: written now, before this tick's movement packet ----
1956
1957    /// Sends a chat line or command (truncated to the version's limit, 100 / 256 UTF-16
1958    /// units, like vanilla).
1959    pub fn chat(&mut self, text: impl Into<String>) {
1960        self.core.out.push(Outbound::Chat(text.into()));
1961    }
1962
1963    /// Asks the server to respawn the player. Only sent while dead; returns whether it was.
1964    pub fn respawn(&mut self) -> bool {
1965        if self.core.dead {
1966            self.core.out.push(Outbound::Respawn);
1967            true
1968        } else {
1969            false
1970        }
1971    }
1972
1973    /// Selects a hotbar slot (0 … 8); sends `held_item_slot` when it changes. Out-of-range
1974    /// slots are ignored.
1975    pub fn select_slot(&mut self, slot: u8) {
1976        if slot < 9 {
1977            if self.core.held_slot != slot {
1978                self.core.hands.stop_using();
1979                self.core.hands.ticks_since_swing = 0;
1980            }
1981            self.core.held_slot = slot;
1982            self.core.inv.select(slot);
1983            if self.core.sent_slot != slot {
1984                self.core.sent_slot = slot;
1985                self.core.out.push(Outbound::HeldSlot(i16::from(slot)));
1986            }
1987        }
1988    }
1989
1990    /// Swings the arm (`arm_animation`).
1991    pub fn swing(&mut self) {
1992        self.core.out.push(Outbound::Swing);
1993    }
1994
1995    /// Escape hatch: queues a serverbound play packet the behaviour encoded itself (`id` and
1996    /// `body` of this session's protocol version, see [`TickContext::version`]), written as
1997    /// given in call order with the other actions, before this tick's movement packet.
1998    /// **You are responsible for protocol correctness**: the client does not look at it, so a
1999    /// packet that changes state it models (movement, held slot, windows, digging) makes the
2000    /// client and the server disagree.
2001    pub fn send_raw(&mut self, id: i32, body: impl Into<bytes::Bytes>) {
2002        self.core
2003            .out
2004            .push(Outbound::Raw(ghast_protocol::RawPacket::new(
2005                id,
2006                body.into(),
2007            )));
2008    }
2009
2010    /// [`TickContext::send_raw`] with a generated packet type (e.g. from
2011    /// `ghast::protocol::v26_2::play::serverbound`); it must belong to this session's version.
2012    /// Refused (nothing queued) unless it is a serverbound play packet.
2013    pub fn send_packet<P: ghast_protocol::Packet>(
2014        &mut self,
2015        packet: &P,
2016    ) -> Result<(), ghast_protocol::EncodeError> {
2017        if P::STATE != ghast_protocol::State::Play
2018            || P::DIRECTION != ghast_protocol::Direction::Serverbound
2019        {
2020            return Err(ghast_protocol::EncodeError::Invalid(
2021                "not a serverbound play packet",
2022            ));
2023        }
2024        let mut body = bytes::BytesMut::new();
2025        packet.encode(&mut body)?;
2026        self.send_raw(P::ID, body.freeze());
2027        Ok(())
2028    }
2029
2030    /// Ends the session after this tick's packets are written.
2031    pub fn disconnect(&mut self, reason: impl Into<String>) {
2032        self.core.quit = Some(reason.into());
2033    }
2034
2035    // ---- intent for this tick's movement step ----
2036
2037    /// Rotation target for this tick: the client turns toward it in whole mouse counts
2038    /// (at most 14° yaw / 10.5° pitch per tick). Call it every tick you want to turn.
2039    pub fn set_aim(&mut self, yaw: f32, pitch: f32) {
2040        self.core.rotation.set_target(yaw, pitch);
2041        self.core.aimed = true;
2042    }
2043
2044    /// Movement keys from now on (kept until changed); the physics turns them into movement
2045    /// like vanilla's `Input` (sneaking scales walking by 0.3).
2046    pub fn set_controls(&mut self, controls: Controls) {
2047        self.core.controls = controls;
2048    }
2049
2050    /// The inventory: player slots, cursor, the open window, the pending click.
2051    #[must_use]
2052    pub fn inventory(&self) -> &ghast_inventory::Inventory {
2053        &self.core.inv
2054    }
2055
2056    /// Clicks in the open screen (`window_click`, written now). Refused (nothing sent) while
2057    /// the player is turning (the look changed in the last movement step or an aim is set for
2058    /// this tick: clicks only while still) or when the inventory refuses it (one click in
2059    /// flight, same-tick packet order, unpredictable result, …). The result arrives in
2060    /// [`TickEvents::inventory`] on a later tick.
2061    pub fn click(&mut self, click: ghast_inventory::Click) -> Result<ClickTicket, ClickRefused> {
2062        if self.core.turned || self.core.aimed {
2063            return Err(ClickRefused::Turning);
2064        }
2065        let o = self
2066            .core
2067            .inv
2068            .click(click)
2069            .map_err(ClickRefused::Inventory)?;
2070        let ticket = match &o {
2071            ghast_inventory::Outgoing::Click(p) => ClickTicket {
2072                window_id: i32::from(p.window_id),
2073                action: p.action,
2074            },
2075            _ => ClickTicket {
2076                window_id: -1,
2077                action: -1,
2078            },
2079        };
2080        self.core.out.push(Outbound::Inventory(o));
2081        Ok(ticket)
2082    }
2083
2084    /// Renames the item in the open anvil (26.1 `rename_item`, written now; nothing is sent
2085    /// when the name did not change or the input slot is empty). An empty name removes a
2086    /// custom name.
2087    pub fn anvil_rename(&mut self, name: &str) -> Result<(), ClickRefused> {
2088        #[cfg(ghast_modern)]
2089        if let Some(o) = self
2090            .core
2091            .inv
2092            .anvil_rename_modern(name)
2093            .map_err(ClickRefused::Inventory)?
2094        {
2095            self.core.out.push(Outbound::Inventory(o));
2096        }
2097        #[cfg(not(ghast_modern))]
2098        let _ = name;
2099        Ok(())
2100    }
2101
2102    /// Selects a banner pattern in the open loom (26.1 `container_button_click`, written now;
2103    /// nothing is sent for a pattern the loom does not offer).
2104    pub fn select_loom_pattern(&mut self, index: i32) -> Result<(), ClickRefused> {
2105        #[cfg(ghast_modern)]
2106        if let Some(o) = self
2107            .core
2108            .inv
2109            .select_loom_pattern_modern(index)
2110            .map_err(ClickRefused::Inventory)?
2111        {
2112            self.core.out.push(Outbound::Inventory(o));
2113        }
2114        #[cfg(not(ghast_modern))]
2115        let _ = index;
2116        Ok(())
2117    }
2118
2119    /// Selects a trade in the open villager screen (26.1 `select_trade`, written now; the
2120    /// payment slots are refilled like the real screen).
2121    pub fn select_trade(&mut self, index: i32) -> Result<(), ClickRefused> {
2122        #[cfg(ghast_modern)]
2123        {
2124            let o = self
2125                .core
2126                .inv
2127                .select_trade_modern(index)
2128                .map_err(ClickRefused::Inventory)?;
2129            self.core.out.push(Outbound::Inventory(o));
2130        }
2131        #[cfg(not(ghast_modern))]
2132        let _ = index;
2133        Ok(())
2134    }
2135
2136    /// Opens the player inventory GUI (1.8: the "open inventory" client command; 1.16: nothing
2137    /// is sent). Window 0 clicks need it open.
2138    pub fn open_inventory(&mut self) -> Result<(), ClickRefused> {
2139        if let Some(o) = self
2140            .core
2141            .inv
2142            .open_inventory()
2143            .map_err(ClickRefused::Inventory)?
2144        {
2145            self.core.out.push(Outbound::Inventory(o));
2146        }
2147        Ok(())
2148    }
2149
2150    /// Closes the open GUI (`close_window` with its id; 0 for the player inventory).
2151    pub fn close_window(&mut self) -> Result<(), ClickRefused> {
2152        let o = self.core.inv.close().map_err(ClickRefused::Inventory)?;
2153        self.core.out.push(Outbound::Inventory(o));
2154        // Vanilla closeHandledScreen: the container ends on the client too.
2155        self.core.open_window = 0;
2156        Ok(())
2157    }
2158
2159    /// Mouse buttons from now on (kept until changed; released by a join, a respawn or an
2160    /// open window). Left held mines what the crosshair is on, right held uses / places
2161    /// (vanilla's key processing, after the behaviour and before the movement packet).
2162    ///
2163    /// **Entities are invisible without [`Interests::ENTITIES`]:** the crosshair then sees
2164    /// blocks only (a player or mob in front of the block does not stop the dig and cannot be
2165    /// attacked) and nothing pushes the bot. Ask for the interest when other entities matter.
2166    pub fn set_buttons(&mut self, buttons: Buttons) {
2167        self.core.buttons = buttons;
2168    }
2169
2170    /// **Not vanilla when off**: whether other entities push the player from now on (default
2171    /// on, see [`crate::Client::entity_push`]). Takes effect on this tick's entity ticks; a
2172    /// no-op on versions whose client does not push the player (1.8.9, 1.12.2, 1.16.5).
2173    pub fn set_entity_push(&mut self, on: bool) {
2174        self.core.entity_push = on;
2175    }
2176
2177    /// Whether other entities push the player ([`TickContext::set_entity_push`]).
2178    #[must_use]
2179    pub fn entity_push(&self) -> bool {
2180        self.core.entity_push
2181    }
2182
2183    /// The dialog the server has open now (26.1+, only with [`Interests::DIALOGS`]; see
2184    /// [`crate::dialog`]).
2185    #[must_use]
2186    pub fn dialog(&self) -> Option<&crate::dialog::Dialog> {
2187        self.core.dialog.as_deref()
2188    }
2189
2190    /// Dialogs the server showed and closed since the behaviour's previous tick, in arrival
2191    /// order (26.1+, only with [`Interests::DIALOGS`]; [`TickContext::dialog`] is the one open
2192    /// now). Like [`TickContext::events`], kept while the behaviour is on hold.
2193    #[must_use]
2194    pub fn dialog_events(&self) -> &[crate::dialog::DialogEvent] {
2195        &self.core.dialogs
2196    }
2197
2198    /// Answers the open dialog the way vanilla does for that button (or Escape): the packets
2199    /// vanilla sends are written now, in call order with the other actions (`chat_command`
2200    /// for a command that needs no confirmation, `custom_click_action` for a custom action;
2201    /// client-only actions send nothing), and the dialog closes, stays or is replaced as its
2202    /// `after_action` and the action say.
2203    pub fn answer_dialog(
2204        &mut self,
2205        answer: &crate::dialog::DialogAnswer,
2206    ) -> Result<crate::dialog::DialogOutcome, crate::dialog::DialogRefused> {
2207        use crate::dialog::{CommandCheck, DialogOutcome, DialogRefused, DialogSent, Effect, Next};
2208        let d = self.core.dialog.clone().ok_or(DialogRefused::NoDialog)?;
2209        let (effect, mut next) = crate::dialog::resolve(&d, answer)?;
2210        let sent = match effect {
2211            Effect::Nothing => DialogSent::Nothing,
2212            Effect::Custom { id, payload } => {
2213                self.core.out.push(Outbound::CustomClickAction {
2214                    id: id.clone(),
2215                    payload: crate::dialog::payload_nbt(payload.as_ref()),
2216                });
2217                DialogSent::Custom(id)
2218            }
2219            Effect::Command(command) => match ((self.commands)(&command), answer.confirms()) {
2220                (CommandCheck::NoIssues, _)
2221                | (CommandCheck::ParseErrors | CommandCheck::PermissionsRequired, true) => {
2222                    self.core.out.push(Outbound::DialogCommand(command.clone()));
2223                    DialogSent::Command(command)
2224                }
2225                (CommandCheck::SignatureRequired, true) => {
2226                    // "Suggest command": the player sends it from the chat line.
2227                    self.core.out.push(Outbound::Chat(format!("/{command}")));
2228                    DialogSent::Command(command)
2229                }
2230                (check, _) => {
2231                    // The confirmation screen returns to the dialog when cancelled.
2232                    next = Next::Stay;
2233                    DialogSent::CommandHeld { command, check }
2234                }
2235            },
2236        };
2237        let (open, waiting) = match next {
2238            Next::Stay => (Some(d.clone()), false),
2239            Next::Closed => (None, false),
2240            Next::Waiting => (None, true),
2241            Next::Open(n) => (Some(n), false),
2242        };
2243        if let Some(n) = &open
2244            && !Arc::ptr_eq(n, &d)
2245        {
2246            self.core
2247                .dialogs_pending
2248                .push(crate::dialog::DialogEvent::Shown(n.clone()));
2249        }
2250        self.core.dialog = open.clone();
2251        Ok(DialogOutcome {
2252            sent,
2253            open,
2254            waiting,
2255        })
2256    }
2257
2258    /// The buttons held.
2259    #[must_use]
2260    pub fn buttons(&self) -> Buttons {
2261        self.core.buttons
2262    }
2263
2264    /// The crosshair as the server judges it: vanilla's pick (block at the game mode's reach,
2265    /// then the entity ray) along the **sent** look from the sent eyes.
2266    fn sent_crosshair(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
2267        *self.crosshair.get_or_init(|| self.pick_sent())
2268    }
2269
2270    fn pick_sent(&self) -> (Option<BlockHit>, Option<hands::EntityHit>) {
2271        let s = &self.core.sent;
2272        let v = self.core.opts.caps;
2273        let eye = if s.sneaking {
2274            v.sneak_eye_height
2275        } else {
2276            v.eye_height
2277        };
2278        let eyes = Vec3::new(s.pos.x, s.pos.y + eye, s.pos.z);
2279        let mut list = PickList::default();
2280        list.fill(self.world, v, eyes);
2281        let t = self.world.crosshair_target(&PickQuery {
2282            eyes,
2283            rotation: (s.yaw, s.pitch),
2284            look: hands::look_vector(s.yaw, s.pitch),
2285            held: None,
2286            now: false,
2287            creative: self.core.game_mode == GameMode::Creative,
2288            player_bb: pick_box(s.pos),
2289            entities: &list.entities,
2290        });
2291        list.split(t, eyes)
2292    }
2293
2294    /// The block the crosshair is on as the server judges it (from the sent pose): `None` when
2295    /// nothing is in reach or an entity is in front of it.
2296    ///
2297    /// **Entities count only with [`Interests::ENTITIES`]:** without entity tracking this is a
2298    /// block pick that looks through players and mobs (and nothing pushes the bot).
2299    #[must_use]
2300    pub fn target(&self) -> Option<BlockHit> {
2301        self.sent_crosshair().0
2302    }
2303
2304    /// The tracked entities (behaviours that ask for [`Interests::ENTITIES`]).
2305    #[must_use]
2306    pub fn entities(&self) -> Option<&ghast_entity::Entities> {
2307        self.world.entities()
2308    }
2309
2310    /// The entity the crosshair is on as the server judges it (from the sent pose; vanilla's
2311    /// pick: within 3 blocks outside creative, nearer than the block hit, boxes grown by the
2312    /// type's targeting margin).
2313    #[must_use]
2314    pub fn target_entity(&self) -> Option<hands::EntityHit> {
2315        self.sent_crosshair().1
2316    }
2317
2318    /// Attacks `entity` (`use_entity` attack and the arm swing in the version's order; 1.16
2319    /// resets the attack cooldown). Refused (`false`, nothing sent) unless the sent crosshair is
2320    /// on that entity.
2321    pub fn attack(&mut self, entity: i32) -> bool {
2322        if self.target_entity().is_none_or(|e| e.id != entity) {
2323            return false;
2324        }
2325        let world = self.world;
2326        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2327        let c = &mut *self.core;
2328        let modern = c.opts.caps.combat_1_9;
2329        let mut placed = false;
2330        let mut io = HandsIo {
2331            blocks: &blocks,
2332            target: None,
2333            held: self.held,
2334            held_stack: None,
2335            food: c.health.food,
2336            modern,
2337            off_held: None,
2338            off_stack: None,
2339            entity: None,
2340            factors: DigFactors::default(),
2341            sneaking: c.pose.sneaking,
2342            out: &mut c.out,
2343            broken: &mut c.broken_now,
2344            placed: &mut placed,
2345            spectator: c.game_mode == GameMode::Spectator,
2346        };
2347        if !modern {
2348            io.out.push(Outbound::Swing);
2349        }
2350        c.hands.attack(entity, &mut io);
2351        if modern {
2352            c.out.push(Outbound::Swing);
2353        }
2354        true
2355    }
2356
2357    /// 1.16 attack strength 0 … 1 for an attack speed (4.0 for an empty hand, swords 1.6,
2358    /// axes 0.8–1.0); 1.0 on 1.8 (no cooldown).
2359    #[must_use]
2360    pub fn attack_strength(&self, attack_speed: f64) -> f32 {
2361        if self.core.opts.caps.combat_1_9 {
2362            self.core.hands.attack_strength(attack_speed)
2363        } else {
2364            1.0
2365        }
2366    }
2367
2368    /// The block being broken with the left button and its progress 0 … 1.
2369    #[must_use]
2370    pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
2371        self.core.hands.mining()
2372    }
2373
2374    /// Blocks broken so far (finish sent).
2375    #[must_use]
2376    pub fn broken(&self) -> u64 {
2377        self.core.hands.broken
2378    }
2379
2380    /// Using the held item (eating, blocking, drawing a bow): movement input is slowed.
2381    #[must_use]
2382    pub fn using_item(&self) -> bool {
2383        self.core.hands.using_item()
2384    }
2385
2386    /// 1.19+ (26.1, 26.2): the block-prediction sequence number of the last predicting packet
2387    /// written so far (`block_dig` start / finish, `block_place`, `use_item` each take the
2388    /// next one; it restarts at 0 in a new level), the number the server's
2389    /// `block_changed_ack` answers with. `None` on 1.8.9 – 1.16.5. The packets this tick
2390    /// writes are not counted yet ([`TickView::outbound`] lists them).
2391    #[must_use]
2392    pub fn prediction_sequence(&self) -> Option<i32> {
2393        self.core.sequence
2394    }
2395
2396    /// The vehicle the player rides (26.1 boats and rafts: boarded when the server's
2397    /// `set_passengers` names the player, e.g. after a right click on the boat with the
2398    /// crosshair on it; the client then moves the boat with the movement keys). Leave it with
2399    /// the sneak key (the server dismounts). `None` when not riding or on older versions.
2400    #[must_use]
2401    pub fn vehicle(&self) -> Option<crate::common::Vehicle> {
2402        self.world.vehicle()
2403    }
2404
2405    /// Riding a vehicle ([`TickContext::vehicle`]).
2406    #[must_use]
2407    pub fn is_riding(&self) -> bool {
2408        self.world.vehicle().is_some()
2409    }
2410
2411    /// Gliding with an elytra (26.1; shared flag 7: set by the client when a glide starts,
2412    /// cleared by the server on landing, in water or when the elytra breaks).
2413    #[must_use]
2414    pub fn is_gliding(&self) -> bool {
2415        self.world.gliding()
2416    }
2417
2418    /// Starts gliding the way a player does (26.1): presses jump for this tick (the controls'
2419    /// `jump`, as [`TickContext::set_controls`] would; release it on the next tick). The client
2420    /// starts a glide on a fresh jump press in the air with an elytra equipped (not on the
2421    /// ground, not flying, not in water, not on a climbable): jump must have been released on the
2422    /// tick before (a held key is not a press). Nothing happens when those conditions do not
2423    /// hold.
2424    pub fn start_gliding(&mut self) {
2425        self.core.controls.jump = true;
2426    }
2427
2428    /// The version facts of an item stack (tool speeds, block item, food, usable), as the
2429    /// hands use them for the held stack. `None` for ids outside the item id range.
2430    ///
2431    /// ```no_run
2432    /// # fn f(ctx: &ghast_client::TickContext<'_>) {
2433    /// if let Some(s) = ctx.inventory().hotbar(0) {
2434    ///     let food = ctx.item_facts(s).is_some_and(|f| f.food);
2435    /// }
2436    /// # }
2437    /// ```
2438    #[must_use]
2439    pub fn item_facts(&self, stack: &ghast_inventory::Stack) -> Option<hands::HeldItem> {
2440        let id = u16::try_from(stack.id()).ok()?;
2441        let count = u8::try_from(stack.count().clamp(0, 255)).unwrap_or(0);
2442        Some(crate::sim::held_item_facts(
2443            self.core.opts.caps.data,
2444            id,
2445            count,
2446            efficiency(stack),
2447        ))
2448    }
2449
2450    /// Break progress per tick (vanilla `calcBlockBreakingData`) of the block at `pos` dug
2451    /// with `stack` (`None` = empty hand), with the factors the left button uses now: on
2452    /// ground, eyes in water, aqua affinity, haste / mining fatigue. The block breaks once the
2453    /// progress sums to 1, so it takes about `ceil(1 / speed)` ticks; 0 = unbreakable.
2454    /// Creative mode breaks every block at once and is not reflected here. `None` when the
2455    /// column is not loaded.
2456    ///
2457    /// ```no_run
2458    /// # fn f(ctx: &ghast_client::TickContext<'_>, pos: ghast_client::BlockPos) {
2459    /// // The hotbar slot that digs `pos` fastest.
2460    /// let best = (0..9u8).max_by(|a, b| {
2461    ///     let s = |k: u8| ctx.dig_speed(pos, ctx.inventory().hotbar(k.into())).unwrap_or(0.0);
2462    ///     s(*a).total_cmp(&s(*b))
2463    /// });
2464    /// # }
2465    /// ```
2466    #[must_use]
2467    pub fn dig_speed(
2468        &self,
2469        pos: ghast_protocol::BlockPos,
2470        stack: Option<&ghast_inventory::Stack>,
2471    ) -> Option<f32> {
2472        let b = self.world.block_query(pos.x, pos.y, pos.z)?;
2473        if b.air {
2474            return Some(0.0);
2475        }
2476        let c = &*self.core;
2477        let eyes = self.eyes(&c.pose);
2478        let in_water = self
2479            .world
2480            .block_query(
2481                eyes.x.floor() as i32,
2482                eyes.y.floor() as i32,
2483                eyes.z.floor() as i32,
2484            )
2485            .is_some_and(|b| b.water);
2486        let held = stack.and_then(|s| self.item_facts(s));
2487        let factors = DigFactors {
2488            on_ground: c.pose.on_ground,
2489            in_water,
2490            aqua_affinity: c.aqua_affinity,
2491            haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
2492            fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
2493        };
2494        Some(hands::relative_hardness(&b, held.as_ref(), factors))
2495    }
2496
2497    /// Starts digging `pos` on `face` (`block_dig` start, then an arm swing), breaking it at
2498    /// once when it is instant for the held item. Refused (nothing sent, `false`) unless the
2499    /// crosshair from the sent pose is on exactly that block face.
2500    pub fn dig(&mut self, pos: ghast_protocol::BlockPos, face: crate::common::Face) -> bool {
2501        if !self
2502            .target()
2503            .is_some_and(|t| t.pos == pos && t.face == face)
2504        {
2505            return false;
2506        }
2507        let world = self.world;
2508        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2509        let c = &mut *self.core;
2510        let mut placed = false;
2511        let mut io = HandsIo {
2512            blocks: &blocks,
2513            target: None,
2514            held: self.held,
2515            held_stack: c.inv.held().cloned(),
2516            food: c.health.food,
2517            modern: c.opts.caps.combat_1_9,
2518            off_held: None,
2519            off_stack: None,
2520            entity: None,
2521            factors: DigFactors {
2522                on_ground: c.pose.on_ground,
2523                in_water: false,
2524                aqua_affinity: c.aqua_affinity,
2525                haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
2526                fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
2527            },
2528            sneaking: c.pose.sneaking,
2529            out: &mut c.out,
2530            broken: &mut c.broken_now,
2531            placed: &mut placed,
2532            spectator: c.game_mode == GameMode::Spectator,
2533        };
2534        c.hands.click_block(pos, face, &mut io);
2535        c.out.push(Outbound::Swing);
2536        true
2537    }
2538
2539    /// Right-clicks `support`'s `face` at the absolute point `hit` (`block_place`, then an arm
2540    /// swing): places the held block or activates the block. Refused (nothing sent, `false`)
2541    /// unless the crosshair from the sent pose is on exactly that block face.
2542    pub fn place(
2543        &mut self,
2544        support: ghast_protocol::BlockPos,
2545        face: crate::common::Face,
2546        hit: Vec3,
2547    ) -> bool {
2548        let Some(t) = self.target().filter(|t| t.pos == support && t.face == face) else {
2549            return false;
2550        };
2551        let world = self.world;
2552        let Some(b) = world.block_query(support.x, support.y, support.z) else {
2553            return false;
2554        };
2555        let blocks = |x: i32, y: i32, z: i32| world.block_query(x, y, z);
2556        let c = &mut *self.core;
2557        let mut placed = false;
2558        let first = c.out.len();
2559        let mut io = HandsIo {
2560            blocks: &blocks,
2561            target: None,
2562            held: self.held,
2563            held_stack: c.inv.held().cloned(),
2564            food: c.health.food,
2565            modern: c.opts.caps.combat_1_9,
2566            off_held: None,
2567            off_stack: None,
2568            entity: None,
2569            factors: DigFactors::default(),
2570            sneaking: c.pose.sneaking,
2571            out: &mut c.out,
2572            broken: &mut c.broken_now,
2573            placed: &mut placed,
2574            spectator: c.game_mode == GameMode::Spectator,
2575        };
2576        c.hands
2577            .right_click_block(BlockHit { hit, ..t }, &b, &mut io);
2578        let _ = placed;
2579        predict_planting(c, world, first);
2580        c.out.push(Outbound::Swing);
2581        true
2582    }
2583
2584    /// When the last inbound bytes arrived (a gap before a setback means lag).
2585    #[must_use]
2586    pub fn last_inbound(&self) -> Option<Instant> {
2587        self.core.last_inbound
2588    }
2589
2590    /// The yaw / pitch this tick's movement step will use, from this tick's
2591    /// [`TickContext::set_aim`] and the digs / places written so far (incl. the turn held by
2592    /// [`crate::Client::hold_turn_on_action`]). Computed on a copy: the rotation's carried
2593    /// budget does not change. Clicks of held buttons, which run after the behaviour, are not
2594    /// seen. Without an aim this tick: the current look.
2595    #[must_use]
2596    pub fn planned_look(&self) -> (f32, f32) {
2597        let c = &*self.core;
2598        let now = (c.pose.yaw, c.pose.pitch);
2599        #[cfg(test)]
2600        if let Some(l) = c.forced_look {
2601            return l;
2602        }
2603        if !c.aimed {
2604            return now;
2605        }
2606        let mut r = c.rotation;
2607        let (yaw, pitch) = r.step(c.pose.yaw, c.pose.pitch);
2608        if c.opts.hold_turn_on_action && !post_look_ok(c, yaw, pitch) {
2609            now
2610        } else {
2611            (yaw, pitch)
2612        }
2613    }
2614
2615    /// Starts or stops creative-style flight: the `abilities` packet goes out before this
2616    /// tick's movement step, like a double-tapped jump (but without the jump). Starting needs
2617    /// the server's "may fly" ability; asking for the current state sends nothing.
2618    pub fn set_flying(&mut self, flying: bool) {
2619        self.core.want_flying = Some(flying);
2620    }
2621
2622    /// Turns held back so far because they would have taken the crosshair off a block dug or
2623    /// placed on the same tick (see [`crate::Client::hold_turn_on_action`]).
2624    #[must_use]
2625    pub fn held_turns(&self) -> u64 {
2626        self.core.held_turns
2627    }
2628
2629    /// Behaviour status line (logged when it changes).
2630    pub fn status(&mut self, text: &str) {
2631        if self.core.status != text {
2632            text.clone_into(&mut self.core.status);
2633            log::info!(
2634                "[{}] t{} status: {text}",
2635                self.core.opts.name,
2636                self.core.tick
2637            );
2638        }
2639    }
2640}
2641
2642/// The engine replays of the modern versions' oracle goldens (`engine_modern_tests.rs`), compiled
2643/// once per version with that version's modules.
2644#[cfg(all(
2645    test,
2646    feature = "v1_8",
2647    feature = "v1_12_2",
2648    feature = "v1_16_5",
2649    feature = "v26_1"
2650))]
2651#[path = "engine_tests_26_1.rs"]
2652mod tests_26_1;
2653
2654#[cfg(all(
2655    test,
2656    feature = "v1_8",
2657    feature = "v1_12_2",
2658    feature = "v1_16_5",
2659    feature = "v26_1",
2660    feature = "v26_2"
2661))]
2662#[path = "engine_tests_26_2.rs"]
2663mod tests_26_2;
2664
2665#[cfg(all(
2666    test,
2667    feature = "v1_8",
2668    feature = "v1_12_2",
2669    feature = "v1_16_5",
2670    feature = "v26_1"
2671))]
2672mod tests {
2673    use super::*;
2674    use crate::common::Teleport;
2675    use crate::common::{ChatPosition, EntityAction, JoinGame};
2676    use ghast_protocol::RawPacket;
2677
2678    pub(super) fn opts(version: GameVersion) -> CoreOptions {
2679        CoreOptions {
2680            name: "test".into(),
2681            caps: version.caps(),
2682            settings: ClientSettings::default(),
2683            brand: Some("vanilla".into()),
2684            sensitivity: 0.5,
2685            silent_hold: Duration::from_millis(1500),
2686            hold_turn_on_action: true,
2687            accept_required_packs: true,
2688            entity_push: true,
2689            inventory: match version {
2690                GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
2691                GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
2692                _ => ghast_inventory::Version::V1_16_5,
2693            },
2694        }
2695    }
2696
2697    /// A 1.8.9 engine (physics) or a 1.16.5 one (stand-still mover).
2698    pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
2699        let sim: Box<dyn Sim> = match version {
2700            GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
2701            GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
2702            GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
2703            #[cfg(feature = "v26_2")]
2704            GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
2705            _ => Box::new(crate::sim::Sim16::new()),
2706        };
2707        Engine::new(opts(version), sim)
2708    }
2709
2710    /// Loads the column of chunk (x, z) the way the connection does.
2711    pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
2712        let raw = match e.core.opts.caps.version {
2713            GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
2714            GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
2715            GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
2716            #[cfg(feature = "v26_2")]
2717            GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
2718            _ => crate::sim::test_chunks::v1_16_5(x, z),
2719        };
2720        e.sim.world_packet(&raw).unwrap();
2721    }
2722
2723    pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
2724        e.handle(Inbound::JoinGame(JoinGame {
2725            entity_id: 7,
2726            game_mode: GameMode::Survival,
2727            dimension: "0".into(),
2728            hardcore: false,
2729            dimension_nbt: None,
2730            respawn_screen: true,
2731        }));
2732        // The player's column and its neighbours (1.21.4+ loads the level only with all nine).
2733        for x in -1..=1 {
2734            for z in -1..=1 {
2735                load(e, x, z);
2736            }
2737        }
2738        e.handle(Inbound::Teleport(Teleport {
2739            x: 8.5,
2740            y: 64.0,
2741            z: 8.5,
2742            yaw: 90.0,
2743            pitch: 0.0,
2744            flags: 0,
2745            teleport_id: None,
2746            ..Default::default()
2747        }));
2748        // 1.21.4+: the server says the level's chunks are coming (game event 13).
2749        e.handle(Inbound::GameState {
2750            reason: 13,
2751            value: 0.0,
2752        });
2753        // The nine columns arrived before the previous tick: the level loads on the next one.
2754        e.core.near_loaded = 1;
2755        e.outbound().clear();
2756    }
2757
2758    /// Records the tick's packets as names.
2759    pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
2760        let v = out
2761            .iter()
2762            .map(|o| match o {
2763                Outbound::Move(m) => m.trace_id(),
2764                Outbound::Chat(_) => "chat",
2765                Outbound::HeldSlot(_) => "held_slot",
2766                Outbound::Swing => "swing",
2767                Outbound::EntityAction { .. } => "entity_action",
2768                Outbound::KeepAlive(_) => "keep_alive",
2769                Outbound::Transaction { .. } => "transaction",
2770                Outbound::TeleportConfirm(_) => "teleport_confirm",
2771                Outbound::Respawn => "respawn",
2772                Outbound::Settings(_) => "settings",
2773                Outbound::Brand(_) => "brand",
2774                Outbound::Abilities { .. } => "abilities",
2775                Outbound::Dig { .. } => "block_dig",
2776                Outbound::Place { .. } | Outbound::UseItem { .. } => "block_place",
2777                Outbound::SwingOffHand => "swing_off",
2778                Outbound::UseEntity { .. } => "use_entity",
2779                Outbound::Inventory(_) => "inventory",
2780                Outbound::PlayerInput(_) => "player_input",
2781                Outbound::TickEnd => "tick_end",
2782                Outbound::PlayerLoaded => "player_loaded",
2783                Outbound::ChatSessionUpdate => "chat_session_update",
2784                Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
2785                Outbound::Pong(_) => "pong",
2786                Outbound::ResourcePackStatus { .. } => "resource_pack",
2787                Outbound::CookieResponse { .. } => "cookie_response",
2788                Outbound::LookAnswer { .. } => "C05",
2789                Outbound::VehicleMove { .. } => "vehicle_move",
2790                Outbound::SteerBoat { .. } => "steer_boat",
2791                Outbound::CustomClickAction { .. } => "custom_click_action",
2792                Outbound::DialogCommand(_) => "chat_command",
2793                Outbound::Raw(_) => "raw",
2794            })
2795            .collect();
2796        out.clear();
2797        v
2798    }
2799
2800    pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
2801    impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
2802        fn tick(&mut self, ctx: &mut TickContext<'_>) {
2803            (self.0)(ctx);
2804        }
2805    }
2806
2807    #[test]
2808    fn join_sends_settings_then_brand() {
2809        let mut e = engine(GameVersion::V1_8_9);
2810        e.handle(Inbound::JoinGame(JoinGame {
2811            entity_id: 1,
2812            game_mode: GameMode::Creative,
2813            dimension: "0".into(),
2814            hardcore: false,
2815            dimension_nbt: None,
2816            respawn_screen: true,
2817        }));
2818        assert_eq!(names(e.outbound()), ["settings", "brand"]);
2819    }
2820
2821    #[test]
2822    fn nothing_before_the_first_teleport() {
2823        let mut e = engine(GameVersion::V1_8_9);
2824        let mut b = Idle;
2825        let t0 = Instant::now();
2826        load(&mut e, 0, 0);
2827        e.outbound().clear();
2828        for i in 0..5 {
2829            e.tick(&mut b, t0 + Duration::from_millis(50 * i));
2830        }
2831        assert!(e.outbound().is_empty());
2832    }
2833
2834    #[test]
2835    fn teleport_reply_per_version() {
2836        let mut e = engine(GameVersion::V1_16_5);
2837        e.handle(Inbound::Teleport(Teleport {
2838            x: 1.0,
2839            y: 2.0,
2840            z: 3.0,
2841            yaw: 450.0,
2842            pitch: 100.0,
2843            flags: 0,
2844            teleport_id: Some(5),
2845            ..Default::default()
2846        }));
2847        let out = std::mem::take(e.outbound());
2848        assert_eq!(out[0], Outbound::TeleportConfirm(5));
2849        match out[1] {
2850            Outbound::Move(MovePacket::PositionLook {
2851                yaw,
2852                pitch,
2853                on_ground,
2854                ..
2855            }) => {
2856                assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
2857            }
2858            ref o => panic!("unexpected {o:?}"),
2859        }
2860        let mut e = engine(GameVersion::V1_8_9);
2861        e.handle(Inbound::Teleport(Teleport {
2862            x: 1.0,
2863            y: 2.0,
2864            z: 3.0,
2865            yaw: 450.0,
2866            pitch: 100.0,
2867            flags: 0,
2868            teleport_id: None,
2869            ..Default::default()
2870        }));
2871        let out = std::mem::take(e.outbound());
2872        assert_eq!(out.len(), 1);
2873        // 1.8 does not clamp the pitch.
2874        assert!(matches!(
2875            out[0],
2876            Outbound::Move(MovePacket::PositionLook {
2877                yaw: 90.0,
2878                pitch: 100.0,
2879                ..
2880            })
2881        ));
2882    }
2883
2884    /// The crosshair is one pick (`ghast_physics::pick::v1_8::pick_target`, oracle-proven on
2885    /// `tests/golden/1.8.9/picks.jsonl.gz`) over the tracked entities: a zombie in front is the
2886    /// target and hides the block; one hit beyond 3 blocks but before the block leaves neither
2887    /// (vanilla's miss), so the block behind it is not dug either.
2888    #[test]
2889    fn entity_pick_uses_the_tracker_and_the_proven_pick() {
2890        use ghast_protocol::v1_8::play::clientbound::id;
2891        use std::cell::Cell;
2892        let raw = |id: i32, b: Vec<u8>| RawPacket {
2893            id,
2894            body: bytes::Bytes::from(b),
2895        };
2896        let zombie = |eid: u8, x: f64| {
2897            let mut b = vec![eid, 54];
2898            for v in [x, 64.0, 8.5] {
2899                b.extend(((v * 32.0) as i32).to_be_bytes());
2900            }
2901            b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
2902            raw(id::SPAWN_ENTITY_LIVING, b)
2903        };
2904        let mut e = engine(GameVersion::V1_8_9);
2905        let mut login = 7i32.to_be_bytes().to_vec();
2906        login.extend([0, 0, 2, 20, 7]);
2907        login.extend(b"default");
2908        login.push(0);
2909        e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
2910        e.sim.set_entities(Some(ghast_entity::Config::default()));
2911        join(&mut e);
2912        // Stone at (4, 65, 8): its east face is 3.5 blocks west of the eyes (8.5, 65.62, 8.5),
2913        // which look west (yaw 90).
2914        let pos: i64 = (4 << 38) | (65 << 26) | 8;
2915        let mut b = pos.to_be_bytes().to_vec();
2916        b.push(1 << 4);
2917        e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
2918        let t0 = Instant::now();
2919        e.note_inbound(t0);
2920        let seen = Cell::new((None, None));
2921        let look = |e: &mut Engine<Box<dyn Sim>>| {
2922            let mut b = Script(|ctx: &mut TickContext<'_>| {
2923                seen.set((
2924                    ctx.target_entity().map(|h| (h.id, h.distance)),
2925                    ctx.target().map(|t| (t.pos, t.face)),
2926                ));
2927            });
2928            e.tick(&mut b, t0);
2929            seen.get()
2930        };
2931        assert_eq!(
2932            look(&mut e),
2933            (
2934                None,
2935                Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
2936            )
2937        );
2938        // A zombie 2 blocks west: its box (0.6 wide) grown by the 1.8 margin 0.1 is hit at
2939        // x = 6.9, 1.6 away; the block behind is not the target.
2940        e.sim.world_packet(&zombie(50, 6.5)).unwrap();
2941        let (ent, block) = look(&mut e);
2942        let (eid, d) = ent.unwrap();
2943        assert_eq!(eid, 50);
2944        assert!((d - 1.6).abs() < 1e-6, "{d}");
2945        assert_eq!(block, None);
2946        // Gone, and one at x = 5.0 instead: hit at 5.4, 3.1 away (> 3) but before the block.
2947        e.sim
2948            .world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
2949            .unwrap();
2950        e.sim.world_packet(&zombie(51, 5.0)).unwrap();
2951        assert_eq!(look(&mut e), (None, None));
2952    }
2953
2954    #[test]
2955    fn actions_precede_the_single_movement_packet() {
2956        let mut e = engine(GameVersion::V1_8_9);
2957        join(&mut e);
2958        let t0 = Instant::now();
2959        e.note_inbound(t0);
2960        let mut b = Script(|ctx: &mut TickContext<'_>| {
2961            if ctx.tick() == 2 {
2962                ctx.select_slot(3);
2963                ctx.chat("hello");
2964                ctx.swing();
2965                ctx.set_controls(Controls {
2966                    sneak: true,
2967                    ..Controls::default()
2968                });
2969            }
2970        });
2971        e.tick(&mut b, t0);
2972        assert_eq!(names(e.outbound()), ["C06"]);
2973        e.tick(&mut b, t0);
2974        assert_eq!(
2975            names(e.outbound()),
2976            ["held_slot", "chat", "swing", "entity_action", "C03"]
2977        );
2978        for _ in 0..100 {
2979            e.tick(&mut b, t0);
2980            let n = names(e.outbound());
2981            assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
2982        }
2983    }
2984
2985    /// Raw packets go out in call order with the other actions, before the movement packet,
2986    /// and the wire writes them as given (the same frame as the typed packet).
2987    #[test]
2988    fn raw_packets_keep_the_call_order() {
2989        use crate::version::ClientVersion;
2990        for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
2991            let mut e = engine(v);
2992            join(&mut e);
2993            let t0 = Instant::now();
2994            e.note_inbound(t0);
2995            let mut refused = None;
2996            let mut b = Script(|ctx: &mut TickContext<'_>| {
2997                if ctx.tick() == 3 {
2998                    ctx.swing();
2999                    ctx.send_raw(0x7f, vec![1, 2, 3]);
3000                    ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
3001                        hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
3002                    })
3003                    .unwrap();
3004                    refused = Some(ctx.send_packet(
3005                        &ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
3006                    ));
3007                    ctx.chat("after");
3008                }
3009            });
3010            for _ in 0..2 {
3011                e.tick(&mut b, t0);
3012            }
3013            e.outbound().clear();
3014            e.tick(&mut b, t0);
3015            let out = e.outbound().clone();
3016            let n = names(e.outbound());
3017            assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
3018            let movement = n.iter().position(|x| {
3019                x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
3020            });
3021            assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
3022            assert!(refused.unwrap().is_err());
3023            // The wire writes the raw packet as the typed one.
3024            let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
3025                hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
3026            };
3027            let mut want = ghast_protocol::FrameEncoder::new();
3028            want.write_packet(&typed).unwrap();
3029            let mut got = ghast_protocol::FrameEncoder::new();
3030            let mut wire = crate::version::Wire26_1::default();
3031            crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
3032            assert_eq!(got.take(), want.take());
3033        }
3034    }
3035
3036    #[test]
3037    fn standing_bot_packets() {
3038        let mut e = engine(GameVersion::V1_8_9);
3039        join(&mut e);
3040        let mut b = Idle;
3041        let t0 = Instant::now();
3042        e.note_inbound(t0);
3043        // First tick: the position differs from the fresh player's lastReported (origin).
3044        e.tick(&mut b, t0);
3045        let out = std::mem::take(e.outbound());
3046        assert!(matches!(
3047            out[..],
3048            [Outbound::Move(MovePacket::PositionLook {
3049                on_ground: false,
3050                ..
3051            })]
3052        ));
3053        // Then flying (on ground) with a position refresh every 21st tick.
3054        let mut kinds = Vec::new();
3055        for _ in 0..42 {
3056            e.tick(&mut b, t0);
3057            kinds.extend(names(e.outbound()));
3058        }
3059        assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
3060        assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
3061        assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
3062        assert!(e.core.sent.on_ground);
3063    }
3064
3065    #[test]
3066    fn silent_server_freezes_behaviour() {
3067        let mut e = engine(GameVersion::V1_8_9);
3068        join(&mut e);
3069        let t0 = Instant::now();
3070        e.note_inbound(t0);
3071        let mut ticks = 0;
3072        let mut b = Script(|ctx: &mut TickContext<'_>| {
3073            ticks += 1;
3074            ctx.set_controls(Controls {
3075                sneak: true,
3076                ..Controls::default()
3077            });
3078        });
3079        e.tick(&mut b, t0 + Duration::from_millis(100));
3080        e.tick(&mut b, t0 + Duration::from_millis(1600));
3081        // Frozen: keys released, so the sneak stops; still one movement packet.
3082        let n = names(e.outbound());
3083        assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
3084        e.note_inbound(t0 + Duration::from_millis(1700));
3085        e.tick(&mut b, t0 + Duration::from_millis(1700));
3086        let _ = b;
3087        assert_eq!(ticks, 2);
3088    }
3089
3090    #[test]
3091    fn keepalive_answered_transactions_left_to_the_inventory() {
3092        let mut e = engine(GameVersion::V1_8_9);
3093        join(&mut e);
3094        e.handle(Inbound::KeepAlive(42));
3095        // The engine never answers confirms: the inventory does (exactly once), see the
3096        // fake-server test.
3097        e.handle(Inbound::Transaction {
3098            window_id: 0,
3099            action: -5,
3100            accepted: false,
3101        });
3102        assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
3103    }
3104
3105    #[test]
3106    fn panicking_behaviour_does_not_stop_the_tick() {
3107        let mut e = engine(GameVersion::V1_8_9);
3108        join(&mut e);
3109        let t0 = Instant::now();
3110        let mut b = Script(|ctx: &mut TickContext<'_>| {
3111            if ctx.tick() == 2 {
3112                panic!("boom");
3113            }
3114        });
3115        let hook = std::panic::take_hook();
3116        std::panic::set_hook(Box::new(|_| {}));
3117        for _ in 0..5 {
3118            e.tick(&mut b, t0);
3119        }
3120        std::panic::set_hook(hook);
3121        assert!(e.state.failed);
3122        assert_eq!(names(e.outbound()).len(), 5);
3123    }
3124
3125    #[test]
3126    fn chat_events_reach_the_behaviour_once() {
3127        let mut e = engine(GameVersion::V1_16_5);
3128        join(&mut e);
3129        e.handle(Inbound::Chat(ChatMessage {
3130            rendered: None,
3131            json: r#"{"text":"hi"}"#.into(),
3132            position: ChatPosition::System,
3133            sender: None,
3134        }));
3135        let mut seen = Vec::new();
3136        let mut b = Script(|ctx: &mut TickContext<'_>| {
3137            seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
3138        });
3139        let t0 = Instant::now();
3140        e.tick(&mut b, t0);
3141        e.tick(&mut b, t0);
3142        let _ = b;
3143        assert_eq!(seen, ["hi"]);
3144    }
3145
3146    #[test]
3147    fn immediate_respawn_1_16() {
3148        let mut e = engine(GameVersion::V1_16_5);
3149        join(&mut e);
3150        e.handle(Inbound::GameState {
3151            reason: 11,
3152            value: 1.0,
3153        });
3154        e.handle(Inbound::Died { entity_id: 7 });
3155        assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
3156    }
3157
3158    /// Left button on the floor: START, swings, FINISH, all before the tick's movement
3159    /// packet; the broken block is predicted air and the player falls into the hole.
3160    #[test]
3161    fn dig_with_the_left_button() {
3162        let mut e = engine(GameVersion::V1_8_9);
3163        join(&mut e);
3164        let t0 = Instant::now();
3165        e.note_inbound(t0);
3166        let mut b = Script(|ctx: &mut TickContext<'_>| {
3167            ctx.set_aim(90.0, 89.5);
3168            let down = ctx.target().is_some_and(|t| {
3169                t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
3170            });
3171            ctx.set_buttons(Buttons {
3172                left: down,
3173                right: false,
3174            });
3175        });
3176        let mut ticks = Vec::new();
3177        for _ in 0..200 {
3178            e.tick(&mut b, t0);
3179            let n = names(e.outbound());
3180            assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
3181            assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
3182            ticks.push(n);
3183        }
3184        let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
3185        assert_eq!(
3186            flat.iter().filter(|x| **x == "block_dig").count(),
3187            2,
3188            "start + finish"
3189        );
3190        assert!(e.core.hands.broken == 1);
3191        // Stone by hand: not harvestable, 1 / 1.5 / 100 per tick -> 151 damage ticks.
3192        let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
3193        let finish = ticks
3194            .iter()
3195            .rposition(|t| t.contains(&"block_dig"))
3196            .unwrap();
3197        assert_eq!(finish - start, 150);
3198        assert!(e.sim.block_query(8, 63, 8).unwrap().air);
3199        assert!(
3200            e.core.pose.pos.y < 64.0,
3201            "falls into the hole: {:?}",
3202            e.core.pose.pos
3203        );
3204    }
3205
3206    /// `TickView::outbound` lists the tick's packets (the left button's dig start among them,
3207    /// ahead of the movement packet); `prediction_sequence` is what the wire reports, and the
3208    /// modern wire counts the predicting packets.
3209    #[test]
3210    fn outbound_visible_to_the_behaviour() {
3211        use crate::version::ClientVersion;
3212        struct Watch {
3213            seen: Vec<Vec<Outbound>>,
3214            seq: Vec<Option<i32>>,
3215        }
3216        impl Behavior for Watch {
3217            fn tick(&mut self, ctx: &mut TickContext<'_>) {
3218                self.seq.push(ctx.prediction_sequence());
3219                ctx.set_aim(90.0, 89.5);
3220                let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
3221                ctx.set_buttons(Buttons {
3222                    left: down,
3223                    right: false,
3224                });
3225            }
3226            fn after_tick(&mut self, view: &TickView<'_>) {
3227                self.seen.push(view.outbound().to_vec());
3228                assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
3229            }
3230        }
3231        let mut e = engine(GameVersion::V1_8_9);
3232        join(&mut e);
3233        let t0 = Instant::now();
3234        e.note_inbound(t0);
3235        let mut b = Watch {
3236            seen: Vec::new(),
3237            seq: Vec::new(),
3238        };
3239        for t in 0..20 {
3240            e.note_sequence(Some(t));
3241            e.tick(&mut b, t0);
3242            assert_eq!(*e.outbound(), *b.seen.last().unwrap());
3243            e.outbound().clear();
3244        }
3245        assert_eq!(b.seq.last(), Some(&Some(19)));
3246        let dig = b
3247            .seen
3248            .iter()
3249            .find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
3250            .expect("a dig start");
3251        assert!(matches!(
3252            dig.iter()
3253                .find(|p| matches!(p, Outbound::Dig { .. }))
3254                .unwrap(),
3255            Outbound::Dig {
3256                status: crate::common::DigStatus::Start,
3257                face: crate::Face::Up,
3258                ..
3259            }
3260        ));
3261        assert!(matches!(dig.last(), Some(Outbound::Move(_))));
3262        // 26.1's wire: start and finish take a new number, abort does not.
3263        let mut wire = crate::version::Wire26_1::default();
3264        let mut enc = ghast_protocol::FrameEncoder::new();
3265        let dig = |status| Outbound::Dig {
3266            status,
3267            pos: ghast_protocol::BlockPos::new(1, 2, 3),
3268            face: crate::Face::Up,
3269        };
3270        use crate::common::DigStatus;
3271        assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
3272        for (s, want) in [
3273            (DigStatus::Start, 1),
3274            (DigStatus::Abort, 1),
3275            (DigStatus::Start, 2),
3276            (DigStatus::Finish, 3),
3277        ] {
3278            crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
3279            assert_eq!(
3280                crate::version::V26_1::prediction_sequence(&wire),
3281                Some(want)
3282            );
3283        }
3284        assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
3285    }
3286
3287    /// `dig_speed` is the left button's per-tick progress; `item_facts` the hands' facts.
3288    #[test]
3289    fn dig_speed_and_item_facts() {
3290        // 1.16.5 facts by name (its test chunk is empty).
3291        let mut e = engine(GameVersion::V1_16_5);
3292        join(&mut e);
3293        let t0 = Instant::now();
3294        e.note_inbound(t0);
3295        let mut b = Script(|ctx: &mut TickContext<'_>| {
3296            let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
3297            let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
3298            assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
3299            let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
3300            assert!(dirt.is_some_and(|f| f.places_block && !f.food));
3301        });
3302        e.tick(&mut b, t0);
3303
3304        let mut e = engine(GameVersion::V1_8_9);
3305        join(&mut e);
3306        e.note_inbound(t0);
3307        let got = std::cell::Cell::new(None);
3308        let mut b = Script(|ctx: &mut TickContext<'_>| {
3309            let stone = ghast_protocol::BlockPos::new(8, 63, 8);
3310            let pick = ghast_inventory::Stack::new(278, 1, 0);
3311            let facts = ctx.item_facts(&pick).unwrap();
3312            assert!(!facts.places_block && !facts.food);
3313            got.set(Some((
3314                ctx.dig_speed(stone, None),
3315                ctx.dig_speed(stone, Some(&pick)),
3316                ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
3317                ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
3318            )));
3319        });
3320        // Land first (in the air the progress is ÷5).
3321        for _ in 0..40 {
3322            e.tick(&mut b, t0);
3323        }
3324        assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
3325        let (hand, pick, air, unloaded) = got.get().expect("ticked");
3326        // Stone by hand: not harvestable, 1 / 1.5 / 100 per tick (the 150 ticks of
3327        // `dig_with_the_left_button`).
3328        assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
3329        // Diamond pickaxe: speed 8, harvestable: 8 / 1.5 / 30.
3330        assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
3331        assert_eq!(air, Some(0.0));
3332        assert_eq!(unloaded, None);
3333    }
3334
3335    /// `place` is refused unless the sent look is on the face; then C08 + C0A before the
3336    /// movement packet.
3337    #[test]
3338    fn place_needs_the_sent_look() {
3339        let mut e = engine(GameVersion::V1_8_9);
3340        join(&mut e);
3341        let t0 = Instant::now();
3342        e.note_inbound(t0);
3343        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3344        let mut results = Vec::new();
3345        let mut b = Script(|ctx: &mut TickContext<'_>| {
3346            ctx.set_aim(90.0, 89.5);
3347            results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
3348        });
3349        // A stack of stone in the selected hotbar slot (window 0 slot 36).
3350        e.core
3351            .inv
3352            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3353        let mut placed_tick = None;
3354        for i in 0..20 {
3355            e.tick(&mut b, t0);
3356            let n = names(e.outbound());
3357            if n.contains(&"block_place") {
3358                assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
3359                placed_tick.get_or_insert(i);
3360            }
3361        }
3362        let _ = b;
3363        let first = results.iter().position(|r| *r).unwrap();
3364        assert!(first > 3, "refused while still turning");
3365        assert_eq!(placed_tick, Some(first));
3366        assert_eq!(e.core.inv.held().map(|s| s.id()), Some(1));
3367    }
3368
3369    #[test]
3370    fn sneak_action_order() {
3371        let mut e = engine(GameVersion::V1_8_9);
3372        join(&mut e);
3373        let mut b = Script(|ctx: &mut TickContext<'_>| {
3374            ctx.set_controls(Controls {
3375                sneak: true,
3376                ..Controls::default()
3377            });
3378        });
3379        e.tick(&mut b, Instant::now());
3380        let out = std::mem::take(e.outbound());
3381        assert_eq!(
3382            out[0],
3383            Outbound::EntityAction {
3384                entity_id: 7,
3385                action: EntityAction::StartSneaking
3386            }
3387        );
3388        assert!(matches!(out[1], Outbound::Move(_)));
3389    }
3390
3391    /// Block changes reach the behaviour once, in arrival order, only when asked for.
3392    #[test]
3393    fn block_updates_per_version() {
3394        use ghast_protocol::BlockPos;
3395        for &v in GameVersion::ALL {
3396            let mut e = engine(v);
3397            join(&mut e);
3398            e.sim.collect_block_updates(true);
3399            let t0 = Instant::now();
3400            e.note_inbound(t0);
3401            let raws = match v {
3402                GameVersion::V1_8_9 => {
3403                    use ghast_protocol::v1_8::play::clientbound as cb;
3404                    vec![
3405                        RawPacket::from_packet(&cb::BlockChange {
3406                            location: BlockPos::new(3, 63, 4),
3407                            r#type: 59 << 4 | 7,
3408                        })
3409                        .unwrap(),
3410                        RawPacket::from_packet(&cb::MultiBlockChange {
3411                            chunk_x: 0,
3412                            chunk_z: 0,
3413                            records: vec![cb::MultiBlockChangeRecords {
3414                                horizontal_pos: 5 << 4 | 6,
3415                                y: 62,
3416                                block_id: 60 << 4 | 7,
3417                            }],
3418                        })
3419                        .unwrap(),
3420                    ]
3421                }
3422                GameVersion::V1_12_2 => {
3423                    use ghast_protocol::v1_12_2::play::clientbound as cb;
3424                    vec![
3425                        RawPacket::from_packet(&cb::BlockChange {
3426                            location: BlockPos::new(3, 63, 4),
3427                            r#type: 59 << 4 | 7,
3428                        })
3429                        .unwrap(),
3430                        RawPacket::from_packet(&cb::MultiBlockChange {
3431                            chunk_x: 0,
3432                            chunk_z: 0,
3433                            records: vec![cb::MultiBlockChangeRecords {
3434                                horizontal_pos: 5 << 4 | 6,
3435                                y: 62,
3436                                block_id: 60 << 4 | 7,
3437                            }],
3438                        })
3439                        .unwrap(),
3440                    ]
3441                }
3442                GameVersion::V26_1 => {
3443                    use ghast_protocol::v26_1::play::clientbound as cb;
3444                    // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
3445                    let local = (5 << 8 | 6 << 4 | 14) as i64;
3446                    vec![
3447                        RawPacket::from_packet(&cb::BlockChange {
3448                            location: BlockPos::new(3, 63, 4),
3449                            r#type: 1,
3450                        })
3451                        .unwrap(),
3452                        RawPacket::from_packet(&cb::MultiBlockChange {
3453                            chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3454                                x: 0,
3455                                z: 0,
3456                                y: -1,
3457                            },
3458                            records: vec![9 << 12 | local],
3459                        })
3460                        .unwrap(),
3461                    ]
3462                }
3463                #[cfg(feature = "v26_2")]
3464                GameVersion::V26_2 => {
3465                    use ghast_protocol::v26_2::play::clientbound as cb;
3466                    // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
3467                    let local = (5 << 8 | 6 << 4 | 14) as i64;
3468                    vec![
3469                        RawPacket::from_packet(&cb::BlockChange {
3470                            location: BlockPos::new(3, 63, 4),
3471                            r#type: 1,
3472                        })
3473                        .unwrap(),
3474                        RawPacket::from_packet(&cb::MultiBlockChange {
3475                            chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3476                                x: 0,
3477                                z: 0,
3478                                y: -1,
3479                            },
3480                            records: vec![9 << 12 | local],
3481                        })
3482                        .unwrap(),
3483                    ]
3484                }
3485                _ => {
3486                    use ghast_protocol::v1_16_5::play::clientbound as cb;
3487                    // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
3488                    let local = (5 << 8 | 6 << 4 | 14) as i64;
3489                    vec![
3490                        RawPacket::from_packet(&cb::BlockChange {
3491                            location: BlockPos::new(3, 63, 4),
3492                            r#type: 1,
3493                        })
3494                        .unwrap(),
3495                        RawPacket::from_packet(&cb::MultiBlockChange {
3496                            chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
3497                                x: 0,
3498                                z: 0,
3499                                y: 0xF_FFFF,
3500                            },
3501                            not_trust_edges: false,
3502                            records: vec![9 << 12 | local],
3503                        })
3504                        .unwrap(),
3505                    ]
3506                }
3507            };
3508            for raw in &raws {
3509                e.sim.world_packet(raw).unwrap();
3510            }
3511            let mut seen = Vec::new();
3512            let mut b = Script(|ctx: &mut TickContext<'_>| {
3513                seen.push(ctx.events().block_updates.clone());
3514            });
3515            e.tick(&mut b, t0);
3516            e.tick(&mut b, t0);
3517            let _ = b;
3518            let want = match v {
3519                GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
3520                    (BlockPos::new(3, 63, 4), 59 << 4 | 7),
3521                    (BlockPos::new(5, 62, 6), 60 << 4 | 7),
3522                ],
3523                _ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
3524            };
3525            assert_eq!(seen, [want, Vec::new()], "{v:?}");
3526
3527            // Not collected when not asked for.
3528            e.sim.collect_block_updates(false);
3529            e.sim.world_packet(&raws[0]).unwrap();
3530            let mut n = usize::MAX;
3531            let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
3532            e.tick(&mut b, t0);
3533            let _ = b;
3534            assert_eq!(n, 0);
3535        }
3536    }
3537
3538    /// `set_flying` sends the abilities packet before the move, only when allowed and changed.
3539    #[test]
3540    fn set_flying_needs_may_fly() {
3541        for &v in GameVersion::ALL {
3542            let mut e = engine(v);
3543            join(&mut e);
3544            let t0 = Instant::now();
3545            e.note_inbound(t0);
3546            // In the air (flight ends on landing, like vanilla).
3547            e.handle(Inbound::Teleport(Teleport {
3548                x: 8.5,
3549                y: 70.0,
3550                z: 8.5,
3551                yaw: 90.0,
3552                pitch: 0.0,
3553                flags: 0,
3554                teleport_id: Some(2),
3555                ..Default::default()
3556            }));
3557            e.outbound().clear();
3558            let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
3559            e.tick(&mut b, t0);
3560            assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
3561            assert!(!e.core.pose.flying);
3562            e.handle(Inbound::Abilities(Abilities {
3563                flags: 4,
3564                ..Abilities::default()
3565            }));
3566            e.tick(&mut b, t0);
3567            let out = std::mem::take(e.outbound());
3568            assert_eq!(
3569                out[0],
3570                Outbound::Abilities {
3571                    flags: 6,
3572                    flying_speed: 0.05,
3573                    walking_speed: 0.1
3574                },
3575                "{v:?}"
3576            );
3577            assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
3578            assert!(e.core.pose.flying && e.core.sent.flying);
3579            // Already flying: nothing more.
3580            e.tick(&mut b, t0);
3581            assert!(!names(e.outbound()).contains(&"abilities"));
3582            let _ = b;
3583        }
3584    }
3585
3586    /// 1.12.2 runs the vanilla-exact physics: the player is added to its chunk on the first
3587    /// tick (nothing sent), then walks on the stone floor and sends its moves; standing still
3588    /// sends no idle on-ground packets (1.9+).
3589    #[test]
3590    fn v1_12_2_walks_with_physics() {
3591        let mut e = engine(GameVersion::V1_12_2);
3592        join(&mut e);
3593        let t0 = Instant::now();
3594        e.note_inbound(t0);
3595        let mut idle = Script(|_: &mut TickContext<'_>| {});
3596        e.tick(&mut idle, t0);
3597        assert!(
3598            !names(e.outbound())
3599                .iter()
3600                .any(|n| matches!(*n, "C04" | "C06"))
3601        );
3602        for _ in 0..5 {
3603            e.tick(&mut idle, t0);
3604        }
3605        e.outbound().clear();
3606        let start = e.core.pose.pos;
3607        assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
3608        let mut walk = Script(|ctx: &mut TickContext<'_>| {
3609            ctx.set_controls(crate::common::Controls {
3610                forward: true,
3611                ..Default::default()
3612            });
3613        });
3614        for _ in 0..10 {
3615            e.tick(&mut walk, t0);
3616        }
3617        let _ = walk;
3618        let moved = names(e.outbound());
3619        assert!(
3620            moved.iter().any(|n| matches!(*n, "C04" | "C06")),
3621            "{moved:?}"
3622        );
3623        // Yaw 90 faces -X.
3624        assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
3625        assert_eq!(e.core.pose.pos.y, 64.0);
3626        let mut stop = Script(|ctx: &mut TickContext<'_>| {
3627            ctx.set_controls(crate::common::Controls::default());
3628        });
3629        for _ in 0..30 {
3630            e.tick(&mut stop, t0);
3631        }
3632        e.outbound().clear();
3633        for _ in 0..5 {
3634            e.tick(&mut stop, t0);
3635        }
3636        let _ = (idle, stop);
3637        // No idle on-ground packets; at most the position refresh every 20 ticks.
3638        let still = names(e.outbound());
3639        assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
3640    }
3641
3642    /// A behaviour that reports `running() == false` is not ticked again.
3643    #[test]
3644    fn finished_behaviour_is_not_ticked() {
3645        struct Three(std::rc::Rc<std::cell::Cell<u32>>);
3646        impl Behavior for Three {
3647            fn tick(&mut self, _ctx: &mut TickContext<'_>) {
3648                self.0.set(self.0.get() + 1);
3649            }
3650            fn running(&self) -> bool {
3651                self.0.get() < 3
3652            }
3653        }
3654        let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
3655        let mut e = engine(GameVersion::V1_8_9);
3656        join(&mut e);
3657        let t0 = Instant::now();
3658        e.note_inbound(t0);
3659        let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
3660        for _ in 0..10 {
3661            e.tick(&mut b, t0);
3662            // The player keeps sending its movement packet.
3663            let out = std::mem::take(e.outbound());
3664            assert!(
3665                out.iter().any(|o| matches!(o, Outbound::Move(_))),
3666                "{out:?}"
3667            );
3668        }
3669        assert_eq!(
3670            ticks.get(),
3671            3,
3672            "not ticked after running() == false (through the Box)"
3673        );
3674    }
3675
3676    /// A turn that would take the crosshair off a block placed this tick waits one tick.
3677    #[test]
3678    fn turn_held_on_a_place_tick() {
3679        let mut e = engine(GameVersion::V1_8_9);
3680        join(&mut e);
3681        let t0 = Instant::now();
3682        e.note_inbound(t0);
3683        e.core
3684            .inv
3685            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3686        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3687        let mut tick = 0;
3688        let mut placed_at = None;
3689        let mut pitches = Vec::new();
3690        let mut b = Script(|ctx: &mut TickContext<'_>| {
3691            tick += 1;
3692            if placed_at.is_none() {
3693                ctx.set_aim(90.0, 89.5);
3694                if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
3695                    placed_at = Some(tick);
3696                    // Look up on the same tick: held back.
3697                    ctx.set_aim(90.0, -60.0);
3698                }
3699            } else {
3700                ctx.set_aim(90.0, -60.0);
3701            }
3702            pitches.push(ctx.pose().pitch);
3703        });
3704        for _ in 0..30 {
3705            e.tick(&mut b, t0);
3706            e.outbound().clear();
3707        }
3708        let _ = b;
3709        let p = placed_at.expect("placed");
3710        assert_eq!(e.core.held_turns, 1);
3711        // Pose at the start of the tick after the place: still the place look.
3712        assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
3713        assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
3714    }
3715
3716    /// `click` returns the ticket its confirm carries.
3717    #[test]
3718    fn click_ticket_matches_the_confirm() {
3719        let mut e = engine(GameVersion::V1_8_9);
3720        join(&mut e);
3721        let t0 = Instant::now();
3722        e.note_inbound(t0);
3723        e.core
3724            .inv
3725            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3726        let mut ticket = None;
3727        let mut n = 0;
3728        let mut b = Script(|ctx: &mut TickContext<'_>| {
3729            n += 1;
3730            if n == 1 {
3731                ctx.open_inventory().unwrap();
3732            } else if ticket.is_none() {
3733                ticket = ctx
3734                    .click(ghast_inventory::Click::Pickup {
3735                        slot: 36,
3736                        right: false,
3737                    })
3738                    .ok();
3739            }
3740        });
3741        for _ in 0..3 {
3742            e.tick(&mut b, t0);
3743        }
3744        let _ = b;
3745        let t = ticket.expect("click sent");
3746        assert_eq!(t.window_id, 0);
3747        assert!(t.matches(&ghast_inventory::ClickResult::new(
3748            0,
3749            t.action,
3750            ghast_inventory::ClickOutcome::Accepted,
3751        )));
3752    }
3753
3754    /// 1.8 planting uses the seed at once (vanilla `SeedItem.use` on the client); a
3755    /// stone block place waits for the server.
3756    #[test]
3757    fn planting_uses_the_seed_at_once() {
3758        use ghast_protocol::v1_8::play::clientbound as cb;
3759        for (soil, item, used) in [
3760            (60 << 4 | 7, 295, true),
3761            (1 << 4, 295, false),
3762            (60 << 4, 1, false),
3763        ] {
3764            let mut e = engine(GameVersion::V1_8_9);
3765            join(&mut e);
3766            let t0 = Instant::now();
3767            e.note_inbound(t0);
3768            let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3769            let raw = RawPacket::from_packet(&cb::BlockChange {
3770                location: floor,
3771                r#type: soil,
3772            })
3773            .unwrap();
3774            e.sim.world_packet(&raw).unwrap();
3775            e.core
3776                .inv
3777                .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
3778            let mut done = false;
3779            let mut b = Script(|ctx: &mut TickContext<'_>| {
3780                ctx.set_aim(90.0, 89.5);
3781                if !done {
3782                    done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
3783                }
3784            });
3785            let mut sent = None;
3786            for _ in 0..20 {
3787                e.tick(&mut b, t0);
3788                for o in e.outbound().drain(..) {
3789                    if let Outbound::Place { held, .. } = o {
3790                        sent = held.map(|h| h.count());
3791                    }
3792                }
3793            }
3794            let _ = b;
3795            assert_eq!(sent, Some(64), "the packet carries the stack before use");
3796            let left = e.core.inv.held().map(|s| s.count());
3797            assert_eq!(
3798                left,
3799                Some(if used { 63 } else { 64 }),
3800                "soil {soil} item {item}"
3801            );
3802        }
3803    }
3804
3805    /// `planned_look` is the look the movement step then uses: a plain turn, a turn held on a
3806    /// place tick, no aim; and it leaves the rotation's budget alone.
3807    #[test]
3808    fn planned_look_is_the_next_look() {
3809        let mut e = engine(GameVersion::V1_8_9);
3810        join(&mut e);
3811        let t0 = Instant::now();
3812        e.note_inbound(t0);
3813        e.core
3814            .inv
3815            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(1, 64, 0)));
3816        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
3817        let mut n = 0;
3818        let mut placed = false;
3819        let mut plans: Vec<(f32, f32)> = Vec::new();
3820        let mut b = Script(|ctx: &mut TickContext<'_>| {
3821            n += 1;
3822            if n % 5 == 0 {
3823                // No aim this tick: the current look.
3824            } else if !placed {
3825                ctx.set_aim(90.0, 89.5);
3826                if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
3827                    placed = true;
3828                    ctx.set_aim(90.0, -60.0);
3829                }
3830            } else {
3831                ctx.set_aim(150.0, -60.0);
3832            }
3833            // Asking twice changes nothing.
3834            let p = ctx.planned_look();
3835            assert_eq!(p, ctx.planned_look());
3836            plans.push(p);
3837        });
3838        let mut looks = Vec::new();
3839        for _ in 0..40 {
3840            e.tick(&mut b, t0);
3841            e.outbound().clear();
3842            looks.push((e.core.pose.yaw, e.core.pose.pitch));
3843        }
3844        let _ = b;
3845        assert!(placed);
3846        assert_eq!(e.core.test_held_turns(), 1);
3847        assert_eq!(plans, looks);
3848    }
3849
3850    /// A teleport event keeps the sent pose from before the overwrite, the raw values and the
3851    /// resolved pose.
3852    #[test]
3853    fn teleport_event_has_the_sent_pose_before() {
3854        for &v in GameVersion::ALL {
3855            let mut e = engine(v);
3856            join(&mut e);
3857            let t0 = Instant::now();
3858            e.note_inbound(t0);
3859            let mut seen = Vec::new();
3860            let mut b = Script(|ctx: &mut TickContext<'_>| {
3861                seen.extend(ctx.events().teleports.iter().copied());
3862            });
3863            e.tick(&mut b, t0);
3864            let sent = e.core.sent;
3865            // Relative yaw +30, absolute position.
3866            let tp = Teleport {
3867                x: 10.5,
3868                y: 64.0,
3869                z: 8.5,
3870                yaw: 30.0,
3871                pitch: 0.0,
3872                flags: crate::common::teleport_flags::YAW,
3873                teleport_id: Some(9),
3874                relative: crate::common::teleport_flags::YAW as u32,
3875                ..Default::default()
3876            };
3877            e.handle(Inbound::Teleport(tp));
3878            e.tick(&mut b, t0);
3879            e.tick(&mut b, t0);
3880            let _ = b;
3881            // The spawn position first (join), then ours, each once.
3882            assert_eq!(seen.len(), 2, "{v:?}");
3883            let ev = seen[1];
3884            assert_eq!(ev.teleport, tp);
3885            assert_eq!(ev.sent_before, sent);
3886            assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
3887            assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
3888        }
3889    }
3890
3891    /// A container the server opened and the behaviour closed (`close_window`) no longer
3892    /// holds the mouse: the left button digs again (both versions). While it is open the
3893    /// buttons are up.
3894    #[test]
3895    fn closed_window_frees_the_buttons() {
3896        for &v in GameVersion::ALL {
3897            let mut e = engine(v);
3898            join(&mut e);
3899            let t0 = Instant::now();
3900            e.note_inbound(t0);
3901            if v == GameVersion::V1_16_5 {
3902                // The 1.16 test chunk is all air: put a stone floor under the player.
3903                use ghast_protocol::v1_16_5::play::clientbound as cb;
3904                let raw = RawPacket::from_packet(&cb::BlockChange {
3905                    location: ghast_protocol::BlockPos::new(8, 63, 8),
3906                    r#type: 1,
3907                })
3908                .unwrap();
3909                e.sim.world_packet(&raw).unwrap();
3910            }
3911            e.core.inv.on_open_window(
3912                5,
3913                Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
3914                "Vault".into(),
3915            );
3916            e.handle(Inbound::OpenWindow(5));
3917            // Something on the cursor: vanilla's client-side close drops it (the server
3918            // throws it out), so the client forgets it too.
3919            e.core
3920                .inv
3921                .on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
3922            let mut n = 0;
3923            let mut closed_at = None;
3924            let mut b = Script(|ctx: &mut TickContext<'_>| {
3925                n += 1;
3926                ctx.set_aim(90.0, 89.5);
3927                ctx.set_buttons(Buttons {
3928                    left: true,
3929                    right: false,
3930                });
3931                if n == 15 {
3932                    assert!(ctx.inventory().cursor().is_some());
3933                    ctx.close_window().unwrap();
3934                    assert_eq!(ctx.open_window(), None);
3935                    let inv = ctx.inventory();
3936                    assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
3937                    closed_at = Some(n);
3938                }
3939            });
3940            let mut first_dig = None;
3941            for i in 1..=30 {
3942                e.tick(&mut b, t0);
3943                let out = std::mem::take(e.outbound());
3944                if first_dig.is_none()
3945                    && out.iter().any(|o| {
3946                        matches!(
3947                            o,
3948                            Outbound::Dig {
3949                                status: crate::common::DigStatus::Start,
3950                                ..
3951                            }
3952                        )
3953                    })
3954                {
3955                    first_dig = Some(i);
3956                }
3957            }
3958            let _ = b;
3959            assert_eq!(closed_at, Some(15));
3960            let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
3961            // The hands run after the behaviour: the closing tick already digs.
3962            assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
3963        }
3964    }
3965
3966    /// `swings` counts every arm swing: the behaviour's, an action's and the held button's.
3967    #[test]
3968    fn swings_count_every_arm_swing() {
3969        let mut e = engine(GameVersion::V1_8_9);
3970        join(&mut e);
3971        let t0 = Instant::now();
3972        e.note_inbound(t0);
3973        let mut n = 0;
3974        let mut seen = Vec::new();
3975        let mut b = Script(|ctx: &mut TickContext<'_>| {
3976            n += 1;
3977            ctx.set_aim(90.0, 89.5);
3978            if n == 1 {
3979                ctx.swing();
3980                ctx.swing();
3981            }
3982            if n == 20 {
3983                // Hold the left button on the stone floor: a swing every tick while digging.
3984                ctx.set_buttons(Buttons {
3985                    left: true,
3986                    right: false,
3987                });
3988            }
3989            seen.push(ctx.swings());
3990        });
3991        let mut sent = 0u64;
3992        for _ in 0..30 {
3993            e.tick(&mut b, t0);
3994            sent += count_swings(&std::mem::take(e.outbound()));
3995        }
3996        let _ = b;
3997        assert_eq!(seen[0], 2, "this tick's own swings count at once");
3998        assert!(sent > 10, "the held button swings: {sent}");
3999        // The last reading misses only the hands' swing of the last tick.
4000        assert_eq!(*seen.last().unwrap() + 1, sent);
4001        assert_eq!(e.core.swings, sent);
4002    }
4003
4004    /// `WorldView::column` gives the stored column; light and biomes only when configured.
4005    #[test]
4006    fn column_view_and_world_config() {
4007        for config in [
4008            None,
4009            Some(
4010                ghast_world::WorldConfig::default()
4011                    .with_biomes(true)
4012                    .with_light(true),
4013            ),
4014        ] {
4015            let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
4016                world: config,
4017                ..crate::sim::SimOptions::default()
4018            });
4019            let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
4020            join(&mut e);
4021            let w: &dyn WorldView = &e.sim;
4022            let col = w.column(0, 0).expect("loaded");
4023            assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
4024            assert_eq!(col.raw(8, 63, 8), 1 << 4);
4025            assert!(w.column(5, 5).is_none());
4026            let light = col.sky_light(8, 63, 8);
4027            assert_eq!(light.is_some(), config.is_some(), "{config:?}");
4028            let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
4029            assert_eq!(biomes, config.is_some(), "{config:?}");
4030        }
4031    }
4032
4033    /// `after_tick` runs after the movement step with the sent pose, also once the behaviour
4034    /// finished; a panic there stops the behaviour only.
4035    #[test]
4036    fn after_tick_sees_the_sent_pose() {
4037        struct Obs {
4038            n: u32,
4039            views: Vec<(u64, Pose, u64)>,
4040        }
4041        impl Behavior for Obs {
4042            fn tick(&mut self, ctx: &mut TickContext<'_>) {
4043                self.n += 1;
4044                ctx.set_aim(150.0, 10.0);
4045                ctx.set_controls(Controls {
4046                    forward: true,
4047                    ..Controls::default()
4048                });
4049            }
4050            fn running(&self) -> bool {
4051                self.n < 5
4052            }
4053            fn after_tick(&mut self, view: &TickView<'_>) {
4054                self.views.push((view.tick(), *view.sent(), view.swings()));
4055                assert!(view.world().is_column_loaded(0, 0));
4056                assert_eq!(view.version(), GameVersion::V1_8_9);
4057            }
4058        }
4059        let mut e = engine(GameVersion::V1_8_9);
4060        join(&mut e);
4061        let t0 = Instant::now();
4062        e.note_inbound(t0);
4063        let mut b = Obs {
4064            n: 0,
4065            views: Vec::new(),
4066        };
4067        let mut sent = Vec::new();
4068        for _ in 0..10 {
4069            e.tick(&mut b, t0);
4070            e.outbound().clear();
4071            sent.push(e.core.sent);
4072        }
4073        assert_eq!(b.n, 5);
4074        assert_eq!(b.views.len(), 10, "also after the behaviour finished");
4075        for (i, (_, p, _)) in b.views.iter().enumerate() {
4076            assert_eq!(*p, sent[i]);
4077        }
4078        assert_ne!(
4079            b.views[0].1.yaw, b.views[4].1.yaw,
4080            "the view follows the turn"
4081        );
4082    }
4083
4084    /// With block entities on, a 1.8 sign update reaches the column (and the packet passes the
4085    /// filter); off by default.
4086    #[test]
4087    fn block_entities_follow_the_world_config() {
4088        use ghast_protocol::v1_8::play::clientbound as cb;
4089        for on in [false, true] {
4090            let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
4091                world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
4092                ..crate::sim::SimOptions::default()
4093            });
4094            assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
4095            let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
4096            join(&mut e);
4097            let raw = RawPacket::from_packet(&cb::UpdateSign {
4098                location: ghast_protocol::BlockPos::new(3, 64, 4),
4099                text1: "\"Hello\"".into(),
4100                text2: "\"\"".into(),
4101                text3: "\"\"".into(),
4102                text4: "\"\"".into(),
4103            })
4104            .unwrap();
4105            e.sim.world_packet(&raw).unwrap();
4106            let w: &dyn WorldView = &e.sim;
4107            let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
4108            assert_eq!(be.is_some(), on, "{be:?}");
4109        }
4110    }
4111}