ghast-inventory 0.5.4

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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! The 26.x-only API: hash registries, creative mode and the creative screen, tags, registry
//! data, mount and merchant screens, anvil names, loom patterns, trades, recipes and the menus'
//! inbound hooks.

use super::*;

impl Inventory {
    /// 26.1: the registry names click hashes and the binding curse check need (the
    /// configuration phase's `minecraft:enchantment` keys in order). Without them, clicks with
    /// enchanted items send hashes the server corrects, and taking enchanted armor off is not
    /// predicted.
    #[cfg(modern)]
    ///
    /// Clients of one process that receive the same names share one copy of them.
    pub fn set_registries_modern(&mut self, reg: crate::item26::HashRegistries) {
        self.reg26 = reg.shared();
    }

    /// 26.1: the registry names set with [`Inventory::set_registries_modern`].
    #[cfg(modern)]
    #[must_use]
    pub fn registries_modern(&self) -> &crate::item26::HashRegistries {
        &self.reg26
    }

    /// 26.1: the name of enchantment registry id `id` as the server's `registry_data` keyed it
    /// (`minecraft:sharpness`), from the registries set with
    /// [`Inventory::set_registries_modern`]; `None` for an unknown id.
    #[cfg(modern)]
    #[must_use]
    pub fn enchantment_name_modern(&self, id: i32) -> Option<&str> {
        self.reg26
            .enchantments()
            .get(usize::try_from(id).ok()?)
            .map(String::as_str)
    }

    /// 26.1: whether the player is in creative mode (instant build): middle-click clones,
    /// clone drags, armor with the binding curse comes off, overflow vanishes. Set from the
    /// `abilities` packet by [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn set_creative_modern(&mut self, creative: bool) {
        self.w26.creative = creative;
    }

    /// 26.1 `update_tags` (configuration `tags` or play `tags`): the body is kept and parsed
    /// at the first click in an anvil, grindstone, loom or mount screen (the item, enchantment,
    /// banner pattern and entity type tags those read). The play packet is also handled by
    /// [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn on_update_tags_modern(&mut self, body: bytes::Bytes) {
        self.d26.set_tags_raw(body);
    }

    /// 26.1 configuration `registry_data`: the `minecraft:enchantment` body is kept (parsed
    /// with the tags) for the anvil's rules; other registries are ignored. Entries sent without
    /// data (a server and client sharing the vanilla pack) use the vanilla definitions.
    #[cfg(modern)]
    pub fn on_registry_data_modern(&mut self, body: bytes::Bytes) {
        self.d26.set_registry_raw(body);
    }

    /// 26.1 `horse_screen_open` (`ClientboundMountScreenOpenPacket`): the mount's inventory
    /// screen. The client builds it from the entity, so the caller passes what the screen reads
    /// off it: the entity type (`minecraft:entity_type` registry id), the packet's inventory
    /// columns and `canUseSlot(SADDLE)` / `canUseSlot(BODY)` (horses, donkeys, mules, camels:
    /// saddle when alive, adult and tamed, body always; llamas: both always; nautili: both when
    /// alive, adult and tame).
    #[cfg(modern)]
    pub fn on_mount_screen_modern(
        &mut self,
        window_id: i32,
        columns: i32,
        entity_type: i32,
        can_saddle: bool,
        can_body: bool,
    ) {
        let cols = u8::try_from(columns.clamp(0, 50)).unwrap_or(0);
        self.on_open_window(
            window_id,
            Some(WindowKind::Horse {
                slots: 2 + cols * 3,
            }),
            "".into(),
        );
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == window_id
        {
            w.menu = MOUNT_MENU;
        }
        self.s26[1] = crate::sim26::Screen26 {
            mount_type: entity_type,
            mount_saddle: can_saddle,
            mount_body: can_body,
            ..Default::default()
        };
    }

    /// 26.1 `merchant_offers`: the open villager screen's offers.
    #[cfg(modern)]
    pub fn on_merchant_offers_modern(&mut self, body: &bytes::Bytes) {
        if let Some((window, offers)) = crate::sim26::parse_offers(self.mv(), body)
            && let ScreenState::Window(w) = &self.screen
            && w.id == window
            && w.menu == 19
        {
            self.s26[1].offers = offers;
        }
    }

    /// Runs one 26.1 screen action on the open menu (no container click).
    #[cfg(modern)]
    pub(super) fn screen_action_modern<T>(
        &mut self,
        f: impl FnOnce(&mut crate::sim26::Sim26<'_>) -> Result<T, crate::sim::Unpredictable>,
    ) -> Result<T, crate::sim::Unpredictable> {
        let kind = self.kind_26();
        let lay = self.layout();
        let mut m = self.m.clone();
        let mut scr = self.s26[1].clone();
        self.w26.binding_curse = self.binding_curse();
        self.w26.can_drop = self.drop_throttle < 1280;
        let r = {
            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,
            };
            f(&mut sim)
        };
        if r.is_ok() {
            self.commit(m, lay);
            self.s26[1] = scr;
        }
        r
    }

    /// 26.1 anvil: types `name` into the name field (`AnvilMenu.setItemName`; the name is
    /// filtered like vanilla's and limited to 50 characters). Returns the `rename_item` to send
    /// when the name changed (`Ok(None)`: nothing to send). An empty name removes a custom
    /// name. Like the real screen, it does nothing while the input slot is empty.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no anvil is open.
    #[cfg(modern)]
    pub fn anvil_rename_modern(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Anvil {
            return Err(ClickError::NoScreen);
        }
        if self.m.container.first().is_none_or(Option::is_none) {
            return Ok(None);
        }
        let filtered: String = name
            .chars()
            .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}')
            .collect();
        if filtered.chars().count() > 50 || self.s26[1].anvil_name.as_deref() == Some(&filtered) {
            return Ok(None);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let n = filtered.clone();
        let r = self.screen_action_modern(|sim| {
            sim.s.anvil_name = Some(n);
            sim.anvil_create()
        });
        if r.is_err() {
            // the result could not be computed: keep the name, the server sends the result
            self.s26[1].anvil_name = Some(filtered.clone());
        }
        Ok(Some(Outgoing::RenameItem(filtered)))
    }

    /// 26.1 `EnchantmentHelper.getTridentSpinAttackStrength(stack)`: 0 run through the
    /// `minecraft:trident_spin_attack_strength` effect of every enchantment in the stack's
    /// `enchantments` (in their order), as the server's enchantment registry defines it
    /// (`registry_data` with data, else vanilla's definition: riptide adds `1.5 + 0.75 ×
    /// (level - 1)`). `Some(0.0)` without such an enchantment.
    ///
    /// `None` when it cannot be computed: an enchantment whose definition is unknown (not sent
    /// with data and not vanilla), an effect that does not read, or one that draws on the
    /// holder's random (`remove_binomial`). The first call parses the raw registry data and
    /// tags (hence `&mut self`).
    #[cfg(modern)]
    pub fn trident_spin_attack_strength_modern(&mut self, stack: &Stack) -> Option<f32> {
        let list = crate::item26::enchantments(self.mv(), stack, false).unwrap_or_default();
        if list.is_empty() {
            return Some(0.0);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let mut v = 0.0f32;
        for (id, level) in list {
            match &self.d26.enchantment(id)?.spin {
                None => {}
                Some(None) => return None,
                Some(Some(fx)) => v = fx.process(level, v)?,
            }
        }
        Some(v)
    }

    /// 26.1 loom: clicks pattern button `index` (`LoomMenu.clickMenuButton`). Returns the
    /// `container_button_click` when the loom accepts it (`Ok(None)`: not a selectable pattern).
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no loom is open; [`ClickError::Unpredictable`] when the
    /// patterns are not known.
    #[cfg(modern)]
    pub fn select_loom_pattern_modern(
        &mut self,
        index: i32,
    ) -> Result<Option<Outgoing>, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Loom {
            return Err(ClickError::NoScreen);
        }
        self.d26.ensure(self.mv(), self.reg26.enchantments());
        let ok = self
            .screen_action_modern(|sim| sim.loom_button(index))
            .map_err(|_| ClickError::Unpredictable)?;
        Ok(ok.then(|| Outgoing::ButtonClick {
            window_id: self.open_id(),
            button: index,
        }))
    }

    /// 26.1 villager screen: picks trade `index` (`setSelectionHint`, `tryMoveItems`: the
    /// payment goes back to the inventory and the trade's costs come out of it). Returns the
    /// `select_trade` to send.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no villager screen is open.
    #[cfg(modern)]
    pub fn select_trade_modern(&mut self, index: i32) -> Result<Outgoing, ClickError> {
        if self.kind_26() != crate::sim26::Kind::Merchant {
            return Err(ClickError::NoScreen);
        }
        if self
            .screen_action_modern(|sim| sim.select_trade(index))
            .is_err()
        {
            self.s26[1].trade_hint = index;
        }
        Ok(Outgoing::SelectTrade(index))
    }

    /// 26.1: keeps an `update_recipes` body for later parsing.
    #[cfg(modern)]
    pub(crate) fn set_recipes_raw_modern(&mut self, body: bytes::Bytes) {
        self.recipes_raw = Some(body);
    }

    #[cfg(modern)]
    pub(crate) fn take_recipes_raw_modern(&mut self) -> Option<bytes::Bytes> {
        self.recipes_raw.take()
    }

    /// 26.1: the packets the creative inventory screen sent in answer to server packets since
    /// the last call (vanilla echoes every window 0 slot the server sets while the screen is
    /// open); send them right away.
    #[cfg(modern)]
    pub fn take_creative_echo_modern(&mut self) -> Vec<CreativePacket> {
        std::mem::take(&mut self.creative_echo)
    }

    /// Whether the 26.1 creative inventory screen is open (window 0 opened in creative mode):
    /// clicks then return [`Outgoing::Creative`].
    #[cfg(modern)]
    #[must_use]
    pub fn creative_screen_modern(&self) -> bool {
        self.creative_screen
    }

    /// `InventoryMenu.broadcastChanges` with the creative listener: every slot that differs
    /// from the last broadcast is sent.
    #[cfg(modern)]
    pub(super) fn creative_broadcast(&mut self, out: &mut Vec<CreativePacket>) {
        let lay = Layout::new(self.version, Screen::Player);
        if self.creative_last.is_empty() {
            // allocated on the first broadcast: a bot that never opens it pays nothing
            self.creative_last = vec![None; 46];
        }
        for i in 0..46 {
            let Some(l) = lay.loc(i) else { break };
            let cur = self.m.at(l);
            let same = match (&self.creative_last[i], cur) {
                (None, None) => true,
                (Some(a), Some(b)) => a.count == b.count && a.id == b.id && a.data_eq(b),
                _ => false,
            };
            if !same {
                self.creative_last[i] = cur.clone();
                out.push(CreativePacket::SetSlot {
                    slot: i as i16,
                    item: cur.clone(),
                });
            }
        }
    }

    /// A click in the creative inventory screen (`CreativeModeInventoryScreen.slotClicked`,
    /// inventory tab): Q / drops are the screen's own; everything else runs window 0's click
    /// and broadcasts. Refused as unpredictable when ghast cannot simulate it (the stacks it
    /// sends would be wrong).
    #[cfg(modern)]
    pub(super) fn creative_click(
        &mut self,
        slot: i16,
        button: u8,
        mode: u8,
    ) -> Result<Outgoing, ClickError> {
        let mode = if slot == OUTSIDE && mode == 0 {
            4
        } else {
            mode
        };
        let lay = Layout::new(self.version, Screen::Player);
        let mut out = Vec::new();
        let idx = usize::try_from(slot).ok();
        if mode == 4 && self.drop_throttle >= 1280 {
            // `canDropItems()` is false: the screen ignores the click
            self.flags.clicked = true;
            return Ok(Outgoing::Creative(out));
        }
        if mode == 4 {
            if let Some(i) = idx
                && let Some(l) = lay.loc(i)
                && let Some(st) = self.m.at(l).clone()
            {
                // slot.remove(button == 0 ? 1 : max stack size): the crafting result is taken
                // whole, other slots split
                let n = if button == 0 {
                    1
                } else {
                    crate::item26::max_stack_size(self.mv(), &st)
                };
                let dropped = if l == Loc::CraftResult {
                    self.m.at_mut(l).take()
                } else {
                    let s = self.m.at_mut(l);
                    let k = n.min(st.count).max(0);
                    let d = (k > 0).then(|| st.with_count(k));
                    if let Some(x) = s {
                        x.count -= k;
                        if x.count <= 0 {
                            *s = None;
                        }
                    }
                    d
                };
                if dropped.is_some() {
                    self.drop_throttle += 20;
                    if self.mv().swing_packet() {
                        out.push(CreativePacket::Swing);
                    }
                    out.push(CreativePacket::SetSlot {
                        slot: -1,
                        item: dropped,
                    });
                }
                out.push(CreativePacket::SetSlot {
                    slot,
                    item: self.m.at(l).clone(),
                });
                self.events.player_changed = true;
                self.flags.clicked = true;
                return Ok(Outgoing::Creative(out));
            }
            if slot == OUTSIDE
                && let Some(c) = self.m.cursor.take()
            {
                self.drop_throttle += 20;
                if self.mv().swing_packet() {
                    out.push(CreativePacket::Swing);
                }
                out.push(CreativePacket::SetSlot {
                    slot: -1,
                    item: Some(c),
                });
                self.events.cursor_changed = true;
                self.flags.clicked = true;
                return Ok(Outgoing::Creative(out));
            }
        }
        let mut m = self.m.clone();
        let mut scr = self.s26[0].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: crate::sim26::Kind::Player,
                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)
        };
        if result.is_err() {
            return Err(ClickError::Unpredictable);
        }
        if self.mv().swing_packet() {
            for _ in 0..swings {
                out.push(CreativePacket::Swing);
            }
        }
        self.commit(m, lay);
        self.s26[0] = scr;
        self.creative_broadcast(&mut out);
        self.flags.clicked = true;
        Ok(Outgoing::Creative(out))
    }

    /// 26.1: the player's experience level (the anvil's result can only be taken with enough);
    /// set from the `experience` packet by [`Inventory::apply_raw_modern`].
    #[cfg(modern)]
    pub fn set_experience_level_modern(&mut self, level: i32) {
        self.w26.xp_level = Some(level);
    }

    /// 26.1 `update_recipes` (`declare_recipes`): the recipe item sets the furnace, smithing
    /// and stonecutter slot rules read (`(set name, item ids)`, e.g.
    /// `("minecraft:furnace_input", …)`) and the stonecutter recipes' inputs (`None` when one
    /// names a tag: shift-clicks into the stonecutter are then not predicted).
    #[cfg(modern)]
    pub fn on_recipes_modern<'a>(
        &mut self,
        sets: impl IntoIterator<Item = (&'a str, &'a [i32])>,
        stonecutter_inputs: Option<Vec<i32>>,
    ) {
        self.recipes_raw = None;
        let w = &mut self.w26;
        for v in [
            &mut w.furnace_input,
            &mut w.blast_input,
            &mut w.smoker_input,
            &mut w.smithing_base,
            &mut w.smithing_template,
            &mut w.smithing_addition,
            &mut w.brewing_reagent,
            &mut w.brewing_input,
        ] {
            v.clear();
        }
        for (name, ids) in sets {
            let target = match name.strip_prefix("minecraft:").unwrap_or(name) {
                "furnace_input" => &mut w.furnace_input,
                "blast_furnace_input" => &mut w.blast_input,
                "smoker_input" => &mut w.smoker_input,
                "smithing_base" => &mut w.smithing_base,
                "smithing_template" => &mut w.smithing_template,
                "smithing_addition" => &mut w.smithing_addition,
                "brewing_reagent" => &mut w.brewing_reagent,
                "brewing_input" => &mut w.brewing_input,
                _ => continue,
            };
            target.extend_from_slice(ids);
            target.sort_unstable();
            target.dedup();
        }
        w.cutter_inputs = stonecutter_inputs.map(|mut v| {
            v.sort_unstable();
            v.dedup();
            v
        });
    }

    /// Modern `open_screen`: the menu registry id (`minecraft:menu`) and the title. Menus the
    /// client has no screen for are ignored.
    #[cfg(modern)]
    pub fn on_open_screen_modern(&mut self, id: i32, menu: i32, title: ByteString) {
        self.on_open_window(id, crate::item26::window_kind(self.mv(), menu), title);
        if let ScreenState::Window(w) = &mut self.screen
            && w.id == id
        {
            w.menu = menu;
        }
        self.s26[1] = Default::default();
    }

    /// 26.1: the client-side effects of setting the open menu's container slots from a packet:
    /// vanilla runs each slot's `set` in order (the container caps it and the menu's
    /// `slotsChanged` recomputes results and remembered state: the anvil's cost and repair
    /// counts, the loom's patterns, the trade, the stonecutter input). `old` is the container
    /// before the packet; the packet's slots are replayed one by one from it.
    /// Whether the open 26.1 menu reacts to server slot packets (container caps, result hooks).
    #[cfg(modern)]
    pub(super) fn hooks_modern(&self) -> bool {
        use crate::sim26::Kind;
        matches!(
            self.kind_26(),
            Kind::Anvil
                | Kind::Beacon
                | Kind::Grindstone
                | Kind::Smithing
                | Kind::Stonecutter
                | Kind::Loom
                | Kind::Cartography
                | Kind::Merchant
        )
    }

    #[cfg(modern)]
    pub(super) fn inbound_modern(
        &mut self,
        old: Vec<Option<Stack>>,
        slots: std::ops::Range<usize>,
    ) {
        use crate::sim26::Kind;
        let kind = self.kind_26();
        if matches!(kind, Kind::Anvil | Kind::Grindstone | Kind::Loom) {
            self.d26.ensure(self.mv(), self.reg26.enchantments());
        }
        let new = std::mem::replace(&mut self.m.container, old);
        let mut scr = self.s26[1].clone();
        let mut m = std::mem::take(&mut self.m);
        let mut ok = true;
        {
            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,
            };
            for k in slots.clone() {
                if k >= new.len() {
                    break;
                }
                if sim.inbound_set(k, new[k].clone()).is_err() {
                    ok = false;
                    break;
                }
            }
        }
        if !ok {
            // a hook ghast cannot compute: the packet's slots as sent
            for k in slots {
                if let (Some(d), Some(v)) = (m.container.get_mut(k), new.get(k)) {
                    *d = v.clone();
                }
            }
        }
        self.m = m;
        self.s26[1] = scr;
    }
}