Skip to content

12 · Systems

What it is

A system is logic: a function that reads and writes the world through queries, resources, events and commands. Components hold data; systems hold every behavior of the game (movement, shooting, damage, spawning waves, drawing).

Why we need it

  • Principles: keeping all logic in systems is what makes components replicable, scriptable and serializable.
  • R2 (Luau): most gameplay systems are written in Luau.
  • R4: declared access lets the scheduler order systems, and later run them in parallel, without changing them.

How others do it

ECS System style Access known by the scheduler?
Bevy Free function; parameters (Query, Res, Commands...) deduced from the signature Yes, from the types
flecs world.system<A, B>().each(callback) Yes, from the query
Unity DOTS ISystem struct with OnUpdate Yes, from queries
Unreal Mass UMassProcessor class with ConfigureQueries + Execute Yes
EnTT No systems: plain functions over views No

Our choice

  • C++: Bevy-style free functions (or lambdas). The parameters are deduced from the signature at registration, which gives the system's access set.
  • Luau: system classes: a table declaring name, phase, query and options, with a run method.
  • Both register the same way into the scheduler, with a name, a phase, ordering constraints, an access set and a side (server, client or both).

How it works

C++ systems

void movement(rtype::ecs::Query<Transform, const Velocity> query, rtype::ecs::Res<Time> time) {
    for (auto [entity, transform, velocity] : query) {
        transform->position += velocity.value * time->fixedDelta;
    }
}

app.addSystem(rtype::ecs::Phase::kFixedUpdate, "rtype.movement", &movement)
    .setSide(rtype::ecs::Side::kBoth);

app.addSystem adds it to the world's schedules, which order, run and flush the systems of each phase. Without an App, a system can also be made from a world and run by hand:

rtype::ecs::System system{world, "rtype.movement", &movement};   // a function, or a lambda without captures
system.setSide(rtype::ecs::Side::kBoth);                          // kServer by default
system.run();             // builds the parameters, calls the function, advances the change tick
system.flushCommands();   // applies its Commands& (the scheduler: after each phase)
system.getAccess();       // what it reads and writes, for the scheduler
Parameter The system keeps Each run gets Access
Query<A, const B, ...> a QueryState (registers its components) a view with the system's lastRun writes A, reads B
Res<T> / ResMut<T> the resource's id the value (throws MissingResourceException if absent) reads / writes resource T
NonSend<T> / NonSendMut<T> same, registered main-thread only same same, and the system must run on the main thread
Commands& (its own buffer) the system's buffer none: applied at the flush
EventReader<T> its EventCursor the events it has not read yet reads event T
EventWriter<T> the event's id a writer to the queue writes event T
DynamicQueries (configured with a QueryList) the built queries a view with the system's lastRun every component of every query, read or write
DynamicResources (configured with a ResourceList) the checked list the bytes of each listed resource each resource, read or write as listed
DynamicEvents (configured with an EventList) the checked list, one EventCursor per event read(i) and send(i, bytes) per listed event each event, read or (when sent) written
DynamicCalls (configured with a CallList) a body of each listed engine call invoke(i, arguments, result) per listed call the access of every listed call

Deduction is done once by templates over the function's parameter types (SystemParam<P>): each parameter type knows what the system keeps for it, how to build it from the world, and what access it adds. Taking anything else (an int, a Query by reference, Commands by value...) is a compile error listing the accepted types; so is a lambda with captures (hidden state), except through ScriptCallable (below).

Configured parameters

Some parameters need more than the world to be built: which queries to run is chosen by the plugin adding the system, not by the parameter's type. Such a parameter is configured: its SystemParam declares a Config type and builds its state with init(World&, Config), and the configuration is given after the function when the system is added (any order; each configured parameter takes the one of its type).

DynamicQueries is the first: queries by ComponentId, for components a system does not know at compile time (the replicated ones, those a script declares), configured with a QueryList:

void snapshot(rtype::ecs::Res<ServerState> state, rtype::ecs::DynamicQueries replicated) {
    for (std::size_t query = 0; query < replicated.getCount(); ++query) {
        for (rtype::ecs::QueryMatch& match : replicated.iter(query)) {            // since this system's last run
            // match.getEntity(), match.get(0)...
        }
        for (rtype::ecs::QueryMatch& match : replicated.iterSince(query, ack)) {  // since any tick
        }
    }
}

app.addSystem(rtype::ecs::Phase::kPostUpdate, "net.snapshot", &snapshot,
              rtype::ecs::QueryList{{rtype::ecs::QueryBuilder{}.read(networkId).read(healthId)}});
  • The queries are built once, when the system is added; a query that cannot be built (an unregistered component, contradicting terms) throws a QueryException naming the query and the component. The components must therefore be registered before the system is added.
  • The system's access set gets every component of every query, so the scheduler orders it and reports ambiguities exactly as for a typed Query.
  • The view is read-only, and a term declared read refuses getMut(): the system writes nothing it did not declare.
  • Mistakes are compile errors with a message: a configured parameter without its configuration, a configuration matching no parameter, or two parameters wanting the same configuration type.

DynamicResources and DynamicEvents follow the same pattern for resources and events known only by id, configured with a ResourceList ({id, write} per resource) and an EventList ({id, read, send} per event):

void run(rtype::ecs::DynamicResources resources, rtype::ecs::DynamicEvents events) {
    std::span<const std::byte> time = resources.get(0);          // empty while the resource has no value
    std::span<std::byte> score = resources.getMut(1);            // empty unless declared write
    for (std::span<const std::byte> bytes : events.read(0)) {}   // each event once, like an EventReader
    std::array<std::byte, sizeof(Explosion)> explosion{};        // a value of the event registered as explosionId
    events.send(1, explosion);                                   // false unless declared send, or a wrong size
}

app.addSystem(rtype::ecs::Phase::kUpdate, "game.run", &run,
              rtype::ecs::ResourceList{{{timeId, false}, {scoreId, true}}},
              rtype::ecs::EventList{{{collisionId, true, false}, {explosionId, false, true}}});
  • The ids must be registered before the system is added, or an exception names the problem (TypeRegistrationException); DynamicResources also refuses a main-thread resource, since a dynamic system may run on any thread.
  • The access set gets each resource as read or written, and each event as read, or written when it is sent (an event listed as both read and sent is written), so the scheduler orders the system as for Res, ResMut, EventReader and EventWriter.
  • An event listed twice shares one cursor, so each event is read once whichever index reads it, and an event declared neither read nor sent is left out of the access set.
  • A resource declared read refuses getMut(), and an event declared only read or only sent refuses the other operation: the system does nothing it did not declare.

Script callables

A script runtime cannot give a function pointer: its system calls a function that lives in the script VM. ScriptCallable is the one way to pass a callable that keeps state, a lambda capturing a handle to that function. Its parameters are deduced from its call operator, so its access is declared as for any system:

auto run = [script](rtype::ecs::DynamicQueries queries, rtype::ecs::Commands& commands) {
    script.call(queries, commands);
};
app.addSystem(rtype::ecs::Phase::kFixedUpdate, "game.ShieldRegen", rtype::ecs::ScriptCallable{run},
              rtype::ecs::QueryList{{rtype::ecs::QueryBuilder{}.write(shieldId).without(deadId)}});

It must take explicit parameter types (no auto) and return void; it is moved into the system, so a move-only handle works. Never put game state in the captures: that is still components and resources.

Engine calls

Some of what a script needs is not data but a call: AtlasAssets::load(), InputLayout::add(), a physics query. Those resources hold maps and queues, so a script cannot get their bytes. An engine call is a named function a plugin registers on the App for scripts; ecs keeps its description, so it stays free of any script language:

struct LoadSound {
    rtype::core::asset::AssetId path;
    bool stream = false;
};
RTYPE_ECS_CALL_DATA(LoadSound, "rtype.audio.LoadSound", path, stream);   // arguments and results: call data
struct Loaded {
    rtype::core::asset::AssetId id;
};
RTYPE_ECS_CALL_DATA(Loaded, "rtype.audio.Loaded", id);

app.addCall("rtype.audio.loadSound", [](rtype::ecs::ResMut<AudioAssets> sounds, const LoadSound& args) {
    return Loaded{.id = sounds->load(args.path, {.stream = args.stream})};
});
  • The function is a function or a lambda without captures. Its parameters are system parameters that need no configuration (Res, ResMut, NonSend, NonSendMut, Query, Commands&, EventReader, EventWriter), then optionally const Args&; it returns void or call data. They give the call's access, as a system's parameters give its own (CallInfo::access).
  • Arguments and results are declared with RTYPE_ECS_CALL_DATA (standard-layout, default-constructible, moved and destroyed without throwing), so their description is a TypeInfo: a script runtime builds them from their defaults and the fields a script names, with the conversions it already has for components.
  • A field is a value, an ecs::String (255 bytes at most), or, for a longer text or a list, a std::string or a std::vector of plain values (kText and list fields, see Reflection): a prompt, a request body, a reply. Plain call data is copied in and out as bytes. Call data with a text or a list owns memory, so the call reads it in place: its bytes must be a CallBuffer of its TypeInfo (aligned, built from the defaults by its construct hook, destroyed with the buffer), for the arguments and for the result alike. The call replaces the result built there with the one it returns. checkCallBytes() refuses misaligned bytes for such data.
  • The world keeps them in its Calls (world.getCalls()), by id and by name; a name taken twice throws a CallException.
  • Calls::invoke(world, id, arguments, result) calls one outside any system (while scripts load): its parameters are built as for a first run, its commands are applied right after it, and the change tick moves forward.
  • A system that calls some at each run lists them in a CallList and takes DynamicCalls. It gets a body of each call of its own (so an EventReader of a call keeps a cursor per system), and the calls' access is merged into its own: a call that writes a resource makes the system a writer of it, and a call that uses a main-thread resource puts the system on the main thread.

Parameters from other libraries

The list above is what the ECS provides, not a closed set. SystemParam is chosen by the compiler when a system is added: no runtime registration, so a library can add a parameter type of its own by specializing rtype::ecs::SystemParam for it, in the same header as the type. Every file that adds a system taking it must include that header. The specialization gives the same three members as the built-in ones:

Member Called Does
State What the system keeps for the parameter between runs
static State init(World&) once, when the system is added Builds the state; only sees the types registered so far
static P get(State&, const SystemContext&) each run Builds the parameter from the state, context.world and context.lastRun
static void addAccess(const State&, SystemAccess&) once, when the system is added Declares every component, resource and event the parameter reads or writes

addAccess must declare everything get gives access to, and P must not allow more than it declares (no mutable access to what it declares as read): the scheduler orders systems only by what is declared. The network's ReplicatedRead (one DynamicQuery per replicated component) is one such parameter (Replication).

Parameters from other libraries

The list above is what the ECS provides, not a closed set. SystemParam is chosen by the compiler when a system is added: no runtime registration, so a library can add a parameter type of its own by specializing rtype::ecs::SystemParam for it, in the same header as the type. Every file that adds a system taking it must include that header. The specialization gives the same three members as the built-in ones:

Member Called Does
State What the system keeps for the parameter between runs
static State init(World&) once, when the system is added Builds the state; only sees the types registered so far
static P get(State&, const SystemContext&) each run Builds the parameter from the state, context.world and context.lastRun
static void addAccess(const State&, SystemAccess&) once, when the system is added Declares every component, resource and event the parameter reads or writes

addAccess must declare everything get gives access to, and P must not allow more than it declares (no mutable access to what it declares as read): the scheduler orders systems only by what is declared. The network's ReplicatedRead (one DynamicQuery per replicated component) is one such parameter (Replication).

Runs and change ticks

run() reads the world's change tick (thisRun), builds the parameters against the system's lastRun, calls the function, then sets lastRun = thisRun and advances the world's change tick by one. So the tick counts system runs, not frames, and every run has its own number:

  • Changed<T> / Added<T> and Res::isChanged() report what changed since this system last ran, including changes made earlier in the same frame by other systems;
  • a system does not see its own changes on its next run;
  • the first run sees everything as added (the initial lastRun is the oldest comparable tick);
  • if the function throws (a missing resource), the run does not count.

Luau systems

local ShieldRegen = ecs.system("game.ShieldRegen", {
    phase = "FixedUpdate",                                   -- default
    side = "server",                                         -- default
    query = { write = { "game.Shield" }, without = { "rtype.Dead" } },
    after = { "rtype.movement" },
})

function ShieldRegen:run(ctx)
    for entity, shield in ctx.query do
        shield.strength = math.min(shield.strength + shield.regen * ctx.time.fixedDelta, 100)
    end
end

return ShieldRegen

ctx gives the query results, ctx.time, ctx.commands, ctx.events, ctx.resources and ctx.call (the engine calls the table lists under calls). Because a script cannot be inspected like a C++ signature, its access is declared in the table, and the bridge refuses writes to anything declared as read-only. On the C++ side the bridge adds a ScriptCallable whose parameters are a DynamicQueries (the table's query, as a QueryList) and the other parameters ctx needs.

The side rule

Side Runs on May write
server (default) the server (and standalone) anything: this is authoritative gameplay
client clients (and standalone) only components that are neither replicated nor server-only (kClientOnly, or a local one such as GlobalTransform); a replicated component would be overwritten by replication and a server-only one does not exist there (SystemConfig::setSide() throws a ScheduleException for a replicated or server-only one; a local, never-replicated component such as GlobalTransform is accepted)
both everywhere components that are simulated identically on both sides (bullet motion for kSpawnOnly entities)

In standalone mode (single player), the App runs server and client systems in one world, so the same game code works solo and online (see App and plugins).

State

A system keeps no hidden state. A cooldown is a component on the weapon; a wave counter is a resource. A ScriptCallable's captures only hold a handle to the script function, never game state. That is what lets the server save, replicate or reload everything.

Connections

Pitfalls

  • Static variables in systems. They survive across worlds and break rooms, tests and hot reload. Use resources.
  • Big systems. A system that does five things blocks ordering and parallelism. Keep one purpose per system.
  • Client systems writing gameplay state. Their writes vanish at the next snapshot; the bridge rejects them at registration.

Open questions

  • Should system parameters include Local<T> (per-system persistent state, as in Bevy), or is "use a resource" enough? (ECS)