Skip to main content

ghast_inventory/inventory/
modern.rs

1//! The 26.x-only API: hash registries, creative mode and the creative screen, tags, registry
2//! data, mount and merchant screens, anvil names, loom patterns, trades, recipes and the menus'
3//! inbound hooks.
4
5use super::*;
6
7impl Inventory {
8    /// 26.1: the registry names click hashes and the binding curse check need (the
9    /// configuration phase's `minecraft:enchantment` keys in order). Without them, clicks with
10    /// enchanted items send hashes the server corrects, and taking enchanted armor off is not
11    /// predicted.
12    #[cfg(modern)]
13    ///
14    /// Clients of one process that receive the same names share one copy of them.
15    pub fn set_registries_modern(&mut self, reg: crate::item26::HashRegistries) {
16        self.reg26 = reg.shared();
17    }
18
19    /// 26.1: the registry names set with [`Inventory::set_registries_modern`].
20    #[cfg(modern)]
21    #[must_use]
22    pub fn registries_modern(&self) -> &crate::item26::HashRegistries {
23        &self.reg26
24    }
25
26    /// 26.1: the name of enchantment registry id `id` as the server's `registry_data` keyed it
27    /// (`minecraft:sharpness`), from the registries set with
28    /// [`Inventory::set_registries_modern`]; `None` for an unknown id.
29    #[cfg(modern)]
30    #[must_use]
31    pub fn enchantment_name_modern(&self, id: i32) -> Option<&str> {
32        self.reg26
33            .enchantments()
34            .get(usize::try_from(id).ok()?)
35            .map(String::as_str)
36    }
37
38    /// 26.1: whether the player is in creative mode (instant build): middle-click clones,
39    /// clone drags, armor with the binding curse comes off, overflow vanishes. Set from the
40    /// `abilities` packet by [`Inventory::apply_raw_modern`].
41    #[cfg(modern)]
42    pub fn set_creative_modern(&mut self, creative: bool) {
43        self.w26.creative = creative;
44    }
45
46    /// 26.1 `update_tags` (configuration `tags` or play `tags`): the body is kept and parsed
47    /// at the first click in an anvil, grindstone, loom or mount screen (the item, enchantment,
48    /// banner pattern and entity type tags those read). The play packet is also handled by
49    /// [`Inventory::apply_raw_modern`].
50    #[cfg(modern)]
51    pub fn on_update_tags_modern(&mut self, body: bytes::Bytes) {
52        self.d26.set_tags_raw(body);
53    }
54
55    /// 26.1 configuration `registry_data`: the `minecraft:enchantment` body is kept (parsed
56    /// with the tags) for the anvil's rules; other registries are ignored. Entries sent without
57    /// data (a server and client sharing the vanilla pack) use the vanilla definitions.
58    #[cfg(modern)]
59    pub fn on_registry_data_modern(&mut self, body: bytes::Bytes) {
60        self.d26.set_registry_raw(body);
61    }
62
63    /// 26.1 `horse_screen_open` (`ClientboundMountScreenOpenPacket`): the mount's inventory
64    /// screen. The client builds it from the entity, so the caller passes what the screen reads
65    /// off it: the entity type (`minecraft:entity_type` registry id), the packet's inventory
66    /// columns and `canUseSlot(SADDLE)` / `canUseSlot(BODY)` (horses, donkeys, mules, camels:
67    /// saddle when alive, adult and tamed, body always; llamas: both always; nautili: both when
68    /// alive, adult and tame).
69    #[cfg(modern)]
70    pub fn on_mount_screen_modern(
71        &mut self,
72        window_id: i32,
73        columns: i32,
74        entity_type: i32,
75        can_saddle: bool,
76        can_body: bool,
77    ) {
78        let cols = u8::try_from(columns.clamp(0, 50)).unwrap_or(0);
79        self.on_open_window(
80            window_id,
81            Some(WindowKind::Horse {
82                slots: 2 + cols * 3,
83            }),
84            "".into(),
85        );
86        if let ScreenState::Window(w) = &mut self.screen
87            && w.id == window_id
88        {
89            w.menu = MOUNT_MENU;
90        }
91        self.s26[1] = crate::sim26::Screen26 {
92            mount_type: entity_type,
93            mount_saddle: can_saddle,
94            mount_body: can_body,
95            ..Default::default()
96        };
97    }
98
99    /// 26.1 `merchant_offers`: the open villager screen's offers.
100    #[cfg(modern)]
101    pub fn on_merchant_offers_modern(&mut self, body: &bytes::Bytes) {
102        if let Some((window, offers)) = crate::sim26::parse_offers(self.mv(), body)
103            && let ScreenState::Window(w) = &self.screen
104            && w.id == window
105            && w.menu == 19
106        {
107            self.s26[1].offers = offers;
108        }
109    }
110
111    /// Runs one 26.1 screen action on the open menu (no container click).
112    #[cfg(modern)]
113    pub(super) fn screen_action_modern<T>(
114        &mut self,
115        f: impl FnOnce(&mut crate::sim26::Sim26<'_>) -> Result<T, crate::sim::Unpredictable>,
116    ) -> Result<T, crate::sim::Unpredictable> {
117        let kind = self.kind_26();
118        let lay = self.layout();
119        let mut m = self.m.clone();
120        let mut scr = self.s26[1].clone();
121        self.w26.binding_curse = self.binding_curse();
122        self.w26.can_drop = self.drop_throttle < 1280;
123        let r = {
124            let mut sim = crate::sim26::Sim26 {
125                kind,
126                m: &mut m,
127                s: &mut scr,
128                w: &self.w26,
129                d: &self.d26,
130                reg: &self.reg26,
131                mv: self.mv(),
132                swings: 0,
133                xp_spent: 0,
134            };
135            f(&mut sim)
136        };
137        if r.is_ok() {
138            self.commit(m, lay);
139            self.s26[1] = scr;
140        }
141        r
142    }
143
144    /// 26.1 anvil: types `name` into the name field (`AnvilMenu.setItemName`; the name is
145    /// filtered like vanilla's and limited to 50 characters). Returns the `rename_item` to send
146    /// when the name changed (`Ok(None)`: nothing to send). An empty name removes a custom
147    /// name. Like the real screen, it does nothing while the input slot is empty.
148    ///
149    /// # Errors
150    /// [`ClickError::NoScreen`] when no anvil is open.
151    #[cfg(modern)]
152    pub fn anvil_rename_modern(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
153        if self.kind_26() != crate::sim26::Kind::Anvil {
154            return Err(ClickError::NoScreen);
155        }
156        if self.m.container.first().is_none_or(Option::is_none) {
157            return Ok(None);
158        }
159        let filtered: String = name
160            .chars()
161            .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}')
162            .collect();
163        if filtered.chars().count() > 50 || self.s26[1].anvil_name.as_deref() == Some(&filtered) {
164            return Ok(None);
165        }
166        self.d26.ensure(self.mv(), self.reg26.enchantments());
167        let n = filtered.clone();
168        let r = self.screen_action_modern(|sim| {
169            sim.s.anvil_name = Some(n);
170            sim.anvil_create()
171        });
172        if r.is_err() {
173            // the result could not be computed: keep the name, the server sends the result
174            self.s26[1].anvil_name = Some(filtered.clone());
175        }
176        Ok(Some(Outgoing::RenameItem(filtered)))
177    }
178
179    /// 26.1 `EnchantmentHelper.getTridentSpinAttackStrength(stack)`: 0 run through the
180    /// `minecraft:trident_spin_attack_strength` effect of every enchantment in the stack's
181    /// `enchantments` (in their order), as the server's enchantment registry defines it
182    /// (`registry_data` with data, else vanilla's definition: riptide adds `1.5 + 0.75 ×
183    /// (level - 1)`). `Some(0.0)` without such an enchantment.
184    ///
185    /// `None` when it cannot be computed: an enchantment whose definition is unknown (not sent
186    /// with data and not vanilla), an effect that does not read, or one that draws on the
187    /// holder's random (`remove_binomial`). The first call parses the raw registry data and
188    /// tags (hence `&mut self`).
189    #[cfg(modern)]
190    pub fn trident_spin_attack_strength_modern(&mut self, stack: &Stack) -> Option<f32> {
191        let list = crate::item26::enchantments(self.mv(), stack, false).unwrap_or_default();
192        if list.is_empty() {
193            return Some(0.0);
194        }
195        self.d26.ensure(self.mv(), self.reg26.enchantments());
196        let mut v = 0.0f32;
197        for (id, level) in list {
198            match &self.d26.enchantment(id)?.spin {
199                None => {}
200                Some(None) => return None,
201                Some(Some(fx)) => v = fx.process(level, v)?,
202            }
203        }
204        Some(v)
205    }
206
207    /// 26.1 loom: clicks pattern button `index` (`LoomMenu.clickMenuButton`). Returns the
208    /// `container_button_click` when the loom accepts it (`Ok(None)`: not a selectable pattern).
209    ///
210    /// # Errors
211    /// [`ClickError::NoScreen`] when no loom is open; [`ClickError::Unpredictable`] when the
212    /// patterns are not known.
213    #[cfg(modern)]
214    pub fn select_loom_pattern_modern(
215        &mut self,
216        index: i32,
217    ) -> Result<Option<Outgoing>, ClickError> {
218        if self.kind_26() != crate::sim26::Kind::Loom {
219            return Err(ClickError::NoScreen);
220        }
221        self.d26.ensure(self.mv(), self.reg26.enchantments());
222        let ok = self
223            .screen_action_modern(|sim| sim.loom_button(index))
224            .map_err(|_| ClickError::Unpredictable)?;
225        Ok(ok.then(|| Outgoing::ButtonClick {
226            window_id: self.open_id(),
227            button: index,
228        }))
229    }
230
231    /// 26.1 villager screen: picks trade `index` (`setSelectionHint`, `tryMoveItems`: the
232    /// payment goes back to the inventory and the trade's costs come out of it). Returns the
233    /// `select_trade` to send.
234    ///
235    /// # Errors
236    /// [`ClickError::NoScreen`] when no villager screen is open.
237    #[cfg(modern)]
238    pub fn select_trade_modern(&mut self, index: i32) -> Result<Outgoing, ClickError> {
239        if self.kind_26() != crate::sim26::Kind::Merchant {
240            return Err(ClickError::NoScreen);
241        }
242        if self
243            .screen_action_modern(|sim| sim.select_trade(index))
244            .is_err()
245        {
246            self.s26[1].trade_hint = index;
247        }
248        Ok(Outgoing::SelectTrade(index))
249    }
250
251    /// 26.1: keeps an `update_recipes` body for later parsing.
252    #[cfg(modern)]
253    pub(crate) fn set_recipes_raw_modern(&mut self, body: bytes::Bytes) {
254        self.recipes_raw = Some(body);
255    }
256
257    #[cfg(modern)]
258    pub(crate) fn take_recipes_raw_modern(&mut self) -> Option<bytes::Bytes> {
259        self.recipes_raw.take()
260    }
261
262    /// 26.1: the packets the creative inventory screen sent in answer to server packets since
263    /// the last call (vanilla echoes every window 0 slot the server sets while the screen is
264    /// open); send them right away.
265    #[cfg(modern)]
266    pub fn take_creative_echo_modern(&mut self) -> Vec<CreativePacket> {
267        std::mem::take(&mut self.creative_echo)
268    }
269
270    /// Whether the 26.1 creative inventory screen is open (window 0 opened in creative mode):
271    /// clicks then return [`Outgoing::Creative`].
272    #[cfg(modern)]
273    #[must_use]
274    pub fn creative_screen_modern(&self) -> bool {
275        self.creative_screen
276    }
277
278    /// `InventoryMenu.broadcastChanges` with the creative listener: every slot that differs
279    /// from the last broadcast is sent.
280    #[cfg(modern)]
281    pub(super) fn creative_broadcast(&mut self, out: &mut Vec<CreativePacket>) {
282        let lay = Layout::new(self.version, Screen::Player);
283        if self.creative_last.is_empty() {
284            // allocated on the first broadcast: a bot that never opens it pays nothing
285            self.creative_last = vec![None; 46];
286        }
287        for i in 0..46 {
288            let Some(l) = lay.loc(i) else { break };
289            let cur = self.m.at(l);
290            let same = match (&self.creative_last[i], cur) {
291                (None, None) => true,
292                (Some(a), Some(b)) => a.count == b.count && a.id == b.id && a.data_eq(b),
293                _ => false,
294            };
295            if !same {
296                self.creative_last[i] = cur.clone();
297                out.push(CreativePacket::SetSlot {
298                    slot: i as i16,
299                    item: cur.clone(),
300                });
301            }
302        }
303    }
304
305    /// A click in the creative inventory screen (`CreativeModeInventoryScreen.slotClicked`,
306    /// inventory tab): Q / drops are the screen's own; everything else runs window 0's click
307    /// and broadcasts. Refused as unpredictable when ghast cannot simulate it (the stacks it
308    /// sends would be wrong).
309    #[cfg(modern)]
310    pub(super) fn creative_click(
311        &mut self,
312        slot: i16,
313        button: u8,
314        mode: u8,
315    ) -> Result<Outgoing, ClickError> {
316        let mode = if slot == OUTSIDE && mode == 0 {
317            4
318        } else {
319            mode
320        };
321        let lay = Layout::new(self.version, Screen::Player);
322        let mut out = Vec::new();
323        let idx = usize::try_from(slot).ok();
324        if mode == 4 && self.drop_throttle >= 1280 {
325            // `canDropItems()` is false: the screen ignores the click
326            self.flags.clicked = true;
327            return Ok(Outgoing::Creative(out));
328        }
329        if mode == 4 {
330            if let Some(i) = idx
331                && let Some(l) = lay.loc(i)
332                && let Some(st) = self.m.at(l).clone()
333            {
334                // slot.remove(button == 0 ? 1 : max stack size): the crafting result is taken
335                // whole, other slots split
336                let n = if button == 0 {
337                    1
338                } else {
339                    crate::item26::max_stack_size(self.mv(), &st)
340                };
341                let dropped = if l == Loc::CraftResult {
342                    self.m.at_mut(l).take()
343                } else {
344                    let s = self.m.at_mut(l);
345                    let k = n.min(st.count).max(0);
346                    let d = (k > 0).then(|| st.with_count(k));
347                    if let Some(x) = s {
348                        x.count -= k;
349                        if x.count <= 0 {
350                            *s = None;
351                        }
352                    }
353                    d
354                };
355                if dropped.is_some() {
356                    self.drop_throttle += 20;
357                    if self.mv().swing_packet() {
358                        out.push(CreativePacket::Swing);
359                    }
360                    out.push(CreativePacket::SetSlot {
361                        slot: -1,
362                        item: dropped,
363                    });
364                }
365                out.push(CreativePacket::SetSlot {
366                    slot,
367                    item: self.m.at(l).clone(),
368                });
369                self.events.player_changed = true;
370                self.flags.clicked = true;
371                return Ok(Outgoing::Creative(out));
372            }
373            if slot == OUTSIDE
374                && let Some(c) = self.m.cursor.take()
375            {
376                self.drop_throttle += 20;
377                if self.mv().swing_packet() {
378                    out.push(CreativePacket::Swing);
379                }
380                out.push(CreativePacket::SetSlot {
381                    slot: -1,
382                    item: Some(c),
383                });
384                self.events.cursor_changed = true;
385                self.flags.clicked = true;
386                return Ok(Outgoing::Creative(out));
387            }
388        }
389        let mut m = self.m.clone();
390        let mut scr = self.s26[0].clone();
391        self.w26.binding_curse = self.binding_curse();
392        self.w26.can_drop = self.drop_throttle < 1280;
393        let (result, swings) = {
394            let mut sim = crate::sim26::Sim26 {
395                kind: crate::sim26::Kind::Player,
396                m: &mut m,
397                s: &mut scr,
398                w: &self.w26,
399                d: &self.d26,
400                reg: &self.reg26,
401                mv: self.mv(),
402                swings: 0,
403                xp_spent: 0,
404            };
405            let r = sim.click(slot, button as i8, mode);
406            (r, sim.swings)
407        };
408        if result.is_err() {
409            return Err(ClickError::Unpredictable);
410        }
411        if self.mv().swing_packet() {
412            for _ in 0..swings {
413                out.push(CreativePacket::Swing);
414            }
415        }
416        self.commit(m, lay);
417        self.s26[0] = scr;
418        self.creative_broadcast(&mut out);
419        self.flags.clicked = true;
420        Ok(Outgoing::Creative(out))
421    }
422
423    /// 26.1: the player's experience level (the anvil's result can only be taken with enough);
424    /// set from the `experience` packet by [`Inventory::apply_raw_modern`].
425    #[cfg(modern)]
426    pub fn set_experience_level_modern(&mut self, level: i32) {
427        self.w26.xp_level = Some(level);
428    }
429
430    /// 26.1 `update_recipes` (`declare_recipes`): the recipe item sets the furnace, smithing
431    /// and stonecutter slot rules read (`(set name, item ids)`, e.g.
432    /// `("minecraft:furnace_input", …)`) and the stonecutter recipes' inputs (`None` when one
433    /// names a tag: shift-clicks into the stonecutter are then not predicted).
434    #[cfg(modern)]
435    pub fn on_recipes_modern<'a>(
436        &mut self,
437        sets: impl IntoIterator<Item = (&'a str, &'a [i32])>,
438        stonecutter_inputs: Option<Vec<i32>>,
439    ) {
440        self.recipes_raw = None;
441        let w = &mut self.w26;
442        for v in [
443            &mut w.furnace_input,
444            &mut w.blast_input,
445            &mut w.smoker_input,
446            &mut w.smithing_base,
447            &mut w.smithing_template,
448            &mut w.smithing_addition,
449            &mut w.brewing_reagent,
450            &mut w.brewing_input,
451        ] {
452            v.clear();
453        }
454        for (name, ids) in sets {
455            let target = match name.strip_prefix("minecraft:").unwrap_or(name) {
456                "furnace_input" => &mut w.furnace_input,
457                "blast_furnace_input" => &mut w.blast_input,
458                "smoker_input" => &mut w.smoker_input,
459                "smithing_base" => &mut w.smithing_base,
460                "smithing_template" => &mut w.smithing_template,
461                "smithing_addition" => &mut w.smithing_addition,
462                "brewing_reagent" => &mut w.brewing_reagent,
463                "brewing_input" => &mut w.brewing_input,
464                _ => continue,
465            };
466            target.extend_from_slice(ids);
467            target.sort_unstable();
468            target.dedup();
469        }
470        w.cutter_inputs = stonecutter_inputs.map(|mut v| {
471            v.sort_unstable();
472            v.dedup();
473            v
474        });
475    }
476
477    /// Modern `open_screen`: the menu registry id (`minecraft:menu`) and the title. Menus the
478    /// client has no screen for are ignored.
479    #[cfg(modern)]
480    pub fn on_open_screen_modern(&mut self, id: i32, menu: i32, title: ByteString) {
481        self.on_open_window(id, crate::item26::window_kind(self.mv(), menu), title);
482        if let ScreenState::Window(w) = &mut self.screen
483            && w.id == id
484        {
485            w.menu = menu;
486        }
487        self.s26[1] = Default::default();
488    }
489
490    /// 26.1: the client-side effects of setting the open menu's container slots from a packet:
491    /// vanilla runs each slot's `set` in order (the container caps it and the menu's
492    /// `slotsChanged` recomputes results and remembered state: the anvil's cost and repair
493    /// counts, the loom's patterns, the trade, the stonecutter input). `old` is the container
494    /// before the packet; the packet's slots are replayed one by one from it.
495    /// Whether the open 26.1 menu reacts to server slot packets (container caps, result hooks).
496    #[cfg(modern)]
497    pub(super) fn hooks_modern(&self) -> bool {
498        use crate::sim26::Kind;
499        matches!(
500            self.kind_26(),
501            Kind::Anvil
502                | Kind::Beacon
503                | Kind::Grindstone
504                | Kind::Smithing
505                | Kind::Stonecutter
506                | Kind::Loom
507                | Kind::Cartography
508                | Kind::Merchant
509        )
510    }
511
512    #[cfg(modern)]
513    pub(super) fn inbound_modern(
514        &mut self,
515        old: Vec<Option<Stack>>,
516        slots: std::ops::Range<usize>,
517    ) {
518        use crate::sim26::Kind;
519        let kind = self.kind_26();
520        if matches!(kind, Kind::Anvil | Kind::Grindstone | Kind::Loom) {
521            self.d26.ensure(self.mv(), self.reg26.enchantments());
522        }
523        let new = std::mem::replace(&mut self.m.container, old);
524        let mut scr = self.s26[1].clone();
525        let mut m = std::mem::take(&mut self.m);
526        let mut ok = true;
527        {
528            let mut sim = crate::sim26::Sim26 {
529                kind,
530                m: &mut m,
531                s: &mut scr,
532                w: &self.w26,
533                d: &self.d26,
534                reg: &self.reg26,
535                mv: self.mv(),
536                swings: 0,
537                xp_spent: 0,
538            };
539            for k in slots.clone() {
540                if k >= new.len() {
541                    break;
542                }
543                if sim.inbound_set(k, new[k].clone()).is_err() {
544                    ok = false;
545                    break;
546                }
547            }
548        }
549        if !ok {
550            // a hook ghast cannot compute: the packet's slots as sent
551            for k in slots {
552                if let (Some(d), Some(v)) = (m.container.get_mut(k), new.get(k)) {
553                    *d = v.clone();
554                }
555            }
556        }
557        self.m = m;
558        self.s26[1] = scr;
559    }
560}