Skip to main content

azalea_registry/registry_holder/
mod.rs

1//! The data sent to the client in the `ClientboundRegistryDataPacket`.
2//!
3//! This module contains the structures used to represent the registry
4//! sent to the client upon login. This contains a lot of information about
5//! the game, including the types of chat messages, dimensions, and
6//! biomes.
7
8pub mod block_predicate;
9pub mod block_state_provider;
10pub mod components;
11pub mod dimension_type;
12pub mod enchantment;
13pub mod entity_effect;
14pub mod float_provider;
15pub mod particle;
16pub mod value;
17
18use std::{any::Any, collections::HashMap, sync::LazyLock};
19
20use azalea_codec::Codec;
21use azalea_core::identifier::Identifier;
22use indexmap::IndexMap;
23use simdnbt::owned::{NbtCompound, NbtTag};
24use tracing::error;
25
26/// The base of the registry.
27///
28/// This is the registry that is sent to the client upon login.
29///
30/// Note that `azalea-client` stores registries per-world rather than
31/// per-client like you might expect. This is an optimization for swarms to
32/// reduce memory usage, since registries are expected to be the same for every
33/// client in a world.
34#[derive(Clone, Debug, Default)]
35pub struct RegistryHolder {
36    // if you add new fields here, don't forget to also update
37    // `RegistryHolder::append`, `protocol_id_to_identifier`, and
38    // `define_default_deserializes_to!` in `data_registry.rs`.
39    #[rustfmt::skip] // allow empty line
40
41    /// Attributes about the dimension.
42    pub dimension_type: RegistryType<dimension_type::DimensionKindElement>,
43    pub enchantment: RegistryType<enchantment::EnchantmentData>,
44    pub world_clock: RegistryType<()>,
45
46    /// Registries that we haven't implemented deserializable types for.
47    ///
48    /// You can still access these just fine, but they'll be NBT instead of
49    /// nicer structs.
50    pub extra: HashMap<Identifier, RegistryType<NbtCompound>>,
51}
52registry_holder_macro::registry_holder!(dimension_type, enchantment, world_clock);
53
54// declared like this so we can use the macro before this block :>
55mod registry_holder_macro {
56    #[macro_export]
57    macro_rules! registry_holder {
58        ($($registry:ident),* $(,)?) => {
59            impl RegistryHolder {
60                pub fn append(
61                    &mut self,
62                    id: Identifier,
63                    entries: Vec<(Identifier, Option<NbtCompound>)>,
64                ) {
65                    if id.namespace() == "minecraft" {
66                        match id.path() {
67                            $(
68                                stringify!($registry) => {
69                                    return self.$registry.append_nbt(id, entries);
70                                }
71                            )*
72                            _ => {}
73                        }
74                    }
75
76                    self.extra
77                        .entry(id.clone())
78                        .or_default()
79                        .append_nbt(id, entries);
80                }
81
82                pub fn extend(&mut self, other: RegistryHolder) {
83                    $(
84                        self.$registry = other.$registry;
85                    )*
86                    self.extra.extend(other.extra);
87                }
88
89                /// Convert a protocol ID for a registry key (like the protocol_id for
90                /// something that implements `DataRegistry`) and convert it to its string
91                /// name.
92                pub fn protocol_id_to_identifier(
93                    &self,
94                    registry: Identifier,
95                    protocol_id: u32,
96                ) -> Option<&Identifier> {
97                    let index = protocol_id as usize;
98
99                    if registry.namespace() == "minecraft" {
100                        match registry.path() {
101                            $(
102                                stringify!($registry) => {
103                                    return self.$registry.map.get_index(index).map(|(k, _)| k);
104                                }
105                            )*
106                            _ => {}
107                        }
108                    }
109
110                    self.extra
111                        .get(&registry)
112                        .and_then(|r| r.map.get_index(index))
113                        .map(|(k, _)| k)
114                }
115
116                pub fn identifier_to_protocol_id(
117                    &self,
118                    registry: &'static str,
119                    ident: Identifier,
120                ) -> Option<u32> {
121                    let registry = Identifier::from(registry);
122                    if registry.namespace() == "minecraft" {
123                        match registry.path() {
124                            $(
125                                stringify!($registry) => {
126                                    return self
127                                        .$registry
128                                        .map
129                                        .get_index_of(&ident)
130                                        .map(|i| i as u32);
131                                }
132                            )*
133                            _ => {}
134                        }
135                    }
136
137                    self.extra
138                        .get(&registry)
139                        .and_then(|r| r.map.get_index_of(&ident))
140                        .map(|i| i as u32)
141                }
142            }
143        };
144    }
145
146    pub use registry_holder;
147}
148
149impl Default for &'static RegistryHolder {
150    fn default() -> Self {
151        static DEFAULT: LazyLock<RegistryHolder> = LazyLock::new(RegistryHolder::default);
152        &DEFAULT
153    }
154}
155impl azalea_buf::ResolverTrait for RegistryHolder {}
156
157/// A collection of values for a certain type of registry data.
158#[derive(Clone, Debug, Codec)]
159pub struct RegistryType<T: Codec<NbtTag>> {
160    pub map: IndexMap<Identifier, T>,
161}
162
163impl<T: Codec<NbtTag>> Default for RegistryType<T> {
164    fn default() -> Self {
165        Self {
166            map: IndexMap::new(),
167        }
168    }
169}
170
171impl<T: Codec<NbtTag>> RegistryType<T> {
172    fn append_nbt(&mut self, id: Identifier, entries: Vec<(Identifier, Option<NbtCompound>)>) {
173        let map = &mut self.map;
174        for (key, value) in entries {
175            if let Some(value) = value {
176                let parsed = T::codec_read(&NbtTag::from(value.clone()));
177                match parsed {
178                    Ok(value) => {
179                        map.insert(key, value);
180                    }
181                    Err(err) => {
182                        error!("Error deserializing {id} entry {key}: {err:?}\n{value:?}");
183                    }
184                }
185            } else {
186                map.shift_remove(&key);
187            }
188        }
189    }
190}
191
192pub trait RegistryDeserializesTo {
193    fn get_for_registry<'a>(
194        registries: &'a RegistryHolder,
195        registry_name: &'static str,
196        protocol_id: u32,
197    ) -> Option<&'a Self>;
198}
199
200impl RegistryDeserializesTo for NbtCompound {
201    fn get_for_registry<'a>(
202        registries: &'a RegistryHolder,
203        registry_name: &'static str,
204        protocol_id: u32,
205    ) -> Option<&'a Self> {
206        registries
207            .extra
208            .get(&Identifier::new(registry_name))?
209            .map
210            .get_index(protocol_id as usize)
211            .map(|i| i.1)
212    }
213}
214impl RegistryDeserializesTo for dimension_type::DimensionKindElement {
215    fn get_for_registry<'a>(
216        registries: &'a RegistryHolder,
217        registry_name: &'static str,
218        protocol_id: u32,
219    ) -> Option<&'a Self> {
220        if registry_name != "dimension_type" {
221            error!(
222                "called RegistryDeserializesTo::get_for_registry with the wrong registry: {registry_name}"
223            );
224        }
225        registries
226            .dimension_type
227            .map
228            .get_index(protocol_id as usize)
229            .map(|i| i.1)
230    }
231}
232impl RegistryDeserializesTo for enchantment::EnchantmentData {
233    fn get_for_registry<'a>(
234        registries: &'a RegistryHolder,
235        registry_name: &'static str,
236        protocol_id: u32,
237    ) -> Option<&'a Self> {
238        if registry_name != "enchantment" {
239            error!(
240                "called RegistryDeserializesTo::get_for_registry with the wrong registry: {registry_name}"
241            );
242        }
243        registries
244            .enchantment
245            .map
246            .get_index(protocol_id as usize)
247            .map(|i| i.1)
248    }
249}
250
251impl<'a> From<azalea_buf::Ctx<'a>> for &'a RegistryHolder {
252    fn from(ctx: azalea_buf::Ctx<'a>) -> Self {
253        (ctx.resolver as &dyn Any)
254            .downcast_ref::<RegistryHolder>()
255            .expect("ctx was expected to have a RegistryHolder")
256    }
257}
258
259impl<'a> From<&'a RegistryHolder> for azalea_buf::Ctx<'a> {
260    fn from(registries: &'a RegistryHolder) -> Self {
261        azalea_buf::Ctx::new(registries)
262    }
263}