async-ecs 0.1.0

Async Parallel Entity Component System for Rust
Documentation
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use std::fmt::Debug;

use hashbrown::hash_map::{Entry, HashMap};
use tokio::{
    sync::watch::channel,
    task::{spawn as spawn_task, spawn_local},
};

use crate::{
    access::Accessor,
    resource::ResourceId,
    system::{AsyncSystem, System},
    world::World,
};

use super::{
    task::{execute_local, execute_local_async, execute_thread, execute_thread_async},
    Dispatcher, Error, LocalRun, LocalRunAsync, Receiver, Sender, SharedWorld, ThreadRun,
    ThreadRunAsync,
};

/// Id of a system inside the `Dispatcher` and the `Builder`.
#[derive(Default, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct SystemId(pub usize);

/// Builder for the [`Dispatcher`].
///
/// [`Dispatcher`]: struct.Dispatcher.html
///
/// ## Barriers
///
/// Barriers are a way of sequentializing parts of
/// the system execution. See `add_barrier()`/`with_barrier()`.
///
/// ## Examples
///
/// This is how you create a dispatcher with
/// a shared thread pool:
///
/// ```rust
/// # #![allow(unused)]
/// #
/// # use async_ecs::*;
/// #
/// # #[derive(Debug, Default)]
/// # struct Res;
/// #
/// # #[derive(SystemData)]
/// # struct Data<'a> { a: Read<'a, Res> }
/// #
/// # struct Dummy;
/// #
/// # impl<'a> System<'a> for Dummy {
/// #   type SystemData = Data<'a>;
/// #
/// #   fn run(&mut self, _: Data<'a>) {}
/// # }
/// #
/// # #[tokio::main]
/// # async fn main() {
/// # let system_a = Dummy;
/// # let system_b = Dummy;
/// # let system_c = Dummy;
/// # let system_d = Dummy;
/// # let system_e = Dummy;
/// #
/// let dispatcher = Dispatcher::builder()
///     .with(system_a, "a", &[])
///     .unwrap()
///     .with(system_b, "b", &["a"])
///     .unwrap() // b depends on a
///     .with(system_c, "c", &["a"])
///     .unwrap() // c also depends on a
///     .with(system_d, "d", &[])
///     .unwrap()
///     .with(system_e, "e", &["c", "d"])
///     .unwrap() // e executes after c and d are finished
///     .build();
/// # }
/// ```
///
/// Systems can be conditionally added by using the `add_` functions:
///
/// ```rust
/// # #![allow(unused)]
/// #
/// # use async_ecs::*;
/// #
/// # #[derive(Debug, Default)]
/// # struct Res;
/// #
/// # #[derive(SystemData)]
/// # struct Data<'a> { a: Read<'a, Res> }
/// #
/// # struct Dummy;
/// #
/// # impl<'a> System<'a> for Dummy {
/// #   type SystemData = Data<'a>;
/// #
/// #   fn run(&mut self, _: Data<'a>) {}
/// # }
/// #
/// # #[tokio::main]
/// # async fn main() {
/// # let b_enabled = true;
/// # let system_a = Dummy;
/// # let system_b = Dummy;
/// let mut builder = Dispatcher::builder().with(system_a, "a", &[]).unwrap();
///
/// if b_enabled {
///     builder.add(system_b, "b", &[]).unwrap();
/// }
///
/// let dispatcher = builder.build();
/// # }
/// ```
pub struct Builder<'a> {
    world: Option<&'a mut World>,
    next_id: SystemId,
    items: HashMap<SystemId, Item>,
    names: HashMap<String, SystemId>,
}

impl<'a> Builder<'a> {
    pub fn new(world: Option<&'a mut World>) -> Self {
        Self {
            world,
            next_id: Default::default(),
            items: Default::default(),
            names: Default::default(),
        }
    }

    /// Builds the `Dispatcher`.
    ///
    /// This method will precompute useful information in order to speed up dispatching.
    pub fn build(self) -> Dispatcher {
        let receivers = self
            .final_systems()
            .into_iter()
            .map(|id| self.items.get(&id).unwrap().receiver.clone())
            .collect();

        let world = SharedWorld::default();
        let (sender, receiver) = channel(());

        for (_, item) in self.items.into_iter() {
            let run = item.run;
            let name = item.name;
            let sender = item.sender;
            let receivers = if item.dependencies.is_empty() {
                vec![receiver.clone()]
            } else {
                item.receivers
            };

            match run {
                RunType::Thread(run) => {
                    spawn_task(execute_thread(name, run, sender, receivers, world.clone()))
                }
                RunType::Local(run) => {
                    spawn_local(execute_local(name, run, sender, receivers, world.clone()))
                }
                RunType::ThreadAsync(run) => spawn_task(execute_thread_async(
                    name,
                    run,
                    sender,
                    receivers,
                    world.clone(),
                )),
                RunType::LocalAsync(run) => spawn_local(execute_local_async(
                    name,
                    run,
                    sender,
                    receivers,
                    world.clone(),
                )),
            };
        }

        Dispatcher {
            sender,
            receivers,
            world,
        }
    }

    /// Adds a new system with a given name and a list of dependencies.
    /// Please note that the dependency should be added before
    /// you add the depending system.
    ///
    /// If you want to register systems which can not be specified as
    /// dependencies, you can use `""` as their name, which will not panic
    /// (using another name twice will).
    ///
    /// Same as [`add()`](struct.Dispatcher::builder().html#method.add), but
    /// returns `self` to enable method chaining.
    pub fn with<S>(mut self, system: S, name: &str, dependencies: &[&str]) -> Result<Self, Error>
    where
        S: for<'s> System<'s> + Send + 'static,
    {
        self.add(system, name, dependencies)?;

        Ok(self)
    }

    /// Adds a new system with a given name and a list of dependencies.
    /// Please note that the dependency should be added before
    /// you add the depending system.
    ///
    /// If you want to register systems which can not be specified as
    /// dependencies, you can use `""` as their name, which will not panic
    /// (using another name twice will).
    pub fn add<S>(
        &mut self,
        mut system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<&mut Self, Error>
    where
        S: for<'s> System<'s> + Send + 'static,
    {
        self.add_inner(
            name,
            dependencies,
            system.accessor().reads(),
            system.accessor().writes(),
            |this, id| {
                if let Some(ref mut w) = this.world {
                    system.setup(w)
                }

                match this.items.entry(id) {
                    Entry::Vacant(e) => e.insert(Item::thread(name.into(), system)),
                    Entry::Occupied(_) => panic!("Item was already created!"),
                }
            },
        )?;

        Ok(self)
    }

    /// Adds a new asynchronous system with a given name and a list of dependencies.
    /// Please note that the dependency should be added before
    /// you add the depending system.
    ///
    /// If you want to register systems which can not be specified as
    /// dependencies, you can use `""` as their name, which will not panic
    /// (using another name twice will).
    ///
    /// Same as [`add()`](struct.Dispatcher::builder().html#method.add), but
    /// returns `self` to enable method chaining.
    pub fn with_async<S>(
        mut self,
        system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<Self, Error>
    where
        S: for<'s> AsyncSystem<'s> + Send + 'static,
    {
        self.add_async(system, name, dependencies)?;

        Ok(self)
    }

    /// Adds a new asynchronous system with a given name and a list of dependencies.
    /// Please note that the dependency should be added before
    /// you add the depending system.
    ///
    /// If you want to register systems which can not be specified as
    /// dependencies, you can use `""` as their name, which will not panic
    /// (using another name twice will).
    pub fn add_async<S>(
        &mut self,
        mut system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<&mut Self, Error>
    where
        S: for<'s> AsyncSystem<'s> + Send + 'static,
    {
        self.add_inner(
            name,
            dependencies,
            system.accessor().reads(),
            system.accessor().writes(),
            |this, id| {
                if let Some(ref mut w) = this.world {
                    system.setup(w)
                }

                match this.items.entry(id) {
                    Entry::Vacant(e) => e.insert(Item::thread_async(name.into(), system)),
                    Entry::Occupied(_) => panic!("Item was already created!"),
                }
            },
        )?;

        Ok(self)
    }

    /// Adds a new thread local system.
    ///
    /// Please only use this if your struct is not `Send` and `Sync`.
    ///
    /// Thread-local systems are dispatched in-order.
    ///
    /// Same as [Dispatcher::builder()::add_local], but returns `self` to
    /// enable method chaining.
    pub fn with_local<S>(
        mut self,
        system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<Self, Error>
    where
        S: for<'s> System<'s> + 'static,
    {
        self.add_local(system, name, dependencies)?;

        Ok(self)
    }

    /// Adds a new thread local system.
    ///
    /// Please only use this if your struct is not `Send` and `Sync`.
    ///
    /// Thread-local systems are dispatched in-order.
    pub fn add_local<S>(
        &mut self,
        mut system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<&mut Self, Error>
    where
        S: for<'s> System<'s> + 'static,
    {
        self.add_inner(
            name,
            dependencies,
            system.accessor().reads(),
            system.accessor().writes(),
            |this, id| {
                if let Some(ref mut w) = this.world {
                    system.setup(w)
                }

                match this.items.entry(id) {
                    Entry::Vacant(e) => e.insert(Item::local(name.into(), system)),
                    Entry::Occupied(_) => panic!("Item was already created!"),
                }
            },
        )?;

        Ok(self)
    }

    /// Adds a new thread local asynchronous system.
    ///
    /// Please only use this if your struct is not `Send` and `Sync`.
    ///
    /// Thread-local systems are dispatched in-order.
    ///
    /// Same as [Dispatcher::builder()::add_local], but returns `self` to
    /// enable method chaining.
    pub fn with_local_async<S>(
        mut self,
        system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<Self, Error>
    where
        S: for<'s> AsyncSystem<'s> + 'static,
    {
        self.add_local_async(system, name, dependencies)?;

        Ok(self)
    }

    /// Adds a new thread local asynchronous system.
    ///
    /// Please only use this if your struct is not `Send` and `Sync`.
    ///
    /// Thread-local systems are dispatched in-order.
    pub fn add_local_async<S>(
        &mut self,
        mut system: S,
        name: &str,
        dependencies: &[&str],
    ) -> Result<&mut Self, Error>
    where
        S: for<'s> AsyncSystem<'s> + 'static,
    {
        self.add_inner(
            name,
            dependencies,
            system.accessor().reads(),
            system.accessor().writes(),
            |this, id| {
                if let Some(ref mut w) = this.world {
                    system.setup(w)
                }

                match this.items.entry(id) {
                    Entry::Vacant(e) => e.insert(Item::local_async(name.into(), system)),
                    Entry::Occupied(_) => panic!("Item was already created!"),
                }
            },
        )?;

        Ok(self)
    }

    fn add_inner<F>(
        &mut self,
        name: &str,
        dependencies: &[&str],
        mut reads: Vec<ResourceId>,
        mut writes: Vec<ResourceId>,
        f: F,
    ) -> Result<&mut Self, Error>
    where
        F: FnOnce(&mut Self, SystemId) -> &mut Item,
    {
        let name = name.to_owned();
        let id = self.next_id();
        let id = match self.names.entry(name) {
            Entry::Vacant(e) => Ok(*e.insert(id)),
            Entry::Occupied(e) => Err(Error::NameAlreadyRegistered(e.key().into())),
        }?;

        reads.sort();
        writes.sort();

        reads.dedup();
        writes.dedup();

        let mut dependencies = dependencies
            .iter()
            .map(|name| {
                self.names
                    .get(*name)
                    .map(Clone::clone)
                    .ok_or_else(|| Error::DependencyWasNotFound((*name).into()))
            })
            .collect::<Result<Vec<_>, _>>()?;

        for read in &reads {
            for (key, value) in &self.items {
                if value.writes.contains(read) {
                    dependencies.push(*key);
                }
            }
        }

        for write in &writes {
            for (key, value) in &self.items {
                if value.reads.contains(write) || value.writes.contains(write) {
                    dependencies.push(*key);
                }
            }
        }

        self.reduce_dependencies(&mut dependencies);

        let receivers = dependencies
            .iter()
            .map(|id| self.items.get(id).unwrap().receiver.clone())
            .collect();

        let item = f(self, id);

        item.reads = reads;
        item.writes = writes;
        item.receivers = receivers;
        item.dependencies = dependencies;

        Ok(self)
    }

    fn final_systems(&self) -> Vec<SystemId> {
        let mut ret = self.items.keys().map(Clone::clone).collect();

        self.reduce_dependencies(&mut ret);

        ret
    }

    fn reduce_dependencies(&self, dependencies: &mut Vec<SystemId>) {
        dependencies.sort();
        dependencies.dedup();

        let mut remove_indices = Vec::new();
        for (i, a) in dependencies.iter().enumerate() {
            for (j, b) in dependencies.iter().enumerate() {
                if self.depends_on(a, b) {
                    remove_indices.push(j);
                } else if self.depends_on(b, a) {
                    remove_indices.push(i);
                }
            }
        }

        remove_indices.sort_unstable();
        remove_indices.dedup();
        remove_indices.reverse();

        for i in remove_indices {
            dependencies.remove(i);
        }
    }

    fn depends_on(&self, a: &SystemId, b: &SystemId) -> bool {
        let item = self.items.get(a).unwrap();

        if item.dependencies.contains(b) {
            return true;
        }

        for d in &item.dependencies {
            if self.depends_on(d, b) {
                return true;
            }
        }

        false
    }

    fn next_id(&mut self) -> SystemId {
        self.next_id.0 += 1;

        self.next_id
    }
}

/// Defines how to execute the `System` with the `Dispatcher`.
enum RunType {
    Thread(ThreadRun),
    Local(LocalRun),
    ThreadAsync(ThreadRunAsync),
    LocalAsync(LocalRunAsync),
}

/// Item that wraps all information of a 'System` within the `Builder`.
struct Item {
    name: String,
    run: RunType,

    sender: Sender,
    receiver: Receiver,
    receivers: Vec<Receiver>,

    reads: Vec<ResourceId>,
    writes: Vec<ResourceId>,
    dependencies: Vec<SystemId>,
}

impl Item {
    fn new(name: String, run: RunType) -> Self {
        let (sender, receiver) = channel(());

        Self {
            name,
            run,

            sender,
            receiver,
            receivers: Vec::new(),

            reads: Vec::new(),
            writes: Vec::new(),
            dependencies: Vec::new(),
        }
    }

    fn thread<S>(name: String, system: S) -> Self
    where
        S: for<'s> System<'s> + Send + 'static,
    {
        Self::new(name, RunType::Thread(Box::new(system)))
    }

    fn local<S>(name: String, system: S) -> Self
    where
        S: for<'s> System<'s> + 'static,
    {
        Self::new(name, RunType::Local(Box::new(system)))
    }

    fn thread_async<S>(name: String, system: S) -> Self
    where
        S: for<'s> AsyncSystem<'s> + Send + 'static,
    {
        Self::new(name, RunType::ThreadAsync(Box::new(system)))
    }

    fn local_async<S>(name: String, system: S) -> Self
    where
        S: for<'s> AsyncSystem<'s> + 'static,
    {
        Self::new(name, RunType::LocalAsync(Box::new(system)))
    }
}

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

    use crate::{
        access::AccessorCow,
        system::{DynamicSystemData, System},
        world::World,
    };

    #[test]
    fn dependencies_on_read_and_write() {
        /*
            - Systems ------------------------------------
                Id:     1       2       3       4       5

            - Resources ----------------------------------
                Read:   A       A       B       C       A
                Write:  B       C       D       D      BCD

            - Dependencies Total -------------------------
                        |       |       |       |       |
                        |<--------------|       |       |
                        |       |       |       |       |
                        |       |<--------------|       |
                        |       |       |<------|       |
                        |       |       |       |       |
                        |<------------------------------|
                        |       |<----------------------|
                        |       |       |<--------------|
                        |       |       |       |<------|
                        |       |       |       |       |

            - Dependencies Reduced -----------------------
                        |       |       |       |       |
                        |<--------------|       |       |
                        |       |       |       |       |
                        |       |<--------------|       |
                        |       |       |<------|       |
                        |       |       |       |       |
                        |       |       |       |<------|
                        |       |       |       |       |
        */

        struct ResA;
        struct ResB;
        struct ResC;
        struct ResD;

        let sys1 = TestSystem::new(
            vec![ResourceId::new::<ResA>()],
            vec![ResourceId::new::<ResB>()],
        );
        let sys2 = TestSystem::new(
            vec![ResourceId::new::<ResA>()],
            vec![ResourceId::new::<ResC>()],
        );
        let sys3 = TestSystem::new(
            vec![ResourceId::new::<ResB>()],
            vec![ResourceId::new::<ResD>()],
        );
        let sys4 = TestSystem::new(
            vec![ResourceId::new::<ResC>()],
            vec![ResourceId::new::<ResD>()],
        );
        let sys5 = TestSystem::new(
            vec![ResourceId::new::<ResA>()],
            vec![
                ResourceId::new::<ResB>(),
                ResourceId::new::<ResC>(),
                ResourceId::new::<ResD>(),
            ],
        );

        let dispatcher = Dispatcher::builder()
            .with(sys1, "sys1", &[])
            .unwrap()
            .with(sys2, "sys2", &[])
            .unwrap()
            .with(sys3, "sys3", &[])
            .unwrap()
            .with(sys4, "sys4", &[])
            .unwrap()
            .with(sys5, "sys5", &[])
            .unwrap();

        let sys1 = dispatcher.items.get(&SystemId(1)).unwrap();
        let sys2 = dispatcher.items.get(&SystemId(2)).unwrap();
        let sys3 = dispatcher.items.get(&SystemId(3)).unwrap();
        let sys4 = dispatcher.items.get(&SystemId(4)).unwrap();
        let sys5 = dispatcher.items.get(&SystemId(5)).unwrap();

        assert_eq!(sys1.dependencies, vec![]);
        assert_eq!(sys2.dependencies, vec![]);
        assert_eq!(sys3.dependencies, vec![SystemId(1)]);
        assert_eq!(sys4.dependencies, vec![SystemId(2), SystemId(3)]);
        assert_eq!(sys5.dependencies, vec![SystemId(4)]);
        assert_eq!(dispatcher.final_systems(), vec![SystemId(5)]);
    }

    struct TestSystem {
        accessor: TestAccessor,
    }

    impl TestSystem {
        fn new(reads: Vec<ResourceId>, writes: Vec<ResourceId>) -> Self {
            Self {
                accessor: TestAccessor { reads, writes },
            }
        }
    }

    impl<'a> System<'a> for TestSystem {
        type SystemData = TestData;

        fn run(&mut self, _data: Self::SystemData) {
            unimplemented!()
        }

        fn accessor<'b>(&'b self) -> AccessorCow<'a, 'b, Self::SystemData> {
            AccessorCow::Borrow(&self.accessor)
        }
    }

    struct TestData;

    impl<'a> DynamicSystemData<'a> for TestData {
        type Accessor = TestAccessor;

        fn setup(_accessor: &Self::Accessor, _world: &mut World) {}

        fn fetch(_access: &Self::Accessor, _world: &'a World) -> Self {
            TestData
        }
    }

    struct TestAccessor {
        reads: Vec<ResourceId>,
        writes: Vec<ResourceId>,
    }

    impl Accessor for TestAccessor {
        fn reads(&self) -> Vec<ResourceId> {
            self.reads.clone()
        }

        fn writes(&self) -> Vec<ResourceId> {
            self.writes.clone()
        }
    }
}