Skip to main content

ghast_inventory/
item.rs

1//! Version-agnostic item accessors: the facts bots read off a stack (name, stack size,
2//! durability, custom name, lore, enchantments, potion), answered from NBT on 1.8 – 1.16.5 and
3//! from data components (patch over the item's defaults) on 26.1. Nothing is decoded until an
4//! accessor is called; each call reads only what it needs.
5//!
6//! | accessor | 1.8 / 1.12 | 1.16.5 | 26.1 |
7//! |---|---|---|---|
8//! | [`Stack::item_name`] | `ghast-data` item table | `ghast-data` | Mojang item registry |
9//! | [`Stack::max_stack_size`] | `ghast-data` | `ghast-data` | `max_stack_size` component |
10//! | [`Stack::max_damage`] | `ghast-data` durability | `ghast-data` | `max_damage` |
11//! | [`Stack::damage_value`] | damage field | `Damage` tag | `damage` |
12//! | [`Stack::unbreakable`] | `Unbreakable` tag | `Unbreakable` | `unbreakable` |
13//! | [`Stack::custom_name`] | `display.Name` (string) | `display.Name` (JSON) | `custom_name` (NBT text) |
14//! | [`Stack::lore`] | `display.Lore` | `display.Lore` (JSON) | `lore` |
15//! | [`Stack::enchantments`] | `ench` (numeric ids) | `Enchantments` (names) | `enchantments` (registry ids) |
16//! | [`Stack::stored_enchantments`] | `StoredEnchantments` | `StoredEnchantments` | `stored_enchantments` |
17//! | [`Stack::potion`] | 1.12 `Potion` tag (1.8: none) | `Potion` | `potion_contents` |
18
19use ghast_protocol::nbt::{Compound, Tag};
20
21use crate::rules::Version;
22use crate::stack::{Stack, last, number};
23
24/// A text field of an item (custom name, lore line) in its version's form.
25#[derive(Debug, Clone, PartialEq)]
26#[non_exhaustive]
27pub enum ItemText {
28    /// 1.8 / 1.12: a string with `§` formatting codes.
29    Legacy(String),
30    /// 1.16.5: a JSON text component.
31    Json(String),
32    /// 26.1: an NBT text component.
33    #[cfg(modern)]
34    Nbt(ghast_protocol::nbt::AnonNbt),
35}
36
37impl ItemText {
38    /// The text without formatting. JSON text (1.16.5) is returned as sent; parse it with
39    /// `ghast_protocol::chat::to_plain_text` (feature `chat-json`).
40    #[must_use]
41    pub fn to_plain(&self) -> String {
42        match self {
43            ItemText::Legacy(s) => ghast_protocol::chat::strip_formatting(s),
44            ItemText::Json(s) => s.clone(),
45            #[cfg(modern)]
46            ItemText::Nbt(n) => ghast_protocol::chat::nbt_to_plain_text(n),
47        }
48    }
49}
50
51/// An enchantment id in its version's form.
52#[derive(Debug, Clone, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum EnchantmentId {
55    /// 1.8 / 1.12: numeric id.
56    Legacy(i16),
57    /// 1.16.5: name (`minecraft:sharpness`).
58    Name(String),
59    /// 26.1: index into the `minecraft:enchantment` registry the server sent during
60    /// configuration (enchantments are data-driven).
61    Registry(i32),
62}
63
64impl EnchantmentId {
65    /// The name, given the 26.1 registry names (ignored for the other forms; `None` for a
66    /// legacy numeric id).
67    #[must_use]
68    pub fn name<'a>(&'a self, registry: &'a [String]) -> Option<&'a str> {
69        match self {
70            EnchantmentId::Legacy(_) => None,
71            EnchantmentId::Name(n) => Some(n),
72            EnchantmentId::Registry(i) => {
73                registry.get(usize::try_from(*i).ok()?).map(String::as_str)
74            }
75        }
76    }
77}
78
79/// One enchantment of a stack.
80#[derive(Debug, Clone, PartialEq, Eq, Hash)]
81#[non_exhaustive]
82pub struct Enchantment {
83    /// Which.
84    pub id: EnchantmentId,
85    /// Level as stored.
86    pub level: i32,
87}
88
89/// A broad item kind, version-independent ([`Stack::kind`]): what combat and tool logic asks
90/// (`#[non_exhaustive]`: kinds may be added).
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92#[non_exhaustive]
93pub enum ItemKind {
94    /// A sword.
95    Sword,
96    /// An axe.
97    Axe,
98    /// A pickaxe.
99    Pickaxe,
100    /// A shovel.
101    Shovel,
102    /// A hoe.
103    Hoe,
104    /// A bow.
105    Bow,
106    /// A crossbow (1.14+).
107    Crossbow,
108    /// A trident (1.13+).
109    Trident,
110    /// A mace (1.21+).
111    Mace,
112    /// A shield (1.9+).
113    Shield,
114    /// A fishing rod.
115    FishingRod,
116    /// A helmet (turtle shell included).
117    Helmet,
118    /// A chestplate.
119    Chestplate,
120    /// Leggings.
121    Leggings,
122    /// Boots.
123    Boots,
124    /// Anything else.
125    Other,
126}
127
128impl ItemKind {
129    /// The kind of an item by its registry name (without `minecraft:`), the same rule on every
130    /// version (`diamond_sword`, `golden_axe`, `turtle_helmet` …).
131    #[must_use]
132    pub fn of_name(name: &str) -> ItemKind {
133        let name = name.strip_prefix("minecraft:").unwrap_or(name);
134        let exact = match name {
135            "bow" => Some(ItemKind::Bow),
136            "crossbow" => Some(ItemKind::Crossbow),
137            "trident" => Some(ItemKind::Trident),
138            "mace" => Some(ItemKind::Mace),
139            "shield" => Some(ItemKind::Shield),
140            "fishing_rod" => Some(ItemKind::FishingRod),
141            "turtle_helmet" => Some(ItemKind::Helmet),
142            _ => None,
143        };
144        if let Some(k) = exact {
145            return k;
146        }
147        // `_pickaxe` before `_axe`.
148        for (suffix, k) in [
149            ("_sword", ItemKind::Sword),
150            ("_pickaxe", ItemKind::Pickaxe),
151            ("_axe", ItemKind::Axe),
152            ("_shovel", ItemKind::Shovel),
153            ("_hoe", ItemKind::Hoe),
154            ("_helmet", ItemKind::Helmet),
155            ("_chestplate", ItemKind::Chestplate),
156            ("_leggings", ItemKind::Leggings),
157            ("_boots", ItemKind::Boots),
158        ] {
159            if name.ends_with(suffix) {
160                return k;
161            }
162        }
163        ItemKind::Other
164    }
165}
166
167/// 1.8 / 1.12 enchantment registry ids by name (`Enchantment.REGISTRY`, from the jars: 9, 10,
168/// 22, 70 and 71 exist since 1.9 – 1.11).
169pub(crate) const LEGACY_ENCHANTMENTS: &[(i16, &str)] = &[
170    (0, "protection"),
171    (1, "fire_protection"),
172    (2, "feather_falling"),
173    (3, "blast_protection"),
174    (4, "projectile_protection"),
175    (5, "respiration"),
176    (6, "aqua_affinity"),
177    (7, "thorns"),
178    (8, "depth_strider"),
179    (9, "frost_walker"),
180    (10, "binding_curse"),
181    (16, "sharpness"),
182    (17, "smite"),
183    (18, "bane_of_arthropods"),
184    (19, "knockback"),
185    (20, "fire_aspect"),
186    (21, "looting"),
187    (22, "sweeping"),
188    (32, "efficiency"),
189    (33, "silk_touch"),
190    (34, "unbreaking"),
191    (35, "fortune"),
192    (48, "power"),
193    (49, "punch"),
194    (50, "flame"),
195    (51, "infinity"),
196    (61, "luck_of_the_sea"),
197    (62, "lure"),
198    (70, "mending"),
199    (71, "vanishing_curse"),
200];
201
202impl EnchantmentId {
203    /// The name without `minecraft:` on every version: 1.8 / 1.12 numeric ids through the
204    /// vanilla registry, 26.x registry ids through `registry` (the server's enchantment
205    /// registry names, [`crate::Inventory::enchantment_name_modern`]'s list).
206    #[must_use]
207    pub fn plain_name<'a>(&'a self, registry: &'a [String]) -> Option<&'a str> {
208        let n = match self {
209            EnchantmentId::Legacy(id) => {
210                return LEGACY_ENCHANTMENTS
211                    .iter()
212                    .find(|(i, _)| i == id)
213                    .map(|(_, n)| *n);
214            }
215            other => other.name(registry)?,
216        };
217        Some(n.strip_prefix("minecraft:").unwrap_or(n))
218    }
219}
220
221impl Stack {
222    /// The broad kind of the item ([`ItemKind::of_name`] of [`Stack::item_name`]).
223    #[must_use]
224    pub fn kind(&self, v: Version) -> ItemKind {
225        self.item_name(v).map_or(ItemKind::Other, ItemKind::of_name)
226    }
227
228    /// `true` for a sword.
229    #[must_use]
230    pub fn is_sword(&self, v: Version) -> bool {
231        self.kind(v) == ItemKind::Sword
232    }
233}
234
235fn root(s: &Stack) -> Option<Compound> {
236    match s.nbt()?.parse().ok()??.tag {
237        Tag::Compound(c) => Some(c),
238        _ => None,
239    }
240}
241
242fn display(s: &Stack) -> Option<Compound> {
243    match last(&root(s)?, "display")? {
244        Tag::Compound(c) => Some(c.clone()),
245        _ => None,
246    }
247}
248
249fn legacy_text(v: Version, s: String) -> ItemText {
250    if v == Version::V1_16_5 {
251        ItemText::Json(s)
252    } else {
253        ItemText::Legacy(s)
254    }
255}
256
257fn nbt_enchantments(s: &Stack, v: Version, stored: bool) -> Vec<Enchantment> {
258    let key = match (v, stored) {
259        (_, true) => "StoredEnchantments",
260        (Version::V1_16_5, false) => "Enchantments",
261        _ => "ench",
262    };
263    let Some(r) = root(s) else { return Vec::new() };
264    let Some(Tag::List(l)) = last(&r, key) else {
265        return Vec::new();
266    };
267    l.items
268        .iter()
269        .filter_map(|e| {
270            let Tag::Compound(e) = e else { return None };
271            let level = last(e, "lvl").and_then(number).unwrap_or(0) as i32;
272            let id = match last(e, "id")? {
273                Tag::String(n) => EnchantmentId::Name(n.clone()),
274                t => EnchantmentId::Legacy(number(t)? as i16),
275            };
276            Some(Enchantment { id, level })
277        })
278        .collect()
279}
280
281impl Stack {
282    /// Item registry name without `minecraft:` (`None` when the id is unknown to the version).
283    #[must_use]
284    pub fn item_name(&self, v: Version) -> Option<&'static str> {
285        let n = v.name(self.id);
286        (!n.is_empty()).then_some(n)
287    }
288
289    /// Largest stack of this item (`ItemStack.getMaxStackSize`; 26.1 reads the component).
290    #[must_use]
291    pub fn max_stack_size(&self, v: Version) -> i32 {
292        v.max_count(self)
293    }
294
295    /// Durability (`None` for items without one).
296    #[must_use]
297    pub fn max_damage(&self, v: Version) -> Option<i32> {
298        match v {
299            #[cfg(modern)]
300            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::max_damage(
301                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
302                self,
303            ),
304            _ => v.max_durability(self.id),
305        }
306    }
307
308    /// Whether the stack loses durability (`isDamageable`: it has durability and is not
309    /// unbreakable).
310    #[must_use]
311    pub fn is_damageable(&self, v: Version) -> bool {
312        v.is_damageable(self)
313    }
314
315    /// Damage taken (0 when not damageable; 1.8 / 1.12 items with variants use the damage field
316    /// as the variant, not as damage).
317    #[must_use]
318    pub fn damage_value(&self, v: Version) -> i32 {
319        match v {
320            Version::V1_8 | Version::V1_12 => {
321                if v.has_subtypes(self.id) {
322                    0
323                } else {
324                    i32::from(self.damage)
325                }
326            }
327            Version::V1_16_5 => self.nbt_int("Damage"),
328            #[cfg(modern)]
329            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::damage_value(
330                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
331                self,
332            ),
333            #[allow(unreachable_patterns)]
334            _ => 0,
335        }
336    }
337
338    /// `Unbreakable` (1.8 – 1.16.5 tag, 26.1 component, including the item default).
339    #[must_use]
340    pub fn unbreakable(&self, v: Version) -> bool {
341        match v {
342            #[cfg(modern)]
343            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::unbreakable(
344                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
345                self,
346            ),
347            _ => self.nbt_bool("Unbreakable"),
348        }
349    }
350
351    /// The custom name (anvil / plugin name), if any.
352    #[must_use]
353    pub fn custom_name(&self, v: Version) -> Option<ItemText> {
354        match v {
355            #[cfg(modern)]
356            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::text(
357                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
358                self,
359                crate::tables::kind::CUSTOM_NAME,
360            )
361            .map(ItemText::Nbt),
362            _ => match last(&display(self)?, "Name")? {
363                Tag::String(n) => Some(legacy_text(v, n.clone())),
364                _ => None,
365            },
366        }
367    }
368
369    /// The lore lines (empty when none).
370    #[must_use]
371    pub fn lore(&self, v: Version) -> Vec<ItemText> {
372        match v {
373            #[cfg(modern)]
374            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::lore(
375                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
376                self,
377            )
378            .into_iter()
379            .map(ItemText::Nbt)
380            .collect(),
381            _ => {
382                let Some(d) = display(self) else {
383                    return Vec::new();
384                };
385                let Some(Tag::List(l)) = last(&d, "Lore") else {
386                    return Vec::new();
387                };
388                l.items
389                    .iter()
390                    .filter_map(|t| match t {
391                        Tag::String(s) => Some(legacy_text(v, s.clone())),
392                        _ => None,
393                    })
394                    .collect()
395            }
396        }
397    }
398
399    /// The enchantments (empty when none).
400    #[must_use]
401    pub fn enchantments(&self, v: Version) -> Vec<Enchantment> {
402        self.enchants(v, false)
403    }
404
405    /// The stored enchantments of an enchanted book (empty when none).
406    #[must_use]
407    pub fn stored_enchantments(&self, v: Version) -> Vec<Enchantment> {
408        self.enchants(v, true)
409    }
410
411    fn enchants(&self, v: Version, stored: bool) -> Vec<Enchantment> {
412        match v {
413            #[cfg(modern)]
414            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::enchantments(
415                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
416                self,
417                stored,
418            )
419            .unwrap_or_default()
420            .into_iter()
421            .map(|(id, level)| Enchantment {
422                id: EnchantmentId::Registry(id),
423                level,
424            })
425            .collect(),
426            _ => nbt_enchantments(self, v, stored),
427        }
428    }
429
430    /// The potion type (`minecraft:healing` on 1.12 / 1.16.5; `healing` on 26.1), when the
431    /// stack names one (1.8 encodes potions in the damage value: `None`).
432    #[must_use]
433    pub fn potion(&self, v: Version) -> Option<String> {
434        match v {
435            #[cfg(modern)]
436            Version::V26_1 | Version::V26_2 | Version::V26_3 => crate::item26::potion(
437                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
438                self,
439            )
440            .map(str::to_string),
441            Version::V1_12 | Version::V1_16_5 => match last(&root(self)?, "Potion")? {
442                Tag::String(p) => Some(p.clone()),
443                _ => None,
444            },
445            _ => None,
446        }
447    }
448}