ghast_inventory/inventory/mod.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, VersionNotEnabled};
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/// Version tags for loops monomorphised per version ([`Inventory::on_window_items`]).
23const V18: u8 = 0;
24const V112: u8 = 1;
25const V1165: u8 = 2;
26const V261: u8 = 3;
27const V262: u8 = 4;
28const V263: u8 = 5;
29
30/// One incoming `window_items` slot: [`Incoming::settle`] stores it (normalised and clamped
31/// like vanilla's handler) and says whether the slot changed.
32trait Incoming {
33 fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool;
34}
35
36impl Incoming for Option<Stack> {
37 #[inline(always)]
38 fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
39 let s = normalize_as::<V>(self);
40 let s = if clamp { clamp_as::<V>(s) } else { s };
41 if same_slot(slot, &s) {
42 false
43 } else {
44 *slot = s;
45 true
46 }
47 }
48}
49
50#[cfg(any(feature = "v1_8", feature = "v1_12"))]
51impl Incoming for &ghast_protocol::types::slot::legacy::Slot {
52 #[inline(always)]
53 fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
54 if legacy_same::<V>(slot, self, clamp) {
55 return false;
56 }
57 crate::stack::from_legacy_slot(self.clone()).settle::<V>(slot, clamp);
58 true
59 }
60}
61
62/// Whether `stored` equals the 1.8 / 1.12 wire slot `w` after normalising and clamping, i.e.
63/// what [`Incoming::settle`] of the converted slot would compare.
64#[cfg(any(feature = "v1_8", feature = "v1_12"))]
65#[inline(always)]
66fn legacy_same<const V: u8>(
67 stored: &Option<Stack>,
68 w: &ghast_protocol::types::slot::legacy::Slot,
69 clamp: bool,
70) -> bool {
71 let Some(ws) = &w.0 else {
72 return stored.is_none();
73 };
74 let id = i32::from(ws.id);
75 let mut count = i32::from(ws.count);
76 if V != V18 && (count <= 0 || id == 0) {
77 return stored.is_none();
78 }
79 if V == V261 || V == V262 || V == V263 || V == V1165 {
80 // legacy slots never reach these versions (see `on_window_items_legacy`)
81 return false;
82 }
83 if clamp && count > 64 {
84 count = 64;
85 }
86 let Some(st) = stored else {
87 return false;
88 };
89 st.id == id
90 && st.count == count
91 && st.damage == ws.damage
92 && match (&st.data, &ws.nbt) {
93 (crate::stack::ItemData::None, None) => true,
94 (crate::stack::ItemData::Nbt(a), Some(b)) => a == b,
95 _ => false,
96 }
97}
98
99/// [`Inventory::normalize`] with the version as a constant.
100#[inline(always)]
101fn normalize_as<const V: u8>(s: Option<Stack>) -> Option<Stack> {
102 if V == V18 {
103 return s;
104 }
105 let mut s = s.filter(|s| s.count > 0 && s.id != 0);
106 if V != V112
107 && let Some(st) = &mut s
108 {
109 st.damage = 0;
110 }
111 s
112}
113
114/// [`crate::sim::clamp_v`] with the version as a constant.
115#[inline(always)]
116fn clamp_as<const V: u8>(mut s: Option<Stack>) -> Option<Stack> {
117 if V == V261 {
118 crate::sim::clamp_v(Version::V26_1, &mut s);
119 } else if V == V262 {
120 crate::sim::clamp_v(Version::V26_2, &mut s);
121 } else if V == V263 {
122 crate::sim::clamp_v(Version::V26_3, &mut s);
123 } else {
124 crate::sim::clamp(&mut s);
125 }
126 s
127}
128
129/// `a == b` for slots, written out so the common equal-NBT case stays a few compares and one
130/// `memcmp` whatever variants `ItemData` has.
131#[inline(always)]
132fn same_slot(a: &Option<Stack>, b: &Option<Stack>) -> bool {
133 match (a, b) {
134 (None, None) => true,
135 (Some(a), Some(b)) => {
136 a.id == b.id && a.count == b.count && a.damage == b.damage && a.data == b.data
137 }
138 _ => false,
139 }
140}
141
142/// The `Window::menu` of a 26.1 mount screen (`horse_screen_open`; not a `minecraft:menu` id).
143#[cfg(modern)]
144const MOUNT_MENU: i32 = 1000;
145
146/// 26.1: ticks without a correcting container packet after which a click counts as accepted
147/// (see [`Inventory::set_click_settle_ticks`]).
148pub const DEFAULT_CLICK_SETTLE_TICKS: u32 = 4;
149
150/// Ticks a click may wait for its confirm before it is given up ([`ClickOutcome::TimedOut`]).
151pub const DEFAULT_CLICK_TIMEOUT_TICKS: u32 = 40;
152
153/// A click intent: the vanilla GUI gestures a bot needs. Slot numbers are the open screen's
154/// (window 0 when only the player inventory is open); [`OUTSIDE`] (-999) is a click outside the
155/// window.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
157#[non_exhaustive]
158pub enum Click {
159 /// Mode 0: left click (`right = false`: pick up / put down / swap the whole stack) or right
160 /// click (pick up half / put down one). On [`OUTSIDE`] it drops the cursor stack (left) or
161 /// one item of it (right).
162 Pickup {
163 /// Slot, or [`OUTSIDE`].
164 slot: i16,
165 /// Right mouse button.
166 right: bool,
167 },
168 /// Mode 1: shift-click (move the stack to the other part of the window).
169 QuickMove {
170 /// Slot.
171 slot: i16,
172 /// Right mouse button (same effect).
173 right: bool,
174 },
175 /// Mode 2: number key over a slot: swap it with hotbar slot `hotbar` (0..=8), or on 1.16.5
176 /// `40` (the swap-hands key) with the offhand.
177 Swap {
178 /// Slot.
179 slot: i16,
180 /// Hotbar index 0..=8, or 40 (offhand, 1.16.5 only).
181 hotbar: u8,
182 },
183 /// Mode 4: drop key over a slot (`all = false`: one item, Q; `all = true`: the stack,
184 /// ctrl+Q). With an empty cursor and [`OUTSIDE`] this is what the vanilla GUI sends for a
185 /// click outside the window (no effect).
186 Drop {
187 /// Slot, or [`OUTSIDE`].
188 slot: i16,
189 /// Whole stack.
190 all: bool,
191 },
192 /// Mode 6: double click: gather items like the cursor stack into it.
193 PickupAll {
194 /// Slot (normally the now empty slot the stack was picked up from).
195 slot: i16,
196 },
197 /// Mode 3: middle click in creative mode: a full stack of the slot's item onto the empty
198 /// cursor (26.1; no effect outside creative mode).
199 Clone {
200 /// Slot.
201 slot: i16,
202 },
203 /// Mode 5: one packet of a drag ("quick craft"): the GUI sends [`DragStage::Start`] (slot
204 /// [`OUTSIDE`]), one [`DragStage::Slot`] per slot the mouse crosses, then
205 /// [`DragStage::End`] (slot [`OUTSIDE`]), each its own click (26.1).
206 QuickCraft {
207 /// Slot ([`OUTSIDE`] for start and end).
208 slot: i16,
209 /// Which packet of the drag.
210 stage: DragStage,
211 /// How the carried stack is spread.
212 kind: DragKind,
213 },
214}
215
216/// The packet of a drag ([`Click::QuickCraft`]): vanilla's quick-craft header.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
218#[non_exhaustive]
219pub enum DragStage {
220 /// Mouse pressed over the screen (header 0).
221 Start,
222 /// The mouse crossed a slot (header 1).
223 Slot,
224 /// Mouse released: the stack is spread (header 2).
225 End,
226}
227
228/// How a drag spreads the carried stack ([`Click::QuickCraft`]): vanilla's quick-craft type.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
230#[non_exhaustive]
231pub enum DragKind {
232 /// Left button: split evenly (type 0).
233 Split,
234 /// Right button: one item per slot (type 1).
235 One,
236 /// Middle button, creative mode: a full stack per slot (type 2).
237 Clone,
238}
239
240impl Click {
241 /// The wire `(slot, button, mode)`.
242 #[must_use]
243 pub fn wire(self) -> (i16, u8, u8) {
244 match self {
245 Click::Pickup { slot, right } => (slot, u8::from(right), 0),
246 Click::QuickMove { slot, right } => (slot, u8::from(right), 1),
247 Click::Swap { slot, hotbar } => (slot, hotbar, 2),
248 Click::Drop { slot, all } => (slot, u8::from(all), 4),
249 Click::PickupAll { slot } => (slot, 0, 6),
250 Click::Clone { slot } => (slot, 2, 3),
251 Click::QuickCraft { slot, stage, kind } => {
252 let header = match stage {
253 DragStage::Start => 0,
254 DragStage::Slot => 1,
255 DragStage::End => 2,
256 };
257 let ty = match kind {
258 DragKind::Split => 0,
259 DragKind::One => 1,
260 DragKind::Clone => 2,
261 };
262 (slot, header | ty << 2, 5)
263 }
264 }
265 }
266}
267
268/// Why a click (or open / close) was refused. Nothing was sent and nothing changed.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
270#[non_exhaustive]
271pub enum ClickError {
272 /// The previous click's confirm has not arrived yet (one click in flight).
273 Pending,
274 /// The server rejected a click and its full window resync has not arrived yet.
275 Resyncing,
276 /// Nothing is open: open the player inventory ([`Inventory::open_inventory`]) or wait for a
277 /// container window.
278 NoScreen,
279 /// A container window is open (the player inventory cannot be opened over it).
280 WindowOpen,
281 /// Same-tick packet order vanilla never produces (and Grim's PacketOrder checks flag): a
282 /// second click this tick, a click / close in the tick the inventory was opened, or the
283 /// other way round. Retry next tick.
284 SameTick,
285 /// The slot does not exist in the open screen (or `OUTSIDE` where not allowed).
286 InvalidSlot,
287 /// Invalid hotbar index for [`Click::Swap`].
288 InvalidButton,
289 /// The result depends on data ghast does not model (recipes, fuel, brewing, trading,
290 /// enchanting, an unknown crafting result); sending it would desynchronise the inventory.
291 Unpredictable,
292}
293
294impl std::fmt::Display for ClickError {
295 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296 f.write_str(match self {
297 ClickError::Pending => "a click is waiting for its confirm",
298 ClickError::Resyncing => "waiting for the window resync after a rejected click",
299 ClickError::NoScreen => "no inventory screen is open",
300 ClickError::WindowOpen => "a container window is open",
301 ClickError::SameTick => "not allowed in the same tick",
302 ClickError::InvalidSlot => "invalid slot",
303 ClickError::InvalidButton => "invalid button",
304 ClickError::Unpredictable => "click outcome cannot be predicted",
305 })
306 }
307}
308
309impl std::error::Error for ClickError {}
310
311/// A window click as sent (`window_click`; 1.8 `ClickWindowC2SPacket`).
312#[derive(Debug, Clone, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct ClickPacket {
315 /// Window id (0 = player inventory).
316 pub window_id: u8,
317 /// Slot, or -999.
318 pub slot: i16,
319 /// Mouse button / hotbar key.
320 pub button: u8,
321 /// Click mode.
322 pub mode: u8,
323 /// Action number: the window's counter, incremented before each click.
324 pub action: i16,
325 /// What vanilla's `onSlotClick` returned (the server compares it with its own result).
326 pub item: Option<Stack>,
327 /// 1.16.5: arm swings (main hand) to send before the click: the client's
328 /// `PlayerEntity.dropItem` swings for each stack the click drops (a throw, a click
329 /// outside with a carried stack); 0 on the other versions.
330 pub swings: u8,
331}
332
333/// A packet the inventory wants sent. Write it right away, in call order (before the tick's
334/// movement packet when it comes from a behaviour action).
335#[derive(Debug, Clone, PartialEq, Eq)]
336#[non_exhaustive]
337pub enum Outgoing {
338 /// `window_click`.
339 Click(ClickPacket),
340 /// `transaction` answer to a rejected confirm (always `accepted = true`, like vanilla).
341 Confirm {
342 /// Window id as received.
343 window_id: i8,
344 /// Action number as received.
345 action: i16,
346 },
347 /// `close_window` with this id (0 = player inventory).
348 CloseWindow(u8),
349 /// 1.8 only: `client_command` "open inventory achievement" (vanilla sends it when E opens
350 /// the inventory).
351 OpenInventory,
352 /// 26.1 `container_click` (no confirm exists: the server applies every click and resends
353 /// the slots whose hashes differ from its own result).
354 ContainerClick(ContainerClick),
355 /// 26.1 creative inventory screen (window 0 in creative mode): the packets the real
356 /// client sends, in order (often none). See [`CreativePacket`].
357 Creative(Vec<CreativePacket>),
358 /// 26.1 `rename_item`: the anvil's name field ([`Inventory::anvil_rename_modern`]).
359 RenameItem(String),
360 /// 26.1 `container_button_click` (a loom pattern: [`Inventory::select_loom_pattern_modern`]).
361 ButtonClick {
362 /// Container id.
363 window_id: i32,
364 /// Button id.
365 button: i32,
366 },
367 /// 26.1 `select_trade` ([`Inventory::select_trade_modern`]).
368 SelectTrade(i32),
369 /// 1.16.5 `arm_animation` (main hand) outside a click: the client dropped a carried stack
370 /// (`PlayerEntity.dropItem` swings), e.g. when a server window replaced the open screen.
371 Swing,
372}
373
374/// One packet the 26.1 creative inventory screen sends (`Outgoing::Creative`): the server
375/// trusts these stacks, so they are exactly what the real client sends.
376#[derive(Debug, Clone, PartialEq, Eq)]
377#[non_exhaustive]
378pub enum CreativePacket {
379 /// `swing` (main hand): a stack was dropped.
380 Swing,
381 /// `set_creative_mode_slot`: window 0 slot `slot` now holds `item` (`slot` -1: `item` is
382 /// dropped).
383 SetSlot {
384 /// Window 0 slot, or -1 for a drop.
385 slot: i16,
386 /// The stack.
387 item: Option<Stack>,
388 },
389}
390
391/// A 26.1 click as sent: what vanilla `MultiPlayerGameMode.handleContainerInput` writes.
392#[derive(Debug, Clone, PartialEq, Eq)]
393#[non_exhaustive]
394pub struct ContainerClick {
395 /// Container id (0 = player inventory).
396 pub window_id: i32,
397 /// The screen's state id (from the last `container_set_content` / `container_set_slot`).
398 pub state_id: i32,
399 /// Slot, or -999.
400 pub slot: i16,
401 /// Mouse button / hotbar key.
402 pub button: u8,
403 /// Click mode (`ContainerInput`).
404 pub mode: u8,
405 /// Slots whose stack the prediction changed, with the new stack (vanilla compares every slot
406 /// before and after the simulated click).
407 pub changed: Vec<(i16, Option<Stack>)>,
408 /// The cursor after the click.
409 pub carried: Option<Stack>,
410 /// `false` when ghast could not predict this click (see [`Inventory::click`]): nothing
411 /// changed locally, `changed` is empty, and the server's corrections bring the result.
412 pub predicted: bool,
413 /// ghast's own number for the click (per screen, like the legacy action number, but never
414 /// sent): the [`ClickResult::action`] that resolves it.
415 pub action: i16,
416 /// How many `swing` (main hand) packets the vanilla client sends right before this click:
417 /// every stack the click drops (outside the window, the drop key, a remainder that does not
418 /// fit) swings the arm. Send them first, then the click (0 when unpredicted; always 0 in
419 /// 26.3, whose swing sends no packet).
420 pub swings: u8,
421}
422
423/// What became of a click.
424#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
425#[non_exhaustive]
426pub enum ClickOutcome {
427 /// The server agreed with the prediction.
428 Accepted,
429 /// The server disagreed; it resends the window (the inventory waits for it).
430 Rejected,
431 /// No confirm within the timeout (the server may not have had that window open).
432 TimedOut,
433}
434
435/// A finished click.
436#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
437#[non_exhaustive]
438pub struct ClickResult {
439 /// Window id the click was sent for.
440 pub window_id: i32,
441 /// Its action number.
442 pub action: i16,
443 /// The outcome.
444 pub outcome: ClickOutcome,
445}
446
447impl ClickResult {
448 /// A result as [`Inventory::drain_events`] reports it (for tests and replays).
449 #[must_use]
450 pub fn new(window_id: i32, action: i16, outcome: ClickOutcome) -> ClickResult {
451 ClickResult {
452 window_id,
453 action,
454 outcome,
455 }
456 }
457}
458
459/// Changes since the last [`Inventory::drain_events`].
460#[derive(Debug, Clone, Default, PartialEq, Eq)]
461#[non_exhaustive]
462pub struct Events {
463 /// Something in the player's inventory (window 0, incl. crafting grid) changed.
464 pub player_changed: bool,
465 /// Something in the open window's own slots changed.
466 pub window_changed: bool,
467 /// The cursor stack changed.
468 pub cursor_changed: bool,
469 /// The server opened a window (its id).
470 pub opened: Option<i32>,
471 /// The open window was closed by the server.
472 pub closed: bool,
473 /// Clicks that were confirmed, rejected or timed out, in order.
474 pub clicks: Vec<ClickResult>,
475 /// The server sent the full contents of window 0 (`window_items` / 26.x
476 /// `container_set_content` for the player inventory): every slot of it, armor and the
477 /// crafting grid included, is the server's now. Servers send it at join, at respawn and
478 /// after a rejected click; a kit given with single `set_slot`s does not set it.
479 pub player_synced: bool,
480 /// The server sent the full contents of the open window (its own slots and the player
481 /// slots it shows).
482 pub window_synced: bool,
483}
484
485/// An open container window.
486#[derive(Debug, Clone, PartialEq, Eq)]
487pub struct Window {
488 id: i32,
489 kind: WindowKind,
490 title: ByteString,
491 action: i16,
492 properties: Vec<(i16, i16)>,
493 /// 26.1 `minecraft:menu` registry id (-1 for other versions).
494 menu: i32,
495}
496
497impl Window {
498 /// Window id (`syncId`).
499 #[must_use]
500 pub fn id(&self) -> i32 {
501 self.id
502 }
503 /// Its type.
504 #[must_use]
505 pub fn kind(&self) -> WindowKind {
506 self.kind
507 }
508 /// The title exactly as sent: a JSON chat component on both versions.
509 #[must_use]
510 pub fn title(&self) -> &ByteString {
511 &self.title
512 }
513 /// A window property (`craft_progress_bar`: furnace progress, enchanting seeds, …).
514 #[must_use]
515 pub fn property(&self, id: i16) -> Option<i16> {
516 self.properties.iter().find(|p| p.0 == id).map(|p| p.1)
517 }
518 /// 26.1: the `minecraft:menu` registry id of `open_screen` (`None` for other versions).
519 #[must_use]
520 pub fn menu_modern(&self) -> Option<i32> {
521 (self.menu >= 0).then_some(self.menu)
522 }
523}
524
525/// Which screen the client has open.
526#[derive(Debug, Clone, PartialEq, Eq)]
527enum ScreenState {
528 None,
529 Inventory,
530 Window(Window),
531}
532
533#[derive(Debug, Clone, Copy)]
534struct PendingClick {
535 window_id: i32,
536 action: i16,
537 age: u32,
538}
539
540#[derive(Debug, Clone, Copy, Default)]
541struct TickFlags {
542 clicked: bool,
543 opened: bool,
544 closed: bool,
545}
546
547/// The client's inventory: player inventory, cursor, the open window, click prediction and
548/// the confirm protocol. Pure and deterministic: packets in, packets out, no I/O or clock
549/// ([`tick`](Inventory::tick) counts time).
550#[derive(Debug, Clone)]
551pub struct Inventory {
552 version: Version,
553 m: Model,
554 screen: ScreenState,
555 player_action: i16,
556 pending: Option<PendingClick>,
557 resync: Option<(i32, u32)>,
558 flags: TickFlags,
559 timeout: u32,
560 settle: u32,
561 events: Events,
562 /// Server writes of each hotbar slot and (last) the off hand (`set_slot`,
563 /// `window_items`), changed or not.
564 hotbar_writes: [u16; 10],
565 book: RecipeBook,
566 /// 1.16.5: the server's item tags (they belong to the connection, like the recipes).
567 tags16: Option<std::sync::Arc<crate::tags16::ItemTags16>>,
568 /// 26.1 state ids: window 0 (`inventoryMenu`) and the open container.
569 state_player: i32,
570 state_window: i32,
571 /// 26.1 registry names for click hashes and the binding curse.
572 #[cfg(modern)]
573 reg26: crate::item26::HashRegistries,
574 /// 26.1: recipe item sets, game mode, experience level.
575 #[cfg(modern)]
576 w26: crate::sim26::World26,
577 /// 26.1: window 0's and the open container's per-screen click state (drags, …).
578 #[cfg(modern)]
579 s26: [crate::sim26::Screen26; 2],
580 /// 26.1: window 0's `lastSlots` (what its last `broadcastChanges` saw; the creative
581 /// screen's listener sends every slot that differs).
582 #[cfg(modern)]
583 creative_last: Vec<Option<Stack>>,
584 /// 26.1: the creative inventory screen is open (window 0 in creative mode).
585 #[cfg(modern)]
586 creative_screen: bool,
587 /// 26.1: packets the creative screen sends in answer to server packets
588 /// ([`Inventory::take_creative_echo_modern`]).
589 #[cfg(modern)]
590 creative_echo: Vec<CreativePacket>,
591 /// 26.1 `LocalPlayer.dropSpamThrottler`: +20 per creative drop, -1 per tick; drops are
592 /// refused from 1280 (`canDropItems`).
593 #[cfg(modern)]
594 drop_throttle: i32,
595 /// 26.1 `update_recipes` body, not parsed yet (parsed when a menu needs its item sets).
596 #[cfg(modern)]
597 recipes_raw: Option<bytes::Bytes>,
598 /// 26.1 tags and enchantment definitions (raw until a menu needs them).
599 #[cfg(modern)]
600 d26: crate::data26::Data26,
601 /// 1.8 – 1.16.5: the creative inventory screen, allocated at its first open.
602 creative16: Option<Box<creative_legacy::CreativeLegacy>>,
603}
604
605mod aliases;
606mod click;
607mod creative_legacy;
608mod hands;
609mod inbound;
610#[cfg(modern)]
611mod modern;
612mod read;
613mod screens;
614
615pub use creative_legacy::CreativeTab;
616
617/// The write counter of a hotbar slot (0 … 8) or the off hand (9) for a slot location.
618#[inline]
619fn hand_writes_index(l: Loc) -> Option<usize> {
620 match l {
621 Loc::Player(k @ 0..9) => Some(k),
622 Loc::Player(40) => Some(9),
623 _ => None,
624 }
625}
626
627impl Inventory {
628 /// An empty inventory (a fresh player entity).
629 ///
630 /// # Errors
631 /// [`VersionNotEnabled`] when this build of the crate lacks the version's feature
632 /// ([`Version::is_enabled`]).
633 pub fn new(version: Version) -> Result<Inventory, VersionNotEnabled> {
634 if version.is_enabled() {
635 Ok(Inventory::empty(version))
636 } else {
637 Err(VersionNotEnabled(version))
638 }
639 }
640
641 fn empty(version: Version) -> Inventory {
642 Inventory {
643 version,
644 m: Model::default(),
645 screen: ScreenState::None,
646 player_action: 0,
647 pending: None,
648 resync: None,
649 flags: TickFlags::default(),
650 timeout: DEFAULT_CLICK_TIMEOUT_TICKS,
651 settle: DEFAULT_CLICK_SETTLE_TICKS,
652 events: Events::default(),
653 hotbar_writes: [0; 10],
654 book: RecipeBook::default(),
655 tags16: None,
656 state_player: 0,
657 state_window: 0,
658 #[cfg(modern)]
659 reg26: crate::item26::HashRegistries::default(),
660 #[cfg(modern)]
661 w26: crate::sim26::World26::default(),
662 #[cfg(modern)]
663 s26: Default::default(),
664 #[cfg(modern)]
665 creative_last: Vec::new(),
666 #[cfg(modern)]
667 creative_screen: false,
668 #[cfg(modern)]
669 creative_echo: Vec::new(),
670 #[cfg(modern)]
671 drop_throttle: 0,
672 #[cfg(modern)]
673 recipes_raw: None,
674 #[cfg(modern)]
675 d26: Default::default(),
676 creative16: None,
677 }
678 }
679
680 /// Sets how many ticks a click may wait for its confirm.
681 pub fn set_click_timeout(&mut self, ticks: u32) {
682 self.timeout = ticks.max(1);
683 }
684
685 /// 26.1: how many ticks after a click without a correcting container packet make it
686 /// [`ClickOutcome::Accepted`]. 26.1 has no confirm: the server applies the click when it
687 /// receives it and answers in the same moment, with `container_set_slot` /
688 /// `container_set_content` / `set_cursor_item` only for slots its result disagrees with, and
689 /// with nothing when the client predicted right. So silence is the acceptance; set this to
690 /// cover the round trip (`ceil(rtt / 50 ms) + 1`; default
691 /// [`DEFAULT_CLICK_SETTLE_TICKS`]). A correction before that makes the click
692 /// [`ClickOutcome::Rejected`] (already applied: no resync wait).
693 pub fn set_click_settle_ticks(&mut self, ticks: u32) {
694 self.settle = ticks.max(1);
695 }
696
697 /// The protocol version.
698 #[must_use]
699 pub fn version(&self) -> Version {
700 self.version
701 }
702
703 /// The level of enchantment `name` (`sharpness` or `minecraft:sharpness`) on `stack`, on
704 /// every version (1.8 / 1.12 numeric ids, 1.16.5 names, 26.x the server's enchantment
705 /// registry from [`Inventory::set_registries_modern`]); 0 when it has none.
706 #[must_use]
707 pub fn enchantment_level(&self, stack: &crate::Stack, name: &str) -> i32 {
708 let want = name.strip_prefix("minecraft:").unwrap_or(name);
709 #[cfg(modern)]
710 let registry: &[String] = self.reg26.enchantments();
711 #[cfg(not(modern))]
712 let registry: &[String] = &[];
713 stack
714 .enchantments(self.version)
715 .iter()
716 .find(|e| e.id.plain_name(registry) == Some(want))
717 .map_or(0, |e| e.level)
718 }
719
720 /// The modern table set of this inventory's version (a placeholder for a legacy one: only
721 /// modern code paths read it).
722 #[cfg(modern)]
723 #[inline]
724 pub(crate) fn mv(&self) -> crate::tables::Mv {
725 crate::tables::Mv::of(self.version).unwrap_or(crate::tables::Mv::ANY)
726 }
727
728 /// A new player entity (join, respawn, dimension change): everything is cleared,
729 /// including the action counters; the server resends the inventory.
730 /// The selected hotbar slot restarts at 0 too (a new `PlayerInventory`).
731 pub fn reset(&mut self) {
732 // the recipe book belongs to the connection, not to the player entity
733 #[cfg(modern)]
734 let reg26 = std::mem::take(&mut self.reg26);
735 #[cfg(modern)]
736 let w26 = std::mem::take(&mut self.w26);
737 #[cfg(modern)]
738 let recipes_raw = self.recipes_raw.take();
739 #[cfg(modern)]
740 let d26 = std::mem::take(&mut self.d26);
741 *self = Inventory {
742 timeout: self.timeout,
743 settle: self.settle,
744 book: std::mem::take(&mut self.book),
745 hotbar_writes: self.hotbar_writes,
746 tags16: self.tags16.take(),
747 #[cfg(modern)]
748 reg26,
749 #[cfg(modern)]
750 w26,
751 #[cfg(modern)]
752 recipes_raw,
753 #[cfg(modern)]
754 d26,
755 creative16: self
756 .creative16
757 .take()
758 .map(creative_legacy::CreativeLegacy::respawned),
759 ..Inventory::empty(self.version)
760 };
761 self.events.player_changed = true;
762 }
763
764 /// Call once at the start of every client tick: resets the per-tick packet-order guard
765 /// and ages the pending click.
766 pub fn tick(&mut self) {
767 self.flags = TickFlags::default();
768 #[cfg(modern)]
769 if self.drop_throttle > 0 {
770 self.drop_throttle -= 1;
771 }
772 if let Some(p) = &mut self.pending {
773 p.age += 1;
774 if self.version.is_modern() && p.age >= self.settle {
775 self.events.clicks.push(ClickResult {
776 window_id: p.window_id,
777 action: p.action,
778 outcome: ClickOutcome::Accepted,
779 });
780 self.pending = None;
781 } else if p.age >= self.timeout {
782 self.events.clicks.push(ClickResult {
783 window_id: p.window_id,
784 action: p.action,
785 outcome: ClickOutcome::TimedOut,
786 });
787 self.pending = None;
788 }
789 }
790 if let Some((_, age)) = &mut self.resync {
791 *age += 1;
792 if *age >= self.timeout {
793 self.resync = None;
794 }
795 }
796 }
797
798 /// Takes the accumulated change flags and click results.
799 pub fn drain_events(&mut self) -> Events {
800 std::mem::take(&mut self.events)
801 }
802}