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
|
use std::any::{type_name, Any};
use std::collections::HashSet;
use std::iter::{Flatten, Map};
use std::marker::PhantomData;
use std::slice::Iter as SliceIter;
use std::sync::{Arc, Weak};
use crate::component::storage::Archetype;
use crate::component::{
Id as ComponentId,
IsOptional as ComponentIsOptional,
Sequence as ComponentSequence,
};
use crate::lock::{Lock, ReadGuard};
use crate::system::{
NoInitParamFlag as NoInitSystemParamFlag,
Param as SystemParam,
System,
};
use crate::{ComponentStorage, EntityComponent, WorldData};
#[derive(Debug)]
pub struct Query<'world, Comps>
where
Comps: ComponentSequence,
{
component_storage: ReadGuard<'world, ComponentStorage>,
component_storage_lock: Weak<Lock<ComponentStorage>>,
comps_pd: PhantomData<Comps>,
}
impl<'world, Comps> Query<'world, Comps>
where
Comps: ComponentSequence,
{
#[must_use]
pub fn iter<'this>(&'this self) -> ComponentIter<'world, Comps>
where
'this: 'world,
{
#[cfg(feature = "debug")]
tracing::debug!("Searching for {}", type_name::<Comps>());
ComponentIter {
entities: self
.component_storage
.find_entities(&Comps::ids())
.unwrap_or_else(|| panic!("Could not find {:?}", type_name::<Comps>()))
.iter()
.map((|archetype| archetype.components.as_slice()) as ComponentIterMapFn)
.flatten(),
comps_pd: PhantomData,
}
}
/// Returns a weak reference query to the same components.
#[must_use]
pub fn to_weak_ref(&self) -> WeakRef<Comps>
{
WeakRef {
component_storage: self.component_storage_lock.clone(),
comps_pd: PhantomData,
}
}
pub(crate) fn new(component_storage: &'world Arc<Lock<ComponentStorage>>) -> Self
{
Self {
component_storage: component_storage
.read_nonblock()
.expect("Failed to acquire read-only component storage lock"),
component_storage_lock: Arc::downgrade(component_storage),
comps_pd: PhantomData,
}
}
}
impl<'world, Comps> IntoIterator for &'world Query<'world, Comps>
where
Comps: ComponentSequence,
{
type IntoIter = ComponentIter<'world, Comps>;
type Item = Comps::Refs<'world>;
fn into_iter(self) -> Self::IntoIter
{
self.iter()
}
}
unsafe impl<'world, Comps> SystemParam<'world> for Query<'world, Comps>
where
Comps: ComponentSequence,
{
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_data: &'world WorldData,
) -> Self
{
Self::new(&world_data.component_storage)
}
fn is_compatible<Other: SystemParam<'world>>() -> bool
{
let other_comparable = Other::get_comparable();
let Some(other_query_component_ids) =
other_comparable.downcast_ref::<QueryComponentIds>()
else {
return true;
};
!other_query_component_ids.contains_component_in::<Comps>()
}
fn get_comparable() -> Box<dyn Any>
{
Box::new(QueryComponentIds { component_ids: Comps::ids() })
}
fn handle_pre_run(world_data: &WorldData)
{
let mut component_storage_lock = world_data
.component_storage
.write_nonblock()
.expect("Failed to acquire read-write component storage lock");
#[cfg(feature = "debug")]
tracing::debug!(
"Adding archetypes lookup entry for components: ({})",
type_name::<Comps>()
);
component_storage_lock.add_archetype_lookup_entry(
&Comps::ids()
.into_iter()
.filter_map(|(component_id, is_optional)| {
if is_optional == ComponentIsOptional::Yes {
return None;
}
Some(component_id)
})
.collect::<Vec<_>>(),
);
}
}
/// A entity query containing a weak reference to the world.
#[derive(Debug)]
pub struct WeakRef<Comps>
where
Comps: ComponentSequence,
{
component_storage: Weak<Lock<ComponentStorage>>,
comps_pd: PhantomData<Comps>,
}
impl<Comps> WeakRef<Comps>
where
Comps: ComponentSequence,
{
/// Returns a struct which can be used to retrieve a [`Query`].
///
/// Returns [`None`] if the [`World`] has been dropped.
#[must_use]
pub fn access(&self) -> Option<Ref<'_, Comps>>
{
Some(Ref {
component_storage: self.component_storage.upgrade()?,
_pd: PhantomData,
})
}
}
impl<Comps> Clone for WeakRef<Comps>
where
Comps: ComponentSequence,
{
fn clone(&self) -> Self
{
Self {
component_storage: self.component_storage.clone(),
comps_pd: PhantomData,
}
}
}
/// Intermediate between [`Query`] and [`WeakRefQuery`]. Contains a strong reference to
/// the world which is not allowed direct access to.
#[derive(Debug, Clone)]
pub struct Ref<'weak_ref, Comps>
where
Comps: ComponentSequence,
{
component_storage: Arc<Lock<ComponentStorage>>,
_pd: PhantomData<&'weak_ref Comps>,
}
impl<'weak_ref, Comps> Ref<'weak_ref, Comps>
where
Comps: ComponentSequence,
{
#[must_use]
pub fn to_query(&self) -> Query<'_, Comps>
{
Query::new(&self.component_storage)
}
}
type ComponentIterMapFn = for<'a> fn(&'a &'a Archetype) -> &'a [Vec<EntityComponent>];
pub struct ComponentIter<'world, Comps>
{
entities: Flatten<Map<SliceIter<'world, &'world Archetype>, ComponentIterMapFn>>,
comps_pd: PhantomData<Comps>,
}
impl<'world, Comps> Iterator for ComponentIter<'world, Comps>
where
Comps: ComponentSequence + 'world,
{
type Item = Comps::Refs<'world>;
fn next(&mut self) -> Option<Self::Item>
{
Some(Comps::from_components(self.entities.next()?.iter()))
}
}
#[derive(Debug)]
struct QueryComponentIds
{
component_ids: Vec<(ComponentId, ComponentIsOptional)>,
}
impl QueryComponentIds
{
fn contains_component_in<OtherComps>(&self) -> bool
where
OtherComps: ComponentSequence,
{
let other_ids = OtherComps::ids()
.into_iter()
.map(|(id, _)| id)
.collect::<HashSet<_>>();
self.component_ids
.iter()
.all(|(id, _)| other_ids.contains(id))
}
}
|