Skip to main content

azalea_protocol/packets/game/
s_container_click.rs

1use azalea_buf::AzBuf;
2use azalea_inventory::operations::ClickType;
3use azalea_protocol_macros::ServerboundGamePacket;
4use azalea_registry::{
5    builtin::{DataComponentKind, ItemKind},
6    item::{ItemStack, checksum::Checksum},
7};
8use indexmap::IndexMap;
9
10#[derive(AzBuf, Clone, Debug, PartialEq, ServerboundGamePacket)]
11pub struct ServerboundContainerClick {
12    #[var]
13    pub container_id: i32,
14    #[var]
15    pub state_id: u32,
16    pub slot_num: i16,
17    pub button_num: u8,
18    pub click_type: ClickType,
19    pub changed_slots: IndexMap<u16, HashedStack>,
20    pub carried_item: HashedStack,
21}
22
23/// Similar to an [`ItemStack`] but only carrying a CRC32 hash of the value of
24/// added data components instead of their entire contents.
25#[derive(AzBuf, Clone, Debug, PartialEq)]
26pub struct HashedStack(pub Option<HashedActualItem>);
27
28#[derive(AzBuf, Clone, Debug, PartialEq)]
29pub struct HashedActualItem {
30    pub kind: ItemKind,
31    #[var]
32    pub count: i32,
33    pub components: HashedPatchMap,
34}
35
36#[derive(AzBuf, Clone, Debug, PartialEq)]
37pub struct HashedPatchMap {
38    #[limit(256)]
39    pub added_components: Vec<(DataComponentKind, Checksum)>,
40    #[limit(256)]
41    pub removed_components: Vec<DataComponentKind>,
42}
43
44impl HashedStack {
45    /// Convert your [`ItemStack`] into a [`HashedStack`] by hashing the data
46    /// components.
47    ///
48    /// Minecraft uses this whenever the client sends data components to the
49    /// server.
50    ///
51    /// The [`RegistryHolder`] is required as some components will hash
52    /// differently based on the server's registries.
53    pub fn from_item_stack(item: &ItemStack) -> Self {
54        let ItemStack::Present(item) = item else {
55            return HashedStack(None);
56        };
57
58        let mut added_components = Vec::new();
59        let mut removed_components = Vec::new();
60
61        for (&kind, data) in item.component_patch.iter() {
62            if let Some(data) = data {
63                let checksum = data.checksum();
64                added_components.push((kind, checksum));
65            } else {
66                removed_components.push(kind);
67            }
68        }
69
70        let components = HashedPatchMap {
71            added_components,
72            removed_components,
73        };
74        let item = HashedActualItem {
75            kind: item.kind,
76            count: item.count,
77            components,
78        };
79        Self(Some(item))
80    }
81}