summaryrefslogtreecommitdiff
path: root/ecs/src/extension.rs
blob: a945d898e8eca8bb28c448bd66572669aee420aa (plain)
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
use crate::component::Sequence as ComponentSequence;
use crate::event::component::TypeTransformComponentsToAddedEvents;
use crate::event::{Event, Sequence as EventSequence};
use crate::sole::Sole;
use crate::system::System;
use crate::tuple::Reduce as TupleReduce;
use crate::{SoleAlreadyExistsError, World};

/// A collection of systems, entities & soles that can be added to a [`World`].
pub trait Extension
{
    fn collect(self, collector: Collector<'_>);
}

/// Passed to a [`Extension`] to collects it's systems, entities & soles.
pub struct Collector<'world>
{
    world: &'world mut World,
}

impl<'world> Collector<'world>
{
    /// Returns a new `Collector` for the given [`World`].
    pub fn new(world: &'world mut World) -> Self
    {
        Self { world }
    }

    /// Adds a system to the [`World`].
    pub fn add_system<'this, EventT, SystemImpl>(
        &'this mut self,
        event: EventT,
        system: impl System<'this, SystemImpl>,
    ) where
        EventT: Event,
    {
        self.world.register_system(event, system);
    }

    /// Adds a entity to the [`World`].
    pub fn add_entity<Comps>(&mut self, components: Comps)
    where
        Comps: ComponentSequence + TupleReduce<TypeTransformComponentsToAddedEvents>,
        Comps::Out: EventSequence,
    {
        self.world.create_entity(components);
    }

    /// Adds a globally shared singleton value to the [`World`].
    ///
    /// # Errors
    /// Returns `Err` if this [`Sole`] has already been added.
    pub fn add_sole<SoleT>(&mut self, sole: SoleT) -> Result<(), SoleAlreadyExistsError>
    where
        SoleT: Sole,
    {
        self.world.add_sole(sole)
    }
}