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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use super::{Archetype, ChainedIterator, GetIter, World};
use std::any::TypeId;
use std::ops::{Deref, DerefMut};
use std::sync::{RwLockReadGuard, RwLockWriteGuard};

#[doc(hidden)]

/// Get data from the world
pub trait Fetch<'a> {
    type Item;
    fn get(world: &'a World, archetypes: usize) -> Result<Self::Item, ComponentAlreadyBorrowed>;
}

#[derive(Debug)]
pub struct ComponentAlreadyBorrowed(&'static str);

impl ComponentAlreadyBorrowed {
    pub fn new<T>() -> Self {
        Self(std::any::type_name::<T>())
    }
}

impl std::fmt::Display for ComponentAlreadyBorrowed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] is already borrowed from the archetype", self.0)
    }
}

impl std::error::Error for ComponentAlreadyBorrowed {}

/// A dummy struct that is never constructed.
/// It is used to specify a Fetch trait.
#[doc(hidden)]
pub struct FetchRead<T> {
    phantom: std::marker::PhantomData<T>,
}

// Borrow a single component channel from an archetype.
impl<'world_borrow, T: 'static> Fetch<'world_borrow> for FetchRead<T> {
    type Item = RwLockReadGuard<'world_borrow, Vec<T>>;
    fn get(
        world: &'world_borrow World,
        archetype: usize,
    ) -> Result<Self::Item, ComponentAlreadyBorrowed> {
        let archetype = &world.archetypes[archetype];
        let type_id = TypeId::of::<T>();

        let index = archetype
            .components
            .iter()
            .position(|c| c.type_id == type_id)
            .unwrap();
        if let Ok(read_guard) = archetype.get(index).try_read() {
            Ok(read_guard)
        } else {
            Err(ComponentAlreadyBorrowed::new::<T>())
        }
    }
}

/// A dummy struct is never constructed.
/// It is used to specify a Fetch trait.
#[doc(hidden)]
pub struct FetchWrite<T> {
    phantom: std::marker::PhantomData<T>,
}

// Immutably borrow a single component channel from an archetype.
impl<'world_borrow, T: 'static> Fetch<'world_borrow> for FetchWrite<T> {
    type Item = RwLockWriteGuard<'world_borrow, Vec<T>>;
    fn get(
        world: &'world_borrow World,
        archetype: usize,
    ) -> Result<Self::Item, ComponentAlreadyBorrowed> {
        let archetype = &world.archetypes[archetype];
        let type_id = TypeId::of::<T>();

        let index = archetype
            .components
            .iter()
            .position(|c| c.type_id == type_id)
            .unwrap();
        if let Ok(write_guard) = archetype.get(index).try_write() {
            Ok(write_guard)
        } else {
            Err(ComponentAlreadyBorrowed::new::<T>())
        }
    }
}

/// The parameters passed into a query. Like: `(&bool, &String)`
pub trait QueryParams {
    type Fetch: for<'a> Fetch<'a>;
}

/// An empty trait used to indicate which queries can be constructed at the top level of a query.
pub trait TopLevelQuery: for<'a> Fetch<'a> {}
impl<'world_borrow, T: QueryParams> TopLevelQuery for Query<'world_borrow, T> {}
impl<'world_borrow, T: 'static> TopLevelQuery for Single<'world_borrow, T> {}
impl<'world_borrow, T: 'static> TopLevelQuery for SingleMut<'world_borrow, T> {}

impl<'a, T: QueryParams> Fetch<'a> for Query<'_, T> {
    type Item = Query<'a, T>;
    fn get(world: &'a World, archetype: usize) -> Result<Self::Item, ComponentAlreadyBorrowed> {
        Ok(Query {
            borrow: <<T as QueryParams>::Fetch as Fetch<'a>>::get(&world, archetype)?,
            phantom: std::marker::PhantomData,
        })
    }
}

/// Used to get a single *immutable* instance of a component from the world.
/// If there are multiple of the component in the world an arbitrary
/// instance is returned.
pub struct Single<'world_borrow, T> {
    pub borrow: RwLockReadGuard<'world_borrow, Vec<T>>,
}

impl<'world_borrow, 'a, T> Single<'world_borrow, T> {
    pub fn get(&'a self) -> Option<&T> {
        self.borrow.get(0)
    }

    pub fn unwrap(&'a self) -> &'a T {
        self.borrow.get(0).unwrap()
    }
}

impl<'world_borrow, T> Deref for Single<'world_borrow, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // This unwrap may be bad. If a Single fails to get its query then this unwrap
        // will panic when attempting to access a member
        self.unwrap()
    }
}

/// Used to get a single *mutable* instance of a component from the world.
/// If there are multiple of the component in the world an arbitrary
/// instance is returned.
pub struct SingleMut<'world_borrow, T> {
    pub borrow: RwLockWriteGuard<'world_borrow, Vec<T>>,
}

impl<'world_borrow, 'a, T> SingleMut<'world_borrow, T> {
    pub fn get(&'a mut self) -> Option<&mut T> {
        self.borrow.get_mut(0)
    }

    pub fn unwrap(&'a mut self) -> &mut T {
        self.borrow.get_mut(0).unwrap()
    }
}

impl<'world_borrow, T> Deref for SingleMut<'world_borrow, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.borrow.get(0).unwrap()
    }
}

impl<'world_borrow, T> DerefMut for SingleMut<'world_borrow, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.unwrap()
    }
}

impl<'a, T: 'static> Fetch<'a> for Single<'_, T> {
    type Item = Single<'a, T>;
    fn get(world: &'a World, _archetypes: usize) -> Result<Self::Item, ComponentAlreadyBorrowed> {
        // The archetypes must be found here.
        let mut archetype_index = None;
        let type_id = TypeId::of::<T>();
        for (i, archetype) in world.archetypes.iter().enumerate() {
            if archetype.components.iter().any(|c| c.type_id == type_id) {
                archetype_index = Some(i);
            }
        }

        if let Some(archetype_index) = archetype_index {
            Ok(Single {
                borrow: FetchRead::<T>::get(&world, archetype_index)?,
            })
        } else {
            Err(ComponentAlreadyBorrowed::new::<T>())
        }
    }
}

impl<'a, T: 'static> Fetch<'a> for SingleMut<'_, T> {
    type Item = SingleMut<'a, T>;
    fn get(world: &'a World, _archetypes: usize) -> Result<Self::Item, ComponentAlreadyBorrowed> {
        // The archetypes must be found here.
        let mut archetype_index = None;
        let type_id = TypeId::of::<T>();
        for (i, archetype) in world.archetypes.iter().enumerate() {
            if archetype.components.iter().any(|c| c.type_id == type_id) {
                archetype_index = Some(i);
            }
        }

        if let Some(archetype_index) = archetype_index {
            Ok(SingleMut {
                borrow: FetchWrite::<T>::get(&world, archetype_index)?,
            })
        } else {
            Err(ComponentAlreadyBorrowed::new::<T>())
        }
    }
}

/// Query for entities with specific components.
pub struct Query<'world_borrow, T: QueryParams> {
    // The archetype borrow will be based on the QueryParams borrow type.
    pub borrow: <<T as QueryParams>::Fetch as Fetch<'world_borrow>>::Item,
    pub(crate) phantom: std::marker::PhantomData<&'world_borrow ()>,
}

impl<'world_borrow, 'iter, D: QueryParams> Query<'world_borrow, D>
where
    <<D as QueryParams>::Fetch as Fetch<'world_borrow>>::Item: GetIter<'iter>,
{
    /// Gets an iterator over the components in this `Query`.
    pub fn iter(
        &'iter mut self,
    ) -> <<<D as QueryParams>::Fetch as Fetch<'world_borrow>>::Item as GetIter<'iter>>::Iter {
        self.borrow.get_iter()
    }
}

impl<'iter, T: GetIter<'iter>> GetIter<'iter> for Vec<T> {
    type Iter = ChainedIterator<<T as GetIter<'iter>>::Iter>;
    fn get_iter(&'iter mut self) -> Self::Iter {
        ChainedIterator::new(self.iter_mut().map(|t| t.get_iter()).collect())
    }
}

impl<'iter, 'world_borrow, T: 'static> GetIter<'iter> for RwLockReadGuard<'world_borrow, Vec<T>> {
    type Iter = std::slice::Iter<'iter, T>;
    fn get_iter(&'iter mut self) -> Self::Iter {
        <[T]>::iter(self)
    }
}

impl<'iter, 'world_borrow, T: 'static> GetIter<'iter> for RwLockWriteGuard<'world_borrow, Vec<T>> {
    type Iter = std::slice::IterMut<'iter, T>;
    fn get_iter(&'iter mut self) -> Self::Iter {
        <[T]>::iter_mut(self)
    }
}

/// A member of a `Query`, like `&A` or `&mut A`
pub trait QueryParam {
    type Fetch: for<'a> Fetch<'a>;

    #[doc(hidden)]
    fn add_types(types: &mut Vec<TypeId>);
    #[doc(hidden)]
    fn matches_archetype(archetype: &Archetype) -> bool;
}

// Implement EntityQueryItem for immutable borrows
impl<'world_borrow, A: 'static> QueryParam for &A {
    type Fetch = FetchRead<A>;

    fn add_types(types: &mut Vec<TypeId>) {
        types.push(TypeId::of::<A>())
    }

    fn matches_archetype(archetype: &Archetype) -> bool {
        let type_id = TypeId::of::<A>();
        archetype.components.iter().any(|c| c.type_id == type_id)
    }
}

// Implement EntityQueryItem for mutable borrows
impl<'world_borrow, A: 'static> QueryParam for &mut A {
    type Fetch = FetchWrite<A>;

    fn add_types(types: &mut Vec<TypeId>) {
        types.push(TypeId::of::<A>())
    }

    fn matches_archetype(archetype: &Archetype) -> bool {
        let type_id = TypeId::of::<A>();
        archetype.components.iter().any(|c| c.type_id == type_id)
    }
}

impl<A: QueryParam> QueryParams for A {
    type Fetch = A;
}

macro_rules! entity_query_params_impl {
    ($($name: ident),*) => {
        #[allow(unused_parens)]
        impl<$($name: QueryParam,)*> QueryParams for ($($name,)*) {
            type Fetch = ($($name),*);
        }

        #[allow(unused_parens)]
        impl<'world_borrow, $($name: QueryParam,)*> Fetch<'world_borrow> for ($($name),*) {
            type Item = Vec<($(<<$name as QueryParam>::Fetch as Fetch<'world_borrow>>::Item),*)>;
            fn get(world: &'world_borrow World, _archetype: usize) -> Result<Self::Item, ComponentAlreadyBorrowed> {
                #[cfg(debug_assertions)]
                {
                    let mut types: Vec<TypeId> = Vec::new();
                    $($name::add_types(&mut types);)*
                    types.sort();
                    debug_assert!(
                        types.windows(2).all(|x| x[0] != x[1]),
                        "Queries cannot have duplicate types"
                    );
                }

                let mut archetype_indices = Vec::new();
                for (i, archetype) in world.archetypes.iter().enumerate() {
                    let matches = $($name::matches_archetype(&archetype))&&*;

                    if matches {
                        archetype_indices.push(i);
                    }
                }

                let mut result = Vec::with_capacity(archetype_indices.len());
                for index in archetype_indices {
                   result.push(($(<<$name as QueryParam>::Fetch as Fetch>::get(world, index)?),*))
                }
                Ok(result)
            }
        }
    };
}

//entity_query_params_impl! {}
entity_query_params_impl! {A}
entity_query_params_impl! {A, B}
entity_query_params_impl! {A, B, C}
entity_query_params_impl! {A, B, C, D}
entity_query_params_impl! {A, B, C, D, E}
entity_query_params_impl! {A, B, C, D, E, F}
entity_query_params_impl! {A, B, C, D, E, F, G}
entity_query_params_impl! {A, B, C, D, E, F, G, H}