Skip to main content

ghast_inventory/
inventory.rs

1//! The inventory state machine: what the vanilla client holds (player inventory, cursor, the
2//! open window), fed by the server's window packets, plus click intents with vanilla's
3//! prediction and the window confirm ("transaction") protocol.
4
5use bytestring::ByteString;
6
7use crate::crafting::RecipeBook;
8use crate::rules::Version;
9use crate::sim::{Layout, Loc, Model, OUTSIDE, Screen, Sim};
10use crate::stack::Stack;
11
12/// Whether `l` is a crafting grid slot of the layout's screen.
13fn is_grid(lay: Layout, l: Loc) -> bool {
14    match (lay.screen, l) {
15        (Screen::Player, Loc::Craft(_)) => true,
16        (Screen::Container(WindowKind::Crafting), Loc::Container(k)) => (1..=9).contains(&k),
17        _ => false,
18    }
19}
20use crate::window::{SlotKind, WindowKind};
21
22/// Ticks a click may wait for its confirm before it is given up ([`ClickOutcome::TimedOut`]).
23pub const DEFAULT_CLICK_TIMEOUT_TICKS: u32 = 40;
24
25/// A click intent: the vanilla GUI gestures a bot needs. Slot numbers are the open screen's
26/// (window 0 when only the player inventory is open); [`OUTSIDE`] (-999) is a click outside the
27/// window.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum Click {
30    /// Mode 0: left click (`right = false`: pick up / put down / swap the whole stack) or right
31    /// click (pick up half / put down one). On [`OUTSIDE`] it drops the cursor stack (left) or
32    /// one item of it (right).
33    Pickup {
34        /// Slot, or [`OUTSIDE`].
35        slot: i16,
36        /// Right mouse button.
37        right: bool,
38    },
39    /// Mode 1: shift-click (move the stack to the other part of the window).
40    QuickMove {
41        /// Slot.
42        slot: i16,
43        /// Right mouse button (same effect).
44        right: bool,
45    },
46    /// Mode 2: number key over a slot: swap it with hotbar slot `hotbar` (0..=8), or on 1.16.5
47    /// `40` (the swap-hands key) with the offhand.
48    Swap {
49        /// Slot.
50        slot: i16,
51        /// Hotbar index 0..=8, or 40 (offhand, 1.16.5 only).
52        hotbar: u8,
53    },
54    /// Mode 4: drop key over a slot (`all = false`: one item, Q; `all = true`: the stack,
55    /// ctrl+Q). With an empty cursor and [`OUTSIDE`] this is what the vanilla GUI sends for a
56    /// click outside the window (no effect).
57    Drop {
58        /// Slot, or [`OUTSIDE`].
59        slot: i16,
60        /// Whole stack.
61        all: bool,
62    },
63    /// Mode 6: double click: gather items like the cursor stack into it.
64    PickupAll {
65        /// Slot (normally the now empty slot the stack was picked up from).
66        slot: i16,
67    },
68}
69
70impl Click {
71    /// The wire `(slot, button, mode)`.
72    #[must_use]
73    pub fn wire(self) -> (i16, u8, u8) {
74        match self {
75            Click::Pickup { slot, right } => (slot, u8::from(right), 0),
76            Click::QuickMove { slot, right } => (slot, u8::from(right), 1),
77            Click::Swap { slot, hotbar } => (slot, hotbar, 2),
78            Click::Drop { slot, all } => (slot, u8::from(all), 4),
79            Click::PickupAll { slot } => (slot, 0, 6),
80        }
81    }
82}
83
84/// Why a click (or open / close) was refused. Nothing was sent and nothing changed.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum ClickError {
87    /// The previous click's confirm has not arrived yet (one click in flight).
88    Pending,
89    /// The server rejected a click and its full window resync has not arrived yet.
90    Resyncing,
91    /// Nothing is open: open the player inventory ([`Inventory::open_inventory`]) or wait for a
92    /// container window.
93    NoScreen,
94    /// A container window is open (the player inventory cannot be opened over it).
95    WindowOpen,
96    /// Same-tick packet order vanilla never produces (and Grim's PacketOrder checks flag): a
97    /// second click this tick, a click / close in the tick the inventory was opened, or the
98    /// other way round. Retry next tick.
99    SameTick,
100    /// The slot does not exist in the open screen (or `OUTSIDE` where not allowed).
101    InvalidSlot,
102    /// Invalid hotbar index for [`Click::Swap`].
103    InvalidButton,
104    /// The result depends on data ghast does not model (recipes, fuel, brewing, trading,
105    /// enchanting, an unknown crafting result); sending it would desynchronise the inventory.
106    Unpredictable,
107}
108
109impl std::fmt::Display for ClickError {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.write_str(match self {
112            ClickError::Pending => "a click is waiting for its confirm",
113            ClickError::Resyncing => "waiting for the window resync after a rejected click",
114            ClickError::NoScreen => "no inventory screen is open",
115            ClickError::WindowOpen => "a container window is open",
116            ClickError::SameTick => "not allowed in the same tick",
117            ClickError::InvalidSlot => "invalid slot",
118            ClickError::InvalidButton => "invalid button",
119            ClickError::Unpredictable => "click outcome cannot be predicted",
120        })
121    }
122}
123
124impl std::error::Error for ClickError {}
125
126/// A window click as sent (`window_click`; 1.8 `ClickWindowC2SPacket`).
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct ClickPacket {
129    /// Window id (0 = player inventory).
130    pub window_id: u8,
131    /// Slot, or -999.
132    pub slot: i16,
133    /// Mouse button / hotbar key.
134    pub button: u8,
135    /// Click mode.
136    pub mode: u8,
137    /// Action number: the window's counter, incremented before each click.
138    pub action: i16,
139    /// What vanilla's `onSlotClick` returned (the server compares it with its own result).
140    pub item: Option<Stack>,
141}
142
143/// A packet the inventory wants sent. Write it right away, in call order (before the tick's
144/// movement packet when it comes from a behaviour action).
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum Outgoing {
147    /// `window_click`.
148    Click(ClickPacket),
149    /// `transaction` answer to a rejected confirm (always `accepted = true`, like vanilla).
150    Confirm {
151        /// Window id as received.
152        window_id: i8,
153        /// Action number as received.
154        action: i16,
155    },
156    /// `close_window` with this id (0 = player inventory).
157    CloseWindow(u8),
158    /// 1.8 only: `client_command` "open inventory achievement" (vanilla sends it when E opens
159    /// the inventory).
160    OpenInventory,
161}
162
163/// What became of a click.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub enum ClickOutcome {
166    /// The server agreed with the prediction.
167    Accepted,
168    /// The server disagreed; it resends the window (the inventory waits for it).
169    Rejected,
170    /// No confirm within the timeout (the server may not have had that window open).
171    TimedOut,
172}
173
174/// A finished click.
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
176pub struct ClickResult {
177    /// Window id the click was sent for.
178    pub window_id: i32,
179    /// Its action number.
180    pub action: i16,
181    /// The outcome.
182    pub outcome: ClickOutcome,
183}
184
185/// Changes since the last [`Inventory::drain_events`].
186#[derive(Debug, Clone, Default, PartialEq, Eq)]
187pub struct Events {
188    /// Something in the player's inventory (window 0, incl. crafting grid) changed.
189    pub player_changed: bool,
190    /// Something in the open window's own slots changed.
191    pub window_changed: bool,
192    /// The cursor stack changed.
193    pub cursor_changed: bool,
194    /// The server opened a window (its id).
195    pub opened: Option<i32>,
196    /// The open window was closed by the server.
197    pub closed: bool,
198    /// Clicks that were confirmed, rejected or timed out, in order.
199    pub clicks: Vec<ClickResult>,
200}
201
202/// An open container window.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub struct Window {
205    id: i32,
206    kind: WindowKind,
207    title: ByteString,
208    action: i16,
209    properties: Vec<(i16, i16)>,
210}
211
212impl Window {
213    /// Window id (`syncId`).
214    #[must_use]
215    pub fn id(&self) -> i32 {
216        self.id
217    }
218    /// Its type.
219    #[must_use]
220    pub fn kind(&self) -> WindowKind {
221        self.kind
222    }
223    /// The title exactly as sent: a JSON chat component on both versions.
224    #[must_use]
225    pub fn title(&self) -> &ByteString {
226        &self.title
227    }
228    /// A window property (`craft_progress_bar`: furnace progress, enchanting seeds, …).
229    #[must_use]
230    pub fn property(&self, id: i16) -> Option<i16> {
231        self.properties.iter().find(|p| p.0 == id).map(|p| p.1)
232    }
233}
234
235/// Which screen the client has open.
236#[derive(Debug, Clone, PartialEq, Eq)]
237enum ScreenState {
238    None,
239    Inventory,
240    Window(Window),
241}
242
243#[derive(Debug, Clone, Copy)]
244struct PendingClick {
245    window_id: i32,
246    action: i16,
247    age: u32,
248}
249
250#[derive(Debug, Clone, Copy, Default)]
251struct TickFlags {
252    clicked: bool,
253    opened: bool,
254    closed: bool,
255}
256
257/// The client's inventory: player inventory, cursor, the open window, click prediction and
258/// the confirm protocol. Pure and deterministic: packets in, packets out, no I/O or clock
259/// ([`tick`](Inventory::tick) counts time).
260#[derive(Debug, Clone)]
261pub struct Inventory {
262    version: Version,
263    m: Model,
264    screen: ScreenState,
265    player_action: i16,
266    pending: Option<PendingClick>,
267    resync: Option<(i32, u32)>,
268    flags: TickFlags,
269    timeout: u32,
270    events: Events,
271    book: RecipeBook,
272}
273
274impl Inventory {
275    /// An empty inventory (a fresh player entity).
276    #[must_use]
277    pub fn new(version: Version) -> Inventory {
278        Inventory {
279            version,
280            m: Model::default(),
281            screen: ScreenState::None,
282            player_action: 0,
283            pending: None,
284            resync: None,
285            flags: TickFlags::default(),
286            timeout: DEFAULT_CLICK_TIMEOUT_TICKS,
287            events: Events::default(),
288            book: RecipeBook::default(),
289        }
290    }
291
292    /// Sets how many ticks a click may wait for its confirm.
293    pub fn set_click_timeout(&mut self, ticks: u32) {
294        self.timeout = ticks.max(1);
295    }
296
297    /// The protocol version.
298    #[must_use]
299    pub fn version(&self) -> Version {
300        self.version
301    }
302
303    /// A new player entity (join, respawn, dimension change): everything is cleared,
304    /// including the action counters; the server resends the inventory.
305    /// The selected hotbar slot restarts at 0 too (a new `PlayerInventory`).
306    pub fn reset(&mut self) {
307        // the recipe book belongs to the connection, not to the player entity
308        *self = Inventory {
309            timeout: self.timeout,
310            book: std::mem::take(&mut self.book),
311            ..Inventory::new(self.version)
312        };
313        self.events.player_changed = true;
314    }
315
316    /// Call once at the start of every client tick: resets the per-tick packet-order guard
317    /// and ages the pending click.
318    pub fn tick(&mut self) {
319        self.flags = TickFlags::default();
320        if let Some(p) = &mut self.pending {
321            p.age += 1;
322            if p.age >= self.timeout {
323                self.events.clicks.push(ClickResult {
324                    window_id: p.window_id,
325                    action: p.action,
326                    outcome: ClickOutcome::TimedOut,
327                });
328                self.pending = None;
329            }
330        }
331        if let Some((_, age)) = &mut self.resync {
332            *age += 1;
333            if *age >= self.timeout {
334                self.resync = None;
335            }
336        }
337    }
338
339    /// Takes the accumulated change flags and click results.
340    pub fn drain_events(&mut self) -> Events {
341        std::mem::take(&mut self.events)
342    }
343
344    // ------------------------------------------------------------------ reading
345
346    /// The cursor ("carried") stack.
347    #[must_use]
348    pub fn cursor(&self) -> Option<&Stack> {
349        self.m.cursor.as_ref()
350    }
351
352    /// `PlayerInventory` slot by vanilla index: 0..=8 hotbar, 9..=35 main, 36..=39 armor
353    /// (feet, legs, chest, head), 40 offhand (1.16.5).
354    #[must_use]
355    pub fn player(&self, index: usize) -> Option<&Stack> {
356        self.m.player.get(index)?.as_ref()
357    }
358
359    /// Hotbar slot 0..=8.
360    #[must_use]
361    pub fn hotbar(&self, k: usize) -> Option<&Stack> {
362        if k < 9 { self.player(k) } else { None }
363    }
364
365    /// The selected hotbar slot.
366    #[must_use]
367    pub fn selected(&self) -> u8 {
368        self.m.selected
369    }
370
371    /// The stack in the selected hotbar slot.
372    #[must_use]
373    pub fn held(&self) -> Option<&Stack> {
374        self.player(usize::from(self.m.selected))
375    }
376
377    /// Armor piece: 0 head, 1 chest, 2 legs, 3 feet.
378    #[must_use]
379    pub fn armor(&self, a: usize) -> Option<&Stack> {
380        if a < 4 { self.player(39 - a) } else { None }
381    }
382
383    /// The offhand stack (1.16.5).
384    #[must_use]
385    pub fn offhand(&self) -> Option<&Stack> {
386        self.player(40)
387    }
388
389    /// The open container window, if any.
390    #[must_use]
391    pub fn window(&self) -> Option<&Window> {
392        match &self.screen {
393            ScreenState::Window(w) => Some(w),
394            _ => None,
395        }
396    }
397
398    /// Whether a GUI is open (a container window or the player inventory).
399    #[must_use]
400    pub fn gui_open(&self) -> bool {
401        self.screen != ScreenState::None
402    }
403
404    /// Whether the player inventory GUI is open (no container window).
405    #[must_use]
406    pub fn inventory_open(&self) -> bool {
407        self.screen == ScreenState::Inventory
408    }
409
410    fn layout(&self) -> Layout {
411        let screen = match &self.screen {
412            ScreenState::Window(w) => Screen::Container(w.kind),
413            _ => Screen::Player,
414        };
415        Layout::new(self.version, screen)
416    }
417
418    /// Number of slots of the current screen (window 0 when no container is open: 45 on 1.8,
419    /// 46 on 1.16.5).
420    #[must_use]
421    pub fn slot_count(&self) -> usize {
422        self.layout().len
423    }
424
425    /// Container slots of the open window (before the player's 36), 0 for window 0.
426    #[must_use]
427    pub fn container_len(&self) -> usize {
428        self.layout().n
429    }
430
431    /// Slot `i` of the current screen (window 0 layout when no container is open).
432    #[must_use]
433    pub fn slot(&self, i: usize) -> Option<&Stack> {
434        let l = self.layout().loc(i)?;
435        self.m.at(l).as_ref()
436    }
437
438    /// Slot `i` of window 0 (`PlayerScreenHandler` numbering), whatever is open.
439    #[must_use]
440    pub fn window0_slot(&self, i: usize) -> Option<&Stack> {
441        let l = Layout::new(self.version, Screen::Player).loc(i)?;
442        self.m.at(l).as_ref()
443    }
444
445    /// Kind of slot `i` of the current screen.
446    #[must_use]
447    pub fn slot_kind(&self, i: usize) -> Option<SlotKind> {
448        let lay = self.layout();
449        (i < lay.len).then(|| lay.kind(i))
450    }
451
452    /// The current screen's slot that shows `PlayerInventory` index `k` (e.g. hotbar 0 is
453    /// window 0 slot 36 and slot 54 of a 3-row chest).
454    #[must_use]
455    pub fn slot_of_player(&self, k: usize) -> Option<i16> {
456        self.layout().slot_of_player(k).map(|i| i as i16)
457    }
458
459    /// First slot of the current screen whose stack matches.
460    pub fn find(&self, mut pred: impl FnMut(&Stack) -> bool) -> Option<i16> {
461        let lay = self.layout();
462        (0..lay.len)
463            .find(|&i| {
464                lay.loc(i)
465                    .and_then(|l| self.m.at(l).as_ref())
466                    .is_some_and(&mut pred)
467            })
468            .map(|i| i as i16)
469    }
470
471    /// Total count of matching stacks in the player inventory (hotbar, main, armor, offhand).
472    pub fn count(&self, mut pred: impl FnMut(&Stack) -> bool) -> i32 {
473        self.m
474            .player
475            .iter()
476            .flatten()
477            .filter(|s| pred(s))
478            .map(|s| s.count)
479            .sum()
480    }
481
482    /// Whether the current screen's crafting result (window 0 slot 0, crafting table slot 0)
483    /// is what the vanilla client shows. The 1.8 client computes results from its recipe book
484    /// (ghast does not) and the server never sends them except in `window_items`; on 1.16.5 the
485    /// server sends each new result as `set_slot`. While unknown, result clicks are
486    /// [`ClickError::Unpredictable`].
487    #[must_use]
488    pub fn result_known(&self) -> bool {
489        match &self.screen {
490            ScreenState::Window(w) if w.kind == WindowKind::Crafting => {
491                self.m.container_result_known
492            }
493            ScreenState::Window(_) => true,
494            _ => self.m.craft_result_known,
495        }
496    }
497
498    /// Whether a click waits for its confirm.
499    #[must_use]
500    pub fn pending(&self) -> bool {
501        self.pending.is_some()
502    }
503
504    /// Whether the inventory waits for the server's resync after a rejected click.
505    #[must_use]
506    pub fn resyncing(&self) -> bool {
507        self.resync.is_some()
508    }
509
510    /// Whether [`click`](Inventory::click) would currently refuse for a reason other than the
511    /// click itself.
512    pub fn can_click(&self) -> Result<(), ClickError> {
513        if self.pending.is_some() {
514            return Err(ClickError::Pending);
515        }
516        if self.resync.is_some() {
517            return Err(ClickError::Resyncing);
518        }
519        if self.flags.clicked || self.flags.opened {
520            return Err(ClickError::SameTick);
521        }
522        if self.screen == ScreenState::None {
523            return Err(ClickError::NoScreen);
524        }
525        Ok(())
526    }
527
528    // ------------------------------------------------------------------ actions
529
530    /// Simulates a click exactly like the vanilla client (`ClientPlayerInteractionManager.clickSlot`:
531    /// next action number, `onSlotClick`, packet with its return value) and returns the packet
532    /// to send now. The prediction is applied immediately; the click is pending until its
533    /// confirm arrives.
534    ///
535    /// Bots should click only while not turning (the server and anticheats see clicks against
536    /// the last sent rotation; vanilla players do not move the camera with a GUI open).
537    pub fn click(&mut self, click: Click) -> Result<Outgoing, ClickError> {
538        self.can_click()?;
539        let lay = self.layout();
540        let (slot, button, mode) = click.wire();
541        let in_range = usize::try_from(slot).is_ok_and(|i| i < lay.len);
542        let slot_ok = match click {
543            Click::Pickup { .. } | Click::Drop { .. } => in_range || slot == OUTSIDE,
544            Click::QuickMove { .. } | Click::Swap { .. } | Click::PickupAll { .. } => in_range,
545        };
546        if !slot_ok {
547            return Err(ClickError::InvalidSlot);
548        }
549        if let Click::Swap { hotbar, .. } = click {
550            let ok = hotbar < 9 || (hotbar == 40 && self.version == Version::V1_16_5);
551            if !ok {
552                return Err(ClickError::InvalidButton);
553            }
554        }
555        let mut m = self.m.clone();
556        let item = {
557            let mut sim = Sim {
558                v: self.version,
559                lay,
560                m: &mut m,
561                book: &self.book,
562            };
563            sim.click(slot, button, mode)
564                .map_err(|_| ClickError::Unpredictable)?
565        };
566        self.commit(m, lay);
567        let (window_id, action) = match &mut self.screen {
568            ScreenState::Window(w) => {
569                w.action = w.action.wrapping_add(1);
570                (w.id, w.action)
571            }
572            _ => {
573                self.player_action = self.player_action.wrapping_add(1);
574                (0, self.player_action)
575            }
576        };
577        self.pending = Some(PendingClick {
578            window_id,
579            action,
580            age: 0,
581        });
582        self.flags.clicked = true;
583        Ok(Outgoing::Click(ClickPacket {
584            window_id: window_id as u8,
585            slot,
586            button,
587            mode,
588            action,
589            item,
590        }))
591    }
592
593    /// Replaces the model with the simulated one, records which parts changed and marks a
594    /// crafting result unknown when its grid changed.
595    fn commit(&mut self, new: Model, lay: Layout) {
596        let old = std::mem::replace(&mut self.m, new);
597        if old.player != self.m.player || old.craft != self.m.craft {
598            self.events.player_changed = true;
599        }
600        if old.craft_result != self.m.craft_result {
601            self.events.player_changed = true;
602        }
603        if old.container != self.m.container {
604            self.events.window_changed = true;
605        }
606        if old.cursor != self.m.cursor {
607            self.events.cursor_changed = true;
608        }
609        // 1.8: the simulation recomputed the result itself; 1.16.5: the server sends it.
610        if self.version == Version::V1_8 {
611            return;
612        }
613        if old.craft != self.m.craft {
614            self.m.craft_result_known = false;
615        }
616        if lay.screen == Screen::Container(WindowKind::Crafting)
617            && old.container.get(1..10) != self.m.container.get(1..10)
618        {
619            self.m.container_result_known = false;
620        }
621    }
622
623    /// Opens the player inventory GUI (key E). Returns the packet to send (1.8: the "open
624    /// inventory achievement" client command; 1.16.5: nothing). No-op when already open.
625    pub fn open_inventory(&mut self) -> Result<Option<Outgoing>, ClickError> {
626        match self.screen {
627            ScreenState::Inventory => return Ok(None),
628            ScreenState::Window(_) => return Err(ClickError::WindowOpen),
629            ScreenState::None => {}
630        }
631        if self.flags.clicked || self.flags.closed {
632            return Err(ClickError::SameTick);
633        }
634        self.screen = ScreenState::Inventory;
635        self.flags.opened = true;
636        Ok((self.version == Version::V1_8).then_some(Outgoing::OpenInventory))
637    }
638
639    /// Closes the open GUI (Escape / E): `close_window` with its id. The client drops the
640    /// cursor stack (the server throws it) and, for the 1.8 player inventory, empties the
641    /// crafting grid (the server drops it).
642    pub fn close(&mut self) -> Result<Outgoing, ClickError> {
643        if self.screen == ScreenState::None {
644            return Err(ClickError::NoScreen);
645        }
646        if self.flags.opened {
647            return Err(ClickError::SameTick);
648        }
649        let id = match &self.screen {
650            ScreenState::Window(w) => w.id as u8,
651            _ => 0,
652        };
653        self.close_screen();
654        self.flags.closed = true;
655        Ok(Outgoing::CloseWindow(id))
656    }
657
658    /// The client side of closing the current screen handler (`closeScreen` + `close`).
659    fn close_screen(&mut self) {
660        if self.m.cursor.take().is_some() {
661            self.events.cursor_changed = true;
662        }
663        match std::mem::replace(&mut self.screen, ScreenState::None) {
664            ScreenState::Inventory => {
665                if self.version == Version::V1_8 {
666                    // PlayerScreenHandler.close: grid dropped, result cleared (also on the client)
667                    if self.m.craft.iter().any(Option::is_some) {
668                        self.events.player_changed = true;
669                    }
670                    self.m.craft = Default::default();
671                }
672                self.m.craft_result = None;
673                self.m.craft_result_known = self.version == Version::V1_8;
674            }
675            ScreenState::Window(_) => {
676                self.m.container.clear();
677                self.m.container_result_known = true;
678            }
679            ScreenState::None => {}
680        }
681        if let Some((w, _)) = self.resync
682            && w != 0
683        {
684            self.resync = None;
685        }
686    }
687
688    /// Client-side use of the held stack (no packet): `n` items off the selected hotbar stack,
689    /// the slot emptied when nothing is left. Vanilla does this when a right click places a block
690    /// or plants seeds (1.8 `BlockItem` / `SeedItem.use`, 1.16.5 `BlockItem.place`) or
691    /// when eating finishes, before the server's `set_slot`; call it then (not in creative,
692    /// where vanilla keeps the count). Returns whether there was a stack.
693    pub fn consume_held(&mut self, n: u8) -> bool {
694        self.consume(usize::from(self.m.selected.min(8)), n)
695    }
696
697    /// [`consume_held`](Inventory::consume_held) for the offhand stack (1.16.5; no-op on 1.8).
698    pub fn consume_offhand(&mut self, n: u8) -> bool {
699        self.version == Version::V1_16_5 && self.consume(40, n)
700    }
701
702    fn consume(&mut self, k: usize, n: u8) -> bool {
703        let slot = &mut self.m.player[k];
704        let Some(s) = slot.as_mut() else {
705            return false;
706        };
707        s.count -= i32::from(n);
708        if s.count <= 0 {
709            *slot = None;
710        }
711        self.events.player_changed = true;
712        true
713    }
714
715    /// Selects a hotbar slot (the behaviour's `select_slot`; vanilla's insertStack prefers it).
716    pub fn select(&mut self, slot: u8) {
717        if slot < 9 {
718            self.m.selected = slot;
719        }
720    }
721
722    // ------------------------------------------------------------------ inbound
723
724    /// `held_item_slot` from the server.
725    pub fn on_held_slot(&mut self, slot: i8) {
726        if (0..9).contains(&slot) {
727            self.m.selected = slot as u8;
728        }
729    }
730
731    /// `open_window`: the server opened a window of this kind (`None`: a type the vanilla
732    /// client has no screen for; ignored). Any open screen is closed client-side first.
733    pub fn on_open_window(&mut self, id: i32, kind: Option<WindowKind>, title: ByteString) {
734        let Some(kind) = kind else { return };
735        if self.screen != ScreenState::None {
736            self.close_screen();
737        }
738        let n = kind.container_len(self.version);
739        self.m.container = vec![None; n];
740        self.m.container_result_known = true;
741        self.screen = ScreenState::Window(Window {
742            id,
743            kind,
744            title,
745            action: 0,
746            properties: Vec::new(),
747        });
748        self.events.opened = Some(id);
749        self.events.window_changed = true;
750    }
751
752    /// `close_window` from the server (closes whatever is open, whatever the id).
753    pub fn on_close_window(&mut self) {
754        if self.screen != ScreenState::None {
755            let was_window = matches!(self.screen, ScreenState::Window(_));
756            self.close_screen();
757            if was_window {
758                self.events.closed = true;
759            }
760        }
761    }
762
763    fn open_id(&self) -> i32 {
764        match &self.screen {
765            ScreenState::Window(w) => w.id,
766            _ => 0,
767        }
768    }
769
770    /// `window_items`: replaces the window's slots (`window_id` as received, unsigned byte).
771    pub fn on_window_items(
772        &mut self,
773        window_id: i32,
774        items: impl IntoIterator<Item = Option<Stack>>,
775    ) {
776        let lay = if window_id == 0 {
777            Layout::new(self.version, Screen::Player)
778        } else if window_id == self.open_id() {
779            self.layout()
780        } else {
781            return;
782        };
783        let mut player = false;
784        let mut window = false;
785        let mut touched_grid = false;
786        for (i, s) in items.into_iter().enumerate() {
787            let Some(l) = lay.loc(i) else { break };
788            touched_grid |= is_grid(lay, l);
789            let mut s = self.normalize(s);
790            if lay.clamps(l) {
791                crate::sim::clamp(&mut s);
792            }
793            let slot = self.m.at_mut(l);
794            if *slot != s {
795                *slot = s;
796                match l {
797                    Loc::Container(_) => window = true,
798                    _ => player = true,
799                }
800            }
801        }
802        if lay.screen == Screen::Player {
803            self.m.craft_result_known = true;
804        } else {
805            self.m.container_result_known = true;
806        }
807        // 1.8: setting the grid slots made the client compute the result itself
808        if self.version == Version::V1_8 && touched_grid {
809            crate::sim::recompute_1_8(&mut self.m, lay);
810        }
811        self.events.player_changed |= player;
812        self.events.window_changed |= window;
813        if self.resync.is_some_and(|(w, _)| w == window_id) {
814            self.resync = None;
815        }
816    }
817
818    /// `set_slot` (`window_id` as received, signed byte): -1 sets the cursor, 1.16.5's -2 a
819    /// `PlayerInventory` index, window 0 slots 36..45 always reach window 0, others only the
820    /// current screen.
821    pub fn on_set_slot(&mut self, window_id: i32, slot: i16, item: Option<Stack>) {
822        let item = self.normalize(item);
823        if window_id == -1 {
824            if self.m.cursor != item {
825                self.m.cursor = item;
826                self.events.cursor_changed = true;
827            }
828            return;
829        }
830        let loc = if window_id == -2 && self.version == Version::V1_16_5 {
831            usize::try_from(slot)
832                .ok()
833                .filter(|&k| k < 41)
834                .map(Loc::Player)
835        } else if window_id == 0 && (36..45).contains(&slot) {
836            Layout::new(self.version, Screen::Player).loc(slot as usize)
837        } else if window_id == self.open_id() {
838            usize::try_from(slot)
839                .ok()
840                .and_then(|i| self.layout().loc(i))
841        } else {
842            None
843        };
844        let Some(l) = loc else { return };
845        let mut item = item;
846        if self.layout().clamps(l) {
847            crate::sim::clamp(&mut item);
848        }
849        match l {
850            Loc::CraftResult => self.m.craft_result_known = true,
851            Loc::Container(0)
852                if matches!(
853                    self.layout().screen,
854                    Screen::Container(WindowKind::Crafting)
855                ) =>
856            {
857                self.m.container_result_known = true;
858            }
859            _ => {}
860        }
861        let s = self.m.at_mut(l);
862        if *s != item {
863            *s = item;
864            match l {
865                Loc::Container(_) => self.events.window_changed = true,
866                _ => self.events.player_changed = true,
867            }
868        }
869        if self.version == Version::V1_8 {
870            // the slot's screen: window 0 for its hotbar slots, else the current one
871            let lay = if window_id == 0 && (36..45).contains(&slot) {
872                Layout::new(self.version, Screen::Player)
873            } else {
874                self.layout()
875            };
876            if is_grid(lay, l) {
877                crate::sim::recompute_1_8(&mut self.m, lay);
878            }
879        }
880    }
881
882    /// The crafting recipes the server declared (1.16.5; 1.8 clients know theirs).
883    #[must_use]
884    pub fn recipes(&self) -> &RecipeBook {
885        &self.book
886    }
887
888    /// 1.16.5 `declare_recipes`: replaces the client's crafting recipes (used for the remainders
889    /// of a taken crafting result).
890    pub fn on_declare_recipes(&mut self, book: RecipeBook) {
891        self.book = book;
892    }
893
894    /// `craft_progress_bar` (window property).
895    pub fn on_window_property(&mut self, window_id: i32, property: i16, value: i16) {
896        if let ScreenState::Window(w) = &mut self.screen
897            && w.id == window_id
898        {
899            match w.properties.iter_mut().find(|p| p.0 == property) {
900                Some(p) => p.1 = value,
901                None => w.properties.push((property, value)),
902            }
903        }
904    }
905
906    /// `transaction` (window confirm) from the server. Returns the answer to send now, exactly
907    /// when vanilla answers (not accepted, and the window is 0 or the open one); resolves the
908    /// pending click when it is its confirm. Route every confirm through here and answer
909    /// nowhere else, so each is answered exactly once.
910    pub fn on_transaction(
911        &mut self,
912        window_id: i8,
913        action: i16,
914        accepted: bool,
915    ) -> Option<Outgoing> {
916        let w = i32::from(window_id);
917        if let Some(p) = self.pending
918            && p.window_id == w
919            && p.action == action
920        {
921            self.pending = None;
922            let outcome = if accepted {
923                ClickOutcome::Accepted
924            } else {
925                self.resync = Some((w, 0));
926                ClickOutcome::Rejected
927            };
928            self.events.clicks.push(ClickResult {
929                window_id: w,
930                action,
931                outcome,
932            });
933        }
934        let known = w == 0 || w == self.open_id();
935        (known && !accepted).then_some(Outgoing::Confirm { window_id, action })
936    }
937
938    /// 1.16.5 drops empty stacks; 1.8 keeps zero-count stacks.
939    fn normalize(&self, s: Option<Stack>) -> Option<Stack> {
940        match self.version {
941            Version::V1_8 => s,
942            Version::V1_16_5 => s
943                .filter(|s| s.count > 0 && s.id != 0)
944                .map(|s| Stack { damage: 0, ..s }),
945        }
946    }
947}