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
/// Trait for systems that can run from any thread in parallel with other systems.
///
/// Types implementing this trait must be `Send` and are usually called `Send` `System`
/// in the documentation.
///
/// Any function that receives an `Entities` and a `Resources` parameter in that order
/// can be added as a `System` to the world.
pub trait System<'a>: Send{
    fn run(&mut self, ::Entities<'a>, ::Resources<'a>);
}

/// Trait for systems that can only run from the main thread but in parallel with
/// `Send` systems.
///
/// Any function that receives an `EntitiesThreadLocal` and a `ResourcesThreadLocal`
/// parameter in that order can be added as a `SystemThreadLocal` to the world.
pub trait SystemThreadLocal<'a>{
    fn run(&mut self, ::EntitiesThreadLocal<'a>, ::ResourcesThreadLocal<'a>);
}

impl<'a, F: FnMut(::Entities<'a>, ::Resources<'a>) + Send> System<'a> for F{
    fn run(&mut self, e: ::Entities<'a>, r: ::Resources<'a>){
        (*self)(e,r)
    }
}

impl<'a, F: FnMut(::EntitiesThreadLocal<'a>, ::ResourcesThreadLocal<'a>)> SystemThreadLocal<'a> for F{
    fn run(&mut self, e: ::EntitiesThreadLocal<'a>, r: ::ResourcesThreadLocal<'a>){
        (*self)(e,r)
    }
}

/// Trait for `Send` `System`s that only use resources but no entities.
///
/// Any function that receives a `Resources` parameter can be added as
/// a `System` to the world.
pub trait SystemResources<'a>: Send{
    fn run(&mut self, ::Resources<'a>);
}

impl<'a, F: FnMut(::Resources<'a>) + Send> SystemResources<'a> for F{
    fn run(&mut self, e: ::Resources<'a>){
        (*self)(e)
    }
}

impl<'a> System<'a> for SystemResources<'a>{
    fn run(&mut self, _: ::Entities<'a>, r: ::Resources<'a>){
        self.run(r)
    }
}

/// Trait for `Send` `System`s that only use entities but no resources,
///
/// Any function that receives a `Entities` parameter can be added as
/// a `System` to the world.
pub trait SystemEntities<'a>: Send{
    fn run(&mut self, ::Entities<'a>);
}

impl<'a, F: FnMut(::Entities<'a>) + Send> SystemEntities<'a> for F{
    fn run(&mut self, e: ::Entities<'a>){
        (*self)(e)
    }
}

impl<'a> System<'a> for SystemEntities<'a>{
    fn run(&mut self, e: ::Entities<'a>, _: ::Resources<'a>){
        self.run(e)
    }
}

/// Trait for systems that receive a data parameter and can run from any
/// thread in parallel with other systems.
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait SystemWithData<'a, D: Send + 'static>: Send{
    fn run(&mut self, data: &mut D, entities: ::Entities, resources: ::Resources);
}

impl<'a, D: Send + 'static, F: FnMut(&mut D,::Entities, ::Resources) + Send> SystemWithData<'a, D> for F {
    fn run(&mut self, data: &mut D, entities: ::Entities, resources: ::Resources){
        self(data, entities, resources)
    }
}

impl<'a, D: Send + 'static, S: SystemWithData<'a,D> + Send> System<'a> for (S, D){
    fn run(&mut self, entities: ::Entities, resources: ::Resources){
        self.0.run(&mut self.1, entities, resources)
    }
}


/// Trait for systems that receive a data parameter and can only run from
/// the main thread but in parallel with `Send` systems.
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait SystemWithDataThreadLocal<'a, D: 'static>{
    fn run(&mut self, data: &mut D, entities: ::EntitiesThreadLocal, resources: ::ResourcesThreadLocal);
}

impl<'a, D: 'static, F: FnMut(&mut D,::EntitiesThreadLocal, ::ResourcesThreadLocal)> SystemWithDataThreadLocal<'a, D> for F {
    fn run(&mut self, data: &mut D, entities: ::EntitiesThreadLocal, resources: ::ResourcesThreadLocal){
        self(data, entities, resources)
    }
}

impl<'a, D: 'static, S: SystemWithDataThreadLocal<'a,D>> SystemThreadLocal<'a> for (S, D){
    fn run(&mut self, entities: ::EntitiesThreadLocal, resources: ::ResourcesThreadLocal){
        self.0.run(&mut self.1, entities, resources)
    }
}

/// Trait for systems that can create entities and resources.
///
/// These systems will run in the main thread and always alone with nothing
/// else running in parallel
pub trait CreationSystem<'a>{
    fn run(&mut self, entities: ::CreationProxy<'a>, resources: ::ResourcesThreadLocal<'a>);
}

/// Trait for systems that receive a data parameter and can create entities and resources.
///
/// These systems will run in the main thread and always alone with nothing
/// else running in parallel
///
/// This trait is mostly useful from dynamic systems that are funcitons with their corresponding
/// objects created outside the dynamic library since dynamic systems can't allocate memory
pub trait CreationSystemWithData<'a, D: 'static>{
    fn run(&mut self, data: &mut D, entities: ::CreationProxy<'a>, resources: ::ResourcesThreadLocal<'a>);
}

impl<'a, F: FnMut(::CreationProxy<'a>, ::ResourcesThreadLocal<'a>)> CreationSystem<'a> for F{
    fn run(&mut self, entities: ::CreationProxy<'a>, resources: ::ResourcesThreadLocal<'a>){
        self(entities, resources)
    }
}


impl<'a, D: 'static, F: FnMut(&mut D, ::CreationProxy<'a>, ::ResourcesThreadLocal<'a>)> CreationSystemWithData<'a, D> for F{
    fn run(&mut self, data: &mut D, entities: ::CreationProxy<'a>, resources: ::ResourcesThreadLocal<'a>){
        self(data, entities, resources)
    }
}

impl<'a, D: 'static, S: CreationSystemWithData<'a, D>> CreationSystem<'a> for (S, D) {
    fn run(&mut self, entities: ::CreationProxy<'a>, resources: ::ResourcesThreadLocal<'a>){
        self.0.run(&mut self.1, entities, resources)
    }
}


#[cfg(feature="stats_events")]
use std::time;
#[cfg(feature="stats_events")]
use hashbrown::HashMap;
#[cfg(feature="stats_events")]
use seitan::{StreamT, SenderRc, Property};
use std::cell::UnsafeCell;
use entity::{Entities, EntitiesThreadLocal, CreationProxy};
#[cfg(feature="debug_parameters")]
use debug::{EntitiesDebug, SystemDebug};
use resource::{Resources, ResourcesThreadLocal};

#[cfg(feature="debug_concurrency")]
use std::intrinsics::type_name;

#[derive(Default)]
pub struct Systems{
    systems: Vec<(Option<String>, SyncSystem)>,
    systems_thread_local: Vec<(Option<String>, Box<for<'a> SystemThreadLocal<'a>>)>,
    systems_creation: Vec<(Option<String>, Box<for<'a> CreationSystem<'a>>)>,
    #[cfg(feature = "debug_parameters")]
    systems_debug: Vec<(Option<String>, Box<for<'a> SystemDebug<'a>>)>,

    #[cfg(feature="stats_events")]
    stats: Vec<(String, time::Duration)>,

    #[cfg(feature="stats_events")]
    gpu_stats: Vec<(String, time::Duration)>,

    #[cfg(feature="stats_events")]
    stats_events: HashMap<String, SenderRc<'static, time::Duration>>,

    #[cfg(all(feature="stats_events", feature="glin"))]
    gpu_stats_counters: HashMap<String, glin::query::Duration>,

    #[cfg(feature="stats_events")]
    gpu_stats_events: HashMap<String, SenderRc<'static, time::Duration>>,

    #[cfg(feature="stats_events")]
    enabled_systems: HashMap<String, Property<'static, bool>>,

    #[cfg(feature="stats_events")]
    send_enabled_systems: HashMap<String, bool>,

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

#[cfg(feature="multithreaded")]
pub struct SendSystems<'a>{
    systems: &'a [(Option<String>, SyncSystem)],

    #[cfg(feature="stats_events")]
    enabled_systems: &'a HashMap<String, bool>,

    #[cfg(feature="stats_events")]
    sender: crossbeam::channel::Sender<(String, time::Duration)>,
}

#[cfg(feature="multithreaded")]
impl<'a> SendSystems<'a>{
    pub fn run_send_system(&self, idx: usize, entities: Entities, resources: Resources) {
        let (_name, system_w) = &self.systems[idx];
        let system_w = unsafe{ system_w.borrow_mut() };

        #[cfg(feature="stats_events")]
        {
            if let Some(ref name) = _name {
                match self.enabled_systems.get(name).map(|e| *e) {
                    Some(true) => {
                        let then = time::Instant::now();
                        system_w.run(entities, resources);
                        let now = time::Instant::now();
                        self.sender.send((name.clone(), now - then)).is_ok();
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        {
            system_w.run(entities, resources);
        }
    }
}

#[cfg(feature="multithreaded")]
pub struct ThreadLocalSystems<'a>{
    systems: &'a mut [(Option<String>, Box<for<'b> SystemThreadLocal<'b>>)],

    #[cfg(feature="stats_events")]
    enabled_systems: &'a HashMap<String, bool>,

    #[cfg(feature="stats_events")]
    stats: &'a mut Vec<(String, time::Duration)>,

    #[cfg(feature="stats_events")]
    receiver: crossbeam::channel::Receiver<(String, time::Duration)>,
}

#[cfg(feature="multithreaded")]
impl<'a> ThreadLocalSystems<'a>{
    pub fn run_thread_local_system(&mut self, idx: usize, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal) {
        let (_name, system_w) = &mut self.systems[idx];

        #[cfg(feature="stats_events")]
        {
            if let Some(name) = _name {
                match self.enabled_systems.get(name).map(|e| *e) {
                    Some(true) => {
                        let then = time::Instant::now();
                        system_w.run(entities, resources);
                        let now = time::Instant::now();
                        self.stats.push((name.clone(), now - then));
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        system_w.run(entities, resources);
    }
}

#[cfg(feature="stats_events")]
#[cfg(feature="multithreaded")]
impl<'a> Drop for ThreadLocalSystems<'a>{
    fn drop(&mut self){
        self.stats.extend(self.receiver.try_iter())
    }
}

impl Systems{
    #[cfg(feature="stats_events")]
    pub fn reset_stats(&mut self){
        self.send_enabled_systems.clear();
        let enabled_systems = self.enabled_systems.iter().map(|(n, e)| (n.to_owned(), **e));
        self.send_enabled_systems.extend(enabled_systems);

        self.stats.clear();

        #[cfg(feature="glin")]
        self.gpu_stats.clear();

        #[cfg(feature = "debug_parameters")]
        let debug_systems = self.systems_debug.len();
        #[cfg(not(feature = "debug_parameters"))]
        let debug_systems = 0;
        self.stats.reserve(
            self.systems.len() +
            self.systems_thread_local.len() +
            self.systems_creation.len() +
            debug_systems);
    }

    #[cfg(feature="multithreaded")]
    pub fn send_and_tl_systems(&mut self) -> (SendSystems, ThreadLocalSystems){
        #[cfg(feature="stats_events")]
        let (sender, receiver) = crossbeam::channel::bounded(self.systems.len());

        let send = SendSystems{
            systems: &self.systems,

            #[cfg(feature="stats_events")]
            enabled_systems: &self.send_enabled_systems,

            #[cfg(feature="stats_events")]
            sender,
        };

        let tl = ThreadLocalSystems{
            systems: &mut self.systems_thread_local,

            #[cfg(feature="stats_events")]
            enabled_systems: &self.send_enabled_systems,

            #[cfg(feature="stats_events")]
            stats: &mut self.stats,

            #[cfg(feature="stats_events")]
            receiver,
        };

        (send, tl)
    }

    pub fn run_send_system(&mut self, idx: usize, entities: Entities, resources: Resources){
        let (_name, system_w) = &mut self.systems[idx];
        let system_w = unsafe{ system_w.borrow_mut() };

        #[cfg(feature="stats_events")]
        {
            if let Some(name) = _name {
                match self.enabled_systems.get(name).map(|e| **e) {
                    Some(true) => {
                        let then = time::Instant::now();

                        system_w.run(entities, resources);

                        let now = time::Instant::now();
                        self.stats.push((name.clone(), now - then));
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        system_w.run(entities, resources);
    }

    pub fn run_thread_local_system(&mut self, idx: usize, entities: EntitiesThreadLocal, resources: ResourcesThreadLocal){
        let (_name, system_w) = &mut self.systems_thread_local[idx];

        #[cfg(feature="stats_events")]
        {
            if let Some(name) = _name {
                match self.enabled_systems.get(name).map(|e| **e) {
                    Some(true) => {

                        #[cfg(feature="glin")]
                        {
                            if let Some(mut counter) = self.gpu_stats_counters.get_mut(name){
                                if let Some(duration) = counter.result() {
                                    self.gpu_stats.push((name.clone(), duration));
                                }
                                counter.begin();
                            }
                        }

                        let then = time::Instant::now();
                        system_w.run(entities, resources);
                        let now = time::Instant::now();

                        #[cfg(feature="glin")]
                        {
                            if let Some(mut counter) = self.gpu_stats_counters.get_mut(name){
                                counter.end();
                            }
                        }

                        self.stats.push((name.clone(), now - then));
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        system_w.run(entities, resources);
    }

    pub fn run_creation_system(&mut self, idx: usize, entities: CreationProxy, resources: ResourcesThreadLocal){
        let (_name, system_w) = &mut self.systems_creation[idx];

        #[cfg(feature="stats_events")]
        {
            if let Some(name) = _name {
                match self.enabled_systems.get(name).map(|e| **e) {
                    Some(true) => {

                        #[cfg(feature="glin")]
                        {
                            if let Some(mut counter) = self.gpu_stats_counters.get_mut(name){
                                if let Some(duration) = counter.result() {
                                    self.gpu_stats.push((name.clone(), duration));
                                }
                                counter.begin();
                            }
                        }

                        let then = time::Instant::now();
                        system_w.run(entities, resources);
                        let now = time::Instant::now();

                        #[cfg(feature="glin")]
                        {
                            if let Some(mut counter) = self.gpu_stats_counters.get_mut(name){
                                counter.end();
                            }
                        }
                        self.stats.push((name.clone(), now - then));
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        system_w.run(entities, resources);
    }

    #[cfg(feature = "debug_parameters")]
    pub fn run_debug_system(&mut self, idx: usize, entities: EntitiesDebug, resources: ResourcesThreadLocal){
        let (_name, system_w) = &mut self.systems_debug[idx];

        #[cfg(feature="stats_events")]
        {
            if let Some(name) = _name {
                match self.enabled_systems.get(name).map(|e| **e) {
                    Some(true) => {
                        let then = time::Instant::now();
                        system_w.run(entities, resources);
                        let now = time::Instant::now();
                        self.stats.push((name.clone(), now - then));
                    }
                    Some(false) => (),
                    None => system_w.run(entities, resources),
                }
            }else{
                system_w.run(entities, resources);
            }
        }

        #[cfg(not(feature="stats_events"))]
        system_w.run(entities, resources);
    }

    pub fn add_system<S, TraitObject>(&mut self, system: S, stat: Option<StatsType>) -> Priority
    where  S: AnySystem<TraitObject> + 'static
    {
        let priority = S::priority(S::collection(self).len());

        #[cfg(feature="debug_concurrency")]
        let name = unsafe{
            Some(stat.map(|stat| stat.name().to_owned())
                    .unwrap_or_else(|| type_name::<S>().to_owned()))
        };

        #[cfg(not(feature="debug_concurrency"))]
        let name = stat.map(|stat| stat.name().to_owned());

        // println!("Adding {:?} as {:?}", name, priority);

        S::collection(self).push((name, system.into_trait_object()));

        #[cfg(feature="stats_events")]
        {
            if let Some(stat) = stat {
                self.stats_events.insert(stat.name().to_owned(), SenderRc::new());
                if let StatsType::Gpu(name) = stat{
                    self.gpu_stats_events.insert(name.to_owned(), SenderRc::new());
                }
                self.enabled_systems.insert(stat.name().to_owned(), Property::new(true));
            }
        }

        priority
    }

    #[cfg(feature="stats_events")]
    pub fn stats(&mut self) -> impl Iterator<Item = (&str, Property<'static, time::Duration>)>{
        self.stats_events.iter_mut()
            .map(|(name, sender)| (name.as_str(), sender.stream().to_property(time::Duration::new(0, 0))))
    }

    #[cfg(all(feature="stats_events", feature="glin"))]
    pub fn gpu_stats<C: glin::CreationContext>(&mut self, gl: &C) -> impl Iterator<Item = (&str, Property<'static, time::Duration>)>{
        for stat in self.gpu_stats_events.keys(){
            if !self.gpu_stats_counters.contains_key(stat){
                self.gpu_stats_counters.insert(stat.clone(), gl.new_duration_query());
            }
        }
        self.gpu_stats_events.iter_mut()
            .map(|(name, sender)| (name.as_str(), sender.stream().to_property(time::Duration::new(0, 0))))
    }

    #[cfg(feature="stats_events")]
    pub fn enabled_systems(&mut self) -> impl Iterator<Item = (&str, Property<'static, bool>)>{
        self.enabled_systems.iter()
            .map(|(name, enabled)| (name.as_str(), enabled.clone()))
    }

    #[cfg(feature="debug_concurrency")]
    pub fn send_system_name(&self, i: usize) -> Option<&String>{
        self.systems[i].0.as_ref()
    }

    #[cfg(feature="debug_concurrency")]
    pub fn thread_local_system_name(&self, i: usize) -> Option<&String>{
        self.systems_thread_local[i].0.as_ref()
    }

    #[cfg(feature="debug_concurrency")]
    pub fn creation_system_name(&self, i: usize) -> Option<&String>{
        self.systems_creation[i].0.as_ref()
    }

    #[cfg(any(feature="debug_parameters", feature="debug_concurrency"))]
    pub fn debug_system_name(&self, i: usize) -> Option<&String>{
        self.systems_debug[i].0.as_ref()
    }

    #[cfg(feature="stats_events")]
    pub fn send_stats(&self){
        for stat in self.stats.iter() {
            if let Some(sender) = self.stats_events.get(&stat.0){
                sender.send(stat.1)
            }
        }
        for stat in self.gpu_stats.iter() {
            if let Some(sender) = self.gpu_stats_events.get(&stat.0){
                sender.send(stat.1)
            }
        }
    }
}


pub struct SyncSystem(UnsafeCell<Box<for<'a> ::system::System<'a>>>);

impl SyncSystem{
    fn new<S: for<'a> ::system::System<'a> + 'static>(s: S) -> SyncSystem{
        SyncSystem(UnsafeCell::new(Box::new(s)))
    }

    unsafe fn borrow_mut(&self) -> &mut for<'a> ::system::System<'a>{
        &mut **self.0.get()
    }

    fn _borrow(&self) -> &for<'a> ::system::System<'a>{
        unsafe{ &**self.0.get() }
    }
}

unsafe impl Send for SyncSystem{}
unsafe impl Sync for SyncSystem{}

#[derive(Clone, Copy, Debug)]
pub enum Priority{
    Send(usize),
    ThreadLocal(usize),
    Creation(usize),
    #[cfg(feature="debug_parameters")]
    Debug(usize),
    Barrier
}

#[derive(Copy,Clone,Debug)]
pub enum StatsType<'a>{
    Cpu(&'a str),
    Gpu(&'a str),
}

impl<'a> StatsType<'a>{
    fn name(&self) -> &str{
        match self{
            StatsType::Cpu(name) | StatsType::Gpu(name) => name,
        }
    }
}

pub trait AnySystem<TraitObject>{
    fn collection(systems: &mut Systems) -> &mut Vec<(Option<String>, TraitObject)>;
    fn priority(p: usize) -> Priority;
    fn into_trait_object(self) -> TraitObject;
}

impl<S: for<'a> System<'a> + 'static> AnySystem<SyncSystem> for S{
    fn collection(systems: &mut Systems) -> &mut Vec<(Option<String>, SyncSystem)>{
        &mut systems.systems
    }

    fn priority(p: usize) -> Priority{
        Priority::Send(p)
    }

    fn into_trait_object(self) -> SyncSystem{
        SyncSystem::new(self)
    }
}

impl<S: for<'a> SystemThreadLocal<'a> + 'static> AnySystem<Box<for<'a> SystemThreadLocal<'a>>> for S{
    fn collection(systems: &mut Systems) -> &mut Vec<(Option<String>, Box<for<'a> SystemThreadLocal<'a>>)>{
        &mut systems.systems_thread_local
    }

    fn priority(p: usize) -> Priority{
        Priority::ThreadLocal(p)
    }

    fn into_trait_object(self) -> Box<for<'a> SystemThreadLocal<'a>>{
        Box::new(self)
    }
}

impl<S: for<'a> CreationSystem<'a> + 'static> AnySystem<Box<for<'a> CreationSystem<'a>>> for S{
    fn collection(systems: &mut Systems) -> &mut Vec<(Option<String>, Box<for<'a> CreationSystem<'a>>)>{
        &mut systems.systems_creation
    }

    fn priority(p: usize) -> Priority{
        Priority::Creation(p)
    }

    fn into_trait_object(self) -> Box<for<'a> CreationSystem<'a>>{
        Box::new(self)
    }
}

#[cfg(feature = "debug_parameters")]
impl<S: for<'a> SystemDebug<'a> + 'static> AnySystem<Box<for<'a> SystemDebug<'a>>> for S{
    fn collection(systems: &mut Systems) -> &mut Vec<(Option<String>, Box<for<'a> SystemDebug<'a>>)>{
        &mut systems.systems_debug
    }

    fn priority(p: usize) -> Priority{
        Priority::Debug(p)
    }

    fn into_trait_object(self) -> Box<for<'a> SystemDebug<'a>>{
        Box::new(self)
    }
}