summaryrefslogtreecommitdiff
path: root/ecs/src/query.rs
blob: f3318bd77f45317dd9d8ce52e8782ce9c448f70e (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use std::iter::{Filter, Flatten, Map};
use std::marker::PhantomData;

use crate::component::storage::{
    Archetype,
    ArchetypeEntity,
    ArchetypeRefIter,
    EntityIter,
    Storage as ComponentStorage,
};
use crate::component::{
    Component,
    Metadata as ComponentMetadata,
    Sequence as ComponentSequence,
};
use crate::lock::{ReadGuard, WriteGuard};
use crate::query::options::Options;
use crate::system::{
    NoInitParamFlag as NoInitSystemParamFlag,
    Param as SystemParam,
    System,
};
use crate::uid::Uid;
use crate::{EntityComponent, World};

pub mod options;

#[derive(Debug)]
pub struct Query<'world, Comps, OptionsT = ()>
where
    Comps: ComponentSequence,
{
    world: &'world World,
    component_storage: ReadGuard<'world, ComponentStorage>,
    _pd: PhantomData<(Comps, OptionsT)>,
}

impl<'world, Comps, OptionsT> Query<'world, Comps, OptionsT>
where
    Comps: ComponentSequence,
    OptionsT: Options,
{
    /// Iterates over the entities matching this query.
    #[must_use]
    pub fn iter_mut(
        &'world self,
    ) -> ComponentIterMut<'world, Comps, QueryEntityIter<'world>>
    {
        #[cfg(feature = "debug")]
        tracing::debug!("Searching for {}", std::any::type_name::<Comps>());

        #[allow(clippy::map_flatten)]
        ComponentIterMut {
            world: self.world,
            entities: self
                .component_storage
                .find_entities(Comps::metadata())
                .map(Archetype::entities as ComponentIterMapFn)
                .flatten()
                .filter(|entity| OptionsT::entity_filter(entity.components())),
            comps_pd: PhantomData,
        }
    }

    /// Iterates over the entities matching this query.
    #[must_use]
    pub fn iter(&'world self) -> ComponentIter<'world, Comps, QueryEntityIter<'world>>
    {
        #[cfg(feature = "debug")]
        tracing::debug!("Searching for {}", std::any::type_name::<Comps>());

        #[allow(clippy::map_flatten)]
        ComponentIter {
            world: self.world,
            entities: self
                .component_storage
                .find_entities(Comps::metadata())
                .map(Archetype::entities as ComponentIterMapFn)
                .flatten()
                .filter(|entity| OptionsT::entity_filter(entity.components())),
            comps_pd: PhantomData,
        }
    }

    /// Iterates over the entities matching this query and has the provided extra
    /// component.
    #[must_use]
    pub fn iter_with_extra_comps(
        &'world self,
        extra_components: impl IntoIterator<Item = ComponentMetadata>,
    ) -> ComponentIter<'world, Comps, QueryEntityIter<'world>>
    {
        #[cfg(feature = "debug")]
        tracing::debug!(
            "Searching for {} + extra components",
            std::any::type_name::<Comps>()
        );

        #[allow(clippy::map_flatten)]
        ComponentIter {
            world: self.world,
            entities: self
                .component_storage
                .find_entities(
                    Comps::metadata()
                        .into_iter()
                        .chain(extra_components)
                        .collect::<Vec<_>>(),
                )
                .map(Archetype::entities as ComponentIterMapFn)
                .flatten()
                .filter(|entity| OptionsT::entity_filter(entity.components())),
            comps_pd: PhantomData,
        }
    }

    /// Returns the UID of the entity at the given query iteration index.
    #[must_use]
    pub fn get_entity_uid(&self, entity_index: usize) -> Option<Uid>
    {
        Some(
            self.component_storage
                .find_entities(Comps::metadata())
                .flat_map(|archetype| archetype.entities())
                .filter(|entity| OptionsT::entity_filter(entity.components()))
                .nth(entity_index)?
                .uid(),
        )
    }

    pub(crate) fn new(world: &'world World) -> Self
    {
        Self {
            world,
            component_storage: world
                .data
                .component_storage
                .read_nonblock()
                .expect("Failed to acquire read-only component storage lock"),
            _pd: PhantomData,
        }
    }
}

impl<'world, Comps, OptionsT> IntoIterator for &'world Query<'world, Comps, OptionsT>
where
    Comps: ComponentSequence,
    OptionsT: Options,
{
    type IntoIter = ComponentIterMut<'world, Comps, QueryEntityIter<'world>>;
    type Item = Comps::MutRefs<'world>;

    fn into_iter(self) -> Self::IntoIter
    {
        self.iter_mut()
    }
}

unsafe impl<'world, Comps, OptionsT> SystemParam<'world>
    for Query<'world, Comps, OptionsT>
where
    Comps: ComponentSequence,
    OptionsT: Options,
{
    type Flags = NoInitSystemParamFlag;
    type Input = ();

    fn initialize<SystemImpl>(
        _system: &mut impl System<'world, SystemImpl>,
        _input: Self::Input,
    )
    {
    }

    fn new<SystemImpl>(
        _system: &'world impl System<'world, SystemImpl>,
        world: &'world World,
    ) -> Self
    {
        Self::new(world)
    }
}

type ComponentIterMapFn = for<'a> fn(&'a Archetype) -> EntityIter<'a>;

type ComponentIterFilterFn = for<'a, 'b> fn(&'a &'b ArchetypeEntity) -> bool;

type QueryEntityIter<'world> = Filter<
    Flatten<Map<ArchetypeRefIter<'world>, ComponentIterMapFn>>,
    ComponentIterFilterFn,
>;

pub struct ComponentIterMut<'world, Comps, EntityIter>
where
    EntityIter: Iterator<Item = &'world ArchetypeEntity>,
{
    world: &'world World,
    entities: EntityIter,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps, EntityIter> Iterator for ComponentIterMut<'world, Comps, EntityIter>
where
    Comps: ComponentSequence + 'world,
    EntityIter: Iterator<Item = &'world ArchetypeEntity>,
{
    type Item = Comps::MutRefs<'world>;

    fn next(&mut self) -> Option<Self::Item>
    {
        Some(Comps::from_components_mut(
            self.entities.next()?.components().iter(),
            self.world,
            lock_component_rw,
        ))
    }
}

fn lock_component_rw(
    entity_component: &EntityComponent,
) -> WriteGuard<'_, Box<dyn Component>>
{
    entity_component
        .component
        .write_nonblock()
        .unwrap_or_else(|_| {
            panic!(
                "Failed to acquire read-write lock to component {}",
                entity_component.name
            );
        })
}

pub struct ComponentIter<'world, Comps, EntityIter>
where
    EntityIter: Iterator<Item = &'world ArchetypeEntity>,
{
    world: &'world World,
    entities: EntityIter,
    comps_pd: PhantomData<Comps>,
}

impl<'world, Comps, EntityIter> Iterator for ComponentIter<'world, Comps, EntityIter>
where
    Comps: ComponentSequence + 'world,
    EntityIter: Iterator<Item = &'world ArchetypeEntity>,
{
    type Item = Comps::Refs<'world>;

    fn next(&mut self) -> Option<Self::Item>
    {
        Some(Comps::from_components(
            self.entities.next()?.components().iter(),
            self.world,
            lock_component_ro,
        ))
    }
}

fn lock_component_ro(
    entity_component: &EntityComponent,
) -> ReadGuard<'_, Box<dyn Component>>
{
    entity_component
        .component
        .read_nonblock()
        .unwrap_or_else(|_| {
            panic!(
                "Failed to acquire read-write lock to component {}",
                entity_component.name
            );
        })
}