summaryrefslogtreecommitdiff
path: root/ecs/src/entity.rs
blob: 3f5a3d3d9bb0753b50ed0bfe626c923c3d7eb055 (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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::any::type_name;

use linkme::distributed_slice;

use crate::component::storage::archetype::{
    Archetype,
    Entity as ArchetypeEntity,
    MatchingComponentIter as ArchetypeMatchingComponentIter,
};
use crate::component::{
    Component,
    Handle as ComponentHandle,
    HandleFromEntityComponentRef,
    HandleMut as ComponentHandleMut,
};
use crate::uid::{Kind as UidKind, Uid};
use crate::{EntityComponentRef, World};

/// A handle to a entity.
#[derive(Debug)]
pub struct Handle<'a>
{
    world: &'a World,
    archetype: &'a Archetype,
    entity: &'a ArchetypeEntity,
}

impl<'a> Handle<'a>
{
    /// Returns the [`Uid`] of this entity.
    #[inline]
    #[must_use]
    pub fn uid(&self) -> Uid
    {
        self.entity.uid()
    }

    pub fn get<ComponentT: Component>(&self) -> Option<ComponentHandle<'_, ComponentT>>
    {
        assert_eq!(ComponentT::id().kind(), UidKind::Component);

        let component = self.get_matching_components(ComponentT::id()).next()?;

        Some(
            ComponentHandle::from_entity_component_ref(Some(component), self.world)
                .unwrap_or_else(|err| {
                    panic!(
                        "Taking component {} lock failed: {err}",
                        type_name::<ComponentT>()
                    );
                }),
        )
    }

    pub fn get_mut<ComponentT: Component>(
        &self,
    ) -> Option<ComponentHandleMut<'_, ComponentT>>
    {
        assert_eq!(ComponentT::id().kind(), UidKind::Component);

        let component = self.get_matching_components(ComponentT::id()).next()?;

        Some(
            ComponentHandleMut::from_entity_component_ref(Some(component), self.world)
                .unwrap_or_else(|err| {
                    panic!(
                        "Taking component {} lock failed: {err}",
                        type_name::<ComponentT>()
                    );
                }),
        )
    }

    #[inline]
    #[must_use]
    pub fn get_matching_components(&self, component_uid: Uid)
        -> MatchingComponentIter<'a>
    {
        MatchingComponentIter {
            inner: self.archetype.get_matching_component_indices(component_uid),
            entity: self.entity,
        }
    }

    pub(crate) fn new(
        world: &'a World,
        archetype: &'a Archetype,
        entity: &'a ArchetypeEntity,
    ) -> Self
    {
        Self { world, archetype, entity }
    }
}

#[derive(Debug)]
pub struct MatchingComponentIter<'a>
{
    inner: ArchetypeMatchingComponentIter<'a>,
    entity: &'a ArchetypeEntity,
}

impl<'a> Iterator for MatchingComponentIter<'a>
{
    type Item = EntityComponentRef<'a>;

    fn next(&mut self) -> Option<Self::Item>
    {
        let (matching_component_id, index) = self.inner.next()?;

        Some(EntityComponentRef::new(
            matching_component_id,
            self.entity.components().get(index).unwrap(),
        ))
    }
}

#[allow(clippy::module_name_repetitions)]
#[macro_export]
macro_rules! static_entity {
    ($visibility: vis $ident: ident, $components: expr) => {
        $visibility static $ident: ::std::sync::LazyLock<$crate::uid::Uid> =
            ::std::sync::LazyLock::new(|| {
                $crate::uid::Uid::new_unique($crate::uid::Kind::Entity)
            });

        $crate::private::paste::paste! {
            mod [<__ecs_ $ident:lower _static_entity_priv>] {
                use super::*;

                #[$crate::private::linkme::distributed_slice(
                    $crate::entity::CREATE_STATIC_ENTITIES
                )]
                #[linkme(crate=$crate::private::linkme)]
                static CREATE_STATIC_ENTITY: fn(&$crate::World) = |world| {
                    world.create_entity_with_uid($components, *$ident);
                };
            }
        }
    }
}

#[distributed_slice]
#[doc(hidden)]
pub static CREATE_STATIC_ENTITIES: [fn(&World)];