Skip to main content

azalea_client/plugins/client_inventory/
equipment_effects.rs

1//! Support for enchantments and items with attribute modifiers.
2
3use std::collections::HashMap;
4
5use azalea_core::identifier::Identifier;
6use azalea_entity::{Attributes, inventory::Inventory};
7use azalea_registry::{
8    builtin::Attribute,
9    data_registry::DeserializableDataRegistry,
10    item::{
11        ItemStack,
12        components::{self, AttributeModifier, EquipmentSlot},
13    },
14    registry_holder::value::AttributeEffect,
15};
16use bevy_ecs::{
17    component::Component,
18    entity::Entity,
19    event::EntityEvent,
20    observer::On,
21    query::With,
22    system::{Commands, Query},
23};
24use tracing::{debug, error, warn};
25
26use crate::local_player::WorldHolder;
27
28/// A component that contains the equipment slots that we had last tick.
29///
30/// This is used by [`collect_equipment_changes`] for applying enchantments.
31#[derive(Component, Debug, Default)]
32pub struct LastEquipmentItems {
33    pub map: HashMap<EquipmentSlot, ItemStack>,
34}
35
36pub fn collect_equipment_changes(
37    mut commands: Commands,
38    mut query: Query<(Entity, &Inventory, Option<&LastEquipmentItems>), With<Attributes>>,
39) {
40    for (entity, inventory, last_equipment_items) in &mut query {
41        let last_equipment_items = if let Some(e) = last_equipment_items {
42            e
43        } else {
44            commands
45                .entity(entity)
46                .insert(LastEquipmentItems::default());
47            continue;
48        };
49
50        let mut changes = HashMap::new();
51
52        for equipment_slot in EquipmentSlot::values() {
53            let current_item = inventory
54                .get_equipment(equipment_slot)
55                .unwrap_or(&ItemStack::Empty);
56            let last_item = last_equipment_items
57                .map
58                .get(&equipment_slot)
59                .unwrap_or(&ItemStack::Empty);
60
61            if current_item == last_item {
62                // item hasn't changed, nothing to do
63                continue;
64            }
65
66            changes.insert(
67                equipment_slot,
68                EquipmentChange {
69                    old: last_item.clone(),
70                    new: current_item.clone(),
71                },
72            );
73        }
74
75        if changes.is_empty() {
76            continue;
77        }
78        commands.trigger(EquipmentChangesEvent {
79            entity,
80            map: changes,
81        });
82    }
83}
84
85#[derive(Debug, EntityEvent)]
86pub struct EquipmentChangesEvent {
87    pub entity: Entity,
88    pub map: HashMap<EquipmentSlot, EquipmentChange>,
89}
90#[derive(Debug)]
91pub struct EquipmentChange {
92    pub old: ItemStack,
93    pub new: ItemStack,
94}
95
96pub fn handle_equipment_changes(
97    equipment_changes: On<EquipmentChangesEvent>,
98    mut query: Query<(&WorldHolder, &mut LastEquipmentItems, &mut Attributes)>,
99) {
100    let Ok((world_holder, mut last_equipment_items, mut attributes)) =
101        query.get_mut(equipment_changes.entity)
102    else {
103        error!(
104            "got EquipmentChangesEvent with unknown entity {}",
105            equipment_changes.entity
106        );
107        return;
108    };
109
110    if !equipment_changes.map.is_empty() {
111        debug!("equipment changes: {:?}", equipment_changes.map);
112    }
113
114    for (&slot, change) in &equipment_changes.map {
115        if change.old.is_present() {
116            // stopLocationBasedEffects
117
118            for (attribute, modifier) in
119                collect_attribute_modifiers_from_item(slot, &change.old, world_holder)
120            {
121                if let Some(attribute) = attributes.get_mut(attribute) {
122                    attribute.remove(&modifier.id);
123                }
124            }
125
126            last_equipment_items.map.remove(&slot);
127        }
128
129        if change.new.is_present() {
130            // see ItemStack.forEachModifier in vanilla
131
132            for (attribute, modifier) in
133                collect_attribute_modifiers_from_item(slot, &change.new, world_holder)
134            {
135                if let Some(attribute) = attributes.get_mut(attribute) {
136                    attribute.remove(&modifier.id);
137                    attribute.insert(modifier);
138                }
139            }
140
141            // runLocationChangedEffects
142
143            last_equipment_items.map.insert(slot, change.new.clone());
144        }
145    }
146}
147
148fn collect_attribute_modifiers_from_item(
149    slot: EquipmentSlot,
150    item: &ItemStack,
151    world_holder: &WorldHolder,
152) -> Vec<(Attribute, AttributeModifier)> {
153    let mut modifiers = Vec::new();
154
155    // handle the attribute_modifiers component first
156    let attribute_modifiers = item
157        .get_component::<components::AttributeModifiers>()
158        .map(|a| a.modifiers.clone())
159        .unwrap_or_default();
160    for modifier in &attribute_modifiers {
161        modifiers.push((modifier.kind, modifier.modifier.clone()));
162    }
163
164    // now handle enchants
165    let enchants = item
166        .get_component::<components::Enchantments>()
167        .map(|e| e.levels.clone())
168        .unwrap_or_default();
169    if !enchants.is_empty() {
170        let registry_holder = &world_holder.shared.read().registries;
171        for (enchant, &level) in &enchants {
172            let Some(enchant_definition) = enchant.resolve(registry_holder) else {
173                warn!(
174                    "Got equipment with an enchantment that wasn't in the registry, so it couldn't be resolved to an ID"
175                );
176                continue;
177            };
178
179            let effects = enchant_definition.effects.get::<AttributeEffect>();
180            for effect in effects.unwrap_or_default() {
181                // TODO: check if the effect definition allows the slot
182
183                let modifier = AttributeModifier {
184                    id: Identifier::new(format!("{}/{slot}", effect.id)),
185                    amount: effect.amount.calculate(level) as f64,
186                    operation: effect.operation,
187                };
188
189                modifiers.push((effect.attribute, modifier));
190            }
191        }
192    }
193
194    modifiers
195}