ghast-inventory 0.5.6

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Clicks: [`Inventory::click`] with the legacy and 26.x predictions, the state id, committing
//! a simulated model, and opening / closing screens.

use super::*;

impl Inventory {
    // ------------------------------------------------------------------ actions

    /// Simulates a click exactly like the vanilla client (`ClientPlayerInteractionManager.clickSlot`:
    /// next action number, `onSlotClick`, packet with its return value) and returns the packet
    /// to send now. The prediction is applied immediately; the click is pending until its
    /// confirm arrives.
    ///
    /// Bots should click only while not turning (the server and anticheats see clicks against
    /// the last sent rotation; vanilla players do not move the camera with a GUI open).
    pub fn click(&mut self, click: Click) -> Result<Outgoing, ClickError> {
        self.can_click()?;
        let lay = self.layout();
        let (slot, button, mode) = click.wire();
        if self.creative_screen_legacy().is_some() {
            return self.creative_click_legacy(slot, button, mode);
        }
        let in_range = usize::try_from(slot).is_ok_and(|i| i < lay.len);
        let slot_ok = match click {
            Click::Pickup { .. } | Click::Drop { .. } => in_range || slot == OUTSIDE,
            Click::QuickMove { .. }
            | Click::Swap { .. }
            | Click::PickupAll { .. }
            | Click::Clone { .. } => in_range,
            Click::QuickCraft { stage, .. } => match stage {
                DragStage::Slot => in_range,
                DragStage::Start | DragStage::End => in_range || slot == OUTSIDE,
            },
        };
        if !slot_ok {
            return Err(ClickError::InvalidSlot);
        }
        if !self.version.is_modern()
            && (matches!(click, Click::QuickCraft { .. })
                || matches!(click, Click::Clone { .. }) && !self.m.creative)
        {
            // the older versions' drags are not modelled; the clone is a creative click
            return Err(ClickError::Unpredictable);
        }
        if let Click::Swap { hotbar, .. } = click {
            let ok = hotbar < 9
                || (hotbar == 40
                    && matches!(
                        self.version,
                        Version::V1_16_5 | Version::V26_1 | Version::V26_2 | Version::V26_3
                    ));
            if !ok {
                return Err(ClickError::InvalidButton);
            }
        }
        #[cfg(modern)]
        if self.version.is_modern() {
            if self.creative_screen {
                return self.creative_click(slot, button, mode);
            }
            return Ok(self.click_26(slot, button, mode));
        }
        let mut m = self.m.clone();
        let simulated = {
            let mut sim = Sim {
                v: self.version,
                lay,
                m: &mut m,
                book: &self.book,
                binding_curse: self.binding_curse(),
                tags: self.tags16.as_deref(),
            };
            sim.click(slot, button, mode)
        };
        let item = simulated.map_err(|_| ClickError::Unpredictable)?;
        let swings = self.drop_swings_1_16(&m, lay, slot, button, mode);
        self.commit(m, lay);
        let (window_id, action) = match &mut self.screen {
            ScreenState::Window(w) => {
                w.action = w.action.wrapping_add(1);
                (w.id, w.action)
            }
            _ => {
                self.player_action = self.player_action.wrapping_add(1);
                (0, self.player_action)
            }
        };
        self.pending = Some(PendingClick {
            window_id,
            action,
            age: 0,
        });
        self.flags.clicked = true;
        Ok(Outgoing::Click(ClickPacket {
            window_id: window_id as u8,
            slot,
            button,
            mode,
            action,
            item,
            swings,
        }))
    }

    pub(super) fn binding_curse(&self) -> Option<i32> {
        #[cfg(modern)]
        {
            self.reg26
                .enchantments()
                .iter()
                .position(|n| n == "minecraft:binding_curse")
                .map(|i| i as i32)
        }
        #[cfg(not(modern))]
        None
    }

    /// 26.1: the state id the next click of the current screen carries.
    #[must_use]
    pub fn state_id(&self) -> i32 {
        match &self.screen {
            ScreenState::Window(_) => self.state_window,
            _ => self.state_player,
        }
    }

    /// The 26.1 menu the click runs in.
    #[cfg(modern)]
    pub(super) fn kind_26(&self) -> crate::sim26::Kind {
        match &self.screen {
            ScreenState::Window(w) => match (crate::sim26::Kind::from_menu(w.menu), w.kind) {
                (Some(k), _) => k,
                (None, WindowKind::Horse { slots }) if w.menu == MOUNT_MENU => {
                    crate::sim26::Kind::Mount(slots.saturating_sub(2) / 3)
                }
                (None, WindowKind::Chest { rows }) => crate::sim26::Kind::Chest(rows),
                (None, _) => crate::sim26::Kind::Chest(0),
            },
            _ => crate::sim26::Kind::Player,
        }
    }

    /// The 26.1 click (`MultiPlayerGameMode.handleContainerInput`): vanilla predicts, then lists
    /// every slot whose stack changed (in the order of its `Int2ObjectOpenHashMap`) and the
    /// carried stack. A click ghast cannot predict is sent unpredicted (nothing changes locally;
    /// the server applies it and sends the true slots), never refused.
    #[cfg(modern)]
    pub(super) fn click_26(&mut self, slot: i16, button: u8, mode: u8) -> Outgoing {
        let kind = self.kind_26();
        if matches!(
            kind,
            crate::sim26::Kind::Furnace(_)
                | crate::sim26::Kind::Smithing
                | crate::sim26::Kind::Stonecutter
        ) {
            self.ensure_recipes_modern();
        }
        // 26.3 brewing reads recipe property sets and an item tag
        let brewing = kind == crate::sim26::Kind::Brewing && self.mv().data_brewing();
        if brewing {
            self.ensure_recipes_modern();
            self.d26.ensure(self.mv(), self.reg26.enchantments());
        }
        if matches!(
            kind,
            crate::sim26::Kind::Anvil
                | crate::sim26::Kind::Grindstone
                | crate::sim26::Kind::Loom
                | crate::sim26::Kind::Mount(_)
        ) {
            self.d26.ensure(self.mv(), self.reg26.enchantments());
        }
        let w = usize::from(matches!(self.screen, ScreenState::Window(_)));
        let mut m = self.m.clone();
        let mut scr = self.s26[w].clone();
        self.w26.binding_curse = self.binding_curse();
        self.w26.can_drop = self.drop_throttle < 1280;
        let (result, swings) = {
            let mut sim = crate::sim26::Sim26 {
                kind,
                m: &mut m,
                s: &mut scr,
                w: &self.w26,
                d: &self.d26,
                reg: &self.reg26,
                mv: self.mv(),
                swings: 0,
                xp_spent: 0,
            };
            let r = sim.click(slot, button as i8, mode);
            (r, (sim.swings, sim.xp_spent))
        };
        let (swings, xp_spent) = swings;
        let predicted = result.is_ok();
        let mut changed = Vec::new();
        let mut swings_out = 0;
        if predicted {
            let mut idx = Vec::new();
            for i in 0..kind.len() {
                let Some(l) = kind.loc(i) else { break };
                let (a, b) = (self.m.at(l), m.at(l));
                let same = match (a, b) {
                    (None, None) => true,
                    (Some(a), Some(b)) => a.count == b.count && a.id == b.id && a.data_eq(b),
                    _ => false,
                };
                if !same {
                    idx.push(i as i32);
                }
            }
            for i in crate::sim26::fastutil_order(&idx) {
                let l = kind.loc(i as usize).unwrap_or(Loc::Player(0));
                changed.push((i as i16, m.at(l).clone()));
            }
            let lay = self.layout();
            self.commit(m, lay);
            self.s26[w] = scr;
            // 26.3: the swing is client-side only (no packet to send)
            if self.mv().swing_packet() {
                swings_out = swings;
            }
            if xp_spent != 0
                && let Some(x) = &mut self.w26.xp_level
            {
                *x -= xp_spent;
            }
        } else {
            // the outcome is unknown, including how far a drag got: start over
            self.s26[w].drag.reset();
        }
        let (window_id, action) = match &mut self.screen {
            ScreenState::Window(w) => {
                w.action = w.action.wrapping_add(1);
                (w.id, w.action)
            }
            _ => {
                self.player_action = self.player_action.wrapping_add(1);
                (0, self.player_action)
            }
        };
        self.pending = Some(PendingClick {
            window_id,
            action,
            age: 0,
        });
        self.flags.clicked = true;
        Outgoing::ContainerClick(ContainerClick {
            action,
            window_id,
            state_id: self.state_id(),
            slot,
            button,
            mode,
            changed,
            carried: self.m.cursor.clone(),
            predicted,
            swings: swings_out,
        })
    }

    /// Replaces the model with the simulated one, records which parts changed and marks a
    /// crafting result unknown when its grid changed.
    pub(super) fn commit(&mut self, new: Model, lay: Layout) {
        let old = std::mem::replace(&mut self.m, new);
        if old.player != self.m.player || old.craft != self.m.craft {
            self.events.player_changed = true;
        }
        if old.craft_result != self.m.craft_result {
            self.events.player_changed = true;
        }
        if old.container != self.m.container {
            self.events.window_changed = true;
        }
        if old.cursor != self.m.cursor {
            self.events.cursor_changed = true;
        }
        // 1.8: the simulation recomputed the result itself; 1.16.5: the server sends it; 1.12:
        // the client keeps the result it has, which no longer belongs to a changed grid.
        if self.version == Version::V1_8 {
            return;
        }
        if self.version == Version::V1_12 {
            if old.craft != self.m.craft {
                self.m.craft_fresh = false;
            }
            if lay.screen == Screen::Container(WindowKind::Crafting)
                && old.container.get(1..10) != self.m.container.get(1..10)
            {
                self.m.container_fresh = false;
            }
            return;
        }
        if old.craft != self.m.craft {
            self.m.craft_result_known = false;
        }
        if lay.screen == Screen::Container(WindowKind::Crafting)
            && old.container.get(1..10) != self.m.container.get(1..10)
        {
            self.m.container_result_known = false;
        }
    }

    /// Opens the player inventory GUI (key E). Returns the packet to send (1.8: the "open
    /// inventory achievement" client command; 1.12 / 1.16.5: nothing). No-op when already open.
    pub fn open_inventory(&mut self) -> Result<Option<Outgoing>, ClickError> {
        match self.screen {
            ScreenState::Inventory => return Ok(None),
            ScreenState::Window(_) => return Err(ClickError::WindowOpen),
            ScreenState::None => {}
        }
        if self.flags.clicked || self.flags.closed {
            return Err(ClickError::SameTick);
        }
        if !self.version.is_modern() && self.m.creative {
            return Ok(self.open_creative_legacy());
        }
        self.screen = ScreenState::Inventory;
        self.flags.opened = true;
        #[cfg(modern)]
        if self.version.is_modern() && self.w26.creative {
            // the creative screen adds its listener: one broadcast
            self.creative_screen = true;
            let mut out = Vec::new();
            self.creative_broadcast(&mut out);
            return Ok((!out.is_empty()).then_some(Outgoing::Creative(out)));
        }
        Ok((self.version == Version::V1_8).then_some(Outgoing::OpenInventory))
    }

    /// Closes the open GUI (Escape / E): `close_window` with its id. The client drops the
    /// cursor stack (the server throws it) and, for the 1.8 player inventory, empties the
    /// crafting grid (the server drops it).
    pub fn close(&mut self) -> Result<Outgoing, ClickError> {
        if self.screen == ScreenState::None {
            return Err(ClickError::NoScreen);
        }
        if self.flags.opened {
            return Err(ClickError::SameTick);
        }
        let id = match &self.screen {
            ScreenState::Window(w) => w.id as u8,
            _ => 0,
        };
        self.close_screen();
        self.flags.closed = true;
        Ok(Outgoing::CloseWindow(id))
    }

    /// The client side of closing the current screen handler (`closeScreen` + `close`).
    pub(super) fn close_screen(&mut self) {
        #[cfg(modern)]
        {
            self.creative_screen = false;
        }
        // 26.1: only the server empties the cursor (`removed` checks for a ServerPlayer); the
        // client's player inventory menu keeps its own, so closing window 0 keeps the cursor,
        // and closing a container returns to window 0's (empty) one.
        let keep_cursor = self.version.is_modern() && self.screen == ScreenState::Inventory;
        if !keep_cursor && self.m.cursor.take().is_some() {
            self.events.cursor_changed = true;
        }
        let creative = self
            .creative16
            .as_mut()
            .is_some_and(|c| std::mem::take(&mut c.open));
        match std::mem::replace(&mut self.screen, ScreenState::None) {
            // the creative screen's handler only drops the cursor
            ScreenState::Inventory if creative => {}
            ScreenState::Inventory => {
                if self.version == Version::V1_8 {
                    // PlayerScreenHandler.close: grid dropped, result cleared (also on the client)
                    if self.m.craft.iter().any(Option::is_some) {
                        self.events.player_changed = true;
                    }
                    self.m.craft = Default::default();
                }
                self.m.craft_result = None;
                self.m.craft_result_known = !matches!(
                    self.version,
                    Version::V1_16_5 | Version::V26_1 | Version::V26_2 | Version::V26_3
                );
                self.m.craft_fresh = false;
            }
            ScreenState::Window(_) => {
                self.m.container.clear();
                self.m.merchant = None;
                self.m.mount = None;
                self.m.station = None;
                self.m.container_result_known = true;
                self.m.container_fresh = true;
                #[cfg(modern)]
                {
                    self.s26[1] = Default::default();
                }
            }
            ScreenState::None => {}
        }
        if let Some((w, _)) = self.resync
            && w != 0
        {
            self.resync = None;
        }
    }
}