pkecs 9.0.0

Another ECS implementation.
Documentation
//! Provides public APIs to insert resources into the ECS from a system.

use std::{any::Any, hash::Hash};
use super::{
    component::Components,
    event::EventQueues,
    system::param::SystemParameter,
    world::UnsafeWorldCell,
};

/// Allows for the addition of components.
pub struct ComponentCommands<'w> {
    components: &'w mut Components,
}

impl<'w> ComponentCommands<'w> {
    /// Initializes [`self`] from a mutable reference to [`Components`].
    pub const fn from_components(components: &'w mut Components) -> Self {
        Self { components }
    }

    /// Adds a component to [`self`].
    pub fn spawn<T>(&mut self, component: T) -> &mut Self
        where
            T: 'static,
    {
        self.components.spawn(component);

        self
    }

    /// Adds an indexed component to [`self`].
    pub fn spawn_indexed<TKey, TValue>(&mut self, key: TKey, component: TValue) -> &mut Self
        where
            TKey: Eq + Hash + 'static,
            TValue: 'static,
    {
        self.components.spawn_indexed(key, component);

        self
    }
}

impl<'w> SystemParameter for ComponentCommands<'w> {
    fn fetch(cell: &UnsafeWorldCell) -> Self {
        let world = cell.get_mut();
        let components = world.components_mut();

        Self { components }
    }
}

pub struct EventCommands<'w> {
    events: &'w mut EventQueues,
}

impl<'w> EventCommands<'w> {
    /// Initializes [`self`] from a mutable reference to [`EventQueues`].
    pub const fn from_events(events: &'w mut EventQueues) -> Self {
        Self { events }
    }

    pub fn queue<E>(&mut self, event: E) -> &mut Self
        where
            E: Any + 'static,
    {
        self.events.queue(event);

        self
    }
}

impl<'w> SystemParameter for EventCommands<'w> {
    fn fetch(cell: &UnsafeWorldCell) -> Self {
        let world = cell.get_mut();
        let events = world.events_mut();

        Self::from_events(events)
    }
}