Skip to main content

azalea_registry/item/default_components/
mod.rs

1use std::{collections::BTreeMap, sync::LazyLock};
2
3use azalea_codec::Codec;
4
5use crate::{
6    builtin::ItemKind,
7    item::components::{DataComponentTrait, patch::DataComponentPatch},
8};
9
10#[derive(Codec)]
11#[codec(transparent)]
12pub struct AllDefaultComponents {
13    pub data: BTreeMap<ItemKind, DataComponentPatch>,
14}
15
16fn uncached_read_default_components() -> AllDefaultComponents {
17    // we read components at runtime to make the code simpler since we can just
18    // reuse our Codec impls
19
20    let data = include_str!("item.json");
21    let mut data = data.to_owned().into_bytes();
22    let json = simd_json::from_slice::<simd_json::OwnedValue>(&mut data).unwrap();
23    //
24    AllDefaultComponents::codec_read(&json).unwrap()
25}
26pub static ALL_DEFAULT_COMPONENTS: LazyLock<AllDefaultComponents> =
27    LazyLock::new(uncached_read_default_components);
28
29/// A trait for data components that some [`ItemKind`]s may have a default value
30/// for.
31pub trait DefaultableComponent: DataComponentTrait {
32    fn default_for_item(item: ItemKind) -> Option<&'static Self>
33    where
34        Self: Sized;
35}
36impl<T: DataComponentTrait> DefaultableComponent for T {
37    default fn default_for_item(item: ItemKind) -> Option<&'static Self> {
38        let a = ALL_DEFAULT_COMPONENTS.data.get(&item)?;
39        a.get::<Self>()
40    }
41}
42pub fn get_default_component<T: DefaultableComponent>(item: ItemKind) -> Option<&'static T> {
43    T::default_for_item(item)
44}
45
46#[cfg(test)]
47mod tests {
48    use azalea_registry_builtin::builtin::ItemKind;
49
50    use crate::{Registry, item::default_components::ALL_DEFAULT_COMPONENTS};
51
52    #[test]
53    fn default_components() {
54        let defaults = &*ALL_DEFAULT_COMPONENTS;
55
56        // and now make sure all items are represented
57        for id in 0..=ItemKind::MAX_ID {
58            let item = ItemKind::from_id(Default::default(), id).unwrap();
59            let item_defaults = defaults.data.get(&item);
60            assert!(item_defaults.is_some());
61        }
62    }
63}