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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use super::{FromResources, Resources};
use crate::{
    system::{SystemId, TypeAccess},
    Resource, ResourceIndex,
};
use bevy_hecs::smaller_tuples_too;
use core::{
    any::TypeId,
    ops::{Deref, DerefMut},
    ptr::NonNull,
};
use std::marker::PhantomData;

/// A shared borrow of a Resource
/// that will only return in a query if the Resource has been changed
pub struct ChangedRes<'a, T: Resource> {
    value: &'a T,
}

impl<'a, T: Resource> ChangedRes<'a, T> {
    /// Creates a reference cell to a Resource from a pointer
    ///
    /// # Safety
    /// The pointer must have correct lifetime / storage
    pub unsafe fn new(value: NonNull<T>) -> Self {
        Self {
            value: &*value.as_ptr(),
        }
    }
}

impl<'a, T: Resource> UnsafeClone for ChangedRes<'a, T> {
    unsafe fn unsafe_clone(&self) -> Self {
        Self { value: self.value }
    }
}

unsafe impl<T: Resource> Send for ChangedRes<'_, T> {}
unsafe impl<T: Resource> Sync for ChangedRes<'_, T> {}

impl<'a, T: Resource> Deref for ChangedRes<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.value
    }
}

/// Shared borrow of a Resource
pub struct Res<'a, T: Resource> {
    value: &'a T,
}

impl<'a, T: Resource> Res<'a, T> {
    /// Creates a reference cell to a Resource from a pointer
    ///
    /// # Safety
    /// The pointer must have correct lifetime / storage
    pub unsafe fn new(value: NonNull<T>) -> Self {
        Self {
            value: &*value.as_ptr(),
        }
    }
}

/// A clone that is unsafe to perform. You probably shouldn't use this.
pub trait UnsafeClone {
    #[allow(clippy::missing_safety_doc)]
    unsafe fn unsafe_clone(&self) -> Self;
}

impl<'a, T: Resource> UnsafeClone for Res<'a, T> {
    unsafe fn unsafe_clone(&self) -> Self {
        Self { value: self.value }
    }
}

unsafe impl<T: Resource> Send for Res<'_, T> {}
unsafe impl<T: Resource> Sync for Res<'_, T> {}

impl<'a, T: Resource> Deref for Res<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.value
    }
}

/// Unique borrow of a Resource
pub struct ResMut<'a, T: Resource> {
    _marker: PhantomData<&'a T>,
    value: *mut T,
    mutated: *mut bool,
}

impl<'a, T: Resource> ResMut<'a, T> {
    /// Creates a mutable reference cell to a Resource from a pointer
    ///
    /// # Safety
    /// The pointer must have correct lifetime / storage / ownership
    pub unsafe fn new(value: NonNull<T>, mutated: NonNull<bool>) -> Self {
        Self {
            value: value.as_ptr(),
            mutated: mutated.as_ptr(),
            _marker: Default::default(),
        }
    }
}

unsafe impl<T: Resource> Send for ResMut<'_, T> {}
unsafe impl<T: Resource> Sync for ResMut<'_, T> {}

impl<'a, T: Resource> Deref for ResMut<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.value }
    }
}

impl<'a, T: Resource> DerefMut for ResMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe {
            *self.mutated = true;
            &mut *self.value
        }
    }
}

impl<'a, T: Resource> UnsafeClone for ResMut<'a, T> {
    unsafe fn unsafe_clone(&self) -> Self {
        Self {
            value: self.value,
            mutated: self.mutated,
            _marker: Default::default(),
        }
    }
}

/// Local<T> resources are unique per-system. Two instances of the same system will each have their own resource.
/// Local resources are automatically initialized using the FromResources trait.
pub struct Local<'a, T: Resource + FromResources> {
    value: *mut T,
    _marker: PhantomData<&'a T>,
}

impl<'a, T: Resource + FromResources> UnsafeClone for Local<'a, T> {
    unsafe fn unsafe_clone(&self) -> Self {
        Self {
            value: self.value,
            _marker: Default::default(),
        }
    }
}

impl<'a, T: Resource + FromResources> Deref for Local<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.value }
    }
}

impl<'a, T: Resource + FromResources> DerefMut for Local<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.value }
    }
}

/// A collection of resource types fetch from a `Resources` collection
pub trait ResourceQuery {
    type Fetch: for<'a> FetchResource<'a>;

    fn initialize(_resources: &mut Resources, _system_id: Option<SystemId>) {}
}

/// Streaming iterators over contiguous homogeneous ranges of resources
pub trait FetchResource<'a>: Sized {
    /// Type of value to be fetched
    type Item: UnsafeClone;

    fn access() -> TypeAccess;
    fn borrow(resources: &Resources);
    fn release(resources: &Resources);

    #[allow(clippy::missing_safety_doc)]
    unsafe fn get(resources: &'a Resources, system_id: Option<SystemId>) -> Self::Item;

    #[allow(clippy::missing_safety_doc)]
    unsafe fn is_some(_resources: &'a Resources, _system_id: Option<SystemId>) -> bool {
        true
    }
}

impl<'a, T: Resource> ResourceQuery for Res<'a, T> {
    type Fetch = FetchResourceRead<T>;
}

/// Fetches a shared resource reference
pub struct FetchResourceRead<T>(NonNull<T>);

impl<'a, T: Resource> FetchResource<'a> for FetchResourceRead<T> {
    type Item = Res<'a, T>;

    unsafe fn get(resources: &'a Resources, _system_id: Option<SystemId>) -> Self::Item {
        Res::new(resources.get_unsafe_ref::<T>(ResourceIndex::Global))
    }

    fn borrow(resources: &Resources) {
        resources.borrow::<T>();
    }

    fn release(resources: &Resources) {
        resources.release::<T>();
    }

    fn access() -> TypeAccess {
        let mut access = TypeAccess::default();
        access.immutable.insert(TypeId::of::<T>());
        access
    }
}

impl<'a, T: Resource> ResourceQuery for ChangedRes<'a, T> {
    type Fetch = FetchResourceChanged<T>;
}

/// Fetches a shared resource reference
pub struct FetchResourceChanged<T>(NonNull<T>);

impl<'a, T: Resource> FetchResource<'a> for FetchResourceChanged<T> {
    type Item = ChangedRes<'a, T>;

    unsafe fn get(resources: &'a Resources, _system_id: Option<SystemId>) -> Self::Item {
        ChangedRes::new(resources.get_unsafe_ref::<T>(ResourceIndex::Global))
    }

    unsafe fn is_some(resources: &'a Resources, _system_id: Option<SystemId>) -> bool {
        let (added, mutated) = resources.get_unsafe_added_and_mutated::<T>(ResourceIndex::Global);
        *added.as_ptr() || *mutated.as_ptr()
    }

    fn borrow(resources: &Resources) {
        resources.borrow::<T>();
    }

    fn release(resources: &Resources) {
        resources.release::<T>();
    }

    fn access() -> TypeAccess {
        let mut access = TypeAccess::default();
        access.immutable.insert(TypeId::of::<T>());
        access
    }
}

impl<'a, T: Resource> ResourceQuery for ResMut<'a, T> {
    type Fetch = FetchResourceWrite<T>;
}

/// Fetches a unique resource reference
pub struct FetchResourceWrite<T>(NonNull<T>);

impl<'a, T: Resource> FetchResource<'a> for FetchResourceWrite<T> {
    type Item = ResMut<'a, T>;

    unsafe fn get(resources: &'a Resources, _system_id: Option<SystemId>) -> Self::Item {
        let (value, type_state) =
            resources.get_unsafe_ref_with_type_state::<T>(ResourceIndex::Global);
        ResMut::new(value, type_state.mutated())
    }

    fn borrow(resources: &Resources) {
        resources.borrow_mut::<T>();
    }

    fn release(resources: &Resources) {
        resources.release_mut::<T>();
    }

    fn access() -> TypeAccess {
        let mut access = TypeAccess::default();
        access.mutable.insert(TypeId::of::<T>());
        access
    }
}

impl<'a, T: Resource + FromResources> ResourceQuery for Local<'a, T> {
    type Fetch = FetchResourceLocalMut<T>;

    fn initialize(resources: &mut Resources, id: Option<SystemId>) {
        let value = T::from_resources(resources);
        let id = id.expect("Local<T> resources can only be used by systems");
        resources.insert_local(id, value);
    }
}

/// Fetches a `Local<T>` resource reference
pub struct FetchResourceLocalMut<T>(NonNull<T>);

impl<'a, T: Resource + FromResources> FetchResource<'a> for FetchResourceLocalMut<T> {
    type Item = Local<'a, T>;

    unsafe fn get(resources: &'a Resources, system_id: Option<SystemId>) -> Self::Item {
        let id = system_id.expect("Local<T> resources can only be used by systems");
        Local {
            value: resources
                .get_unsafe_ref::<T>(ResourceIndex::System(id))
                .as_ptr(),
            _marker: Default::default(),
        }
    }

    fn borrow(resources: &Resources) {
        resources.borrow_mut::<T>();
    }

    fn release(resources: &Resources) {
        resources.release_mut::<T>();
    }

    fn access() -> TypeAccess {
        let mut access = TypeAccess::default();
        access.mutable.insert(TypeId::of::<T>());
        access
    }
}

macro_rules! tuple_impl {
    ($($name: ident),*) => {
        impl<'a, $($name: FetchResource<'a>),*> FetchResource<'a> for ($($name,)*) {
            type Item = ($($name::Item,)*);

            #[allow(unused_variables)]
            fn borrow(resources: &Resources) {
                $($name::borrow(resources);)*
            }

            #[allow(unused_variables)]
            fn release(resources: &Resources) {
                $($name::release(resources);)*
            }

            #[allow(unused_variables)]
            unsafe fn get(resources: &'a Resources, system_id: Option<SystemId>) -> Self::Item {
                ($($name::get(resources, system_id),)*)
            }

            #[allow(unused_variables)]
            unsafe fn is_some(resources: &'a Resources, system_id: Option<SystemId>) -> bool {
                true $(&& $name::is_some(resources, system_id))*
            }

            #[allow(unused_mut)]
            fn access() -> TypeAccess {
                let mut access = TypeAccess::default();
                $(access.union(&$name::access());)*
                access
            }
        }

        impl<$($name: ResourceQuery),*> ResourceQuery for ($($name,)*) {
            type Fetch = ($($name::Fetch,)*);

            #[allow(unused_variables)]
            fn initialize(resources: &mut Resources, system_id: Option<SystemId>) {
                $($name::initialize(resources, system_id);)*
            }
        }

        #[allow(unused_variables)]
        #[allow(non_snake_case)]
        impl<$($name: UnsafeClone),*> UnsafeClone for ($($name,)*) {
            unsafe fn unsafe_clone(&self) -> Self {
                let ($($name,)*) = self;
                ($($name.unsafe_clone(),)*)
            }
        }
    };
}

smaller_tuples_too!(tuple_impl, O, N, M, L, K, J, I, H, G, F, E, D, C, B, A);

pub struct OrRes<T>(T);

pub struct FetchResourceOr<T>(NonNull<T>);

macro_rules! tuple_impl_or {
    ($($name: ident),*) => {
        impl<'a, $($name: FetchResource<'a>),*> FetchResource<'a> for FetchResourceOr<($($name,)*)> {
            type Item = OrRes<($($name::Item,)*)>;

            #[allow(unused_variables)]
            fn borrow(resources: &Resources) {
                $($name::borrow(resources);)*
            }

            #[allow(unused_variables)]
            fn release(resources: &Resources) {
                $($name::release(resources);)*
            }

            #[allow(unused_variables)]
            unsafe fn get(resources: &'a Resources, system_id: Option<SystemId>) -> Self::Item {
                OrRes(($($name::get(resources, system_id),)*))
            }

            #[allow(unused_variables)]
            unsafe fn is_some(resources: &'a Resources, system_id: Option<SystemId>) -> bool {
                false $(|| $name::is_some(resources, system_id))*
            }

            #[allow(unused_mut)]
            fn access() -> TypeAccess {
                let mut access = TypeAccess::default();
                $(access.union(&$name::access());)*
                access
            }
        }

        impl<$($name: ResourceQuery),*> ResourceQuery for OrRes<($($name,)*)> {
            type Fetch = FetchResourceOr<($($name::Fetch,)*)>;

            #[allow(unused_variables)]
            fn initialize(resources: &mut Resources, system_id: Option<SystemId>) {
                $($name::initialize(resources, system_id);)*
            }
        }

        #[allow(unused_variables)]
        #[allow(non_snake_case)]
        impl<$($name: UnsafeClone),*> UnsafeClone for OrRes<($($name,)*)> {
            unsafe fn unsafe_clone(&self) -> Self {
                let OrRes(($($name,)*)) = self;
                OrRes(($($name.unsafe_clone(),)*))
            }
        }

        impl<$($name,)*> Deref for OrRes<($($name,)*)> {
            type Target = ($($name,)*);

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

smaller_tuples_too!(tuple_impl_or, O, N, M, L, K, J, I, H, G, F, E, D, C, B, A);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn changed_resource() {
        let mut resources = Resources::default();
        resources.insert(123);
        assert_eq!(
            resources.query::<ChangedRes<i32>>().as_deref(),
            Some(&(123 as i32))
        );
        resources.clear_trackers();
        assert_eq!(resources.query::<ChangedRes<i32>>().as_deref(), None);
        *resources.query::<ResMut<i32>>().unwrap() += 1;
        assert_eq!(
            resources.query::<ChangedRes<i32>>().as_deref(),
            Some(&(124 as i32))
        );
    }

    #[test]
    fn or_changed_resource() {
        let mut resources = Resources::default();
        resources.insert(123);
        resources.insert(0.2);
        assert!(resources
            .query::<OrRes<(ChangedRes<i32>, ChangedRes<f64>)>>()
            .is_some(),);
        resources.clear_trackers();
        assert!(resources
            .query::<OrRes<(ChangedRes<i32>, ChangedRes<f64>)>>()
            .is_none(),);
        *resources.query::<ResMut<i32>>().unwrap() += 1;
        assert!(resources
            .query::<OrRes<(ChangedRes<i32>, ChangedRes<f64>)>>()
            .is_some(),);
        assert!(resources
            .query::<(ChangedRes<i32>, ChangedRes<f64>)>()
            .is_none(),);
    }
}