Skip to main content

azalea_registry/registry_holder/
components.rs

1use std::{any::Any, fmt::Debug};
2
3use azalea_codec::Codec;
4use azalea_registry_builtin::builtin::LootConditionKind;
5
6use crate::{
7    HolderSet,
8    builtin::{EnchantmentEffectComponentKind, SoundEvent},
9    registry_holder::{
10        entity_effect::EntityEffect,
11        value::{AttributeEffect, ValueEffect},
12    },
13};
14
15#[macro_export]
16macro_rules! define_effect_components {
17    ( $( $x:ident: $t:ty ),* $(,)? ) => {
18        #[derive(Clone, Debug, PartialEq)]
19        pub enum EffectComponents {
20            $( $x(Vec<$t>), )*
21        }
22
23        impl EffectComponents {
24            pub fn codec_read_as<O: azalea_codec::Ops>(
25                kind: EnchantmentEffectComponentKind,
26                ops: &O,
27            ) -> azalea_codec::error::ReadResult<Self> {
28                Ok(match kind {
29                    $( EnchantmentEffectComponentKind::$x => {
30                        azalea_codec::types::CompactListCodec::<Vec<$t>>::codec_read(ops)
31                            .map(|i| Self::$x(i.0))?
32                    }, )*
33                })
34            }
35            pub fn codec_write_values<O: azalea_codec::Ops>(
36                &self,
37            ) -> azalea_codec::error::WriteResult<O> {
38                // we do this instead of implementing Codec since the codec_read
39                // implementation on this type wouldn't make much sense. maybe
40                // in the future we could implement MapCodec without Codec or
41                // something, so it only works when flattened? idk
42                Ok(match self {
43                    $(
44                        Self::$x(v) => {
45                          azalea_codec::types::CompactListCodec(v.clone()).codec_write()?
46                        },
47                    )*
48                })
49            }
50            pub fn kind(&self) -> EnchantmentEffectComponentKind {
51                match self {
52                    $( Self::$x(_) => EnchantmentEffectComponentKind::$x, )*
53                }
54            }
55            pub fn as_kind<T: EffectComponentTrait>(&self) -> Option<&[T]>
56            where
57                for<'a> &'a [T]: TryFrom<&'a EffectComponents>,
58            {
59                <&[T]>::try_from(self).ok()
60            }
61        }
62
63        $(
64            impl EffectComponentTrait for $t {
65                const KIND: EnchantmentEffectComponentKind = EnchantmentEffectComponentKind::$x;
66            }
67            impl<'a> TryFrom<&'a EffectComponents> for &'a [$t] {
68                type Error = ();
69                fn try_from(v: &'a EffectComponents) -> Result<Self, Self::Error> {
70                    if let EffectComponents::$x(v) = v {
71                        return Ok(v);
72                    }
73                    Err(())
74                }
75            }
76        )*
77    };
78}
79
80define_effect_components!(
81    DamageProtection: DamageProtection,
82    DamageImmunity: ConditionalEffect<DamageImmunity>,
83    Damage: Damage,
84    SmashDamagePerFallenBlock: SmashDamagePerFallenBlock,
85    Knockback: Knockback,
86    ArmorEffectiveness: ArmorEffectiveness,
87    PostAttack: PostAttack,
88    PostPiercingAttack: PostPiercingAttack,
89    HitBlock: ConditionalEntityEffect,
90    ItemDamage: ConditionalValueEffect,
91    Attributes: AttributeEffect,
92    EquipmentDrops: EquipmentDrops,
93    LocationChanged: ConditionalEffect<LocationBasedEffect>,
94    Tick: Tick,
95    AmmoUse: AmmoUse,
96    ProjectilePiercing: ProjectilePiercing,
97    ProjectileSpawned: ProjectileSpawned,
98    ProjectileSpread: ProjectileSpread,
99    ProjectileCount: ProjectileCount,
100    TridentReturnAcceleration: TridentReturnAcceleration,
101    FishingTimeReduction: FishingTimeReduction,
102    FishingLuckBonus: FishingLuckBonus,
103    BlockExperience: BlockExperience,
104    MobExperience: MobExperience,
105    RepairWithXp: RepairWithXp,
106    CrossbowChargeTime: CrossbowChargeTime,
107    CrossbowChargingSounds: CrossbowChargingSounds,
108    TridentSound: TridentSound,
109    PreventEquipmentDrop: PreventEquipmentDrop,
110    PreventArmorChange: PreventArmorChange,
111    TridentSpinAttackStrength: TridentSpinAttackStrength,
112);
113
114/// A trait that's implemented on all effect components so we can access them
115/// from [`Effects::get`](super::enchantment::Effects::get).
116pub trait EffectComponentTrait: Any + Sized
117where
118    for<'a> &'a [Self]: TryFrom<&'a EffectComponents>,
119{
120    const KIND: EnchantmentEffectComponentKind;
121}
122
123#[derive(Clone, Debug, PartialEq, Codec)]
124pub struct ConditionalEffect<T: Debug + Clone + PartialEq> {
125    pub effect: T,
126    #[codec(optional)]
127    pub requirements: Option<LootItemCondition>,
128}
129#[derive(Clone, Debug, PartialEq, Codec)]
130pub struct TargetedConditionalEffect<T: Debug + Clone + PartialEq> {
131    pub enchanted: EnchantmentTarget,
132    pub affected: EnchantmentTarget,
133    pub effect: T,
134    #[codec(optional)]
135    pub requirements: Option<LootItemCondition>,
136}
137#[derive(Clone, Debug, PartialEq, Codec)]
138pub struct EquipmentDropsEffect<T: Debug + Clone + PartialEq> {
139    pub enchanted: NonDamageEnchantmentTarget,
140    pub effect: T,
141    #[codec(optional)]
142    pub requirements: Option<LootItemCondition>,
143}
144
145#[derive(Clone, Debug, PartialEq, Codec)]
146#[codec(default_snake_case_key)]
147pub enum EnchantmentTarget {
148    Attacker,
149    DamagingEntity,
150    Victim,
151}
152#[derive(Clone, Debug, PartialEq, Codec)]
153#[codec(default_snake_case_key)]
154pub enum NonDamageEnchantmentTarget {
155    Attacker,
156    Victim,
157}
158
159#[derive(Clone, Debug, PartialEq, Codec)]
160#[codec(tag = "type", tag_as = LootConditionKind)]
161#[codec(default_snake_case_key)]
162pub enum LootItemCondition {
163    Inverted {
164        term: Box<LootItemCondition>,
165    },
166    AnyOf {
167        terms: HolderSet<LootItemCondition>,
168    },
169    AllOf {
170        terms: HolderSet<LootItemCondition>,
171    },
172    // TODO: implement the rest
173    #[codec(allow_unknown_keys)]
174    RandomChance,
175    #[codec(allow_unknown_keys)]
176    RandomChanceWithEnchantedBonus,
177    #[codec(allow_unknown_keys)]
178    EntityProperties,
179    #[codec(allow_unknown_keys)]
180    KilledByPlayer,
181    #[codec(allow_unknown_keys)]
182    EntityScores,
183    #[codec(allow_unknown_keys)]
184    MatchBlock,
185    #[codec(allow_unknown_keys)]
186    MatchTool,
187    #[codec(allow_unknown_keys)]
188    TableBonus,
189    #[codec(allow_unknown_keys)]
190    SurvivesExplosion,
191    #[codec(allow_unknown_keys)]
192    DamageSourceProperties,
193    #[codec(allow_unknown_keys)]
194    LocationCheck,
195    #[codec(allow_unknown_keys)]
196    WeatherCheck,
197    #[codec(allow_unknown_keys)]
198    TimeCheck,
199    #[codec(allow_unknown_keys)]
200    IntValueCheck,
201    #[codec(allow_unknown_keys)]
202    FloatValueCheck,
203    #[codec(allow_unknown_keys)]
204    EnchantmentActiveCheck,
205    #[codec(allow_unknown_keys)]
206    EnvironmentAttributeCheck,
207}
208// azalea_codec::impl_defaultable!(LootItemCondition);
209
210// makes for cleaner-looking types
211type ConditionalValueEffect = ConditionalEffect<ValueEffect>;
212type ConditionalEntityEffect = ConditionalEffect<EntityEffect>;
213
214macro_rules! declare_newtype_components {
215    ( $( $struct_name:ident: $inner_type:ty ),* $(,)? ) => {
216        $(
217            #[derive(Clone, Debug, PartialEq, Codec)]
218            pub struct $struct_name(pub $inner_type);
219        )*
220    };
221}
222
223declare_newtype_components! {
224    DamageProtection: ConditionalValueEffect,
225    Damage: ConditionalValueEffect,
226    SmashDamagePerFallenBlock: ConditionalValueEffect,
227    Knockback: ConditionalValueEffect,
228    ArmorEffectiveness: ConditionalValueEffect,
229    PostAttack: TargetedConditionalEffect<EntityEffect>,
230    PostPiercingAttack: ConditionalEffect<EntityEffect>,
231    HitBlock: ConditionalEntityEffect,
232    ItemDamage: ConditionalValueEffect,
233    EquipmentDrops: EquipmentDropsEffect<ValueEffect>,
234    Tick: ConditionalEntityEffect,
235    AmmoUse: ConditionalValueEffect,
236    ProjectilePiercing: ConditionalValueEffect,
237    ProjectileSpawned: ConditionalEntityEffect,
238    ProjectileSpread: ConditionalValueEffect,
239    ProjectileCount: ConditionalValueEffect,
240    TridentReturnAcceleration: ConditionalValueEffect,
241    FishingTimeReduction: ConditionalValueEffect,
242    FishingLuckBonus: ConditionalValueEffect,
243    BlockExperience: ConditionalValueEffect,
244    MobExperience: ConditionalValueEffect,
245    RepairWithXp: ConditionalValueEffect,
246    CrossbowChargeTime: ValueEffect,
247    TridentSpinAttackStrength: ValueEffect,
248
249}
250
251#[derive(Clone, Debug, PartialEq, Codec)]
252pub struct DamageImmunity {}
253
254#[derive(Clone, Debug, PartialEq, Codec)]
255pub struct CrossbowChargingSounds(pub Vec<CrossbowChargingSound>);
256
257#[derive(Clone, Debug, PartialEq, Codec)]
258pub struct CrossbowChargingSound {
259    #[codec(optional)]
260    pub start: Option<SoundEvent>,
261    #[codec(optional)]
262    pub mid: Option<SoundEvent>,
263    #[codec(optional)]
264    pub end: Option<SoundEvent>,
265}
266
267#[derive(Clone, Debug, PartialEq, Codec)]
268pub struct TridentSound(pub Vec<SoundEvent>);
269
270#[derive(Clone, Debug, PartialEq, Codec)]
271#[codec(allow_unknown_keys)]
272pub struct LocationBasedEffect {
273    // TODO
274}
275
276#[derive(Clone, Debug, PartialEq, Codec)]
277#[codec(allow_unknown_keys)]
278pub struct PreventEquipmentDrop {}
279
280#[derive(Clone, Debug, PartialEq, Codec)]
281#[codec(allow_unknown_keys)]
282pub struct PreventArmorChange {}