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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use crate::{DataAccesses, MaskType, sync::{ReadGuardRef, WriteGuardRef, Lock}};
use hashbrown::HashMap;
use std::any::{TypeId, Any};
#[cfg(feature="dynamic_systems")]
use crate::dynamic_system_loader::DynamicSystemsLoader;
#[cfg(feature="dynamic_systems")]
use crate::DynamicSymbol;
#[cfg(all(feature="parallel_systems", feature="lockfree"))]
#[cfg(not(components_bigint))]
use num_traits::Zero;

/// Marker to access resources from functions that use signature to access them instead of
/// resources parameter
pub struct Res<'a, T> (pub &'a T);

impl<'a,T> std::ops::Deref for Res<'a, T> {
    type Target = T;
    fn deref(&self) -> &T{
        &self.0
    }
}

impl<'a, T: 'static> DataAccesses for Res<'a, T> {
    fn reads() -> Vec<TypeId> {
        vec![TypeId::of::<T>()]
    }

    fn writes() -> Vec<TypeId> {
        vec![]
    }
}

/// Marker to access resources mutably from functions that use signature to access them instead of
/// resources parameter
pub struct ResMut<'a, T> (pub &'a mut T);

impl<'a,T> std::ops::Deref for ResMut<'a, T> {
    type Target = T;
    fn deref(&self) -> &T{
        &self.0
    }
}

impl<'a,T> std::ops::DerefMut for ResMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T{
        &mut self.0
    }
}

impl<'a, T: 'static> DataAccesses for ResMut<'a, T> {
    fn reads() -> Vec<TypeId> {
        vec![TypeId::of::<T>()]
    }

    fn writes() -> Vec<TypeId> {
        vec![TypeId::of::<T>()]
    }
}

/// Gives access to the world global `Send` resources for reading and writing
///
/// Resources are useful for certain data that needs to be accessed from
/// several systems but doesn't belong to any specific entity
///
/// It's similar to a singleton in that it can be accessed from any system
/// and there's only one instance per type
#[derive(Clone, Copy)]
pub struct Resources<'a>{
    pub(crate) resources: &'a ResourcesContainer,
    pub(crate) resource_mask_r: Option<&'a MaskType>,
    pub(crate) resource_mask_w: Option<&'a MaskType>,
    pub(crate) system_info: &'a str,

    #[cfg(feature="dynamic_systems")]
    pub(crate) dynamic_systems: &'a DynamicSystemsLoader,
}

unsafe impl<'a> Send for Resources<'a>{}
unsafe impl<'a> Sync for Resources<'a>{}

impl<'a> Resources<'a>{
    pub fn get<T: 'static + Send>(&self) -> Option<ReadGuardRef<'a, T>>{
        self.resources.get(self.resource_mask_r, self.system_info)
    }

    pub fn get_mut<T: 'static + Send>(&self) -> Option<WriteGuardRef<'a, T>>{
        self.resources.get_mut(self.resource_mask_w, self.system_info)
    }

    pub fn as_trait<T: 'static + Send + ?Sized>(&self) -> Option<ReadGuardRef<'a, T>>{
        self.resources.as_trait(self.resource_mask_r, self.system_info)
    }

    pub fn as_trait_mut<T: 'static + Send + ?Sized>(&self) -> Option<WriteGuardRef<'a, T>>{
        self.resources.as_trait_mut(self.resource_mask_w, self.system_info)
    }

    /// Retrieves a symbol of the specified type from a dynamic library
    ///
    /// If the dynamic library is not laoded yet it'll be laoded first.
    ///
    /// The symbol path passed as parameter has the format `"lib_name::symbol_name"` an as
    /// second parameter the parameter to pass to the dynamic function being called
    ///
    /// ```no_run
    /// # let world = rinecs::World::new();
    /// # let resources = world.resources();
    /// let somefn = unsafe{ resources.get_dynamic_symbol::<fn(usize) -> usize>("somelib::somefn").unwrap() };
    /// let a = somefn(5);
    /// ```
    #[cfg(feature="dynamic_systems")]
    pub unsafe fn get_dynamic_symbol<S>(&self, symbol_path: &str) -> Result<DynamicSymbol<S>, String>{
        self.dynamic_systems.get_dynamic_symbol(symbol_path)
    }

    pub(crate) fn check_resource(&self, id: &TypeId, func: &Box<dyn Any>) -> bool {
        self.resources.check_resource(id, func)
    }

    pub(crate) fn has_resource(&self, id: &TypeId) -> bool {
        self.resources.has_resource(id)
    }
}

/// Gives access to the world global `Send` and thread local resources
/// for reading and writing
///
/// Resources are useful for certain data that needs to be accessed from
/// several systems but doesn't belong to any specific entity
///
/// It's similar to a singleton in that it can be accessed from any system
/// and there's only one instance per type
#[derive(Clone, Copy)]
pub struct ResourcesThreadLocal<'a>{
    pub(crate) resources: &'a ResourcesContainer,
    pub(crate) resource_mask_r: Option<&'a MaskType>,
    pub(crate) resource_mask_w: Option<&'a MaskType>,
    pub(crate) system_info: &'a str,

    #[cfg(feature="dynamic_systems")]
    pub(crate) dynamic_systems: &'a DynamicSystemsLoader,
}

impl<'a> ResourcesThreadLocal<'a>{
    pub fn get<T: 'static>(&self) -> Option<ReadGuardRef<'a, T>>{
        self.resources.get(self.resource_mask_r, self.system_info)
    }

    pub fn get_mut<T: 'static>(&self) -> Option<WriteGuardRef<'a, T>>{
        self.resources.get_mut(self.resource_mask_w, self.system_info)
    }

    pub fn as_trait<T: 'static + ?Sized>(&self) -> Option<ReadGuardRef<'a, T>>{
        self.resources.as_trait(self.resource_mask_r, self.system_info)
    }

    pub fn as_trait_mut<T: 'static + ?Sized>(&self) -> Option<WriteGuardRef<'a, T>>{
        self.resources.as_trait_mut(self.resource_mask_w, self.system_info)
    }

    pub fn to_send(&self) -> Resources<'a>{
        Resources{
            resources: self.resources,
            resource_mask_r: self.resource_mask_r,
            resource_mask_w: self.resource_mask_w,
            system_info: self.system_info,

            #[cfg(feature="dynamic_systems")]
            dynamic_systems: self.dynamic_systems,
        }
    }

    /// Retrieves a symbol of the specified type from a dynamic library
    ///
    /// If the dynamic library is not laoded yet it'll be laoded first.
    ///
    /// The symbol path passed as parameter has the format `"lib_name::symbol_name"` an as
    /// second parameter the parameter to pass to the dynamic function being called
    ///
    /// ```no_run
    /// # let world = rinecs::World::new();
    /// # let resources = world.resources_thread_local();
    /// let somefn = unsafe{ resources.get_dynamic_symbol::<fn(usize) -> usize>("somelib::somefn").unwrap() };
    /// let a = somefn(5);
    /// ```
    #[cfg(feature="dynamic_systems")]
    pub unsafe fn get_dynamic_symbol<S>(&self, symbol_path: &str) -> Result<DynamicSymbol<S>, String>{
        self.dynamic_systems.get_dynamic_symbol(symbol_path)
    }

    pub(crate) fn check_resource(&self, id: &TypeId, func: &Box<dyn Any>) -> bool {
        self.resources.check_resource(id, func)
    }

    pub(crate) fn has_resource(&self, id: &TypeId) -> bool {
        self.resources.has_resource(id)
    }

    pub fn clone(&mut self) -> Resources {
        Resources {
            resources: self.resources,
            resource_mask_r: self.resource_mask_r,
            resource_mask_w: self.resource_mask_w,
            system_info: self.system_info,

            #[cfg(feature="dynamic_systems")]
            dynamic_systems: self.dynamic_systems
        }
    }
}

/// Gives access to the world global `Send` and thread local resources
/// for reading and writing
///
/// Resources are useful for certain data that needs to be accessed from
/// several systems but doesn't belong to any specific entity
///
/// It's similar to a singleton in that it can be accessed from any system
/// and there's only one instance per type
pub struct ResourcesCreation<'a>{
    pub(crate) resources: &'a mut ResourcesContainer,
    pub(crate) system_info: &'a str,

    #[cfg(feature="dynamic_systems")]
    pub(crate) dynamic_systems: &'a DynamicSystemsLoader,
}

impl<'a> ResourcesCreation<'a>{
    pub fn get<T: 'static>(&self) -> Option<ReadGuardRef<T>>{
        self.resources.get(None, self.system_info)
    }

    pub fn get_mut<T: 'static>(&self) -> Option<WriteGuardRef<T>>{
        self.resources.get_mut(None, self.system_info)
    }

    pub fn as_trait<T: 'static + ?Sized>(&self) -> Option<ReadGuardRef<T>>{
        self.resources.as_trait(None, self.system_info)
    }

    pub fn as_trait_mut<T: 'static + ?Sized>(&self) -> Option<WriteGuardRef<T>>{
        self.resources.as_trait_mut(None, self.system_info)
    }

    pub fn to_send(&mut self) -> Resources {
        Resources{
            resources: self.resources,
            resource_mask_r: None,
            resource_mask_w: None,
            system_info: self.system_info,

            #[cfg(feature="dynamic_systems")]
            dynamic_systems: self.dynamic_systems,
        }
    }

    pub fn to_thread_local(&mut self) -> ResourcesThreadLocal {
        ResourcesThreadLocal{
            resources: self.resources,
            resource_mask_r: None,
            resource_mask_w: None,
            system_info: self.system_info,

            #[cfg(feature="dynamic_systems")]
            dynamic_systems: self.dynamic_systems,
        }
    }

    /// Retrieves a symbol of the specified type from a dynamic library
    ///
    /// If the dynamic library is not laoded yet it'll be laoded first.
    ///
    /// The symbol path passed as parameter has the format `"lib_name::symbol_name"` an as
    /// second parameter the parameter to pass to the dynamic function being called
    ///
    /// ```no_run
    /// # let world = rinecs::World::new();
    /// # let resources = world.resources_thread_local();
    /// let somefn = unsafe{ resources.get_dynamic_symbol::<fn(usize) -> usize>("somelib::somefn").unwrap() };
    /// let a = somefn(5);
    /// ```
    #[cfg(feature="dynamic_systems")]
    pub unsafe fn get_dynamic_symbol<S>(&self, symbol_path: &str) -> Result<DynamicSymbol<S>, String>{
        self.dynamic_systems.get_dynamic_symbol(symbol_path)
    }

    pub(crate) fn check_resource(&self, id: &TypeId, func: &Box<dyn Any>) -> bool {
        self.resources.check_resource(id, func)
    }

    pub(crate) fn has_resource(&self, id: &TypeId) -> bool {
        self.resources.has_resource(id)
    }

    /// Adds a `Send` resource to the world.
    ///
    /// Resources are globally accesible by any system through
    /// the `Resources` object passed as parameter to them.
    pub fn add<T: 'static + Send>(&mut self, resource: T){
        self.resources.add(resource);
    }

    /// Adds a non `Send` resource to the world.
    ///
    /// Non `Send` resources are globally accesible by any `SystemThreadLocal`
    /// through the `ResourcesThreadLocal` object passed as parameter to them.
    pub fn add_thread_local<T: 'static>(&mut self, resource: T){
        self.resources.add_thread_local(resource);
    }

    /// Adds a `Send` resource to the world accessible as a &dyn Trait.
    ///
    /// Resources are globally accesible by any system through
    /// the `Resources` object passed as parameter to them.
    pub fn add_as_trait<T, U, F, FMut>(&mut self, resource: (T, F, FMut))
    where T: 'static + Send,
        U: 'static + Send + ?Sized,
        F: Fn(&T) -> &U + 'static,
        FMut: Fn(&mut T) -> &mut U + 'static,
    {
        let (resource, f, fmut) = resource;
        self.add(resource);
        self.resources.add_as_trait::<T,U,F,FMut>(f, fmut)
    }

    /// Adds a non `Send` resource to the world accessible as a &dyn Trait.
    ///
    /// Resources are globally accesible by any system through
    /// the `Resources` object passed as parameter to them.
    pub fn add_as_trait_thread_local<T, U, F, FMut>(&mut self, resource: (T, F, FMut))
    where T: 'static,
        U: 'static + ?Sized,
        F: Fn(&T) -> &U + 'static,
        FMut: Fn(&mut T) -> &mut U + 'static,
    {
        let (resource, f, fmut) = resource;
        self.add_thread_local(resource);
        self.resources.add_as_trait_thread_local::<T,U,F,FMut>(f, fmut)
    }


    /// Removes a resource of the specified type.
    pub fn remove<T: 'static>(&mut self) -> Option<T>{
        self.resources.remove()
    }

    pub fn clone(&mut self) -> ResourcesCreation {
        ResourcesCreation {
            resources: self.resources,
            system_info: self.system_info,

            #[cfg(feature="dynamic_systems")]
            dynamic_systems: self.dynamic_systems
        }
    }
}

pub trait ResourcesExt {
    fn resource<T: 'static + Send>(&self) -> Option<ReadGuardRef<T>>;
    fn resource_mut<T: 'static + Send>(&self) -> Option<WriteGuardRef<T>>;
    fn resource_as_trait<T: 'static + Send + ?Sized>(&self) -> Option<ReadGuardRef<T>>;
    fn resource_as_trait_mut<T: 'static + Send + ?Sized>(&self) -> Option<WriteGuardRef<T>>;
}

pub trait ResourcesThreadLocalExt {
    fn resource_thread_local<T: 'static>(&self) -> Option<ReadGuardRef<T>>;
    fn resource_thread_local_mut<T: 'static>(&self) -> Option<WriteGuardRef<T>>;
    fn resource_as_trait_thread_local<T: 'static + ?Sized>(&self) -> Option<ReadGuardRef<T>>;
    fn resource_as_trait_thread_local_mut<T: 'static + ?Sized>(&self) -> Option<WriteGuardRef<T>>;
}

impl<'a> ResourcesExt for Resources<'a> {
    fn resource<T: 'static + Send>(&self) -> Option<ReadGuardRef<T>> {
        self.get()
    }

    fn resource_mut<T: 'static + Send>(&self) -> Option<WriteGuardRef<T>> {
        self.get_mut()
    }

    fn resource_as_trait<T: 'static + Send + ?Sized>(&self) -> Option<ReadGuardRef<T>> {
        self.as_trait()
    }

    fn resource_as_trait_mut<T: 'static + Send + ?Sized>(&self) -> Option<WriteGuardRef<T>> {
        self.as_trait_mut()
    }
}

impl<'a> ResourcesExt for ResourcesThreadLocal<'a> {
    fn resource<T: 'static + Send>(&self) -> Option<ReadGuardRef<T>> {
        self.get()
    }

    fn resource_mut<T: 'static + Send>(&self) -> Option<WriteGuardRef<T>> {
        self.get_mut()
    }

    fn resource_as_trait<T: 'static + Send + ?Sized>(&self) -> Option<ReadGuardRef<T>> {
        self.as_trait()
    }

    fn resource_as_trait_mut<T: 'static + Send + ?Sized>(&self) -> Option<WriteGuardRef<T>> {
        self.as_trait_mut()
    }
}

impl<'a> ResourcesThreadLocalExt for ResourcesThreadLocal<'a> {
    fn resource_thread_local<T: 'static>(&self) -> Option<ReadGuardRef<T>> {
        self.get()
    }

    fn resource_thread_local_mut<T: 'static>(&self) -> Option<WriteGuardRef<T>> {
        self.get_mut()
    }

    fn resource_as_trait_thread_local<T: 'static + ?Sized>(&self) -> Option<ReadGuardRef<T>> {
        self.as_trait()
    }

    fn resource_as_trait_thread_local_mut<T: 'static + ?Sized>(&self) -> Option<WriteGuardRef<T>> {
        self.as_trait_mut()
    }
}

impl<'a> ResourcesExt for ResourcesCreation<'a> {
    fn resource<T: 'static + Send>(&self) -> Option<ReadGuardRef<T>> {
        self.get()
    }

    fn resource_mut<T: 'static + Send>(&self) -> Option<WriteGuardRef<T>> {
        self.get_mut()
    }

    fn resource_as_trait<T: 'static + Send + ?Sized>(&self) -> Option<ReadGuardRef<T>> {
        self.as_trait()
    }

    fn resource_as_trait_mut<T: 'static + Send + ?Sized>(&self) -> Option<WriteGuardRef<T>> {
        self.as_trait_mut()
    }
}

impl<'a> ResourcesThreadLocalExt for ResourcesCreation<'a> {
    fn resource_thread_local<T: 'static>(&self) -> Option<ReadGuardRef<T>> {
        self.get()
    }

    fn resource_thread_local_mut<T: 'static>(&self) -> Option<WriteGuardRef<T>> {
        self.get_mut()
    }

    fn resource_as_trait_thread_local<T: 'static + ?Sized>(&self) -> Option<ReadGuardRef<T>> {
        self.as_trait()
    }

    fn resource_as_trait_thread_local_mut<T: 'static + ?Sized>(&self) -> Option<WriteGuardRef<T>> {
        self.as_trait_mut()
    }
}

pub struct MaskedResource {
    dependency_mask: MaskType,
    resource: Box<dyn Any>,
}

pub struct MaskedTraitResource {
    resource_dependency_mask: MaskType,
    trait_dependency_mask: MaskType,
    resource_typeid: TypeId,
    trait_to_resource: Box<dyn Any>,
}

#[derive(Default)]
pub struct ResourcesContainer{
    resources: HashMap<TypeId, MaskedResource>,
    resources_traits: HashMap<TypeId, MaskedTraitResource>,
    resources_traits_mut: HashMap<TypeId, MaskedTraitResource>,
    resource_checks: HashMap<TypeId, Box<dyn Fn(&Box<dyn Any>, &Box<dyn Any>) -> bool>>,
    resources_index: HashMap<TypeId, MaskType>,
    reverse_trait_index: HashMap<TypeId, TypeId>,
    traits_changed: bool,
}

impl ResourcesContainer{
    pub fn set_resources_index(&mut self, resources_index: HashMap<TypeId, MaskType>){
        self.resources_index = resources_index.clone();
        for (typeid, resource) in self.resources.iter_mut(){
            resource.dependency_mask = resources_index.get(&typeid).cloned().unwrap_or(MaskType::zero());
        }
        for (typeid, resource_trait) in self.resources_traits.iter_mut(){
            resource_trait.resource_dependency_mask = resources_index
                .get(&resource_trait.resource_typeid)
                .cloned()
                .unwrap_or(MaskType::zero());
                resource_trait.trait_dependency_mask = resources_index.get(&typeid).cloned().unwrap_or(MaskType::zero());
        }
        for (typeid, resource_trait) in self.resources_traits_mut.iter_mut(){
            resource_trait.resource_dependency_mask = resources_index
                .get(&resource_trait.resource_typeid)
                .cloned()
                .unwrap_or(MaskType::zero());
            resource_trait.trait_dependency_mask = resources_index.get(&typeid).cloned().unwrap_or(MaskType::zero());
        }
    }

    pub fn reverse_trait_index(&self) -> &HashMap<TypeId, TypeId> {
        &self.reverse_trait_index
    }

    pub fn take_traits_changed(&mut self) -> bool {
        std::mem::replace(&mut self.traits_changed, false)
    }

    /// Adds a `Send` resource to the world.
    ///
    /// Resources are globally accesible by any system through
    /// the `Resources` object passed as parameter to them.
    pub fn add<T: 'static + Send>(&mut self, resource: T){
        self.resources.insert(TypeId::of::<T>(), MaskedResource{
            dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource: Box::new(Lock::new(resource)) as Box<dyn Any>
        });

        let resource_check = |resource: &Box<dyn Any>, check: &Box<dyn Any>|{
            let check: &Box<dyn Fn(&T) -> bool> = check.downcast_ref().unwrap();
            let resource: &Lock<T> = resource.downcast_ref().unwrap();
            check(&resource.read())
        };

        self.resource_checks.insert(TypeId::of::<T>(), Box::new(resource_check));
    }


    /// Adds a non `Send` resource to the world.
    ///
    /// Non `Send` resources are globally accesible by any `SystemThreadLocal`
    /// through the `ResourcesThreadLocal` object passed as parameter to them.
    pub fn add_thread_local<T: 'static>(&mut self, resource: T){
        self.resources.insert(TypeId::of::<T>(), MaskedResource{
            dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource: Box::new(Lock::new(resource)) as Box<dyn Any>
        });

        let resource_check = |resource: &Box<dyn Any>, check: &Box<dyn Any>|{
            let check: &Box<dyn Fn(&T) -> bool> = check.downcast_ref().unwrap();
            let resource: &Lock<T> = resource.downcast_ref().unwrap();
            check(&resource.read())
        };

        self.resource_checks.insert(TypeId::of::<T>(), Box::new(resource_check));
    }

    pub fn add_as_trait<T, U, F, FMut>(&mut self, f: F, fmut: FMut)
    where T: 'static + Send,
        U: 'static + Send + ?Sized,
        F: Fn(&T) -> &U + 'static,
        FMut: Fn(&mut T) -> &mut U + 'static,
    {
        let f: Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> ReadGuardRef<'a, U>>
            = Box::new(move |resources: &ResourcesContainer, mask: Option<&MaskType>, system_info: &str|{
                ReadGuardRef::map(resources.get::<T>(mask, system_info).unwrap(), |t| f(t))
            });
        let fmut: Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> WriteGuardRef<'a, U>>
            = Box::new(move |resources: &ResourcesContainer, mask: Option<&MaskType>, system_info: &str|{
                WriteGuardRef::map(resources.get_mut::<T>(mask, system_info).unwrap(), |t| fmut(t))
            });
        self.resources_traits.insert(TypeId::of::<U>(), MaskedTraitResource{
            trait_dependency_mask: self.resources_index.get(&TypeId::of::<U>()).cloned().unwrap_or(MaskType::zero()),
            resource_dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource_typeid: TypeId::of::<T>(),
            trait_to_resource: Box::new(f),
        });
        self.resources_traits_mut.insert(TypeId::of::<U>(), MaskedTraitResource{
            trait_dependency_mask: self.resources_index.get(&TypeId::of::<U>()).cloned().unwrap_or(MaskType::zero()),
            resource_dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource_typeid: TypeId::of::<T>(),
            trait_to_resource: Box::new(fmut),
        });
        self.reverse_trait_index.insert(TypeId::of::<T>(), TypeId::of::<U>());
        self.traits_changed = true;
    }

    pub fn add_as_trait_thread_local<T, U, F, FMut>(&mut self, f: F, fmut: FMut)
    where T: 'static,
        U: 'static + ?Sized,
        F: Fn(&T) -> &U + 'static,
        FMut: Fn(&mut T) -> &mut U + 'static,
    {
        let f: Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> ReadGuardRef<'a, U>>
            = Box::new(move |resources: &ResourcesContainer, mask: Option<&MaskType>, system_info: &str|{
                ReadGuardRef::map(resources.get::<T>(mask, system_info).unwrap(), |t| f(t))
            });
        let fmut: Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> WriteGuardRef<'a, U>>
            = Box::new(move |resources: &ResourcesContainer, mask: Option<&MaskType>, system_info: &str|{
                WriteGuardRef::map(resources.get_mut::<T>(mask, system_info).unwrap(), |t| fmut(t))
            });
        self.resources_traits.insert(TypeId::of::<U>(), MaskedTraitResource{
            trait_dependency_mask: self.resources_index.get(&TypeId::of::<U>()).cloned().unwrap_or(MaskType::zero()),
            resource_dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource_typeid: TypeId::of::<T>(),
            trait_to_resource: Box::new(f),
        });
        self.resources_traits_mut.insert(TypeId::of::<U>(), MaskedTraitResource{
            trait_dependency_mask: self.resources_index.get(&TypeId::of::<U>()).cloned().unwrap_or(MaskType::zero()),
            resource_dependency_mask: self.resources_index.get(&TypeId::of::<T>()).cloned().unwrap_or(MaskType::zero()),
            resource_typeid: TypeId::of::<T>(),
            trait_to_resource: Box::new(fmut),
        });
        self.reverse_trait_index.insert(TypeId::of::<T>(), TypeId::of::<U>());
        self.traits_changed = true;
    }

    #[inline]
    pub fn check_resource(&self, id: &TypeId, func: &Box<dyn Any>) -> bool {
        let resource = &self.resources[id].resource;
        self.resource_checks[id](resource, func)
    }

    #[inline]
    pub fn resources_mut(&mut self) -> &mut HashMap<TypeId, MaskedResource>{
        &mut self.resources
    }

    /// Removes a resource of the specified type.
    pub fn remove<T: 'static>(&mut self) -> Option<T> {
        self.resources.remove(&TypeId::of::<T>()).map(|t| {
            let t: Box<Lock<T>> = t.resource.downcast().unwrap();
            t.into_inner()
        })
    }

    /// Returns a resource of the specified type if it exists for reading.
    #[inline]
    pub fn get<T: 'static>(&self, _mask: Option<&MaskType>, _system_info: &str) -> Option<ReadGuardRef<T>>{
        self.resources.get(&TypeId::of::<T>()).map(|t| {

            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            if let Some(mask) = _mask {
                if mask & &t.dependency_mask == MaskType::zero() {
                    println!("Doesn't have mask {:?}", mask);
                    panic!("Trying to retrieve resource {} that this system doesn't have read access to. {}",
                        std::any::type_name::<T>(),
                        _system_info
                    );
                }
            }

            let t: &Lock<T> = t.resource.downcast_ref().unwrap();
            ReadGuardRef::new(t.read())
        })
    }

    /// Returns a resource of the specified type if it exists for writing.
    #[inline]
    pub fn get_mut<T: 'static>(&self, _mask: Option<&MaskType>, _system_info: &str) -> Option<WriteGuardRef<T>>{
        self.resources.get(&TypeId::of::<T>()).map(|t| {

            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            if let Some(mask) = _mask {
                if mask & &t.dependency_mask == MaskType::zero() {
                    panic!("Trying to retrieve resource {} that this system doesn't have write access to. {}",
                        std::any::type_name::<T>(),
                        _system_info
                    );
                }
            }

            let t: &Lock<T> = t.resource.downcast_ref().unwrap();
            WriteGuardRef::new(t.write())
        })
    }

    pub fn as_trait<T: 'static + ?Sized>(&self, mask: Option<&MaskType>, system_info: &str) -> Option<ReadGuardRef<T>>{
        self.resources_traits.get(&TypeId::of::<T>()).map(|f| {

            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            let mask = mask.map(|mask| if mask & &f.trait_dependency_mask != MaskType::zero(){
                mask & !&f.trait_dependency_mask | &f.resource_dependency_mask
            }else{
                mask.clone()
            });
            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            let mask = mask.as_ref();

            let f: &Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> ReadGuardRef<'a, T>>
                = f.trait_to_resource.downcast_ref().unwrap();
            f(self, mask, system_info)
        })
    }

    pub fn as_trait_mut<T: 'static + ?Sized>(&self, mask: Option<&MaskType>, system_info: &str) -> Option<WriteGuardRef<T>>{
        self.resources_traits_mut.get(&TypeId::of::<T>()).map(|f| {

            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            let mask = mask.map(|mask| if mask & &f.trait_dependency_mask != MaskType::zero(){
                mask & !&f.trait_dependency_mask | &f.resource_dependency_mask
            }else{
                mask.clone()
            });
            #[cfg(all(feature="parallel_systems", feature="lockfree"))]
            let mask = mask.as_ref();

            let f: &Box<dyn for<'a> Fn(&'a ResourcesContainer, Option<&MaskType>, &str) -> WriteGuardRef<'a, T>>
                = f.trait_to_resource.downcast_ref().unwrap();
            f(self, mask, system_info)
        })
    }

    pub(crate) fn has_resource(&self, id: &TypeId) -> bool {
        self.resources.contains_key(id)
    }
}