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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
//! Component events.
use std::convert::Infallible;
use crate::Component;
use crate::component::{Handle as ComponentHandle, HandleMut as ComponentHandleMut};
use crate::entity::Handle as EntityHandle;
use crate::pair::Pair;
use crate::system::observer::{EventMatch, Observed};
/// Implemented by the relations of component event pairs
pub trait EventRelation: 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);
impl EventRelation for Added {}
/// 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);
impl EventRelation for Removed {}
#[derive(Debug, Component)]
pub struct Changed(Infallible);
impl EventRelation for Changed {}
/// [`EventMatch`] extension trait for component event matches.
pub trait EventMatchExt<Target>: sealed::Sealed
{
#[must_use]
fn get_entity(&self) -> EntityHandle<'_>;
#[must_use]
fn get_ent_target_comp(&self) -> ComponentHandle<'_, Target>
where
Target: Component;
#[must_use]
fn get_ent_target_comp_mut(&self) -> ComponentHandleMut<'_, Target>
where
Target: Component;
}
impl<ComponentEventRelation: EventRelation, Target> EventMatchExt<Target>
for EventMatch<'_, Pair<ComponentEventRelation, Target>>
where
Pair<ComponentEventRelation, Target>: Observed,
{
fn get_entity(&self) -> EntityHandle<'_>
{
let Some(ent) = self.try_get_entity() else {
unreachable!();
};
ent
}
fn get_ent_target_comp(&self) -> ComponentHandle<'_, Target>
where
Target: Component,
{
let ent = self.get_entity();
let Some(comp) = ent.get::<Target>() else {
unreachable!();
};
comp
}
fn get_ent_target_comp_mut(&self) -> ComponentHandleMut<'_, Target>
where
Target: Component,
{
let ent = self.get_entity();
let Some(comp) = ent.get_mut::<Target>() else {
unreachable!();
};
comp
}
}
impl<ComponentEventRelation: EventRelation, Target> sealed::Sealed
for EventMatch<'_, Pair<ComponentEventRelation, Target>>
where
Pair<ComponentEventRelation, Target>: Observed,
{
}
mod sealed
{
pub trait Sealed {}
}
|