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
89fn root(s: &Stack) -> Option<Compound> {
90    match s.nbt()?.parse().ok()??.tag {
91        Tag::Compound(c) => Some(c),
92        _ => None,
93    }
94}
95
96fn display(s: &Stack) -> Option<Compound> {
97    match last(&root(s)?, "display")? {
98        Tag::Compound(c) => Some(c.clone()),
99        _ => None,
100    }
101}
102
103fn legacy_text(v: Version, s: String) -> ItemText {
104    if v == Version::V1_16_5 {
105        ItemText::Json(s)
106    } else {
107        ItemText::Legacy(s)
108    }
109}
110
111fn nbt_enchantments(s: &Stack, v: Version, stored: bool) -> Vec<Enchantment> {
112    let key = match (v, stored) {
113        (_, true) => "StoredEnchantments",
114        (Version::V1_16_5, false) => "Enchantments",
115        _ => "ench",
116    };
117    let Some(r) = root(s) else { return Vec::new() };
118    let Some(Tag::List(l)) = last(&r, key) else {
119        return Vec::new();
120    };
121    l.items
122        .iter()
123        .filter_map(|e| {
124            let Tag::Compound(e) = e else { return None };
125            let level = last(e, "lvl").and_then(number).unwrap_or(0) as i32;
126            let id = match last(e, "id")? {
127                Tag::String(n) => EnchantmentId::Name(n.clone()),
128                t => EnchantmentId::Legacy(number(t)? as i16),
129            };
130            Some(Enchantment { id, level })
131        })
132        .collect()
133}
134
135impl Stack {
136    /// Item registry name without `minecraft:` (`None` when the id is unknown to the version).
137    #[must_use]
138    pub fn item_name(&self, v: Version) -> Option<&'static str> {
139        let n = v.name(self.id);
140        (!n.is_empty()).then_some(n)
141    }
142
143    /// Largest stack of this item (`ItemStack.getMaxStackSize`; 26.1 reads the component).
144    #[must_use]
145    pub fn max_stack_size(&self, v: Version) -> i32 {
146        v.max_count(self)
147    }
148
149    /// Durability (`None` for items without one).
150    #[must_use]
151    pub fn max_damage(&self, v: Version) -> Option<i32> {
152        match v {
153            #[cfg(modern)]
154            Version::V26_1 | Version::V26_2 => crate::item26::max_damage(
155                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
156                self,
157            ),
158            _ => v.max_durability(self.id),
159        }
160    }
161
162    /// Whether the stack loses durability (`isDamageable`: it has durability and is not
163    /// unbreakable).
164    #[must_use]
165    pub fn is_damageable(&self, v: Version) -> bool {
166        v.is_damageable(self)
167    }
168
169    /// Damage taken (0 when not damageable; 1.8 / 1.12 items with variants use the damage field
170    /// as the variant, not as damage).
171    #[must_use]
172    pub fn damage_value(&self, v: Version) -> i32 {
173        match v {
174            Version::V1_8 | Version::V1_12 => {
175                if v.has_subtypes(self.id) {
176                    0
177                } else {
178                    i32::from(self.damage)
179                }
180            }
181            Version::V1_16_5 => self.nbt_int("Damage"),
182            #[cfg(modern)]
183            Version::V26_1 | Version::V26_2 => crate::item26::damage_value(
184                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
185                self,
186            ),
187            #[allow(unreachable_patterns)]
188            _ => 0,
189        }
190    }
191
192    /// `Unbreakable` (1.8 – 1.16.5 tag, 26.1 component, including the item default).
193    #[must_use]
194    pub fn unbreakable(&self, v: Version) -> bool {
195        match v {
196            #[cfg(modern)]
197            Version::V26_1 | Version::V26_2 => crate::item26::unbreakable(
198                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
199                self,
200            ),
201            _ => self.nbt_bool("Unbreakable"),
202        }
203    }
204
205    /// The custom name (anvil / plugin name), if any.
206    #[must_use]
207    pub fn custom_name(&self, v: Version) -> Option<ItemText> {
208        match v {
209            #[cfg(modern)]
210            Version::V26_1 | Version::V26_2 => crate::item26::text(
211                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
212                self,
213                crate::tables::kind::CUSTOM_NAME,
214            )
215            .map(ItemText::Nbt),
216            _ => match last(&display(self)?, "Name")? {
217                Tag::String(n) => Some(legacy_text(v, n.clone())),
218                _ => None,
219            },
220        }
221    }
222
223    /// The lore lines (empty when none).
224    #[must_use]
225    pub fn lore(&self, v: Version) -> Vec<ItemText> {
226        match v {
227            #[cfg(modern)]
228            Version::V26_1 | Version::V26_2 => crate::item26::lore(
229                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
230                self,
231            )
232            .into_iter()
233            .map(ItemText::Nbt)
234            .collect(),
235            _ => {
236                let Some(d) = display(self) else {
237                    return Vec::new();
238                };
239                let Some(Tag::List(l)) = last(&d, "Lore") else {
240                    return Vec::new();
241                };
242                l.items
243                    .iter()
244                    .filter_map(|t| match t {
245                        Tag::String(s) => Some(legacy_text(v, s.clone())),
246                        _ => None,
247                    })
248                    .collect()
249            }
250        }
251    }
252
253    /// The enchantments (empty when none).
254    #[must_use]
255    pub fn enchantments(&self, v: Version) -> Vec<Enchantment> {
256        self.enchants(v, false)
257    }
258
259    /// The stored enchantments of an enchanted book (empty when none).
260    #[must_use]
261    pub fn stored_enchantments(&self, v: Version) -> Vec<Enchantment> {
262        self.enchants(v, true)
263    }
264
265    fn enchants(&self, v: Version, stored: bool) -> Vec<Enchantment> {
266        match v {
267            #[cfg(modern)]
268            Version::V26_1 | Version::V26_2 => crate::item26::enchantments(
269                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
270                self,
271                stored,
272            )
273            .unwrap_or_default()
274            .into_iter()
275            .map(|(id, level)| Enchantment {
276                id: EnchantmentId::Registry(id),
277                level,
278            })
279            .collect(),
280            _ => nbt_enchantments(self, v, stored),
281        }
282    }
283
284    /// The potion type (`minecraft:healing` on 1.12 / 1.16.5; `healing` on 26.1), when the
285    /// stack names one (1.8 encodes potions in the damage value: `None`).
286    #[must_use]
287    pub fn potion(&self, v: Version) -> Option<String> {
288        match v {
289            #[cfg(modern)]
290            Version::V26_1 | Version::V26_2 => crate::item26::potion(
291                crate::tables::Mv::of(v).unwrap_or(crate::tables::Mv::ANY),
292                self,
293            )
294            .map(str::to_string),
295            Version::V1_12 | Version::V1_16_5 => match last(&root(self)?, "Potion")? {
296                Tag::String(p) => Some(p.clone()),
297                _ => None,
298            },
299            _ => None,
300        }
301    }
302}