EntityX - A fast, type-safe C++ Entity-Component system

Overview

EntityX - A fast, type-safe C++ Entity Component System

Build Status Build status Gitter chat

NOTE: The current stable release 1.0.0 breaks backward compatibility with < 1.0.0. See the change log for details.

Entity Component Systems (ECS) are a form of decomposition that completely decouples entity logic and data from the entity "objects" themselves. The Evolve your Hierarchy article provides a solid overview of EC systems and why you should use them.

EntityX is an EC system that uses C++11 features to provide type-safe component management, event delivery, etc. It was built during the creation of a 2D space shooter.

Downloading

You can acquire stable releases here.

Alternatively, you can check out the current development version with:

git clone https://github.com/alecthomas/entityx.git

See below for installation instructions.

Contact

Feel free to jump on my Gitter channel if you have any questions/comments. This is a single channel for all of my projects, so please mention you're asking about EntityX to avoid (my) confusion.

You can also contact me directly via email or Twitter.

Benchmarks / Comparisons

EntityX includes its own benchmarks, but @abeimler has created a benchmark suite testing up to 2M entities in EntityX, the EntityX compile-time branch, Anax, and Artemis C++.

Recent Notable Changes

  • 2014-03-02 - (1.0.0alpha1) Switch to using cache friendly component storage (big breaking change). Also eradicated use of std::shared_ptr for components.
  • 2014-02-13 - Visual C++ support thanks to Jarrett Chisholm!
  • 2013-10-29 - Boost has been removed as a primary dependency for builds not using python.
  • 2013-08-21 - Remove dependency on boost::signal and switch to embedded Simple::Signal.
  • 2013-08-18 - Destroying an entity invalidates all other references
  • 2013-08-17 - Python scripting, and a more robust build system

See the ChangeLog for details.

EntityX extensions and example applications

DEPRECATED - 0.1.x ONLY

Example

An SFML2 example application is available that shows most of EntityX's concepts. It spawns random circles on a 2D plane moving in random directions. If two circles collide they will explode and emit particles. All circles and particles are entities.

It illustrates:

  • Separation of data via components.
  • Separation of logic via systems.
  • Use of events (colliding bodies trigger a CollisionEvent).

Compile with:

c++ -O3 -std=c++11 -Wall -lsfml-system -lsfml-window -lsfml-graphics -lentityx example.cc -o example

Overview

In EntityX data associated with an entity is called a entityx::Component. Systems encapsulate logic and can use as many component types as necessary. An entityx::EventManager allows systems to interact without being tightly coupled. Finally, a Manager object ties all of the systems together for convenience.

As an example, a physics system might need position and mass data, while a collision system might only need position - the data would be logically separated into two components, but usable by any system. The physics system might emit collision events whenever two entities collide.

Tutorial

Following is some skeleton code that implements Position and Direction components, a MovementSystem using these data components, and a CollisionSystem that emits Collision events when two entities collide.

To start with, add the following line to your source file:

#include "entityx/entityx.h"

Entities

An entityx::Entity is a convenience class wrapping an opaque uint64_t value allocated by the entityx::EntityManager. Each entity has a set of components associated with it that can be added, queried or retrieved directly.

Creating an entity is as simple as:

#include <entityx/entityx.h>

entityx::EntityX ex;

entityx::Entity entity = ex.entities.create();

And destroying an entity is done with:

entity.destroy();

Implementation details

  • Each entityx::Entity is a convenience class wrapping an entityx::Entity::Id.
  • An entityx::Entity handle can be invalidated with invalidate(). This does not affect the underlying entity.
  • When an entity is destroyed the manager adds its ID to a free list and invalidates the entityx::Entity handle.
  • When an entity is created IDs are recycled from the free list first, before allocating new ones.
  • An entityx::Entity ID contains an index and a version. When an entity is destroyed, the version associated with the index is incremented, invalidating all previous entities referencing the previous ID.
  • To improve cache coherence, components are constructed in contiguous memory ranges by using entityx::EntityManager::assign<C>(id, ...).

Components (entity data)

The general idea with the EntityX interpretation of ECS is to have as little logic in components as possible. All logic should be contained in Systems.

To that end Components are typically POD types consisting of self-contained sets of related data. Components can be any user defined struct/class.

Creating components

As an example, position and direction information might be represented as:

struct Position {
  Position(float x = 0.0f, float y = 0.0f) : x(x), y(y) {}

  float x, y;
};

struct Direction {
  Direction(float x = 0.0f, float y = 0.0f) : x(x), y(y) {}

  float x, y;
};

Assigning components to entities

To associate a component with a previously created entity call entityx::Entity::assign<C>() with the component type, and any component constructor arguments:

// Assign a Position with x=1.0f and y=2.0f to "entity"
entity.assign<Position>(1.0f, 2.0f);

Querying entities and their components

To query all entities with a set of components assigned you can use two methods. Both methods will return only those entities that have all of the specified components associated with them.

entityx::EntityManager::each(f) provides functional-style iteration over entity components:

entities.each<Position, Direction>([](Entity entity, Position &position, Direction &direction) {
  // Do things with entity, position and direction.
});

For iterator-style traversal of components, use entityx::EntityManager::entities_with_components():

ComponentHandle<Position> position;
ComponentHandle<Direction> direction;
for (Entity entity : entities.entities_with_components(position, direction)) {
  // Do things with entity, position and direction.
}

To retrieve a component associated with an entity use entityx::Entity::component<C>():

ComponentHandle<Position> position = entity.component<Position>();
if (position) {
  // Do stuff with position
}

Component dependencies

In the case where a component has dependencies on other components, a helper class exists that will automatically create these dependencies.

eg. The following will also add Position and Direction components when a Physics component is added to an entity.

#include "entityx/deps/Dependencies.h"

system_manager->add<entityx::deps::Dependency<Physics, Position, Direction>>();

Implementation notes

  • Components must provide a no-argument constructor.
  • The default implementation can handle up to 64 components in total. This can be extended by changing the entityx::EntityManager::MAX_COMPONENTS constant.
  • Each type of component is allocated in (mostly) contiguous blocks to improve cache coherency.

Systems (implementing behavior)

Systems implement behavior using one or more components. Implementations are subclasses of System<T> and must implement the update() method, as shown below.

A basic movement system might be implemented with something like the following:

struct MovementSystem : public System<MovementSystem> {
  void update(entityx::EntityManager &es, entityx::EventManager &events, TimeDelta dt) override {
    es.each<Position, Direction>([dt](Entity entity, Position &position, Direction &direction) {
      position.x += direction.x * dt;
      position.y += direction.y * dt;
    });
  };
};

Events (communicating between systems)

Events are objects emitted by systems, typically when some condition is met. Listeners subscribe to an event type and will receive a callback for each event object emitted. An entityx::EventManager coordinates subscription and delivery of events between subscribers and emitters. Typically subscribers will be other systems, but need not be. Events are not part of the original ECS pattern, but they are an efficient alternative to component flags for sending infrequent data.

As an example, we might want to implement a very basic collision system using our Position data from above.

Creating event types

First, we define the event type, which for our example is simply the two entities that collided:

struct Collision {
  Collision(entityx::Entity left, entityx::Entity right) : left(left), right(right) {}

  entityx::Entity left, right;
};

Emitting events

Next we implement our collision system, which emits Collision objects via an entityx::EventManager instance whenever two entities collide.

class CollisionSystem : public System<CollisionSystem> {
 public:
  void update(entityx::EntityManager &es, entityx::EventManager &events, TimeDelta dt) override {
    ComponentHandle<Position> left_position, right_position;
    for (Entity left_entity : es.entities_with_components(left_position)) {
      for (Entity right_entity : es.entities_with_components(right_position)) {
        if (collide(left_position, right_position)) {
          events.emit<Collision>(left_entity, right_entity);
        }
      }
    }
  };
};

Subscribing to events

Objects interested in receiving collision information can subscribe to Collision events by first subclassing the CRTP class Receiver<T>:

struct DebugSystem : public System<DebugSystem>, public Receiver<DebugSystem> {
  void configure(entityx::EventManager &event_manager) {
    event_manager.subscribe<Collision>(*this);
  }

  void update(entityx::EntityManager &entities, entityx::EventManager &events, TimeDelta dt) {}

  void receive(const Collision &collision) {
    LOG(DEBUG) << "entities collided: " << collision.left << " and " << collision.right << endl;
  }
};

Builtin events

Several events are emitted by EntityX itself:

  • EntityCreatedEvent - emitted when a new entityx::Entity has been created.
    • entityx::Entity entity - Newly created entityx::Entity.
  • EntityDestroyedEvent - emitted when an entityx::Entity is about to be destroyed.
    • entityx::Entity entity - entityx::Entity about to be destroyed.
  • ComponentAddedEvent<C> - emitted when a new component is added to an entity.
    • entityx::Entity entity - entityx::Entity that component was added to.
    • ComponentHandle<C> component - The component added.
  • ComponentRemovedEvent<C> - emitted when a component is removed from an entity.
    • entityx::Entity entity - entityx::Entity that component was removed from.
    • ComponentHandle<C> component - The component removed.

Implementation notes

  • There can be more than one subscriber for an event; each one will be called.
  • Event objects are destroyed after delivery, so references should not be retained.
  • A single class can receive any number of types of events by implementing a receive(const EventType &) method for each event type.
  • Any class implementing Receiver can receive events, but typical usage is to make Systems also be Receivers.
  • When an Entity is destroyed it will cause all of its components to be removed. This triggers ComponentRemovedEvents to be triggered for each of its components. These events are triggered before the EntityDestroyedEvent.

Manager (tying it all together)

Managing systems, components and entities can be streamlined by using the "quick start" class EntityX. It simply provides pre-initialized EventManager, EntityManager and SystemManager instances.

To use it, subclass EntityX:

class Level : public EntityX {
public:
  explicit Level(filename string) {
    systems.add<DebugSystem>();
    systems.add<MovementSystem>();
    systems.add<CollisionSystem>();
    systems.configure();

    level.load(filename);

    for (auto e : level.entity_data()) {
      entityx::Entity entity = entities.create();
      entity.assign<Position>(rand() % 100, rand() % 100);
      entity.assign<Direction>((rand() % 10) - 5, (rand() % 10) - 5);
    }
  }

  void update(TimeDelta dt) {
    systems.update<DebugSystem>(dt);
    systems.update<MovementSystem>(dt);
    systems.update<CollisionSystem>(dt);
  }

  Level level;
};

You can then step the entities explicitly inside your own game loop:

while (true) {
  level.update(0.1);
}

Installation

Arch Linux

pacman -S entityx

OSX

brew install entityx

Windows

Build it manually.

Requirements:

  • Visual Studio 2015 or later, or a C++ compiler that supports a basic set of C++11 features (ie. Clang >= 3.1 or GCC >= 4.7).
  • CMake

Building entityx - Using vcpkg

You can download and install entityx using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install entityx

The entityx port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Other systems

Build it manually.

Requirements:

  • A C++ compiler that supports a basic set of C++11 features (ie. Clang >= 3.1, GCC >= 4.7).
  • CMake

C++11 compiler and library support

C++11 support is quite...raw. To make life more interesting, C++ support really means two things: language features supported by the compiler, and library features. EntityX tries to support the most common options, including the default C++ library for the compiler/platform, and libstdc++.

Installing on Ubuntu 12.04

On Ubuntu LTS (12.04, Precise) you will need to add some PPAs to get either clang-3.1 or gcc-4.7. Respective versions prior to these do not work.

For gcc-4.7:

sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
sudo apt-get update -qq
sudo apt-get install gcc-4.7 g++-4.7
CC=gcc-4.7 CXX=g++4.7 cmake ...

For clang-3.1 (or 3.2 or 3.3):

sudo apt-add-repository ppa:h-rayflood/llvm
sudo apt-get update -qq
sudo apt-get install clang-3.1
CC=clang-3.1 CXX=clang++3.1 cmake ...

Options

Once these dependencies are installed you should be able to build and install EntityX as below. The following options can be passed to cmake to modify how EntityX is built:

  • -DENTITYX_RUN_BENCHMARKS=1 - In conjunction with -DENTITYX_BUILD_TESTING=1, also build benchmarks.
  • -DENTITYX_MAX_COMPONENTS=64 - Override the maximum number of components that can be assigned to each entity.
  • -DENTITYX_BUILD_SHARED=1 - Whether to build shared libraries (defaults to 1).
  • -DENTITYX_BUILD_TESTING=1 - Whether to build tests (defaults to 0). Run with "make && make test".
  • -DENTITYX_DT_TYPE=double - The type used for delta time in EntityX update methods.

Once you have selected your flags, build and install with:

mkdir build
cd build
cmake <flags> ..
make
make install

EntityX has currently only been tested on Mac OSX (Lion and Mountain Lion), Linux Debian 12.04 and Arch Linux. Reports and patches for builds on other platforms are welcome.

Comments
  • Does not compile on Windows with Visual Studio 2013

    Does not compile on Windows with Visual Studio 2013

    Does not compile on Windows with Visual Studio 2013.

    1. First issue was gcc specific compiler flags. To remove:
    2. go to Project -> Properties -> Configuration Properties -> C/C++ -> Command Line
    3. Remove all the flags in the 'Additional Options' box
    4. Second issue: Cannot open include file: 'unistd.h': No such file or directory I think unistd.h is unix only. Need to find a replacement for Windows.
    5. After commenting out the first unistd.h include I saw (in simplesignal.h), I get lots of errors - 648 to be exact. Some of them I think are just missing includes. Some of them, I'm not sure if VS doesn't support some C++11 features? For example, in simplesignal.h, I get an error for this bit of code:
    /// CollectorInvocation specialisation for regular signals.
    template<class Collector, class R, class... Args>
    struct CollectorInvocation<Collector, R (Args...)> {
      inline bool
      invoke (Collector &collector, const std::function<R (Args...)> &cbf, Args... args)
      {
        return collector (cbf (args...));
      }
    };
    

    The errors are:

    1. Error 12 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    2. Error 13 error C2143: syntax error : missing ',' before '<'
    opened by jarrettchisholm 38
  • entity_test failed: double free or corruption (fasttop)

    entity_test failed: double free or corruption (fasttop)

    Greetings.

    I use the latest version from repository, 089d26cf. Compiled and built successfully. It fails during make test. here's the log:

    [email protected]:~/entityx/build$ make test Running tests... Test project /home/varnie/entityx/build Start 1: pool_test 1/7 Test #1: pool_test ........................ Passed 0.00 sec Start 2: entity_test *** Error in `/home/varnie/entityx/build/entity_test': double free or corruption (fasttop): 0x095f71a0 *** 2/7 Test #2: entity_test ......................***Exception: Other 0.16 sec Start 3: event_test 3/7 Test #3: event_test ....................... Passed 0.00 sec Start 4: system_test 4/7 Test #4: system_test ...................... Passed 0.01 sec Start 5: tags_component_test 5/7 Test #5: tags_component_test .............. Passed 0.00 sec Start 6: dependencies_test 6/7 Test #6: dependencies_test ................ Passed 0.00 sec Start 7: benchmarks_test 7/7 Test #7: benchmarks_test .................. Passed 11.25 sec

    86% tests passed, 1 tests failed out of 7

    Total Test time (real) = 11.43 sec

    The following tests FAILED: 2 - entity_test (OTHER_FAULT) Errors while running CTest make: *** [test] Error 8

    I compiled it with:

    cmake -DENTITYX_RUN_BENCHMARKS=1 -DENTITYX_BUILD_TESTING=1 -DENTITYX_DT_TYPE=float ..`

    My system:

    [email protected]:~/entityx/build$ uname -a Linux heimdal 3.13.0-79-generic #123-Ubuntu SMP Fri Feb 19 14:28:32 UTC 2016 i686 i686 i686 GNU/Linux

    g++ version:

    [email protected]:~/entityx/build$ g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-linux-gnu/4.8/lto-wrapper Target: i686-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.8.4-2ubuntu1~14.04.1' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libmudflap --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-i386/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-i386 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-i386 --with-arch-directory=i386 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-targets=all --enable-multiarch --disable-werror --with-arch-32=i686 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=i686-linux-gnu --host=i686-linux-gnu --target=i686-linux-gnu Thread model: posix gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.1) `

    I attached the valgrind output:

    [email protected]:~/entityx/build$ valgrind --tool=memcheck ./entity_test ==21007== Memcheck, a memory error detector ==21007== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==21007== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info ==21007== Command: ./entity_test ==21007== ==21007== Invalid read of size 4 ==21007== at 0x4095751: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80BCFDB: destroy (Entity.h:388) ==21007== by 0x80BCFDB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::___C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== by 0x80BC0A2: Catch::Session::run() (catch.hpp:5221) ==21007== by 0x80680BA: run (catch.hpp:5204) ==21007== by 0x80680BA: main (catch.hpp:8181) ==21007== Address 0x43ff7f0 is 8 bytes inside a block of size 16 free'd ==21007== at 0x402B838: operator delete(void) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) ==21007== by 0x40FC1AA: std::string::_Rep::_M_destroy(std::allocator const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x4095769: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80B6F9F: remove (Entity.h:458) ==21007== by 0x80B6F9F: remove (Entity.h:742) ==21007== by 0x80B6F9F: entityx::Pool<Tag, 8192u>::remove_component(entityx::Entity) (Pool.h:98) ==21007== by 0x80BCFCB: destroy (Entity.h:387) ==21007== by 0x80BCFCB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::____C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== ==21007== Invalid write of size 4 ==21007== at 0x4095757: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80BCFDB: destroy (Entity.h:388) ==21007== by 0x80BCFDB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::___C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== by 0x80BC0A2: Catch::Session::run() (catch.hpp:5221) ==21007== by 0x80680BA: run (catch.hpp:5204) ==21007== by 0x80680BA: main (catch.hpp:8181) ==21007== Address 0x43ff7f0 is 8 bytes inside a block of size 16 free'd ==21007== at 0x402B838: operator delete(void) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) ==21007== by 0x40FC1AA: std::string::_Rep::_M_destroy(std::allocator const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x4095769: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80B6F9F: remove (Entity.h:458) ==21007== by 0x80B6F9F: remove (Entity.h:742) ==21007== by 0x80B6F9F: entityx::Pool<Tag, 8192u>::remove_component(entityx::Entity) (Pool.h:98) ==21007== by 0x80BCFCB: destroy (Entity.h:387) ==21007== by 0x80BCFCB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::___C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== ==21007== Invalid free() / delete / delete[] / realloc() ==21007== at 0x402B838: operator delete(void) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) ==21007== by 0x40FC1AA: std::string::_Rep::_M_destroy(std::allocator const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x4095769: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80BCFDB: destroy (Entity.h:388) ==21007== by 0x80BCFDB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::___C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== by 0x80BC0A2: Catch::Session::run() (catch.hpp:5221) ==21007== Address 0x43ff7e8 is 0 bytes inside a block of size 16 free'd ==21007== at 0x402B838: operator delete(void) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) ==21007== by 0x40FC1AA: std::string::_Rep::_M_destroy(std::allocator const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x4095769: ??? (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.19) ==21007== by 0x80953A2: ~basic_string (basic_string.h:539) ==21007== by 0x80953A2: ~Tag (Entity_test.cc:73) ==21007== by 0x80953A2: entityx::Pool<Tag, 8192u>::destroy(unsigned int) (Pool.h:94) ==21007== by 0x80B6F9F: remove (Entity.h:458) ==21007== by 0x80B6F9F: remove (Entity.h:742) ==21007== by 0x80B6F9F: entityx::Pool<Tag, 8192u>::remove_component(entityx::Entity) (Pool.h:98) ==21007== by 0x80BCFCB: destroy (Entity.h:387) ==21007== by 0x80BCFCB: entityx::Entity::destroy() (Entity.cc:26) ==21007== by 0x80BD5EE: entityx::EntityManager::reset() (Entity.cc:42) ==21007== by 0x80BD715: entityx::EntityManager::~EntityManager() (Entity.cc:38) ==21007== by 0x8092EC8: ~EntityManagerFixture (Entity_test.cc:87) ==21007== by 0x8092EC8: ~____C_A_T_C_H____T_E_S_T____200 (Entity_test.cc:200) ==21007== by 0x8092EC8: Catch::MethodTestCase<(anonymous namespace)::____C_A_T_C_H____T_E_S_T____200>::invoke() const (catch.hpp:430) ==21007== by 0x809AE8D: invoke (catch.hpp:6216) ==21007== by 0x809AE8D: Catch::RunContext::runCurrentTest(std::string&, std::string&) (catch.hpp:4961) ==21007== by 0x80B8385: runTest (catch.hpp:4807) ==21007== by 0x80B8385: Catch::Runner::runTestsForGroup(Catch::RunContext&, Catch::TestCaseFilters const&) (catch.hpp:5098) ==21007== by 0x80BB169: Catch::Runner::runTests() (catch.hpp:5079) ==21007== All tests passed (164 assertions in 32 test cases) ==21007== ==21007== HEAP SUMMARY: ==21007== in use at exit: 0 bytes in 0 blocks ==21007== total heap usage: 2,964 allocs, 2,966 frees, 2,484,650 bytes allocated ==21007== ==21007== All heap blocks were freed -- no leaks are possible ==21007== ==21007== For counts of detected and suppressed errors, rerun with: -v ==21007== ERROR SUMMARY: 6 errors from 3 contexts (suppressed: 0 from 0)

    If you need more details regarding my system setup, please ask.

    opened by varnie 23
  • Not receiving entity destruction events

    Not receiving entity destruction events

    I'm updated to the latest version of EntityX, and I'm catching other events properly.

    In the following gist, the function TestSystem::receive(const entityx::EntityDestroyedEvent &entity_destruction) should be getting called, but does not appear to be.

    https://gist.github.com/dustinfreeman/11048767

    in progress 
    opened by dustinfreeman 22
  • Example request

    Example request

    Hello ,

    I have read the tutorial on the main page but some of the stuff are changed in the latest release and can't compile. Can I request an example where an Entity is inflicting damage on a few monsters let say, throwing a bomb that will subtract their health. I just can't figure some stuff on how to combine your system with timed events like bomb for example. Something similar like in the Trefall's entity system: https://xp-dev.com/svn/Trefall-ComponentSystem/TestEntity/main.cpp

    Thanks in advance,

    Alex

    opened by sabotage3d 17
  • Entity creation / destruction slows down over time?

    Entity creation / destruction slows down over time?

    I've found a very odd situation that I'm trying to troubleshoot right now using entityx.

    I'm using OpenCV to detect and track objects from frame-to-frame in a video, and then using entityx to manage the physics of each tracked object. I've found that as my project runs, the framerate drops -- it starts at 60 fps, then within 30 minutes it's dropped down to 48 or so, and by the 90 minute mark it's barely hitting 20 fps. After several rounds of surgically removing / adding code back into the project to identify the issue, I've found that the creation / destruction of objects completely slows down the software:

    void setup(void* display) {
    	Display* parentDisplay = static_cast<Display*>(display);
    	mEntityHandle = parentDisplay->mEntities.create();
    	mEntityHandle.assign<Id>(-1);
    }
    
    void update(void* display) {
    	Display* parentDisplay = static_cast<Display*>(display);
    
    	if (mEntityHandle.valid()) {
    		auto id_component = mEntityHandle.component<Id>();
    		id_component->mId = getLabel();
    	}
    }
    
    void destroy(void* display) {
    	Display* parentDisplay = static_cast<Display*>(display);
    	entityx::ComponentHandle<sitara::Id> id;
    	//entityx::ComponentHandle<sitara::ecs::Attractor> force;
    	for (auto entity : parentDisplay->mEntities.entities_with_components(id)) {
    		if (id->mId == getLabel()) {
    			entity.destroy();
    		}
    	}
    }
    

    These three functions are simply hooks that are called by my object tracker, and input a void* display that represents the parent class of my entityx::EntityManager objects. But I've found that removing these few lines of code removes my slowdown problem completely, and re-adding them causes the issue I'm observing.

    So my question is: what could possibly be causing this? While running in VS2019 I don't see any memory leaks (memory usage looks pretty steady); it could be that there's a very expensive memory alignment operations that occurs somewhere due to the constant destruction / creation of entities, but if so, I'm not sure how to compensate for it.

    For further troubleshooting information, my Id Component is very simple:

    	struct Id {
    		Id(int id) {
    			mId = id;
    		}
    
    		int mId;
    	};
    

    So I doubt that there's any issues with this being a very expensive operation...

    opened by morphogencc 15
  • 2.0 Branch questions.

    2.0 Branch questions.

    As you can see in my last failed pull request, I'm trying to get the exporting as a DLL of this library, but before that I have some questions.

    I saw that in the 2.0 branch you removed the event subsystem. Will the next release not have Events? (I vote yes for that, and removing simplesignals etc.. )

    Can we update the 2.0 branch and define some milestones for it? I'm new to opensource working workflow, so I don't know exactly where we can define those things here in github.

    I don't fully examined your code but, is there a reason to make this a compiled library instead of a template header only library?

    (I have the dll exporting working but there is one test that fails, and is related to the event system)

    opened by roig 13
  • Acces violations when more than 1024 entities are created (compile_time_branch)

    Acces violations when more than 1024 entities are created (compile_time_branch)

    I'm experiencing some nasty access violations to my components member variables maybe due to object memory data corruption or overflow. I'm trying to send you the minimal code to reproduce it but it's hard, I think it only happens when more than 1024 entities with components are created.

    I tried the ColumnStorage and ContiguousStorage and I have similar acces violations on both with more than 1024 entities.

    Have you any test or something that check what happens after the INITIAL_CAPACITY = 1024 capacity is resized? I will post again with more info, but maybe there is a bug when resize happens.

    opened by roig 12
  • Are there any plans to remove Boost?

    Are there any plans to remove Boost?

    Python support aside, are there any major hurdles to removing boost? I have only spent a short while looking at the source but depending on boost is a bit of a red flag for me. My colleague and I are considering a fork to remove boost but any initial thoughts or reasonings would be appreciated...

    Thanks :+1:

    opened by acron0 12
  • Replace boost::shared_ptr with std::shared_ptr

    Replace boost::shared_ptr with std::shared_ptr

    I think it's worthwhile to replace boost::shared_ptr with the std:: variant. entityx depends on C++11 anyway, so one reference to boost can be dropped this way.

    Here's a patch implementing this, passed all tests.

    If you want, I can create a pull request.

    opened by hanst99 12
  • More elegant iteration

    More elegant iteration

    I've noticed this pattern occurs very frequently, where the entity is thrown away when iterating over components. It's also kind of redundant having to pre-declare the component handles:

      void update(EntityManager &entities, EventManager &events, TimeDelta dt) override {
        Notification::Handle notification;
        for (auto _ : entities.entities_with_components(notification)) {
          notification->components_added.reset();
          notification->components_removed.reset();
        }
      }
    

    With std::tuple this could be simplified to:

      void update(EntityManager &entities, EventManager &events, TimeDelta dt) override {
        for (auto c : entities.with_components<Notification>()) {
          std::get<0>(c)->components_added.reset();
          std::get<0>(c)->components_added.reset();
        }
      }
    

    Better? Worse? Unsure.

    discussion 
    opened by alecthomas 10
  • [bug?] Entity destruction not calling on_component_removed() for every component assigned.

    [bug?] Entity destruction not calling on_component_removed() for every component assigned.

    Maybe it's intentional, but destroying an entity is not calling the function call on_component_removed for each assigned components when those are removed from the entity.

    Now I'm forced to check for every component inside on_entity_destroyed, and call my on_component_removed callback for each component.

    I think entityx should handle this, because now the behavior seems inconsistent.

    • If you call remove<..>() from an Entity, the component is removed from entity and callback is called.
    • If you call destroy() from an Entity, the component is removed from the entity and NO callback is called. What do you think?
    opened by roig 9
  • Shared library not working in Windows

    Shared library not working in Windows

    EntityX is in ConanCenter: https://conan.io/center/entityx

    But the shared library build has been removed for Windows: https://github.com/conan-io/conan-center-index/blob/ff8bf5423a93bd972099a16f2a7b2646d53b7f69/recipes/entityx/all/conanfile.py#L52

    Removing those lines, the output shows as the result of CMake install:

    -- Install configuration: "Release"
      -- Installing: C:/.../lib/pkgconfig/entityx.pc
      -- Installing: C:/.../include/entityx
      -- Installing: C:/.../include/entityx/deps
      -- Installing: C:/.../include/entityx/deps/Dependencies.h
    ...
      -- Installing: C:/.../include/entityx/System.h
      -- Installing: C:/.../include/entityx/tags
      -- Installing: C:/.../include/entityx/tags/TagsComponent.h
      -- Installing: C:/.../bin/entityx.dll
    

    Further inspection shows that the .lib static library is not being created at all. The ENTITYX_BUILD_SHARED is being defined.

    Is this intended behavior? I can see that shared libraries are working fine in other platforms, is shared .dll library support for Windows? Thanks!

    opened by memsharded 1
  • Passing an entity as a pointer (Question)

    Passing an entity as a pointer (Question)

    Hi @alecthomas , great library!

    I have a scenario in one of my projects, where I need to pass an entity or a component to the physics engine (bullet) as a pointer (void*).

    When I am trying to receive the pointer back, if I cast it to an entity for example, I can't access any of the components because It gives me some error like the id is invalid or if I am trying to use the id it tells me that the index is smaller than the component mask (or something close to this).

    Is there any other way to pass an entity as a pointer and access it in some other part of the code without being invalid?

    Thanks.

    opened by ghost 11
  • more efficient way of looping trough a bunch of classes?

    more efficient way of looping trough a bunch of classes?

    my game uses a lot of classes, and every time I add a new class type I have to add for (Entity entity : ex.entities.entities_with_components(ClassName)) to be able to update and draw it, this is crowding up my update function, is there a more efficient way of doing this?

    opened by BBQGiraffe 1
  • UUIDCollisionResolver

    UUIDCollisionResolver

    I'm trying to integrate cereal serialization library with entityx

    Also I have read https://github.com/alecthomas/entityx/issues/117, https://github.com/alecthomas/entityx/issues/14 and https://github.com/alecthomas/entityx/issues/25

    I got four basic ideas:

    1. We should use custom UUID component instead of Entity id
    2. For serialization we should check manually if entity has specific components (and, well, iterate through all of them)
    3. (because of 2) We should manually decide what components should be registered and how components should be serialized/deserialized
    4. To iterate over all alive entities we must use entities_for_debugging(). It marked "not very fast, so should only be used for debugging", but well I don't see any other alternatives for serialization

    My big question is: how elegantly implement UUIDCollisionResolver? I mean, UUIDGenerator automatically attaches UUID component for every new Entity, and when we try to deserialize some entities from external file here is high probability that UUIDs of that entities are already taken

    Also, some components can store UUID in themselves, so UUID must be replaced with a correct one too

    To be more specific, lets say we have such components:

    struct UUID
    {
        //UUID(...) {...}
    
        uint32_t value;
    };
    
    struct TreeNode
    {
        //TreeNode(...) {...}
    
        std::string name;
    };
    
    struct Transform
    {
        //Transform(...) {...}
    
        glm::vec3 position;
        glm::vec3 scale;
        glm::vec3 rotation;
    
        bool is_dirty;
        glm::mat4 cache;
    
        UUID parent;
        std::list<UUID> childs; 
    };
    
    opened by NukeBird 2
  • Assertion failure when removing a component while an entity is being destroyed

    Assertion failure when removing a component while an entity is being destroyed

    Hi,

    I noticed that when you are destroying an entity, if you attempt to remove another component from that entity at the same time (e.g: from a component's destructor), you will get an assertion failure in Entity::remove()

    As far as I could investigate, the issue is located in EntityManager::destroy(Entity::Id entity).

    Old code:

      void destroy(Entity::Id entity) {
        assert_valid(entity);
        uint32_t index = entity.index();
        auto mask = entity_component_mask_[index];
        for (size_t i = 0; i < component_helpers_.size(); i++) {
          BaseComponentHelper *helper = component_helpers_[i];
          if (helper && mask.test(i))
            helper->remove_component(Entity(this, entity));
        }
        event_manager_.emit<EntityDestroyedEvent>(Entity(this, entity));
        entity_component_mask_[index].reset();
        entity_version_[index]++;
        free_list_.push_back(index);
      }
    

    New code that fixes the issue:

      void destroy(Entity::Id entity) {
        assert_valid(entity);
        uint32_t index = entity.index();
        for (size_t i = 0; i < component_helpers_.size(); i++) {
          BaseComponentHelper *helper = component_helpers_[i];
          if (helper && entity_component_mask_[index].test(i))
            helper->remove_component(Entity(this, entity));
        }
        event_manager_.emit<EntityDestroyedEvent>(Entity(this, entity));
        entity_component_mask_[index].reset();
        entity_version_[index]++;
        free_list_.push_back(index);
      }
    

    The issue is caused by the fact mask is being cached before the for loop. As a result, if there is any attempt to remove a component in an other component's destructor, the so called component will be removed twice, hence causing the assertion failure.

    Since I'm not in a situation where I can commit anything and/or submit a PR for a few days, I just wanted to let you know about the issue and the fix ;)

    Best regards.

    opened by dolphineye 0
  • Add method to move entity from one entity manager to another

    Add method to move entity from one entity manager to another

    I'm using the entity manager class for all entities that are currently loaded into the game, as it has many useful features for querying entities with specific components. However, I often find myself having to create entity vectors in order to know what entities I should be querying based on where somebody currently is in the game, which obviously ends up leading to me re-creating querying this structure. I think there would be a lot of use for this if it were added in

    opened by hak33m16 0
Releases(1.1.2)
  • 1.1.1(Apr 24, 2015)

    This release fixes an issue where const entities caused components to disappear. This is now fixed and additionally disallows non-const access to components on const entities.

    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Feb 9, 2015)

    Components and events no longer need to be inherited from Component and Event respectively. This allows direct use of classes and structs from third parties without wrapping them.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.1(Oct 21, 2014)

  • 1.0.0(Sep 29, 2014)

  • 1.0.0alpha1(May 5, 2014)

    EntityX has switched to a more cache-friendly memory layout for components. This is achieved by requiring the use of assign<Component>(arg0, arg1, ...) and removing assign(component). This allows EntityX to explicitly control the layout of components. The current lyout algorithm reserves space for components in chunks (8192 by default).

    This change also necessitated a move away from the use of shared_ptr<> for components, which I had never been that pleased with anyway. Replacing it is a very lightweight ComponentHandle<C> smart pointer. This checks for validity of the entity associated with the component, and validity of the component itself. It also allows future iterations of EntityX to do even more interesting things with memory layout if desirable.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Dec 18, 2013)

  • 0.1.0(Dec 2, 2013)

    First "official" release of EntityX.

    Recent notable changes:

    • 2013-10-29 - Boost has been removed as a primary dependency for builds not using python.
    Source code(tar.gz)
    Source code(zip)
Owner
Alec Thomas
Alec Thomas
Gaming meets modern C++ - a fast and reliable entity component system (ECS) and much more

EnTT is a header-only, tiny and easy to use library for game programming and much more written in modern C++. Among others, it's used in Minecraft by

Michele Caini 7.2k Sep 16, 2022
apecs: A Petite Entity Component System

apecs: A Petite Entity Component System A header-only, very small entity component system with no external dependencies.

Matt Cummins 17 Jun 1, 2022
[WIP] Experimental C++14 multithreaded compile-time entity-component-system library.

ecst Experimental & work-in-progress C++14 multithreaded compile-time Entity-Component-System header-only library. Overview Successful development of

Vittorio Romeo 446 Aug 27, 2022
C++ single-header entity component system library

ECS This is a simple C++ header-only type-safe entity component system library. It makes heavy use of C++11 constructs, so make sure you have an up to

Sam Bloomberg 409 Sep 21, 2022
C++ entity-component system

CORGI Version 1.0.2 {#corgi_readme} CORGI is a C++ entity-component system library developed primarily for games that focus on simplicity and flexibil

Google 250 Jul 26, 2022
Thoughts about entity-component-system

About Warning: This is not a complete production-ready library for entity-component-system. This is only my thoughts about how the modern entity-compo

Sergey Makeev 176 Sep 9, 2022
"SaferCPlusPlus" is essentially a collection of safe data types intended to facilitate memory and data race safe C++ programming

A collection of safe data types that are compatible with, and can substitute for, common unsafe native c++ types.

null 318 Sep 21, 2022
Type-safe Printf in C

Type-Safe Printf For C This uses macro magic, compound literals, and _Generic to take printf() to the next level: type-safe printing, printing into co

Henrik Theiling 60 Jul 17, 2022
Type safe - Zero overhead utilities for preventing bugs at compile time

type_safe type_safe provides zero overhead abstractions that use the C++ type system to prevent bugs. Zero overhead abstractions here and in following

Jonathan Müller 1.1k Sep 20, 2022
An open source C++ entity system.

anax ARCHIVED: as I haven't maintained this library for at least a couple of years. I don't have the time or interest to work on this. Please use anot

Miguel Martin 457 Aug 27, 2022
A drop-in entity editor for EnTT with Dear ImGui

imgui_entt_entity_editor A drop-in, single-file entity editor for EnTT, with ImGui as graphical backend. demo-code (live) Editor Editor with Entiy-Lis

Erik Scholz 144 Sep 3, 2022
Simple ESPHome Wiegand custom component

esphome-wiegand Simple ESPHome Wiegand custom component Based on this code: https://github.com/Luisiado/wiegand_esphome_module To use: Drop wiegand_de

Av 19 Aug 29, 2022
A component based project manager.

Component Based Project Manager CBPM provides an interface to manage a component-based project. Build To build CBPM, you must install xmake: a build-s

null 1 Nov 2, 2021
Spin-off component from existing IBM/mcas open source project

PyMM PyMM is a python library that allows the storing and manipulation of existing heavily used types such as Numpy ndarray and PyTorch on Persistent

International Business Machines 15 Jun 1, 2022
bsdiff changed to remove bz2, the header and to allow streaming interfaces, to be used on the esp32 with idf as a component

bspatch for esp32 This project adds support for bspatch to the esp32 with some changes: no compression (bz2), no header and changed the interfaces to

Blockstream 10 Jul 20, 2022
Custom ESPHome Component for generic Sit-Stand-Desks

ESPHomeGenericSitStandDesk I have one of those generic relatively cheap Sit Stand Desks. In an effort to monitor my desk usage I developed this overki

Till 17 Jun 11, 2022