aboutsummaryrefslogtreecommitdiff
path: root/azalea-entity/src/plugin/effect_events.rs
blob: 2d37c4632bea36622262594911cf66d4418d3b02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use azalea_registry::builtin::MobEffect;
use bevy_ecs::{entity::Entity, event::EntityEvent, observer::On, system::Query};
use tracing::warn;

use crate::{ActiveEffects, Attributes, MobEffectData, effects::attribute_modifier_for_effect};

#[derive(EntityEvent)]
pub struct AddEffectEvent {
    pub entity: Entity,
    pub id: MobEffect,
    pub data: MobEffectData,
}
pub fn handle_add_effect(
    add_effect: On<AddEffectEvent>,
    mut query: Query<(&mut ActiveEffects, &mut Attributes)>,
) {
    let Ok((mut active_effects, mut attributes)) = query.get_mut(add_effect.entity) else {
        warn!("got handle_add_effect for an entity without the required components");
        return;
    };

    active_effects.insert(add_effect.id, add_effect.data.clone());

    if let Some((attribute, modifier)) = attribute_modifier_for_effect(add_effect.id) {
        let modifier = modifier.create(add_effect.data.amplifier);
        if let Some(attribute) = attributes.get_mut(attribute) {
            attribute.insert(modifier);
        }
    }
}

#[derive(EntityEvent)]
pub struct RemoveEffectsEvent {
    pub entity: Entity,
    pub effects: Vec<MobEffect>,
}
pub fn handle_remove_effects(
    remove_effects: On<RemoveEffectsEvent>,
    mut query: Query<(&mut ActiveEffects, &mut Attributes)>,
) {
    let Ok((mut active_effects, mut attributes)) = query.get_mut(remove_effects.entity) else {
        warn!("got handle_remove_effects for an entity without the required components");
        return;
    };

    for &effect in &remove_effects.effects {
        active_effects.remove(effect);

        if let Some((attribute, modifier)) = attribute_modifier_for_effect(effect) {
            // we're just trying to get the id of the modifier, so the amplifier passed here
            // doesn't matter
            let modifier = modifier.create(0);
            if let Some(attribute) = attributes.get_mut(attribute) {
                attribute.remove(&modifier.id);
            }
        }
    }
}