[][src]Crate specs

SPECS Parallel ECS

This library provides an ECS variant designed for parallel execution and convenient usage. It is highly flexible when it comes to actual component data and the way it is stored and accessed.

Features:

  • depending on chosen features either 0 virtual function calls or one per system
  • parallel iteration over components
  • parallel execution of systems

High-level overview

One could basically split this library up into two parts: The data part and the execution part.

The data

World is where component storages, resources and entities are stored. See the docs of World for more.

Components can be easily implemented like this:

use specs::prelude::*;

struct MyComp;

impl Component for MyComp {
    type Storage = VecStorage<Self>;
}

Or alternatively, if you enable the specs-derive feature, you can use a custom #[derive] macro:

use specs::{prelude::*, Component};

#[derive(Component)]
#[storage(VecStorage)] // default is `DenseVecStorage`
struct MyComp;

You can choose different storages according to your needs.

These storages can be joined together, for example joining a Velocity and a Position storage means you'll only get entities which have both of them. Thanks to rayon, this is even possible in parallel! See ParJoin for more.

System execution

Here we have System and Dispatcher as our core types. Both types are provided by a library called shred.

The Dispatcher can be seen as an optional part here; it allows dispatching the systems in parallel, given a list of systems and their dependencies on other systems.

If you don't like it, you can also execute the systems yourself by using RunNow.

Systems are traits with a run() method and an associated SystemData, allowing type-safe aspects (knowledge about the reads / writes of the systems).

Examples

This is a basic example of using Specs:

extern crate specs;

use specs::prelude::*;

// A component contains data which is
// associated with an entity.

struct Vel(f32);

impl Component for Vel {
    type Storage = VecStorage<Self>;
}

struct Pos(f32);

impl Component for Pos {
    type Storage = VecStorage<Self>;
}

struct SysA;

impl<'a> System<'a> for SysA {
    // These are the resources required for execution.
    // You can also define a struct and `#[derive(SystemData)]`,
    // see the `full` example.
    type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>);

    fn run(&mut self, (mut pos, vel): Self::SystemData) {
        // The `.join()` combines multiple components,
        // so we only access those entities which have
        // both of them.

        // This joins the component storages for Position
        // and Velocity together; it's also possible to do this
        // in parallel using rayon's `ParallelIterator`s.
        // See `ParJoin` for more.
        for (pos, vel) in (&mut pos, &vel).join() {
            pos.0 += vel.0;
        }
    }
}

fn main() {
    // The `World` is our
    // container for components
    // and other resources.

    let mut world = World::new();
    world.register::<Pos>();
    world.register::<Vel>();

    // An entity may or may not contain some component.

    world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build();
    world.create_entity().with(Vel(4.0)).with(Pos(1.6)).build();
    world.create_entity().with(Vel(1.5)).with(Pos(5.4)).build();

    // This entity does not have `Vel`, so it won't be dispatched.
    world.create_entity().with(Pos(2.0)).build();

    // This builds a dispatcher.
    // The third parameter of `add` specifies
    // logical dependencies on other systems.
    // Since we only have one, we don't depend on anything.
    // See the `full` example for dependencies.
    let mut dispatcher = DispatcherBuilder::new().with(SysA, "sys_a", &[]).build();

    // This dispatches all the systems in parallel (but blocking).
    dispatcher.dispatch(&mut world);
}

You can also easily create new entities on the fly:

use specs::prelude::*;

struct EnemySpawner;

impl<'a> System<'a> for EnemySpawner {
    type SystemData = Entities<'a>;

    fn run(&mut self, entities: Entities<'a>) {
        let enemy = entities.create();
    }
}

See the repository's examples directory for more examples.

Re-exports

pub extern crate hibitset;
pub extern crate rayon;
pub extern crate shred;
pub extern crate shrev;
pub extern crate uuid;
pub use crate::changeset::ChangeSet;
pub use crate::join::Join;
pub use crate::storage::Storage;
pub use crate::world::Builder;
pub use crate::world::EntityBuilder;

Modules

changeset

Provides a changeset that can be collected from an iterator.

error

Specs errors

join

Joining of components for iteration over entities with specific components.

prelude

Prelude module

saveload

Save and load entities from various formats with serde.

storage

Component storage types, implementations for component joins, etc.

world

Entities, resources, components, and general world management.

Structs

AsyncDispatcher

Like, Dispatcher but works asynchronously.

BatchAccessor

The BatchAccessor is used to notify the main dispatcher of the read and write resources of the Systems contained in the batch ("sub systems").

BatchUncheckedWorld

The BatchUncheckedWorld wraps an instance of the world. You have to specify this as SystemData for a System implementing BatchController.

BitSet

A BitSet is a simple set designed to track which indices are placed into it.

DefaultBatchControllerSystem

The DefaultBatchControllerSystem is a simple implementation that will dispatch the inner dispatcher one time.

DenseVecStorage

Dense vector storage. Has a redirection 2-way table between entities and components, allowing to leave no gaps within the data.

Dispatcher

The dispatcher struct, allowing systems to be executed in parallel.

DispatcherBuilder

Builder for the Dispatcher.

Entity

Entity type, as seen by the user.

FlaggedStorage

Wrapper storage that tracks modifications, insertions, and removals of components through an EventChannel.

HashMapStorage

HashMap-based storage. Best suited for rare components.

LazyUpdate

Lazy updates can be used for world updates that need to borrow a lot of resources and as such should better be done at the end. They work lazily in the sense that they are dispatched when calling world.maintain().

NullStorage

A null storage type, used for cases where the component doesn't contain any data and instead works as a simple flag.

Read

Allows to fetch a resource in a system immutably.

ReaderId

A reader ID which represents a subscription to the events pushed to the EventChannel.

StaticAccessor

The static accessor that is used for SystemData.

VecStorage

Vector storage. Uses a simple Vec. Supposed to have maximum performance for the components mostly present in entities.

World

A [Resource] container, which provides methods to insert, access and manage the contained resources.

Write

Allows to fetch a resource in a system mutably.

Enums

AccessorCow

Either an Accessor of the system T or a reference to it.

RunningTime

Traits

Accessor

A trait for accessing read/write multiple resources from a system. This can be used to create dynamic systems that don't specify what they fetch at compile-time.

BatchController

The BatchController is the additional trait that a normal System must implement in order to be used as a system controlling the execution of a batch.

Component

Abstract component type. Doesn't have to be Copy or even Clone.

ParJoin

The purpose of the ParJoin trait is to provide a way to access multiple storages in parallel at the same time with the merged bit set.

RunNow

Trait for fetching data and running systems. Automatically implemented for systems.

System

A System, executed with a set of required Resources.

SystemData

A static system data that can specify its dependencies at statically (at compile-time). Most system data is a SystemData, the DynamicSystemData type is only needed for very special setups.

Tracked

UnprotectedStorages that track modifications, insertions, and removals of components.

WorldExt

This trait provides some extension methods to make working with shred's World easier.

Type Definitions

Entities

A wrapper for a read Entities resource. Note that this is just Read<Entities>, so you can easily use it in your system:

ReadExpect

Allows to fetch a resource in a system immutably. This will panic if the resource does not exist. Usage of Read or Option<Read> is therefore recommended.

ReadStorage

A storage with read access.

WriteExpect

Allows to fetch a resource in a system mutably. This will panic if the resource does not exist. Usage of Write or Option<Write> is therefore recommended.

WriteStorage

A storage with read and write access.

Derive Macros

Component

Custom derive macro for the Component trait.

ConvertSaveload

Custom derive macro for the ConvertSaveload trait.

SystemData

Used to #[derive] the trait SystemData.