summaryrefslogtreecommitdiff
path: root/ecs/src/entity.rs
blob: 34fd19f476190aed62b525dbb5de570d77244035 (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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::any::type_name;
use std::ops::Deref;
use std::sync::LazyLock;

use crate::component::storage::archetype::{
    Archetype,
    Entity as ArchetypeEntity,
    MatchingComponentIter as ArchetypeMatchingComponentIter,
};
use crate::component::{
    Component,
    Handle as ComponentHandle,
    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>
{
    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()
    }

    /// Returns a reference to the specified component in this entity. `None` is
    /// returned if the component isn't found in the entity.
    ///
    /// # Panics
    /// Will panic if:
    /// - The component's ID is not a component ID
    /// - The component is mutably borrowed elsewhere
    #[must_use]
    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(&component).unwrap_or_else(
                |err| {
                    panic!(
                        "Creating handle to component {} failed: {err}",
                        type_name::<ComponentT>()
                    );
                },
            ),
        )
    }

    /// Returns a mutable reference to the specified component in this entity. `None` is
    /// returned if the component isn't found in the entity.
    ///
    /// # Panics
    /// Will panic if:
    /// - The component's ID is not a component ID
    /// - The component is borrowed elsewhere
    #[must_use]
    pub fn get_mut<ComponentT: Component>(
        &self,
    ) -> Option<ComponentHandleMut<'a, ComponentT>>
    {
        assert_eq!(ComponentT::id().kind(), UidKind::Component);

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

        Some(
            ComponentHandleMut::from_entity_component_ref(&component).unwrap_or_else(
                |err| {
                    panic!(
                        "Creating handle to component {} failed: {err}",
                        type_name::<ComponentT>()
                    );
                },
            ),
        )
    }

    /// Returns a mutable reference to the component with the ID `id` in this entity.
    /// `None` is returned if the component isn't found.
    ///
    /// # Panics
    /// Will panic if:
    /// - The ID is not a component/pair ID
    /// - The component is borrowed elsewhere
    /// - The component type is incorrect
    #[must_use]
    pub fn get_with_id_mut<ComponentData: 'static>(
        &self,
        id: Uid,
    ) -> Option<ComponentHandleMut<'a, ComponentData>>
    {
        assert!(
            matches!(id.kind(), UidKind::Component | UidKind::Pair),
            "ID {id:?} is not a component/pair ID"
        );

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

        Some(
            ComponentHandleMut::from_entity_component_ref(&component).unwrap_or_else(
                |err| {
                    panic!(
                        "Creating handle to component {} failed: {err}",
                        type_name::<ComponentData>()
                    );
                },
            ),
        )
    }

    #[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(archetype: &'a Archetype, entity: &'a ArchetypeEntity) -> Self
    {
        Self { 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(),
        ))
    }
}

/// The data type of a declaration of a entity.
#[derive(Debug)]
pub struct Declaration
{
    uid: LazyLock<Uid>,
    create_func: fn(&mut World),
}

impl Declaration
{
    pub(crate) fn create(&self, world: &mut World)
    {
        (self.create_func)(world);
    }

    #[doc(hidden)]
    pub const fn new(create_func: fn(&mut World)) -> Self
    {
        Self {
            uid: LazyLock::new(|| Uid::new_unique(UidKind::Entity)),
            create_func,
        }
    }
}

impl Deref for Declaration
{
    type Target = Uid;

    fn deref(&self) -> &Self::Target
    {
        &self.uid
    }
}

#[allow(clippy::module_name_repetitions)]
#[macro_export]
macro_rules! declare_entity {
    ($visibility: vis $ident: ident, $components: expr) => {
        $visibility static $ident: $crate::entity::Declaration =
            $crate::entity::Declaration::new(|world| {
                world.create_entity_with_uid(*$ident, $components);
            });
    }
}