Skip to main content

ghast_inventory/inventory/
inbound.rs

1//! The server's inventory packets: held slot, open / close window, window items, set slot
2//! (legacy and 26.x), cursor, player inventory, recipes, window properties and confirms.
3
4use super::*;
5
6impl Inventory {
7    // ------------------------------------------------------------------ inbound
8
9    /// `held_item_slot` from the server.
10    pub fn on_held_slot(&mut self, slot: i8) {
11        if (0..9).contains(&slot) {
12            self.m.selected = slot as u8;
13            self.m.player.touch();
14        }
15    }
16
17    /// `open_window`: the server opened a window of this kind (`None`: a type the vanilla
18    /// client has no screen for; ignored). Any open screen is closed client-side first.
19    pub fn on_open_window(&mut self, id: i32, kind: Option<WindowKind>, title: ByteString) {
20        let Some(kind) = kind else { return };
21        if self.screen != ScreenState::None {
22            self.close_screen();
23        }
24        let n = kind.container_len(self.version);
25        self.m.container = vec![None; n];
26        self.m.merchant = (kind == WindowKind::Merchant
27            && crate::menus::modelled(self.version, kind))
28        .then(Box::default);
29        self.m.mount = None;
30        self.m.furnace = 0;
31        self.m.station = crate::station::Station::of(self.version, kind).map(Box::new);
32        self.m.container_result_known = true;
33        self.m.container_fresh = true;
34        self.screen = ScreenState::Window(Window {
35            id,
36            kind,
37            title,
38            action: 0,
39            properties: Vec::new(),
40            menu: -1,
41        });
42        self.events.opened = Some(id);
43        self.events.window_changed = true;
44    }
45
46    /// `close_window` from the server (closes whatever is open, whatever the id).
47    pub fn on_close_window(&mut self) {
48        if self.screen != ScreenState::None {
49            let was_window = matches!(self.screen, ScreenState::Window(_));
50            self.close_screen();
51            if was_window {
52                self.events.closed = true;
53            }
54        }
55    }
56
57    pub(super) fn open_id(&self) -> i32 {
58        match &self.screen {
59            ScreenState::Window(w) => w.id,
60            _ => 0,
61        }
62    }
63
64    /// `window_items`: replaces the window's slots (`window_id` as received, unsigned byte).
65    pub fn on_window_items(
66        &mut self,
67        window_id: i32,
68        items: impl IntoIterator<Item = Option<Stack>>,
69    ) {
70        // One loop per version: the per-slot normalising and clamping rules are constants
71        // inside it, so the legacy hot path carries no version tests.
72        let items = items.into_iter();
73        match self.version {
74            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items),
75            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items),
76            Version::V1_16_5 => self.window_items_as::<V1165, _>(window_id, items),
77            Version::V26_1 => self.window_items_as::<V261, _>(window_id, items),
78            #[cfg(feature = "v26_2")]
79            Version::V26_2 => self.window_items_as::<V262, _>(window_id, items),
80            // no inventory exists for a disabled version
81            #[cfg(not(feature = "v26_2"))]
82            Version::V26_2 => {}
83            #[cfg(feature = "v26_3")]
84            Version::V26_3 => self.window_items_as::<V263, _>(window_id, items),
85            #[cfg(not(feature = "v26_3"))]
86            Version::V26_3 => {}
87        }
88    }
89
90    /// `window_items` straight from the 1.8 / 1.12 wire slots: a slot equal to the stored stack
91    /// is compared without being converted (no NBT refcount traffic for unchanged slots, the
92    /// common case of a refreshed shop window).
93    #[cfg(any(feature = "v1_8", feature = "v1_12"))]
94    pub(crate) fn on_window_items_legacy(
95        &mut self,
96        window_id: i32,
97        items: &[ghast_protocol::types::slot::legacy::Slot],
98    ) {
99        match self.version {
100            Version::V1_8 => self.window_items_as::<V18, _>(window_id, items.iter()),
101            Version::V1_12 => self.window_items_as::<V112, _>(window_id, items.iter()),
102            // not reached: the legacy packets belong to 1.8 / 1.12 connections
103            _ => self.on_window_items(
104                window_id,
105                items.iter().cloned().map(crate::stack::from_legacy_slot),
106            ),
107        }
108    }
109
110    #[inline]
111    pub(super) fn window_items_as<const V: u8, W: Incoming>(
112        &mut self,
113        window_id: i32,
114        items: impl Iterator<Item = W>,
115    ) {
116        let lay = if window_id == 0 {
117            Layout::new(self.version, Screen::Player)
118        } else if window_id == self.open_id() {
119            self.layout()
120        } else {
121            return;
122        };
123        let mut player = false;
124        let mut window = false;
125        let mut touched_grid = false;
126        // a workstation sees its slots set one by one
127        let before = (lay.screen != Screen::Player && self.m.station.is_some())
128            .then(|| self.m.container.clone());
129        for (i, s) in items.enumerate() {
130            let Some(l) = lay.loc(i) else { break };
131            if let Some(k) = hand_writes_index(l) {
132                self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
133            }
134            touched_grid |= is_grid(lay, l);
135            let clamps = if V == V261 || V == V262 || V == V263 {
136                lay.clamps_26(l)
137            } else {
138                lay.clamps(l)
139            };
140            let slot = self.m.at_mut(l);
141            if s.settle::<V>(slot, clamps) {
142                match l {
143                    Loc::Container(_) => window = true,
144                    _ => player = true,
145                }
146            }
147        }
148        if lay.screen == Screen::Player {
149            self.m.craft_result_known = true;
150            self.m.craft_fresh = true;
151        } else {
152            self.m.container_result_known = true;
153            self.m.container_fresh = true;
154        }
155        // villager screen: every slot set marked the trading inventory dirty
156        if lay.screen != Screen::Player && self.m.merchant.is_some() {
157            crate::merchant::update(self.version, &mut self.m);
158        }
159        // workstation: the inputs were set (the menu looked its result up), then the result
160        // slot got the packet's stack
161        if let Some(before) = before {
162            self.station_window_items(before);
163        }
164        // 1.16.5 beacon: the payment inventory caps at 1 (one check per packet, not per slot)
165        if V == V1165 && window && lay.screen == Screen::Container(WindowKind::Beacon) {
166            lay.clamp_menu(Loc::Container(0), self.m.at_mut(Loc::Container(0)));
167        }
168        // 1.8: setting the grid slots made the client compute the result itself
169        if V == V18 && touched_grid {
170            crate::sim::recompute_1_8(&mut self.m, lay);
171        }
172        self.events.player_changed |= player;
173        self.events.window_changed |= window;
174        if lay.screen == Screen::Player {
175            self.events.player_synced = true;
176        } else {
177            self.events.window_synced = true;
178        }
179        if self.resync.is_some_and(|(w, _)| w == window_id) {
180            self.resync = None;
181        }
182    }
183
184    /// `set_slot` (`window_id` as received, signed byte): -1 sets the cursor, 1.12 / 1.16.5 -2 a
185    /// `PlayerInventory` index, window 0 slots 36..45 always reach window 0, others only the
186    /// current screen.
187    pub fn on_set_slot(&mut self, window_id: i32, slot: i16, item: Option<Stack>) {
188        if self.creative_items_ignore_legacy(window_id, slot) {
189            return;
190        }
191        let item = self.normalize(item);
192        if window_id == -1 {
193            if self.m.cursor != item {
194                self.m.cursor = item;
195                self.events.cursor_changed = true;
196            }
197            return;
198        }
199        let loc = if window_id == -2 && self.version != Version::V1_8 {
200            usize::try_from(slot)
201                .ok()
202                .filter(|&k| k < 41)
203                .map(Loc::Player)
204        } else if window_id == 0 && (36..45).contains(&slot) {
205            Layout::new(self.version, Screen::Player).loc(slot as usize)
206        } else if window_id == self.open_id() {
207            usize::try_from(slot)
208                .ok()
209                .and_then(|i| self.layout().loc(i))
210        } else {
211            None
212        };
213        let Some(l) = loc else { return };
214        if let Some(k) = hand_writes_index(l) {
215            self.hotbar_writes[k] = self.hotbar_writes[k].wrapping_add(1);
216        }
217        let mut item = item;
218        if self.layout().clamps(l) {
219            crate::sim::clamp_v(self.version, &mut item);
220            self.layout().clamp_menu(l, &mut item);
221        }
222        let crafting_table = matches!(
223            self.layout().screen,
224            Screen::Container(WindowKind::Crafting)
225        );
226        let anvil = !self.version.is_modern()
227            && !matches!(
228                self.version,
229                Version::V1_16_5 | Version::V1_12 | Version::V1_8
230            )
231            && matches!(self.layout().screen, Screen::Container(WindowKind::Anvil));
232        match l {
233            Loc::CraftResult => {
234                self.m.craft_result_known = true;
235                self.m.craft_fresh = true;
236            }
237            Loc::Container(0) if crafting_table => {
238                self.m.container_result_known = true;
239                self.m.container_fresh = true;
240            }
241            // the server's anvil output; an input set by the server makes the client compute it
242            Loc::Container(2) if anvil => self.m.container_result_known = true,
243            Loc::Container(0 | 1) if anvil => {
244                let first = if l == Loc::Container(0) {
245                    item.is_none()
246                } else {
247                    self.m.container.first().is_none_or(Option::is_none)
248                };
249                if first {
250                    if let Some(out) = self.m.container.get_mut(2) {
251                        *out = None;
252                    }
253                    self.m.container_result_known = true;
254                } else {
255                    self.m.container_result_known = false;
256                }
257            }
258            // 1.12: a grid slot changed under the result the client holds
259            Loc::Craft(_) if self.version == Version::V1_12 => self.m.craft_fresh = false,
260            Loc::Container(1..=9) if crafting_table && self.version == Version::V1_12 => {
261                self.m.container_fresh = false;
262            }
263            _ => {}
264        }
265        let s = self.m.at_mut(l);
266        if *s != item {
267            *s = item;
268            match l {
269                Loc::Container(_) => self.events.window_changed = true,
270                _ => self.events.player_changed = true,
271            }
272        }
273        if self.version == Version::V1_8 {
274            // the slot's screen: window 0 for its hotbar slots, else the current one
275            let lay = if window_id == 0 && (36..45).contains(&slot) {
276                Layout::new(self.version, Screen::Player)
277            } else {
278                self.layout()
279            };
280            if is_grid(lay, l) {
281                crate::sim::recompute_1_8(&mut self.m, lay);
282            }
283        }
284        // villager screen: `Slot.setStack` marks the trading inventory dirty
285        if matches!(l, Loc::Container(0..=2)) && self.m.merchant.is_some() {
286            crate::merchant::update(self.version, &mut self.m);
287        }
288        if let Loc::Container(k) = l {
289            self.station_inbound(Some(k));
290        }
291    }
292
293    /// 26.1: a container packet arrived while a click waits to settle: the server disagreed.
294    pub(super) fn correction_modern(&mut self, window_id: Option<i32>) {
295        if let Some(p) = self.pending
296            && window_id.is_none_or(|w| w == p.window_id || w == 0)
297        {
298            self.pending = None;
299            self.events.clicks.push(ClickResult {
300                window_id: p.window_id,
301                action: p.action,
302                outcome: ClickOutcome::Rejected,
303            });
304        }
305    }
306
307    /// 26.1 `container_set_content` (vanilla `initializeContents`): window 0 or the open
308    /// container's slots, its carried stack and its state id. Window 0's carried stack only
309    /// shows while no container is open (the client keeps one per menu).
310    pub fn on_window_items_modern(
311        &mut self,
312        window_id: i32,
313        state_id: i32,
314        items: impl IntoIterator<Item = Option<Stack>>,
315        carried: Option<Stack>,
316    ) {
317        let current = window_id == self.open_id();
318        if window_id != 0 && !current {
319            return;
320        }
321        self.correction_modern(Some(window_id));
322        #[cfg(modern)]
323        let old = (window_id != 0 && self.hooks_modern()).then(|| self.m.container.clone());
324        self.on_window_items(window_id, items);
325        if window_id == 0 {
326            self.state_player = state_id;
327        } else {
328            self.state_window = state_id;
329            #[cfg(modern)]
330            if let Some(old) = old {
331                let n = old.len();
332                self.inbound_modern(old, 0..n);
333            }
334        }
335        if current {
336            self.on_set_cursor(carried);
337        }
338    }
339
340    /// 26.1 `container_set_slot`: window 0 slots always reach window 0 (any slot), the open
341    /// container's only that container; the menu's state id follows.
342    pub fn on_set_slot_modern(
343        &mut self,
344        window_id: i32,
345        state_id: i32,
346        slot: i16,
347        item: Option<Stack>,
348    ) {
349        let item = self.normalize(item);
350        let lay = if window_id == 0 {
351            Layout::new(self.version, Screen::Player)
352        } else if window_id == self.open_id() {
353            self.layout()
354        } else {
355            return;
356        };
357        if window_id == 0 {
358            self.state_player = state_id;
359        } else {
360            self.state_window = state_id;
361        }
362        self.correction_modern(Some(window_id));
363        let Some(l) = usize::try_from(slot).ok().and_then(|i| lay.loc(i)) else {
364            return;
365        };
366        let mut item = item;
367        if lay.clamps_26(l) {
368            crate::sim::clamp_v(self.version, &mut item);
369        }
370        match l {
371            Loc::CraftResult => self.m.craft_result_known = true,
372            Loc::Container(0) if lay.screen == Screen::Container(WindowKind::Crafting) => {
373                self.m.container_result_known = true;
374            }
375            _ => {}
376        }
377        #[cfg(modern)]
378        let old = (matches!(l, Loc::Container(_)) && self.hooks_modern())
379            .then(|| self.m.container.clone());
380        let s = self.m.at_mut(l);
381        if *s != item {
382            *s = item;
383            match l {
384                Loc::Container(_) => self.events.window_changed = true,
385                _ => self.events.player_changed = true,
386            }
387        }
388        #[cfg(modern)]
389        if let (Loc::Container(k), Some(old)) = (l, old)
390            && window_id != 0
391        {
392            self.inbound_modern(old, k..k + 1);
393        }
394        // the creative screen broadcasts window 0 after every server slot
395        #[cfg(modern)]
396        if window_id == 0 && self.creative_screen {
397            let mut out = std::mem::take(&mut self.creative_echo);
398            self.creative_broadcast(&mut out);
399            self.creative_echo = out;
400        }
401    }
402
403    /// 26.1 `set_cursor_item`: the open menu's carried stack.
404    pub fn on_set_cursor(&mut self, item: Option<Stack>) {
405        if self.version.is_modern() {
406            self.correction_modern(None);
407            // the creative screen keeps its own cursor
408            #[cfg(modern)]
409            if self.creative_screen {
410                return;
411            }
412        }
413        let item = self.normalize(item);
414        if self.m.cursor != item {
415            self.m.cursor = item;
416            self.events.cursor_changed = true;
417        }
418    }
419
420    /// 26.1 `set_player_inventory`: a `PlayerInventory` index (0..=40; the body armor and saddle
421    /// slots 41 and 42 are not kept).
422    pub fn on_set_player_inventory(&mut self, slot: i32, item: Option<Stack>) {
423        self.correction_modern(None);
424        let item = self.normalize(item);
425        let Some(k) = usize::try_from(slot).ok().filter(|&k| k < 41) else {
426            return;
427        };
428        if self.m.player[k] != item {
429            self.m.player[k] = item;
430            self.events.player_changed = true;
431        }
432    }
433
434    /// The crafting recipes the server declared (1.16.5; 1.8 clients know theirs).
435    #[must_use]
436    pub fn recipes(&self) -> &RecipeBook {
437        &self.book
438    }
439
440    /// Forgets the server's recipes and item tags (1.16.5): what reads them is refused again
441    /// until they are sent anew (ghast-client calls this when `Interests::RECIPES` is
442    /// switched off).
443    pub fn clear_server_data(&mut self) {
444        self.book = RecipeBook::default();
445        self.tags16 = None;
446    }
447
448    /// 1.16.5 `declare_recipes`: replaces the client's recipes (the remainders of a taken
449    /// crafting result, a furnace's shift-click, the smithing table, the stonecutter; until a
450    /// declared book arrives those are refused as unpredictable).
451    pub fn on_declare_recipes(&mut self, book: RecipeBook) {
452        self.book = book;
453    }
454
455    /// `craft_progress_bar` (window property).
456    pub fn on_window_property(&mut self, window_id: i32, property: i16, value: i16) {
457        if let ScreenState::Window(w) = &mut self.screen
458            && w.id == window_id
459        {
460            match w.properties.iter_mut().find(|p| p.0 == property) {
461                Some(p) => p.1 = value,
462                None => w.properties.push((property, value)),
463            }
464            // 1.16.5 anvil: the level cost
465            if property == 0
466                && let Some(crate::station::Station::Anvil(a)) = self.m.station.as_deref_mut()
467            {
468                a.cost = i32::from(value);
469            }
470            // 1.16.5 stonecutter / loom: the selected recipe / pattern (no result update)
471            if property == 0
472                && let Some(
473                    crate::station::Station::Stonecutter { selected, .. }
474                    | crate::station::Station::Loom { selected },
475                ) = self.m.station.as_deref_mut()
476            {
477                *selected = i32::from(value);
478            }
479            #[cfg(modern)]
480            match w.menu {
481                // anvil: the cost data slot
482                8 if property == 0 => self.s26[1].anvil_cost = i32::from(value),
483                // loom: the selected pattern
484                18 if property == 0 => self.s26[1].loom_selected = i32::from(value),
485                // crafter: slot locks
486                7 if (0..9).contains(&property) => {
487                    let bit = 1u16 << property;
488                    if value == 1 {
489                        self.s26[1].crafter_locked |= bit;
490                    } else {
491                        self.s26[1].crafter_locked &= !bit;
492                    }
493                }
494                _ => {}
495            }
496        }
497    }
498
499    /// `transaction` (window confirm) from the server. Returns the answer to send now, exactly
500    /// when vanilla answers (not accepted, and the window is 0 or the open one); resolves the
501    /// pending click when it is its confirm. Route every confirm through here and answer
502    /// nowhere else, so each is answered exactly once.
503    pub fn on_transaction(
504        &mut self,
505        window_id: i8,
506        action: i16,
507        accepted: bool,
508    ) -> Option<Outgoing> {
509        let w = i32::from(window_id);
510        if let Some(p) = self.pending
511            && p.window_id == w
512            && p.action == action
513        {
514            self.pending = None;
515            let outcome = if accepted {
516                ClickOutcome::Accepted
517            } else {
518                self.resync = Some((w, 0));
519                ClickOutcome::Rejected
520            };
521            self.events.clicks.push(ClickResult {
522                window_id: w,
523                action,
524                outcome,
525            });
526        }
527        let known = w == 0 || w == self.open_id();
528        (known && !accepted).then_some(Outgoing::Confirm { window_id, action })
529    }
530
531    /// 1.12 / 1.16.5 drop empty stacks (1.16.5 also has no damage field); 1.8 keeps zero-count
532    /// stacks.
533    ///
534    /// Works in place: moving an `Option<Stack>` through a `match` per slot cost the legacy
535    /// `window_items` path measurably once `Stack` grew the 26.1 variant.
536    #[inline]
537    pub(super) fn normalize(&self, mut s: Option<Stack>) -> Option<Stack> {
538        self.normalize_in_place(&mut s);
539        s
540    }
541
542    #[inline]
543    pub(super) fn normalize_in_place(&self, s: &mut Option<Stack>) {
544        if self.version == Version::V1_8 {
545            return;
546        }
547        if s.as_ref().is_some_and(|s| s.count <= 0 || s.id == 0) {
548            *s = None;
549        } else if self.version != Version::V1_12
550            && let Some(st) = s
551        {
552            st.damage = 0;
553        }
554    }
555}