summaryrefslogtreecommitdiff
path: root/ecs/src/event/component.rs
blob: ed6b7cfe5826627723651086a338546f5df54fe3 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
//! Component events.

use std::convert::Infallible;

use crate::component::{Handle as ComponentHandle, HandleMut as ComponentHandleMut};
use crate::entity::Handle as EntityHandle;
use crate::pair::Pair;
use crate::system::observer::EventMatch;
use crate::util::impl_multiple;
use crate::Component;

/// Pair relation for events emitted when:
/// a) A entity with the target component is spawned.
/// b) The target component is added to a entity.
#[derive(Debug, Component)]
pub struct Added(Infallible);

/// Pair relation for events emitted **before**:
/// a) The target component is removed from a entity.
/// b) A entity with the target component is despawned.
#[derive(Debug, Component)]
pub struct Removed(Infallible);

#[derive(Debug, Component)]
pub struct Changed(Infallible);

impl_multiple!(
    EventMatch,
    (
        impl<Target: Component> _<'_><Pair<Removed, Target>> (removed),
        impl<Target: Component> _<'_><Pair<Added, Target>> (added),
        impl<Target: Component> _<'_><Pair<Changed, Target>> (changed)
    )
    cb=(type_params=(observable_type), event_name) => {
        paste::paste! {
            #[must_use]
            pub fn [<get_ $event_name _comp>](&self) -> ComponentHandle<'_, Target>
            {
                let ent = self.get_ent_infallible();

                let Some(comp) = ent.get::<Target>() else {
                    unreachable!();
                };

                comp
            }

            #[must_use]
            pub fn [<get_ $event_name _comp_mut>](&self) -> ComponentHandleMut<'_, Target>
            {
                let ent = self.get_ent_infallible();

                let Some(comp) = ent.get_mut::<Target>() else {
                    unreachable!();
                };

                comp
            }
        }

        #[must_use]
        pub fn get_ent_infallible(&self) -> EntityHandle<'_>
        {
            let Some(ent) = self.get_entity() else {
                unreachable!();
            };

            ent
        }
    }
);