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
use amethyst_assets::{PrefabData, PrefabError};
use amethyst_core::specs::prelude::{Component, Entities, Entity, Join, NullStorage, ReadStorage,
                                    WriteStorage};
use std::marker::PhantomData;

/// Tag component that can be used with a custom type to tag entities for processing
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Tag<T> {
    _m: PhantomData<T>,
}

impl<T> Default for Tag<T> {
    fn default() -> Self {
        Tag { _m: PhantomData }
    }
}

impl<T> Component for Tag<T>
where
    T: Send + Sync + 'static,
{
    type Storage = NullStorage<Self>;
}

impl<'a, T> PrefabData<'a> for Tag<T>
where
    T: Clone + Send + Sync + 'static,
{
    type SystemData = WriteStorage<'a, Tag<T>>;
    type Result = ();

    fn load_prefab(
        &self,
        entity: Entity,
        storage: &mut Self::SystemData,
        _: &[Entity],
    ) -> Result<(), PrefabError> {
        storage.insert(entity, self.clone()).map(|_| ())
    }
}

/// Utility lookup for tag components
#[derive(SystemData)]
pub struct TagFinder<'a, T>
where
    T: Send + Sync + 'static,
{
    pub entities: Entities<'a>,
    pub tags: ReadStorage<'a, Tag<T>>,
}

impl<'a, T> TagFinder<'a, T>
where
    T: Send + Sync + 'static,
{
    pub fn find(&self) -> Option<Entity> {
        (&*self.entities, &self.tags)
            .join()
            .map(|(entity, _)| entity)
            .next()
    }
}