Overview / Math, game & observability

ecs

Entities, components and systems with archetype storage, in 16 KB chunks with one contiguous array per component, and 64-bit generational entities.

Always compiled: part of the core build.Include #include <ethereal/cpp/ecs/ecs_inc.hpp>C layer

ecs_inc.hpp

#include <ethereal/cpp/ecs/ecs_inc.hpp>

Includes the whole Ecs module.

command.hpp

#include <ethereal/cpp/ecs/command.hpp>

Command buffer of the Ecs module.

Changing the structure in the middle of an iteration is the classic ECS accident. Adding a component to an entity moves it to another archetype, which takes it out of the chunk being walked and brings the last entity into its place. The running loop then skips one entity and visits another twice, with no error, only wrong behaviour.

So every structural change is deferred: it is written here and applied at a sync point, when no iteration is running.

The capacity is reserved up front and overflow is documented, as the spec asks. On overflow the buffer does not grow: the call returns eOverflow and the command is dropped. Growing in the middle of a system would be an allocation on the path the spec requires to have none, and growing silently would hide a badly chosen capacity. Whoever sees eOverflow raises the capacity. The rejection counter stays in the stats, so the case is visible even when nobody checks the return value.

Entities created here are promises. Create returns a handle with the top bit set: it does not exist in the world yet. It serves to add components in the same buffer, and it is resolved to a real handle when the buffer is applied. A promise given to another system before Apply is worth nothing, and IsAlive on it returns false, which is true.

enum

ECommandKind

Ethereal::Ecs#
C++
enum class   ECommandKind : ETL_UINT8
{
    /// @brief    Creates an entity (resolves a promise).
    eCreate = 0,

    /// @brief    Destroys an entity.
    eDestroy,

    /// @brief    Adds a component.
    eAdd,

    /// @brief    Removes a component.
    eRemove
};

What a command does.

struct

SCommand

Ethereal::Ecs#
C++
struct   SCommand   final
{
    /// @brief    What the command does.
    ECommandKind    eKind = ECommandKind::eCreate;

    /// @brief    Component id, for eAdd and eRemove.
    ETL_UINT32        uId = 0u;

    /// @brief    Target entity, or a promise.
    SEntity            Target{};

    /// @brief    Where the component value is stored, in the byte arena.
    ETL_UINT32        uOffset = 0u;

    /// @brief    Size of the value. Zero for a tag or no value.
    ETL_UINT32        uSize = 0u;
};

A deferred command.

const

kPromise

Ethereal::Ecs#
inline constexpr ETL_UINT32 kPromise = 0x80000000u;

Marks the handles that do not exist in the world yet.

class

CCommandBuffer

Ethereal::Ecs#

Structural changes recorded now and applied at a sync point.

class CCommandBuffer final
constructor

CCommandBuffer

#
CCommandBuffer() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( std::size_t uMaxCommands, std::size_t uMaxValueBytes ) noexcept;

Reserves the capacity. All the memory is requested here.

uMaxCommands
Command slots.
uMaxValueBytes
Bytes for the component values.
eOk or eInvalidArgument. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Create

#
SEntity Create() noexcept;

An entity that does not exist yet (a promise). SEntity::None() on overflow.

function

Destroy

#
EStatus Destroy( SEntity E ) noexcept;

Records the destruction of an entity. eOverflow when full.

function

AddRaw

#
EStatus AddRaw( SEntity E, ETL_UINT32 uId, const void * pValue, ETL_UINT32 uSize ) noexcept;

Records the addition of a component. The value is copied now.

E
Entity or promise.
uId
Component id.
pValue
Value. May be null.
uSize
Size of the value. Zero for a tag.
eOk or eOverflow.
function

RemoveRaw

#
EStatus RemoveRaw( SEntity E, ETL_UINT32 uId ) noexcept;

Records the removal of a component. eOverflow when full.

function

Add

#
template< typename T > EStatus Add( const SEntity E, const T & Value ) noexcept

Records the addition of T.

function

Remove

#
template< typename T > EStatus Remove( const SEntity E ) noexcept

Records the removal of T.

function

Apply

#
EStatus Apply( CWorld & World ) noexcept;

Applies the commands in the order they were recorded, then clears.

The spec: commands are "merged at the sync point in a deterministic order so parallel execution produces identical results run to run". Inside a buffer, commands are applied in the order they were written. Across buffers of different workers, the merge applies them in worker order, not in order of arrival (see ApplyMany). Without that, two runs of the same program with the same initial state would give different worlds depending on which thread finished first.

World
The world.
eOk.
function

ApplyMany

#
static EStatus ApplyMany( CWorld & World, CCommandBuffer * const * pBuffers, std::size_t uCount ) noexcept;

Applies several buffers, in the order of the array, then clears them.

World
The world.
pBuffers
The buffers. Null entries are skipped.
uCount
Number of buffers.
eOk, or eInvalidArgument when pBuffers is null.
function

Clear

#
void Clear() noexcept;

Drops every command, destroying the stored non trivial values.

function

Count

#
std::size_t Count() const noexcept

Commands recorded.

function

Capacity

#
std::size_t Capacity() const noexcept

Command slots.

function

Rejected

#
std::size_t Rejected() const noexcept

Commands rejected because they did not fit.

ecs_types.hpp

#include <ethereal/cpp/ecs/ecs_types.hpp>

Common types of the Ecs module.

The status codes, the entity handle, the component mask, the component registry, the access check and the chunk constants.

The module exists for iteration speed, and every decision here follows from the memory layout:

  • Storage by archetype. Entities with the same component set live in the same chunk, and each component has its own contiguous array inside the chunk. Iterating walks flat arrays with unit stride, which is what lets the compiler vectorize.
  • Chunks of 16 KB, fixed at compile time. A runtime value would turn a shift into a division.
  • Iteration hands out raw pointers to the chunk arrays, never per entity accessor objects.
  • No allocations while iterating or running systems. Every structural change is deferred to a command buffer.
  • The identity is a 64 bit number: index and generation. Checking that an entity is alive is one array index and one compare, never a hash map lookup.
enum

EStatus

Ethereal::Ecs#
C++
enum class   EStatus : ETL_UINT8
{
    /// @brief    Success.
    eOk = 0,

    /// @brief    Init was not called, or it failed.
    eNotInitialized,

    /// @brief    An allocation failed.
    eOutOfMemory,

    /// @brief    A parameter is out of range.
    eInvalidArgument,

    /// @brief    The entity no longer exists, or the handle is stale.
    eDeadEntity,

    /// @brief    The command buffer has no free slots left.
    eOverflow,

    /// @brief    The component is not registered, or it does not fit in a chunk.
    eBadComponent,

    /// @brief    The system order has a cycle.
    eCycle,

    /// @brief    A system wrote a component it did not declare.
    eUndeclaredAccess,

    /// @brief    Refused: no license was accepted and the evaluation of this machine has
    ///            ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed,

    /// @brief    Old British spelling of eNotInitialized, same value. Will be removed.
    eNotInitialised [[deprecated( "use EStatus::eNotInitialized" )]] = eNotInitialized
};

How an operation ended.

function

StatusName

Ethereal::Ecs#
const ETL_CHAR * StatusName( EStatus eStatus ) noexcept;

Short text for a status, for logs and tests.

struct

SEntity

Ethereal::Ecs#
C++
struct   SEntity   final
{
    /// @brief    Slot in the entity record table.
    ETL_UINT32        uIndex = 0u;

    /// @brief    Generation of the slot when the handle was made.
    ETL_UINT32        uGeneration = 0u;


    /// @brief    Same index and same generation.
    ///
    ETL_API_NOIGN    bool operator==( const SEntity & O ) const ETL_NOEXCEPT
    {
        return ( uIndex == O.uIndex ) && ( uGeneration == O.uGeneration );
    }

    /// @brief    Different index or different generation.
    ///
    ETL_API_NOIGN    bool operator!=( const SEntity & O ) const ETL_NOEXCEPT
    {
        return !( *this == O );
    }


    /// @brief    The value that never matches any entity.
    ///
    ETL_API_NOIGN    static SEntity None() ETL_NOEXCEPT
    {
        return SEntity{ 0xFFFFFFFFu, 0xFFFFFFFFu };
    }
};

The identity of an entity. Eight bytes, trivially copyable.

The index says where the entity record is. The generation says which of the entities that have used that slot the handle refers to.

Without the generation, recycling an index would make a stale handle point to a new entity with no error at all. That is the classic ECS defect: an object moves because of code that talks about another object that is already dead.

Destroying an entity advances the generation. From then on every old handle fails the compare, even when the index is given to another entity.

const

kMaxComponents

Ethereal::Ecs#
inline constexpr ETL_UINT32 kMaxComponents = 256u;

How many component types fit in a world.

const

kMaskWords

Ethereal::Ecs#
inline constexpr ETL_UINT32 kMaskWords = kMaxComponents / 64u;

64 bit words in a component mask.

struct

SComponentMask

Ethereal::Ecs#
C++
struct   SComponentMask   final
{
    /// @brief    The bits, one per component id.
    ETL_UINT64        a[ kMaskWords ] = {};


    /// @brief    Sets the bit of uId. Ids out of range are ignored.
    ///
    ETL_FORCE_INLINE void Set( const ETL_UINT32 uId ) ETL_NOEXCEPT
    {
        if( uId < kMaxComponents )
            a[ uId >> 6 ] |= ( 1ull << ( uId & 63u ) );
    }


    /// @brief    Clears the bit of uId. Ids out of range are ignored.
    ///
    ETL_FORCE_INLINE void Clear( const ETL_UINT32 uId ) ETL_NOEXCEPT
    {
        if( uId < kMaxComponents )
            a[ uId >> 6 ] &= ~( 1ull << ( uId & 63u ) );
    }


    /// @brief    true when the bit of uId is set.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE bool Test( const ETL_UINT32 uId ) const ETL_NOEXCEPT
    {
        return ( uId < kMaxComponents )
            && ( ( a[ uId >> 6 ] & ( 1ull << ( uId & 63u ) ) ) != 0ull );
    }


    /// @brief    true when this mask has every bit of O.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE bool Contains( const SComponentMask & O ) const ETL_NOEXCEPT
    {
        for( ETL_UINT32 i = 0; i < kMaskWords; ++i )
        {
            if( ( a[ i ] & O.a[ i ] ) != O.a[ i ] )
                return false;
        }

        return true;
    }


    /// @brief    true when the two masks share at least one bit.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE bool Intersects( const SComponentMask & O ) const ETL_NOEXCEPT
    {
        for( ETL_UINT32 i = 0; i < kMaskWords; ++i )
        {
            if( ( a[ i ] & O.a[ i ] ) != 0ull )
                return true;
        }

        return false;
    }


    /// @brief    true when no bit is set.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE bool Empty() const ETL_NOEXCEPT
    {
        for( ETL_UINT32 i = 0; i < kMaskWords; ++i )
        {
            if( a[ i ] != 0ull )
                return false;
        }

        return true;
    }


    /// @brief    Same bits.
    ///
    ETL_API_NOIGN    bool operator==( const SComponentMask & O ) const ETL_NOEXCEPT
    {
        for( ETL_UINT32 i = 0; i < kMaskWords; ++i )
        {
            if( a[ i ] != O.a[ i ] )
                return false;
        }

        return true;
    }


    /// @brief    Different bits.
    ///
    ETL_API_NOIGN    bool operator!=( const SComponentMask & O ) const ETL_NOEXCEPT
    {
        return !( *this == O );
    }
};

Which components an archetype has.

Four 64 bit words, not a set container. A query compares masks thousands of times per frame. With a set, each compare would be a tree walk. Here it is four operations.

struct

SComponentInfo

Ethereal::Ecs#
C++
struct   SComponentInfo   final
{
    /// @brief    Component id, or 0xFFFFFFFF when the slot is unused.
    ETL_UINT32        uId = 0xFFFFFFFFu;

    /// @brief    Bytes per entity. Zero for a tag.
    ETL_UINT32        uSize = 0u;

    /// @brief    Alignment of the type.
    ETL_UINT32        uAlignment = 0u;

    /// @brief    A tag: it is in the mask and takes no bytes per entity.
    bool            bTag = false;

    /// @brief    Optional name.
    const ETL_CHAR * pName = nullptr;
};

What the world needs to know about a component type.

The id is assigned on first use and kept for the life of the process, in a function local static. A constexpr counter does not work across translation units: the id would depend on the order in which files are compiled and linked, and two programs linking the same objects in another order would get incompatible worlds.

The cost on the hot path is nothing. Queries read the id once, when they are built, and then work with masks and precomputed offsets. The id never shows up inside a loop.

A tag (an empty struct) takes zero bytes per entity. It has no array in the chunk, it lives only in the archetype mask. A test counts how many entities fit in a chunk with and without tags and requires the same number.

function

RegisterComponent

Ethereal::Ecs#
ETL_UINT32 RegisterComponent( ETL_UINT32 uSize, ETL_UINT32 uAlignment, bool bTag, const ETL_CHAR * pName ) noexcept;

Registers a type and returns its id. Called once per type.

uSize
Bytes per entity.
uAlignment
Alignment of the type.
bTag
true for an empty type.
pName
Optional name. May be null.
The new id, or kMaxComponents when the registry is full.
function

ComponentInfo

Ethereal::Ecs#
const SComponentInfo & ComponentInfo( ETL_UINT32 uId ) noexcept;

Information about a component id. An empty record for an id out of range.

function

RegisteredComponentCount

Ethereal::Ecs#
ETL_UINT32 RegisteredComponentCount() noexcept;

Number of component types registered so far.

struct

SComponentTraits

Ethereal::Ecs#
C++
template< typename T >
struct   SComponentTraits
{
    /// @brief    true when T was declared non trivial.
    static constexpr bool    kNonTrivial = false;
};

Specialize it to declare that T is not trivially copyable.

Use the macro ETL_ECS_NON_TRIVIAL_COMPONENT, which does it.

Components must be trivially copyable by default. An archetype moves rows with memcpy: on each removal the last entity goes into the hole, on each migration the shared components jump to another chunk. With a component that owns a pointer (a string, a vector), copying the bytes duplicates the pointer and two owners free the same memory. memcpy compiles with any type, so this used to fail far from the cause. Now it is refused at compile time.

Non trivial components are supported through an explicit opt in that supplies copy, move and destroy functions:

C++
struct SName { std::string s; };

ETL_ECS_NON_TRIVIAL_COMPONENT( SName )        // global scope

ETL_UNUSED( RegisterNonTrivial< SName >() );   // at startup, once

The cost is in the README: each row move becomes one indirect call per component instead of one memcpy of everything, and serialization cannot save them.

struct

SComponentOps

Ethereal::Ecs#
C++
struct   SComponentOps   final
{
    /// @brief    Constructs at pDest a copy of pSrc. pDest is raw memory.
    void    ( * pCopy )( void * pDest, const void * pSrc ) = nullptr;

    /// @brief    Constructs at pDest by moving from pSrc. pSrc stays valid and is
    ///            destroyed right after.
    void    ( * pMove )( void * pDest, void * pSrc ) = nullptr;

    /// @brief    Destroys the object at p.
    void    ( * pDestroy )( void * p ) = nullptr;
};

What the world needs to handle a non trivial component.

function

RegisterComponentOps

Ethereal::Ecs#
EStatus RegisterComponentOps( ETL_UINT32 uId, const SComponentOps & Ops ) noexcept;

Binds the copy, move and destroy functions of a component.

uId
Component id.
Ops
The three functions. All three are required.
eOk, eBadComponent or eInvalidArgument.
function

ComponentOps

Ethereal::Ecs#
const SComponentOps * ComponentOps( ETL_UINT32 uId ) noexcept;

The functions of uId, or nullptr when it is trivially copyable.

function

NonTrivialComponents

Ethereal::Ecs#
const SComponentMask & NonTrivialComponents() noexcept;

Mask of the non trivial components. One bitwise AND checks them all.

function

ComponentId

Ethereal::Ecs#
template< typename T > ETL_UINT32 ComponentId() noexcept

The id of T in this process. Assigned on first use.

function

RegisterNonTrivial

Ethereal::Ecs#
template< typename T > EStatus RegisterNonTrivial() noexcept

Binds the functions of T. At startup, once, before using it.

T must also be declared with ETL_ECS_NON_TRIVIAL_COMPONENT. The macro is the compile time part, this call is the runtime part.

function

NoteQueryAccess

Ethereal::Ecs#
void NoteQueryAccess( const SComponentMask & Reads, const SComponentMask & Writes ) noexcept;

A query reports what it will touch. Checked against the running system.

The scheduler runs two systems at the same time because they declared that they do not overlap. If the declaration lies, both write the same array from two cores and there is no error, only swapped data. The spec asks for a hard error in debug builds.

A query says what it does in its type: CQuery< const SPos, SVel > reads the position, writes the velocity, and hands out 'const SPos ' and 'SVel '. The scheduler compares that with what the system declared.

With no system running (a query built by hand) this does nothing.

Reads
Components the query reads.
Writes
Components the query writes.
const

kChunkBytes

Ethereal::Ecs#
inline constexpr ETL_UINT32 kChunkBytes = 16u * 1024u;

Size of a chunk.

The spec asks for a fixed 16 KB that sits inside L1 and L2, and asks to measure it. The measurement is in the README: on this machine (i7-6700, 32 KB of L1 data and 256 KB of L2 per core), 16 KB is the best of 4, 8, 16, 32 and 64.

It is a compile time constant because then the division that maps an entity index to chunk and row is a shift. With a runtime value it would be an integer division, more than twenty cycles inside the hottest loop of the module.

const

kChunkHeaderBytes

Ethereal::Ecs#
inline constexpr ETL_UINT32 kChunkHeaderBytes = 64u;

The header takes a whole cache line, so the arrays start aligned and the entity count does not share a line with component data.

const

kChunkDataBytes

Ethereal::Ecs#
inline constexpr ETL_UINT32 kChunkDataBytes = kChunkBytes - kChunkHeaderBytes;

Bytes left for the arrays.

struct

SWorldParams

Ethereal::Ecs#
C++
struct   SWorldParams   final
{
    /// @brief    sizeof( SWorldParams ), for version checks.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SWorldParams ) );

    /// @brief    How many entities fit before the record table grows.
    std::size_t        uInitialEntities = 1024u;

    /// @brief    How many chunks are made in advance.
    std::size_t        uInitialChunks = 16u;
};

World parameters.

struct

SWorldStats

Ethereal::Ecs#
C++
struct   SWorldStats   final
{
    /// @brief    Entities alive now.
    ETL_UINT64    uLiveEntities = 0;

    /// @brief    Entities created since Init.
    ETL_UINT64    uCreatedEntities = 0;

    /// @brief    Entities destroyed since Init.
    ETL_UINT64    uDestroyedEntities = 0;

    /// @brief    Archetypes that exist.
    ETL_UINT64    uArchetypes = 0;

    /// @brief    Chunks allocated, in use or free.
    ETL_UINT64    uChunks = 0;

    /// @brief    Chunks in the free pool.
    ETL_UINT64    uFreeChunks = 0;

    /// @brief    Archetype migrations since Init.
    ETL_UINT64    uMigrations = 0;

    /// @brief    Bytes of all chunks.
    ETL_UINT64    uChunkBytes = 0;
};

World counters.

hierarchy.hpp

#include <ethereal/cpp/ecs/hierarchy.hpp>

Hierarchy and transform propagation of the Ecs module.

The spec: "depth order is maintained incrementally so the walk is linear, not a recursive tree traversal per frame".

A recursive walk costs one call per node, a stack that grows with the depth and, worst of all, unpredictable memory jumps. The children of a node are wherever they landed, and the prefetcher guesses none of them.

Instead, the nodes are kept in increasing depth order, in a flat array. Walking it from end to end visits each node after its parent, always, because the parent has a smaller depth. One pass, no recursion and no stack.

What "incrementally" means here:

  • A new leaf costs nothing. It goes into the bucket of its depth and nothing else changes. This is by far the most common case, it happens for every entity that appears.
  • Reparenting a node forces a rebuild, because the depth of all its descendants changes. It is marked, and the rebuild happens on the next walk, once and not per frame. The walk per frame pays nothing. A scene that reparents one node per frame pays one rebuild per frame.

Cycles are refused up front. A node that is its own ancestor has no depth and the walk would never end. SetParent climbs the chain of the new parent before accepting, and refuses when it finds the child there.

struct

SParent

Ethereal::Ecs#
C++
struct   SParent   final
{
    /// @brief    The parent entity.
    SEntity        Parent{};
};

The parent of this entity. It lives in the child.

In the child and not in the parent, and that decides the rest. A parent may have zero or a thousand children, and a variable size list inside a component would break the chunk layout. In the child it is always one entity, always eight bytes.

The other direction (from parent to children) is a query by this component, or the list CHierarchy keeps.

struct

STransform

Ethereal::Ecs#
C++
struct   STransform   final
{
    /// @brief    Position.
    float        fPos[ 3 ] = { 0.0f, 0.0f, 0.0f };

    /// @brief    Quaternion, x y z w. The identity is {0,0,0,1}.
    float        fRot[ 4 ] = { 0.0f, 0.0f, 0.0f, 1.0f };

    /// @brief    Scale.
    float        fScale[ 3 ] = { 1.0f, 1.0f, 1.0f };
};

Translation, rotation and scale. What the user writes.

This does not use the Math module. Section 2 of the conventions forbids a module from including another module header to get functionality, and the spec promises "Depends on: nothing at link time". It is thirty lines of quaternions, so a user who only wants an ECS does not drag the math module along.

It is translation, rotation and scale, not a 4x4 matrix. Sixteen floats per entity against ten, and composing two matrices takes sixty four multiplications against twenty or so for two TRS. Who needs the matrix builds it at the end, once, not at every level of the tree.

struct

SWorldTransform

Ethereal::Ecs#
C++
struct   SWorldTransform   final
{
    /// @brief    Position.
    float        fPos[ 3 ] = { 0.0f, 0.0f, 0.0f };

    /// @brief    Quaternion, x y z w.
    float        fRot[ 4 ] = { 0.0f, 0.0f, 0.0f, 1.0f };

    /// @brief    Scale.
    float        fScale[ 3 ] = { 1.0f, 1.0f, 1.0f };
};

The result of composing the whole chain. What propagation writes.

function

Compose

Ethereal::Ecs#
void Compose( const SWorldTransform & Parent, const STransform & Local, SWorldTransform * pOut ) noexcept;

pOut = Parent ∘ Local. Scales, then rotates, then translates.

Parent
World transform of the parent.
Local
Local transform of the child.
pOut
Receives the world transform of the child.
class

CHierarchy

Ethereal::Ecs#

Parent links kept in depth order, for a linear walk.

class CHierarchy final
constructor

CHierarchy

#
CHierarchy() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( CWorld & World ) noexcept;

Binds the hierarchy to a world.

function

SetParent

#
EStatus SetParent( SEntity Child, SEntity NewParent ) noexcept;

Puts Child under NewParent. Writes the SParent component.

Child
The child.
NewParent
The parent.
eOk, eNotInitialized, eDeadEntity, or eInvalidArgument when it would make a cycle.
function

ClearParent

#
EStatus ClearParent( SEntity Child ) noexcept;

Takes it out from under its parent. It becomes a root.

function

Parent

#
SEntity Parent( SEntity Child ) const noexcept;

Parent of Child, or SEntity::None().

function

Depth

#
ETL_UINT32 Depth( SEntity Node ) const noexcept;

Zero for a root. 0xFFFFFFFF when the entity is not in the hierarchy.

function

ChildCount

#
std::size_t ChildCount( SEntity ParentNode ) const noexcept;

Number of direct children.

alias

void

#
using NodeFn = void ( * )( void * pCtx, SEntity Child, SEntity ParentNode );

pFn( pCtx, Child, ParentNode ), always with the parent already visited.

function

ForEachInDepthOrder

#
void ForEachInDepthOrder( NodeFn pFn, void * pCtx ) noexcept;

Visits every node in increasing depth order. One linear pass.

function

PropagateTransforms

#
std::size_t PropagateTransforms() noexcept;

Computes SWorldTransform for every node.

For each node, the world transform is the parent's composed with the local one. Since the walk visits parents first, the parent's is already computed when the child is reached, and the tree is never climbed.

An entity without SParent is a root: its world transform is the local one, with no composition. A node without SWorldTransform is skipped. That is not an error: it tells a node that wants the result from one that only exists to have children.

Number of nodes written.
function

NodeCount

#
std::size_t NodeCount() const noexcept;

Number of nodes.

function

MaxDepth

#
ETL_UINT32 MaxDepth() const noexcept;

Largest depth.

function

Rebuilds

#
ETL_UINT64 Rebuilds() const noexcept;

How many times the order had to be rebuilt. Should be low.

observer.hpp

#include <ethereal/cpp/ecs/observer.hpp>

Observers of the Ecs module: add, remove and destroy events.

The spec: OnAdd, OnRemove and OnDestroy hooks per component type, "invoked at sync points, never in the middle of an iteration, because mutating during iteration is the classic ECS crash".

The obvious design, calling the observer the moment the component is added, runs user code inside Add. That code almost always adds or removes another component (an "enemy spawned" observer gives it health, a weapon and a sound). That is a structural change in the middle of another: the entity changes archetype while the Add that was moving it still holds pointers to the old chunk. Inside an iteration, the running loop would skip entities and visit others twice.

So events are recorded and delivered at a sync point, for the same reasons as the command buffer.

The value travels with the event. An OnRemove observer almost always wants to see what was removed (to release a resource, close a file, notify someone). If the event kept only the entity and the component id, the value would be gone by delivery time. So the bytes are copied into the event. The cost is one copy per event, only for watched components.

Without observers there is no cost beyond one bitwise AND per Add: the world tests a bit in a mask before recording anything.

enum

EObserverEvent

Ethereal::Ecs#
C++
enum class   EObserverEvent : ETL_UINT8
{
    /// @brief    The component was added to an entity that did not have it.
    eAdded = 0,

    /// @brief    It was removed, and the entity is still alive.
    eRemoved,

    /// @brief    The entity was destroyed and took it along.
    ///
    /// @details    Different from eRemoved, and the difference matters: an observer
    ///                of "a weapon is no longer equipped" wants to drop it on the
    ///                ground, an observer of "the owner died" may not.
    eDestroyed
};

What happened.

struct

SObserverEvent

Ethereal::Ecs#
C++
struct   SObserverEvent   final
{
    /// @brief    What happened.
    EObserverEvent        eKind = EObserverEvent::eAdded;

    /// @brief    Component id.
    ETL_UINT32            uId = 0u;

    /// @brief    The entity.
    SEntity                Who{};

    /// @brief    The bytes of the component at the moment it happened.
    ///            Null for a tag or a non trivial component.
    const void *        pValue = nullptr;

    /// @brief    Size of pValue.
    ETL_UINT32            uSize = 0u;
};

An event, with the value inside.

alias

void

Ethereal::Ecs#
using ObserverFn = void ( * )( void * pCtx, const SObserverEvent & Event );

Observer callback.

class

CObservers

Ethereal::Ecs#

Watches per component and the events waiting for delivery.

class CObservers final
constructor

CObservers

#
CObservers() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( std::size_t uMaxEvents, std::size_t uMaxBytes ) noexcept;

Reserves the capacity. All the memory is requested here.

uMaxEvents
Event slots.
uMaxBytes
Bytes for the event values.
eOk or eInvalidArgument. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Watch

#
EStatus Watch( ETL_UINT32 uId, EObserverEvent eEvent, ObserverFn pFn, void * pCtx ) noexcept;

Registers a callback for one event of one component.

uId
Component id.
eEvent
The event.
pFn
The callback.
pCtx
Passed back to pFn.
eOk, eInvalidArgument or eNotInitialized.
function

OnAdd

#
template< typename T > EStatus OnAdd( const ObserverFn pFn, void * const pCtx ) noexcept

Watches the addition of T.

function

OnRemove

#
template< typename T > EStatus OnRemove( const ObserverFn pFn, void * const pCtx ) noexcept

Watches the removal of T.

function

OnDestroy

#
template< typename T > EStatus OnDestroy( const ObserverFn pFn, void * const pCtx ) noexcept

Watches the destruction of entities that have T.

function

ClearWatches

#
void ClearWatches() noexcept;

Removes every watch.

function

Watched

#
const SComponentMask & Watched() const noexcept

Union of every watched component. Serves a mask test.

This test runs on every Add. It is inline on purpose: a library call on each Add of a program with no observers would be paying for a feature nobody asked for.

function

Watches

#
bool Watches( const ETL_UINT32 uId ) const noexcept

true when someone watches uId.

function

Notify

#
void Notify( EObserverEvent eEvent, SEntity Who, ETL_UINT32 uId, const void * pValue, ETL_UINT32 uSize ) noexcept;

Records an event. Calls nobody.

eEvent
What happened.
Who
The entity.
uId
Component id.
pValue
Bytes of the component. May be null.
uSize
Size of pValue.
function

Dispatch

#
std::size_t Dispatch() noexcept;

Delivers every recorded event and empties the list.

Called where the command buffer is applied: at the end of a stage, when no iteration is running. CSystemScheduler does it, and code that runs systems by hand calls it by hand.

An observer may change the world, which is what it is for. The events it causes are kept for the next delivery, not this one. Otherwise a chain of observers calling each other would never end.

How many callbacks were called.
function

Pending

#
std::size_t Pending() const noexcept

Events waiting for delivery.

function

Dropped

#
std::size_t Dropped() const noexcept

Events lost because they did not fit.

function

WatchCount

#
std::size_t WatchCount() const noexcept;

Number of watches.

query.hpp

#include <ethereal/cpp/ecs/query.hpp>

Queries of the Ecs module.

A query is a list of matching archetypes, and iterating walks their chunks. Inside a chunk it is a loop over flat arrays with unit stride, which is what lets the compiler vectorize.

The list is computed once. The spec: "a query caches its matching archetype list and is invalidated only when a new archetype is created". Creating or destroying an entity invalidates nothing. Adding a component only invalidates when the target archetype did not exist yet, and it comes to exist once in the life of the program.

ForEachChunk is the path the benchmarks use. It hands out ( SEntity , T0 , T1 *, ..., size_t ), raw pointers to the chunk arrays. The documentation recommends it for hot systems, and the one million entity benchmark uses it. ForEach is per entity, easier and slower: each step pays one more indirection and the compiler has much less to work with.

struct

SChunkView

Ethereal::Ecs#
C++
struct   SChunkView   final
{
    /// @brief    The entities of this chunk. Always the first column, always present.
    SEntity *        pEntities = nullptr;

    /// @brief    One per requested component, in the order they were requested.
    ///            Null for a tag.
    void **            ppColumns = nullptr;

    /// @brief    Number of columns in ppColumns.
    std::size_t        uColumnCount = 0u;

    /// @brief    Entities in the chunk.
    std::size_t        uCount = 0u;

    /// @brief    Version of the chunk (see SChunk::uVersion).
    ETL_UINT32        uVersion = 0u;
};

A chunk, seen from outside the template.

const

kMaxQueryColumns

Ethereal::Ecs#
inline constexpr std::size_t kMaxQueryColumns = 32u;

How many components fit in a query by ids.

Fixed so the walk allocates nothing: the columns of each chunk live on the stack of the caller.

class

CDynamicQuery

Ethereal::Ecs#

A query built from component ids instead of types.

class CDynamicQuery final

CQuery< SPos, SVel > is the normal path and the fast one: the columns are resolved in the template and the loop stays flat. The types are not always known. A C API cannot take templates (the spec: "the template surface does not cross"), and an editor, an interpreter or a scene loader does not know them either. What they have is a list of ids.

The cost: columns are resolved per archetype instead of per type, and the callback gets 'void **' instead of typed pointers. The inner loop is still flat and over the same arrays. What is lost is the compiler knowing the types, and with it the chance to inline the body into the loop.

alias

void

#
using ChunkFn = void ( * )( void * pCtx, const SChunkView & View );

Chunk callback.

constructor

CDynamicQuery

#
CDynamicQuery() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( CWorld & World, const ETL_UINT32 * pInclude, std::size_t uInclude, const ETL_UINT32 * pExclude, std::size_t uExclude ) noexcept;

Sets the components to include and to exclude.

This query declares no access, and it could not: it does not know what the caller does with the pointers. It skips the scheduler check, and a system that uses it must declare the access by hand in its descriptor.

World
The world to query.
pInclude
Required components. Also the order of the columns.
uInclude
Number of required components, up to kMaxQueryColumns.
pExclude
Components that rule an archetype out.
uExclude
Number of excluded components.
eOk, eInvalidArgument or eBadComponent. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

ForEachChunk

#
void ForEachChunk( ChunkFn pFn, void * pCtx ) noexcept;

Calls pFn once per non empty chunk.

function

Count

#
std::size_t Count() noexcept;

Number of matching entities.

function

ChunkCount

#
std::size_t ChunkCount() noexcept;

Number of chunks in the matching archetypes.

alias

TBare

Ethereal::Ecs#
template< typename T > using TBare = typename std::remove_const< T >::type;
class

CQuery

Ethereal::Ecs#

A view over the entities that have all these components.

template< typename... TInclude > class CQuery final

The const in the template argument is the access declaration: CQuery< const SPos, SVel > reads the position and writes the velocity. This is what makes parallel execution checkable. The scheduler runs two systems at the same time because they declared that they do not overlap, and the query is where the declaration meets what the code does.

Half of the check never reaches runtime: ForEachChunk hands out 'const SPos ' and 'SVel ', so writing to a position declared as read does not compile.

constructor

CQuery

#
explicit CQuery( CWorld & World ) noexcept : m_pWorld( &World )

Builds the masks and reports the access to the scheduler.

function

Without

#
template< typename... TExclude > CQuery & Without() noexcept

Excludes entities that have any of these.

function

Changed

#
CQuery & Changed( const ETL_UINT32 uSinceVersion ) noexcept

Only the chunks written after the last pass of this consumer.

The version is per chunk, not per entity. A mark per entity would cost one byte per entity and one store per write, and the spec says that is too expensive.

The cost: a chunk counts as changed even if only one of its hundreds of entities changed.

uSinceVersion
Chunk version seen on the last pass.
This query.
function

Count

#
std::size_t Count() noexcept

Number of matching entities.

function

ForEachChunk

#
template< typename TFn > void ForEachChunk( TFn && Fn ) noexcept

The fast path: raw pointers and a flat loop.

Fn( SEntity pEntities, TInclude ... pArrays, std::size_t uCount ). Inside a chunk there is no indirection, no test per entity, and the arrays do not overlap. That is what the compiler needs to vectorize.

function

ForEach

#
template< typename TFn > void ForEach( TFn && Fn ) noexcept

Per entity. Easier and slower, see ForEachChunk.

function

ChunkCount

#
std::size_t ChunkCount() noexcept

How many chunks this query covers.

function

MatchedArchetypes

#
std::size_t MatchedArchetypes() noexcept

How many archetypes match.

resources.hpp

#include <ethereal/cpp/ecs/resources.hpp>

Resources of the Ecs module: singletons that are not per entity.

The spec: "singleton data that is not per entity (time, input state, render context), stored separately from archetypes and accessed by type with a direct array index".

A resource is not an entity with a component. That is the obvious temptation (an ECS already stores data) and it is wrong for three reasons:

  • One archetype per resource. Each singleton with its own component set creates an archetype with one entity and a 16 KB chunk to hold it. Ten singletons are ten chunks with one row each.
  • Each of them enters every query that happens to match. A query for STime would have to exclude them by hand.
  • Reading one would cost a random access: find the entity, the chunk, the row. Here it costs one array index, which is what the spec asks for.

Resource ids come from another counter. A resource is not a component and takes no bit in the archetype mask. Spending the 256 slots of the mask on things that never appear in an archetype would be waste.

const

kMaxResources

Ethereal::Ecs#
inline constexpr ETL_UINT32 kMaxResources = 128u;

How many resource types fit in a world.

function

RegisterResource

Ethereal::Ecs#
ETL_UINT32 RegisterResource( ETL_UINT32 uSize, ETL_UINT32 uAlignment, const ETL_CHAR * pName ) noexcept;

Registers a resource type and returns its id.

uSize
Size of the type.
uAlignment
Alignment of the type.
pName
Optional name. May be null.
The new id, or kMaxResources when the registry is full.
function

RegisteredResourceCount

Ethereal::Ecs#
ETL_UINT32 RegisteredResourceCount() noexcept;

Number of resource types registered so far.

function

ResourceSize

Ethereal::Ecs#
ETL_UINT32 ResourceSize( ETL_UINT32 uId ) noexcept;

Size of a resource type. Zero for an id out of range.

function

ResourceId

Ethereal::Ecs#
template< typename T > ETL_UINT32 ResourceId() noexcept

The id of T in this process. Assigned on first use.

class

CResources

Ethereal::Ecs#

Where the singletons of a world live.

class CResources final
constructor

CResources

#
CResources() = default;

Default constructor.

function

SetRaw

#
EStatus SetRaw( ETL_UINT32 uId, const void * pValue, ETL_UINT32 uSize ) noexcept;

Sets a resource, or writes over it. The first time allocates the bytes.

This is the only function of this file that allocates, and it belongs to startup: a resource is set once and read thousands of times. A new resource starts zeroed.

uId
Resource id.
pValue
Value to copy. Null keeps the current bytes.
uSize
Size of the type. Must match the first call.
eOk, eInvalidArgument or eOutOfMemory.
function

GetRaw

#
void * GetRaw( const ETL_UINT32 uId ) const noexcept

The bytes of a resource, or nullptr.

One array index and nothing else, which is why this store exists. It is inline on purpose: a library call per read would undo half of the point.

function

HasRaw

#
bool HasRaw( const ETL_UINT32 uId ) const noexcept

true when the resource exists.

function

RemoveRaw

#
bool RemoveRaw( ETL_UINT32 uId ) noexcept;

Frees the bytes. The resource stops existing, it is not zeroed.

function

Clear

#
void Clear() noexcept;

Frees every resource.

function

Count

#
std::size_t Count() const noexcept;

Number of resources that exist.

function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes used by the resources.

function

Set

#
template< typename T > EStatus Set( const T & Value ) noexcept

Sets resource T.

function

GetOrAdd

#
template< typename T > T * GetOrAdd() noexcept

Creates the resource zeroed when it does not exist, and returns it.

function

Get

#
template< typename T > T * Get() const noexcept

Resource T, or nullptr.

function

Has

#
template< typename T > bool Has() const noexcept

true when resource T exists.

function

Remove

#
template< typename T > bool Remove() noexcept

Frees resource T.

serialize.hpp

#include <ethereal/cpp/ecs/serialize.hpp>

Saving and loading worlds in the Ecs module.

The spec asks for "an ISerializer seam", and section 2 of the conventions explains why: this module cannot include the Serialization module to get functionality, and it promised "Depends on: nothing at link time".

The seam is two virtual functions called once per block of bytes, not per entity and even less per component. One virtual call per megabyte shows up in no measurement.

class

IEcsWriter

Ethereal::Ecs#

Where a world snapshot goes.

class IEcsWriter
destructor

~IEcsWriter

#
virtual ~IEcsWriter() = default;

Virtual destructor.

function

Write

#
virtual bool Write( const void * pData, std::size_t uBytes ) noexcept = 0;

Writes uBytes from pData.

false when it did not fit. Saving stops there.
class

IEcsReader

Ethereal::Ecs#
class IEcsReader
destructor

~IEcsReader

#
virtual ~IEcsReader() = default;

Virtual destructor.

function

Read

#
virtual bool Read( void * pData, std::size_t uBytes ) noexcept = 0;

Reads uBytes into pData. false when there are not enough bytes.

function

Remaining

#
virtual std::size_t Remaining() const noexcept = 0;

Bytes left. It is what stops a truncated file from making the load allocate memory that does not exist.

function

SetComponentName

Ethereal::Ecs#
EStatus SetComponentName( ETL_UINT32 uId, const ETL_CHAR * pName ) noexcept;
function

NameComponent

Ethereal::Ecs#
template< typename T > EStatus NameComponent( const ETL_CHAR * const pName ) noexcept

Names component T. See SetComponentName.

class

CEntityRemap

Ethereal::Ecs#

From what an entity was to what it is now.

class CEntityRemap final

The spec: "entity ID remapping on load, since indices will differ". A loaded world creates the entities again, and the indices they get depend on what was already there. A saved handle is worth nothing after a load, and this table makes it useful again.

A component that stores an entity inside (a parent, a target, an owner) keeps a stale handle. Saving the bytes is not enough, someone has to fix them. See SetComponentFixup.

function

Clear

#
void Clear() noexcept;

Empties the table.

function

Add

#
void Add( SEntity Old, SEntity New ) noexcept;

Records that Old is now New.

function

Map

#
SEntity Map( SEntity Old ) const noexcept;

Translates. SEntity::None() for a handle that was not in the snapshot.

function

Count

#
std::size_t Count() const noexcept

Number of pairs added.

alias

void

Ethereal::Ecs#
using FixupFn = void ( * )( void * pComponent, const CEntityRemap & Remap );
function

SetComponentFixup

Ethereal::Ecs#
EStatus SetComponentFixup( ETL_UINT32 uId, FixupFn pFn ) noexcept;

Tells how to fix the handles stored inside a component.

The module does not guess which fields of a component are entities, and it cannot without a type description, which this SDK does not have and will not have. Who stores an entity inside a component says here how to fix it.

SParent comes with its own, because it belongs to the module.

uId
Component id.
pFn
The fixup. Null removes it.
eOk or eInvalidArgument.
function

SetFixup

Ethereal::Ecs#
template< typename T > EStatus SetFixup( const FixupFn pFn ) noexcept

Sets the fixup of T. See SetComponentFixup.

const

kMaxSkipped

Ethereal::Ecs#
inline constexpr std::size_t kMaxSkipped = 32u;

How many components a report can list as skipped.

const

kMaxComponentName

Ethereal::Ecs#
inline constexpr std::size_t kMaxComponentName = 64u;

Bytes of the longest component name a snapshot carries, the terminator included. SetComponentName refuses longer names.

struct

SSaveReport

Ethereal::Ecs#
C++
struct   SSaveReport   final
{
    /// @brief    Entities written.
    ETL_UINT64        uEntities = 0;

    /// @brief    Archetypes written.
    ETL_UINT64        uArchetypes = 0;

    /// @brief    Bytes the writer accepted. On eOverflow, the ones before the refusal.
    ETL_UINT64        uBytes = 0;

    /// @brief    How many were left out for not being trivially copyable.
    ///
    /// @details    Their bytes are pointers into memory of this run. Saving them
    ///                would save addresses that mean nothing when read back.
    ETL_UINT32        uNonTrivialComponents = 0u;

    /// @brief    How many component types were left out for having no name.
    ETL_UINT32        uUnnamedComponents = 0u;

    /// @brief    Their ids, so the report can say which.
    ETL_UINT32        uSkipped[ kMaxSkipped ] = {};
};

What SaveWorld wrote.

struct

SLoadReport

Ethereal::Ecs#
C++
struct   SLoadReport   final
{
    /// @brief    Entities created.
    ETL_UINT64        uEntities = 0;

    /// @brief    Archetypes read.
    ETL_UINT64        uArchetypes = 0;

    /// @brief    How many types were in the snapshot and are unknown to this program.
    ETL_UINT32        uUnknown = 0u;

    /// @brief    Their names, copied into the report.
    ///
    /// @details    They used to be pointers into a table shared by every load,
    ///                and two loads on different threads overwrote each other.
    ///                The copy belongs to the report and lives as long as it does.
    ///
    ETL_CHAR        aSkipped[ kMaxSkipped ][ kMaxComponentName ] = {};

    /// @brief    Component values skipped, over all entities.
    ETL_UINT64        uSkippedComponents = 0;
};

What LoadWorld read.

The spec: "unknown components are skipped with a report rather than failing the whole load". It is the difference between a game save that still opens after an update and a player who loses everything. The snapshot stores the size of each component, so one this program does not know is skipped by size and the rest of the entity is still read.

The cost: the entity comes back without that component, and so in another archetype. If it was what made the entity match a query, it stops matching. The report says which ones, so the caller can decide.

function

SaveWorld

Ethereal::Ecs#
EStatus SaveWorld( CWorld & World, IEcsWriter & Writer, SSaveReport * pReport ) noexcept;

Writes a snapshot of the whole world.

It does not save the resources nor the hierarchy. The resources belong to the program, not to the world, and the hierarchy is rebuilt from the SParent components the snapshot carries.

World
The world.
Writer
Where the bytes go.
pReport
Receives the report. May be null.
eOk, or eOverflow when the writer refused bytes. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

LoadWorld

Ethereal::Ecs#
EStatus LoadWorld( CWorld & World, IEcsReader & Reader, CEntityRemap * pRemap, SLoadReport * pReport ) noexcept;

Loads a snapshot into a world that is already running, keeping what is there.

World
The world.
Reader
Where the bytes come from.
pRemap
Receives the handle translation. May be null.
pReport
Receives the report. May be null.
eOk, or eInvalidArgument for a bad or truncated snapshot. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

BindModuleDefaults

Ethereal::Ecs#
void BindModuleDefaults() noexcept;

Binds the name and the fixup of SParent.

It belongs to the module, so the module brings it. Who saves a scene tree does not have to know that SParent stores an entity inside, nor remember to name it.

Call it once, at startup, before saving or loading.

class

CMemoryWriter

Ethereal::Ecs#

Writes into a byte vector.

class CMemoryWriter final : public IEcsWriter
function

Write

#
bool Write( const void * pData, std::size_t uBytes ) noexcept override;

Appends the bytes. Always true.

function

Bytes

#
const std::vector< ETL_UINT8 > & Bytes() const noexcept

The bytes written so far.

function

Clear

#
void Clear() noexcept

Drops the bytes.

class

CMemoryReader

Ethereal::Ecs#

Reads from a block of bytes it does not own.

class CMemoryReader final : public IEcsReader
constructor

CMemoryReader

#
CMemoryReader( const ETL_UINT8 * const pBytes, const std::size_t uBytes ) noexcept : m_pBytes( pBytes ), m_uBytes( uBytes )

Reads from pBytes. The block must outlive the reader.

function

Read

#
bool Read( void * pData, std::size_t uBytes ) noexcept override;

Copies the next uBytes. false when there are not enough.

function

Remaining

#
std::size_t Remaining() const noexcept override

Bytes left.

system.hpp

#include <ethereal/cpp/ecs/system.hpp>

Systems, stages and the scheduler of the Ecs module.

The spec: "stages create explicit sync points where deferred commands are applied". Inside a stage the systems run, possibly in parallel, and none of them changes the structure of the world: what they do is write commands. At the end of the stage the commands of all of them are applied in a fixed order.

That is what makes everything predictable. A system that deleted an entity in the middle of the stage would pull the floor from another walking the same chunk, and since both could be on different cores, the defect would only show up now and then.

The scheduler brings no threads, on purpose. The spec says "Depends on: nothing at link time" and makes parallel execution "optional glue with Concurrency". If this module brought its own thread pool, who only wants the ECS would drag it along, and who already has a pool would end up with two. So it brings the seam: the scheduler says "run these N tasks and return when all are done", and whoever gives it an executor decides with which threads. Without an executor everything runs in sequence, which is correct and is the default.

enum

EStage

Ethereal::Ecs#
C++
enum class   EStage : ETL_UINT8
{
    /// @brief    Before everything: input, time, incoming network.
    eFirst = 0,

    /// @brief    Before the main update.
    ePreUpdate,

    /// @brief    Where almost everything lives.
    eUpdate,

    /// @brief    After the main update.
    ePostUpdate,

    /// @brief    After everything: presentation, outgoing network.
    eLast,

    /// @brief    Number of stages.
    eCount
};

The order in which systems run. There is a sync point between stages.

const

kStageCount

Ethereal::Ecs#
inline constexpr ETL_UINT32 kStageCount = static_cast< ETL_UINT32 >( EStage::eCount );

Number of stages, as an integer.

struct

SSystemDescriptor

Ethereal::Ecs#
C++
struct   SSystemDescriptor   final
{
    /// @brief    sizeof( SSystemDescriptor ), for version checks.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SSystemDescriptor ) );

    /// @brief    The name. The order is declared by name, and it must be unique.
    const ETL_CHAR *    pName = nullptr;

    /// @brief    Passed back to pRun.
    void *            pContext = nullptr;

    /// @brief    The system body.
    void            ( * pRun )( void * pCtx, CWorld & World, float fDelta ) = nullptr;

    /// @brief    Components the system reads.
    ///
    /// @details    This is not documentation: it decides who runs next to whom. Two
    ///                systems run at the same time when their masks do not overlap,
    ///                and the detection is a bitwise AND.
    ///
    ///                It is checked. A query that touches a component the system did
    ///                not declare makes Run return eUndeclaredAccess (see
    ///                SSchedulerParams).
    SComponentMask    Reads;

    /// @brief    Components the system writes.
    SComponentMask    Writes;

    /// @brief    Runs after these. Names, which may not have been added yet.
    const ETL_CHAR * const *    pAfter = nullptr;

    /// @brief    Number of names in pAfter.
    std::size_t        uAfter = 0u;

    /// @brief    Runs before these.
    const ETL_CHAR * const *    pBefore = nullptr;

    /// @brief    Number of names in pBefore.
    std::size_t        uBefore = 0u;

    /// @brief    The stage.
    EStage            eStage = EStage::eUpdate;
};

All the scheduler needs to know about a system.

class

IExecutor

Ethereal::Ecs#

Runs a group of systems that do not overlap.

class IExecutor
destructor

~IExecutor

#
virtual ~IExecutor() = default;

Virtual destructor.

function

RunAll

#
virtual void RunAll( void ( * pFn )( void * pCtx, std::size_t i ), void * pCtx, std::size_t uCount ) noexcept = 0;

Runs pFn( pCtx, i ) for i from zero to uCount, and returns only when all are done.

pFn
The task.
pCtx
Passed back to pFn.
uCount
Number of tasks.
function

Width

#
virtual std::size_t Width() const noexcept = 0;

How many run at the same time. It is how many command buffers the scheduler prepares.

function

SerialExecutor

Ethereal::Ecs#
IExecutor & SerialExecutor() noexcept;
struct

SSchedulerParams

Ethereal::Ecs#
C++
struct   SSchedulerParams   final
{
    /// @brief    sizeof( SSchedulerParams ), for version checks.
    ETL_UINT32        uStructSize = static_cast< ETL_UINT32 >( sizeof( SSchedulerParams ) );

    /// @brief    Who runs the groups. Null runs in sequence.
    IExecutor *        pExecutor = nullptr;

    /// @brief    How many commands fit in the buffer of each worker.
    std::size_t        uCommandsPerWorker = 4096u;

    /// @brief    Bytes for component values in the buffer of each worker.
    std::size_t        uBytesPerWorker = 256u * 1024u;

    /// @brief    Access check: on in debug builds, off in Release.
    ///
    /// @details    The spec asks for "a hard error in debug builds". In Release it
    ///                would cost two mask compares per query built, little, but in a
    ///                place where there should be nothing.
    ///
    ///                The hard error is Run returning eUndeclaredAccess. This module
    ///                does not use exceptions and does not kill the process on its
    ///                own. Refusing the pass is the hardest error it can give, and a
    ///                test can check it, which an abort would not allow.
#ifdef ETHEREAL_DEBUG_BUILD
    bool            bCheckAccess = true;
#else
    bool            bCheckAccess = false;
#endif
};

Scheduler parameters.

struct

SSchedulerStats

Ethereal::Ecs#
C++
struct   SSchedulerStats   final
{
    /// @brief    Calls to Run.
    ETL_UINT64    uRounds = 0;

    /// @brief    Systems run.
    ETL_UINT64    uSystemsRun = 0;

    /// @brief    Groups run.
    ETL_UINT64    uGroups = 0;

    /// @brief    Commands applied at sync points.
    ETL_UINT64    uCommandsApplied = 0;

    /// @brief    Undeclared accesses detected.
    ETL_UINT64    uAccessViolations = 0;

    /// @brief    Size of the largest group run.
    ETL_UINT64    uLargestGroup = 0;
};

Scheduler counters.

class

CSystemScheduler

Ethereal::Ecs#

Orders the systems, groups them and runs them stage by stage.

class CSystemScheduler final
constructor

CSystemScheduler

#
CSystemScheduler() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( CWorld & World, const SSchedulerParams & Params ) noexcept;

Binds the scheduler to a world and makes one command buffer per worker.

World
The world.
Params
Scheduler parameters.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Add

#
EStatus Add( const SSystemDescriptor & Desc ) noexcept;

Adds a system. The order of the calls does not matter, pAfter and pBefore do.

function

Build

#
EStatus Build() noexcept;

Sorts the systems and builds the groups.

The spec: "ordering is a topological sort with cycle reporting". A cycle (A after B, B after A) has no solution, and the only thing worse than no solution is picking one silently. Build returns eCycle and the names of the systems left unsorted are in CycleName.

Run without Build calls it.

function

CycleCount

#
std::size_t CycleCount() const noexcept;

Systems a cycle left unsorted. Zero when there was none.

function

CycleName

#
const ETL_CHAR * CycleName( std::size_t i ) const noexcept;

Name of the i-th system left unsorted, or nullptr.

function

Run

#
EStatus Run( float fDelta ) noexcept;

One pass: every stage, in order, with a sync point between them.

function

CurrentCommands

#
static CCommandBuffer * CurrentCommands() noexcept;

The command buffer of the running system.

A system does not get the buffer as a parameter, the signature the spec fixes has no room for it. It gets it here, and what it gets is the buffer of that worker, not a shared one. So two systems running at the same time write commands without touching, and the merge at the end of the stage is in worker order, which is what makes two runs of the same program give the same world.

function

CurrentSystem

#
static const SSystemDescriptor * CurrentSystem() noexcept;

The system running on this thread, or nullptr.

function

Stats

#
SSchedulerStats Stats() const noexcept;

Scheduler counters.

function

SystemCount

#
std::size_t SystemCount() const noexcept;

Number of systems added.

function

GroupCount

#
std::size_t GroupCount( EStage eStage ) const noexcept;

How many groups a stage ended up with. A group is a set of systems that do not overlap and may run at the same time.

function

GroupSize

#
std::size_t GroupSize( EStage eStage, std::size_t uGroup ) const noexcept;

Number of systems in a group.

function

GroupMember

#
const ETL_CHAR * GroupMember( EStage eStage, std::size_t uGroup, std::size_t i ) const noexcept;

Name of the i-th system of a group, or nullptr.

function

Conflict

Ethereal::Ecs#
bool Conflict( const SSystemDescriptor & A, const SSystemDescriptor & B ) noexcept
function

MaskOf

Ethereal::Ecs#
template< typename... T > SComponentMask MaskOf() noexcept

Mask with the components T... (const is ignored).

function

noexcept

Ethereal::Ecs#
template<> inline SComponentMask MaskOf<>() noexcept

Empty mask.

world.hpp

#include <ethereal/cpp/ecs/world.hpp>

The world of the Ecs module: chunks, archetypes and entities.

A chunk of 16 KB holds the entities of one archetype as a structure of arrays:

[ header, 64 bytes ][ SEntity[N] ][ C0[N] ][ C1[N] ][ ... ]

A system that reads only position and velocity walks two dense arrays and touches nothing else. With an array of structures, each cache line would also bring the components that system does not use, and the bandwidth would go to data that is thrown away.

The header takes a whole cache line for two reasons: the arrays start aligned, and the entity count (which changes on every creation) does not share a line with data the systems are reading.

const

kNoArchetype

Ethereal::Ecs#
inline constexpr ETL_UINT32 kNoArchetype = 0xFFFFFFFFu;

Archetype index of an entity that is in no archetype.

const

kNoColumn

Ethereal::Ecs#
inline constexpr ETL_UINT32 kNoColumn = 0xFFFFFFFFu;

Column offset of a component with no array (a tag), or a column not found.

struct

SChunk

Ethereal::Ecs#
C++
ETL_BEGIN_INTENDED_PADDING
struct   alignas( 64 )   SChunk   final
{
    /// @brief    Entities stored in the chunk.
    ETL_UINT32        uCount = 0u;

    /// @brief    Goes up on every write. It is what change detection compares.
    ///
    /// @details    Per chunk, not per entity. A mark per entity would cost one byte
    ///                per entity and one store per write, and the spec says that is
    ///                too expensive.
    ETL_UINT32        uVersion = 0u;

    /// @brief    Archetype that owns the chunk, or kNoArchetype when it is free.
    ETL_UINT32        uArchetype = kNoArchetype;

    /// @brief    Position of the chunk in the chunk list of its archetype.
    ETL_UINT32        uIndexInArchetype = 0u;

    /// @brief    Link of the free chunk list of the pool.
    SChunk *        pNextFree = nullptr;


    /// @brief    Start of the arrays, right after the header.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE ETL_UINT8 * Data() ETL_NOEXCEPT
    {
        return reinterpret_cast< ETL_UINT8 * >( this ) + kChunkHeaderBytes;
    }


    /// @brief    Start of the arrays, right after the header.
    ///
    ETL_API_NOIGN    ETL_FORCE_INLINE const ETL_UINT8 * Data() const ETL_NOEXCEPT
    {
        return reinterpret_cast< const ETL_UINT8 * >( this ) + kChunkHeaderBytes;
    }
};

Header of a chunk. It lives in the first 64 bytes of the chunk itself.

The padding of this type is intended (the alignment). See 'ETL_BEGIN_INTENDED_PADDING'.

struct

SArchetype

Ethereal::Ecs#
C++
struct   SArchetype   final
{
    /// @brief    The component set.
    SComponentMask                Mask;

    /// @brief    Component ids, in increasing order. Tags included.
    std::vector< ETL_UINT32 >    Ids;

    /// @brief    Where the array of each component starts, inside the chunk data.
    ///            @ref kNoColumn for tags, which have no array.
    std::vector< ETL_UINT32 >    Offsets;

    /// @brief    Bytes per entity of each component.
    std::vector< ETL_UINT32 >    Sizes;

    /// @brief    How many entities fit in a chunk of this archetype.
    ETL_UINT32                    uCapacity = 0u;

    /// @brief    The chunks of this archetype.
    std::vector< SChunk * >        Chunks;


    /// @brief    Column of a component, or @ref kNoColumn.
    ///
    ETL_API_NOIGN    ETL_UINT32 Column( const ETL_UINT32 uId ) const ETL_NOEXCEPT
    {
        for( std::size_t i = 0; i < Ids.size(); ++i )
        {
            if( Ids[ i ] == uId )
                return static_cast< ETL_UINT32 >( i );
        }

        return kNoColumn;
    }
};

All the entities with exactly this component set.

struct

SEntityRecord

Ethereal::Ecs#
C++
struct   SEntityRecord   final
{
    /// @brief    Which of the entities that used this slot the handle refers to.
    ETL_UINT32        uGeneration = 0u;

    /// @brief    Archetype of the entity, or kNoArchetype.
    ETL_UINT32        uArchetype = kNoArchetype;

    /// @brief    Chunk, as a position in the chunk list of the archetype.
    ETL_UINT32        uChunk = 0u;

    /// @brief    Row inside the chunk.
    ETL_UINT32        uRow = 0u;
};

Where an entity lives. Sixteen bytes, in a dense array.

class

CWorld

Ethereal::Ecs#

Entities, archetypes, chunks, resources and observers.

class CWorld final

Adding a component to an entity is a migration: the new mask is computed, the archetype with that mask is found or created, a row is taken in one of its chunks, the shared components are copied array by array, and the entity leaves the old chunk with the last one moved into the hole. It costs, and the spec asks to measure and document it. That is why CreateWith exists: creating with three components is one migration, creating and adding three is four.

constructor

CWorld

#
CWorld() = default;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const SWorldParams & Params ) noexcept;

Reserves the record table and the first chunks.

Params
World parameters.
eOk, eInvalidArgument or eOutOfMemory. Also eNotLicensed when the library is not licensed (see Bundle::UnlockBundle).
function

Create

#
SEntity Create() noexcept;

Creates an entity with no components. SEntity::None() on failure.

function

Destroy

#
void Destroy( SEntity E ) noexcept;

Destroys an entity. A dead handle is ignored.

function

IsAlive

#
bool IsAlive( const SEntity E ) const noexcept

true when the handle refers to a live entity.

One array index and one compare, never a hash map lookup, as the spec requires. This is called everywhere: on each deferred command, each random access query, each hierarchy walk. A hash would cost a cache miss per call.

The generation is what makes one compare enough. Destroying an entity advances it, so no old handle matches again, even when the index is recycled.

function

CreateBatch

#
std::size_t CreateBatch( std::size_t uCount, SEntity * pOut ) noexcept;

Creates many entities with no components.

The spec requires the batch path to be at least 10x faster than creating 100 000 entities one at a time. One at a time finds the archetype, finds a chunk with room and writes the record, per entity. In a batch all of that is done once per chunk, and what is left per entity is writing eight bytes in the entity array and sixteen in the record.

uCount
How many to create.
pOut
Receives the handles. May be null.
How many were created.
function

DestroyBatch

#
void DestroyBatch( const SEntity * pEntities, std::size_t uCount ) noexcept;

Destroys many entities.

pEntities
The handles.
uCount
How many.
function

AddRaw

#
EStatus AddRaw( SEntity E, ETL_UINT32 uId, const void * pValue ) noexcept;

Adds a component, or overwrites it when the entity already has it.

E
The entity.
uId
Component id.
pValue
Initial value. Null leaves it zeroed for a trivial type.
eOk, eDeadEntity or eBadComponent.
function

RemoveRaw

#
EStatus RemoveRaw( SEntity E, ETL_UINT32 uId ) noexcept;

Removes a component. eOk when the entity did not have it.

function

GetRaw

#
void * GetRaw( SEntity E, ETL_UINT32 uId ) noexcept;

Pointer to a component, or nullptr (dead entity, missing, or a tag).

function

HasRaw

#
bool HasRaw( const SEntity E, const ETL_UINT32 uId ) const noexcept

true when the entity is alive and has the component.

function

Add

#
template< typename T > EStatus Add( const SEntity E, const T & Value ) noexcept

Adds T with a value.

function

Add

#
template< typename T > EStatus Add( const SEntity E ) noexcept

Adds T without a value (a tag, or a zeroed component).

function

Remove

#
template< typename T > EStatus Remove( const SEntity E ) noexcept

Removes T.

function

Get

#
template< typename T > T * Get( const SEntity E ) noexcept

Random access. This is the slow path.

Systems use queries. Here each entity is an indirection to a chunk that may be anywhere in memory, which is the pattern the archetype exists to avoid.

function

Has

#
template< typename T > bool Has( const SEntity E ) const noexcept

true when the entity is alive and has T.

function

CreateWithRaw

#
SEntity CreateWithRaw( const ETL_UINT32 * pIds, const void * const * pValues, std::size_t uCount ) noexcept;

Creates an entity with these components, by id. One migration instead of N.

Serialization and the C API use it. Neither knows the types, and neither can pay one migration per component.

pIds
Component ids.
pValues
One value per id. A null value is a tag or a zeroed component.
uCount
Number of ids.
The entity, or SEntity::None() on failure.
function

CreateWith

#
template< typename... TComponents > SEntity CreateWith( const TComponents &... Values ) noexcept

Creates an entity with these components. One migration instead of N.

function

Resources

#
CResources & Resources() noexcept

The resources of this world.

Singletons are not entities (see resources.hpp). A singleton as an entity would need an archetype with one row, a 16 KB chunk to hold it, and it would show up in every query that happened to match. Here reading one costs an array index.

function

Resources

#
const CResources & Resources() const noexcept

The resources of this world.

function

Observers

#
CObservers & Observers() noexcept

The observers of this world.

The world only records the events. A sync point delivers them (see observer.hpp). With no observers, this costs one bitwise AND per Add.

function

SetResource

#
template< typename T > EStatus SetResource( const T & Value ) noexcept

Sets resource T.

function

GetResource

#
template< typename T > T * GetResource() const noexcept

Resource T, or nullptr.

function

GetOrAddResource

#
template< typename T > T * GetOrAddResource() noexcept

Resource T, created zeroed when missing.

function

HasResource

#
template< typename T > bool HasResource() const noexcept

true when resource T exists.

function

ArchetypeCount

#
std::size_t ArchetypeCount() const noexcept

Number of archetypes.

function

Archetype

#
const SArchetype & Archetype( const std::size_t i ) const noexcept

Archetype i.

function

Archetype

#
SArchetype & Archetype( const std::size_t i ) noexcept

Archetype i.

function

ArchetypeVersion

#
ETL_UINT64 ArchetypeVersion() const noexcept

Goes up whenever an archetype is created. It invalidates the list a query keeps, and nothing else does.

function

Stats

#
SWorldStats Stats() const noexcept;

World counters.

function

EntityCapacity

#
std::size_t EntityCapacity() const noexcept

Size of the record table.

function

Record

#
const SEntityRecord * Record( const SEntity E ) const noexcept

Where an entity lives, or nullptr. Used by queries and commands.