Skip to main content

azalea_registry/item/
mod.rs

1// this module is contained in azalea-registry (as opposed to being in
2// azalea-inventory or its own thing) because Particle needs ItemStack. maybe we
3// should move `item` and `registry_holder` to its own crate? idk, it's probably
4// fine like this for now.
5
6pub mod checksum;
7pub mod components;
8pub mod consume_effect;
9pub mod default_components;
10
11use std::{
12    fmt::Debug,
13    io::{self, Cursor, Write},
14};
15
16use azalea_buf::{AzBuf, AzBufVar, BufReadError};
17use azalea_codec::Codec;
18
19use crate::{
20    builtin::ItemKind,
21    item::{
22        components::{
23            DataComponent, MaxStackSize,
24            patch::{DataComponentPatch, EMPTY_DATA_COMPONENT_PATCH},
25        },
26        default_components::get_default_component,
27    },
28};
29
30pub trait MaxStackSizeExt {
31    /// Get the maximum stack size for this item.
32    ///
33    /// This is a signed integer to be consistent with the `count` field of
34    /// [`ItemStackData`].
35    ///
36    /// [`ItemStackData`]: crate::item::ItemStackData
37    fn max_stack_size(&self) -> i32;
38
39    /// Whether this item can be stacked with other items.
40    ///
41    /// This is equivalent to `self.max_stack_size() > 1`.
42    fn stackable(&self) -> bool {
43        self.max_stack_size() > 1
44    }
45}
46
47impl MaxStackSizeExt for ItemKind {
48    fn max_stack_size(&self) -> i32 {
49        get_default_component::<MaxStackSize>(*self).map_or(64, |s| s.count)
50    }
51}
52
53/// Either an item in an inventory or nothing.
54#[derive(Clone, Debug, Default, PartialEq, Codec)]
55pub enum ItemStack {
56    #[codec(unit)]
57    #[default]
58    Empty,
59    Present(ItemStackData),
60}
61
62impl ItemStack {
63    /// Create a new [`ItemStack`] with the given number of [`ItemKind`]s.
64    ///
65    /// If item is air or the count isn't positive, then it'll be set to an
66    /// empty `ItemStack`.
67    pub fn new(item: ItemKind, count: i32) -> Self {
68        let mut i = ItemStack::Present(ItemStackData::new(item, count));
69        // set it to Empty if the item is air or if the count isn't positive
70        i.update_empty();
71        i
72    }
73
74    /// Check if the slot is ItemStack::Empty, if the count is <= 0, or if the
75    /// item is air.
76    ///
77    /// This is the opposite of [`ItemStack::is_present`].
78    pub fn is_empty(&self) -> bool {
79        match self {
80            ItemStack::Empty => true,
81            ItemStack::Present(item) => item.is_empty(),
82        }
83    }
84    /// Check if the slot is not ItemStack::Empty, if the count is > 0, and if
85    /// the item is not air.
86    ///
87    /// This is the opposite of [`ItemStack::is_empty`].
88    pub fn is_present(&self) -> bool {
89        !self.is_empty()
90    }
91
92    /// Return the amount of the item in the slot, or 0 if the slot is empty.
93    ///
94    /// Note that it's possible for the count to be zero or negative when the
95    /// slot is present.
96    pub fn count(&self) -> i32 {
97        match self {
98            ItemStack::Empty => 0,
99            ItemStack::Present(i) => i.count,
100        }
101    }
102
103    /// Remove `count` items from this slot, returning the removed items.
104    pub fn split(&mut self, count: u32) -> ItemStack {
105        match self {
106            ItemStack::Empty => ItemStack::Empty,
107            ItemStack::Present(i) => {
108                let returning = i.split(count);
109                if i.is_empty() {
110                    *self = ItemStack::Empty;
111                }
112                ItemStack::Present(returning)
113            }
114        }
115    }
116
117    /// Get the `kind` of the item in this slot, or [`ItemKind::Air`]
118    pub fn kind(&self) -> ItemKind {
119        match self {
120            ItemStack::Empty => ItemKind::Air,
121            ItemStack::Present(i) => i.kind,
122        }
123    }
124
125    /// Update whether this slot is empty, based on the count.
126    pub fn update_empty(&mut self) {
127        if let ItemStack::Present(i) = self
128            && i.is_empty()
129        {
130            *self = ItemStack::Empty;
131        }
132    }
133
134    /// Convert this slot into an [`ItemStackData`], if it's present.
135    pub fn as_present(&self) -> Option<&ItemStackData> {
136        match self {
137            ItemStack::Empty => None,
138            ItemStack::Present(i) => Some(i),
139        }
140    }
141
142    pub fn as_present_mut(&mut self) -> Option<&mut ItemStackData> {
143        match self {
144            ItemStack::Empty => None,
145            ItemStack::Present(i) => Some(i),
146        }
147    }
148
149    pub fn component_patch(&self) -> &DataComponentPatch {
150        self.as_present()
151            .map_or_else(|| &*EMPTY_DATA_COMPONENT_PATCH, |i| &i.component_patch)
152    }
153
154    /// Get the value of a data component for this item.
155    ///
156    /// This is used for things like getting the damage of an item, or seeing
157    /// how much food it replenishes.
158    pub fn get_component<T: components::DataComponentTrait>(&self) -> Option<&T> {
159        self.as_present().and_then(|i| i.get_component::<T>())
160    }
161
162    pub fn with_component<T: components::DataComponentTrait>(
163        mut self,
164        component: impl Into<Option<T>>,
165    ) -> Self {
166        if let ItemStack::Present(i) = &mut self {
167            let component: Option<T> = component.into();
168            let component: Option<DataComponent> = component.map(|c| c.into());
169            i.component_patch.insert_component(T::KIND, component);
170        }
171        self
172    }
173}
174
175/// An item in an inventory, with a count and a set of data components.
176///
177/// Usually you want [`ItemStack`] or [`ItemKind`] instead.
178#[derive(Clone, Debug, PartialEq, Codec)]
179pub struct ItemStackData {
180    #[codec(rename = "id")]
181    pub kind: ItemKind,
182    /// The amount of the item in this slot.
183    ///
184    /// The count can be zero or negative, but this is rare.
185    pub count: i32,
186    /// The item's components that the server set to be different from the
187    /// defaults.
188    #[codec(optional, rename = "components")]
189    pub component_patch: DataComponentPatch,
190}
191
192impl ItemStackData {
193    /// Create a new [`ItemStackData`] with the given number of [`ItemKind`]s.
194    pub fn new(item: ItemKind, count: i32) -> Self {
195        ItemStackData {
196            count,
197            kind: item,
198            component_patch: Default::default(),
199        }
200    }
201
202    /// Remove `count` items from this slot, returning the removed items.
203    pub fn split(&mut self, count: u32) -> ItemStackData {
204        let returning_count = i32::min(count as i32, self.count);
205        let mut returning = self.clone();
206        returning.count = returning_count;
207        self.count -= returning_count;
208        returning
209    }
210
211    /// Check if the count of the item is <= 0 or if the item is air.
212    pub fn is_empty(&self) -> bool {
213        self.count <= 0 || self.kind == ItemKind::Air
214    }
215
216    /// Whether this item is the same as another item, ignoring the count.
217    ///
218    /// ```
219    /// # use azalea_registry::{builtin::ItemKind, item::ItemStackData};
220    /// let mut a = ItemStackData::from(ItemKind::Stone);
221    /// let mut b = ItemStackData::new(ItemKind::Stone, 2);
222    /// assert!(a.is_same_item_and_components(&b));
223    ///
224    /// b.kind = ItemKind::Dirt;
225    /// assert!(!a.is_same_item_and_components(&b));
226    /// ```
227    pub fn is_same_item_and_components(&self, other: &ItemStackData) -> bool {
228        self.kind == other.kind && self.component_patch == other.component_patch
229    }
230
231    /// Get the value of a data component for this item.
232    ///
233    /// This is used for things like getting the damage of an item, or seeing
234    /// how much food it replenishes.
235    pub fn get_component<T: components::DataComponentTrait>(&self) -> Option<&T> {
236        if let Some(c) = self.component_patch.get::<T>() {
237            Some(c)
238        } else {
239            get_default_component::<T>(self.kind)
240        }
241    }
242}
243
244impl AzBuf for ItemStack {
245    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
246        let count = i32::azalea_read_var(ctx, buf)?;
247        if count <= 0 {
248            Ok(ItemStack::Empty)
249        } else {
250            let kind = ItemKind::azalea_read(ctx, buf)?;
251            let component_patch = DataComponentPatch::azalea_read(ctx, buf)?;
252            Ok(ItemStack::from(ItemStackData {
253                count,
254                kind,
255                component_patch,
256            }))
257        }
258    }
259    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
260        match self {
261            ItemStack::Empty => 0_i32.azalea_write_var(ctx, buf)?,
262            ItemStack::Present(i) => {
263                i.count.azalea_write_var(ctx, buf)?;
264                i.kind.azalea_write(ctx, buf)?;
265                i.component_patch.azalea_write(ctx, buf)?;
266            }
267        };
268        Ok(())
269    }
270}
271
272impl From<ItemStackData> for ItemStack {
273    fn from(item: ItemStackData) -> Self {
274        if item.is_empty() {
275            ItemStack::Empty
276        } else {
277            ItemStack::Present(item)
278        }
279    }
280}
281impl From<ItemKind> for ItemStack {
282    fn from(item: ItemKind) -> Self {
283        ItemStack::new(item, 1)
284    }
285}
286impl From<(ItemKind, i32)> for ItemStack {
287    fn from(item: (ItemKind, i32)) -> Self {
288        ItemStack::new(item.0, item.1)
289    }
290}
291impl From<ItemKind> for ItemStackData {
292    fn from(item: ItemKind) -> Self {
293        ItemStackData::new(item, 1)
294    }
295}
296impl From<(ItemKind, i32)> for ItemStackData {
297    fn from(item: (ItemKind, i32)) -> Self {
298        ItemStackData::new(item.0, item.1)
299    }
300}
301
302#[derive(Clone, Debug, PartialEq, AzBuf)]
303pub struct ItemStackTemplate {
304    pub kind: ItemKind,
305    #[var]
306    pub count: i32,
307    pub component_patch: DataComponentPatch,
308}
309impl From<ItemKind> for ItemStackTemplate {
310    fn from(kind: ItemKind) -> Self {
311        Self {
312            kind,
313            count: 1,
314            component_patch: Default::default(),
315        }
316    }
317}
318#[derive(Codec)]
319enum ItemStackTemplateCodec {
320    Item(ItemKind),
321    Map {
322        id: ItemKind,
323        #[codec(optional, default = 1)]
324        count: i32,
325        #[codec(optional)]
326        components: DataComponentPatch,
327    },
328}
329azalea_codec::impl_codec_from!(ItemStackTemplate, ItemStackTemplateCodec, struct IncompleteItemStackTemplate);
330impl From<ItemStackTemplate> for ItemStackTemplateCodec {
331    fn from(i: ItemStackTemplate) -> Self {
332        Self::Map {
333            id: i.kind,
334            count: i.count,
335            components: i.component_patch,
336        }
337    }
338}
339impl From<ItemStackTemplateCodec> for ItemStackTemplate {
340    fn from(i: ItemStackTemplateCodec) -> Self {
341        match i {
342            ItemStackTemplateCodec::Item(kind) => kind.into(),
343            ItemStackTemplateCodec::Map {
344                id,
345                count,
346                components,
347            } => Self {
348                kind: id,
349                count,
350                component_patch: components,
351            },
352        }
353    }
354}