EasyEcs

Systems and [ForEach]

Write per-tick logic as stateless systems with [ForEach] methods: parameters, filters, ordering, groups, batch and parallel methods, runners and errors.

A system is one job of the server's tick: move units, apply burning damage, kill the dead, send state to clients. It derives from EcsSystem, keeps no state of its own (state is in components and singletons) and never references another system. Its loops are [ForEach] methods: a static method whose parameters name the components it reads and writes, which the source generator compiles into a struct job as fast as a hand-written loop.

When to use it

Use it for

All per-tick behavior: one responsibility per system, one [ForEach] method per loop, ordering with [UpdateAfter<T>], groups for different cadences (input whenever it arrives, simulation at a fixed tick), UpdateInterval for work that runs every N-th tick. Group filters keep a whole group to one kind of entity, and a generic group interface gives each type its own group (one group per actor type).

Skip it for

A one-off pass that a request or a tool runs between ticks: write a [ForEach] runner or a query. State that must survive between ticks: put it in a component or a singleton, never in a system field (EECS007).

How to use it

Write the system

Each [ForEach] method runs once per matching entity, every update. ref parameters are written, in parameters read; attributes filter the entities.

Combat.cs
public record struct Burning(int Ticks, int Damage) : IComponent;
public struct Player : IComponent;                                         // a tag
public record struct BurnTotals(int Damage) : ISingletonComponent;

public class BurnSystem : EcsSystem
{
    [ForEach, Without<Dead>]                                               // living entities only
    static void Burn(ref Health hp, in Burning burning, ref BurnTotals totals)
    {
        hp.Value -= burning.Damage;
        totals.Damage += burning.Damage;
    }
}

[UpdateAfter<BurnSystem>]                                                  // damage first, then death
public class DeathSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Die(Entity unit, in Health hp)
    {
        if (hp.Value <= 0) unit.SetDead();                                 // a structural change, applied now
    }
}

Add it and update

var world = new World();
world.AddSingleton<BurnTotals>();                  // BurnSystem reads it: add it before the first update
world.AddSystem<DeathSystem>();                    // added first, runs second: [UpdateAfter] orders it
world.AddSystem<BurnSystem>();
world.CreateEntity(new Health(5), new Burning(3, 10), new Player());

world.Update();                                    // one tick
int dealt = world.BurnTotals.Damage;               // 10

Lifecycle

Hook or memberWhen
OnCreate()once, when the system is added (world.AddSystem<T>() / AddSystem(system))
OnUpdate()every update of its group, before its [ForEach] methods
[ForEach] methodsevery update, after OnUpdate, in source order (a base class's first)
OnDestroy()once, on world.RemoveSystem<T>() or world.Dispose() (reverse order)
Worldthe owning world, set before OnCreate
Enabledfalse skips the system in Update() and Update<TGroup>()
LastRunTickthe change tick of its last run (change tracking)
Stats, Errormeasurements and the exception that switched it off

AddSystem<T>() returns the system; GetSystem<T>() finds one (for tools and tests, never from another system: EECS008); world.Systems lists every system without allocating; UpdateCount counts the default group's updates. A system belongs to one world: adding it to a second throws.

var burn = world.GetSystem<BurnSystem>();
foreach (var system in world.Systems) Console.WriteLine(system.GetType().Name);
world.RemoveSystem<BurnSystem>();                  // OnDestroy runs
long updates = world.UpdateCount;

One update

no

yes

world.Update()

enabled and due?

next system

OnUpdate()

[ForEach] methods, in source order

Systems run in registration order unless ordered. Structural changes apply at once, so later methods and systems of the same update see them. Everything runs on the thread that calls Update(), unless WorldOptions.ParallelSystems runs systems with no order and no conflict between them at the same time (Threading); the result is the same as running them in order.

Ordering

[UpdateBefore<T>] and [UpdateAfter<T>] move a system just before or after system T (and its subclasses) of the same group, whatever the order they were added in; the others keep their relative order. The order is resolved when a system is added: a cycle throws there and the system stays out. The analyzer reports the cycles (EECS019) and cross-group orderings (EECS020) it can see.

UpdateInterval and UpdatePhase

A system that overrides UpdateInterval runs every N-th update of its group: on the updates whose count is a multiple of N, so first on the N-th. UpdatePhase (0 to N - 1) shifts which of the N updates it takes, so systems with the same interval spread their work instead of all running on the same tick. Both must be constants (EECS018); to pause a system, set Enabled.

public record struct Autosave(long Count) : ISingletonComponent;

public class SaveSystem : EcsSystem
{
    public override int UpdateInterval => 60;      // every 60th update
    public override int UpdatePhase => 30;         // half a cycle after the others with the same interval

    protected override void OnUpdate() => World.GetOrAddAutosave().Count++;
}

[ForEach] methods

A [ForEach] method is declared in a class that derives from EcsSystem (no partial needed). It may be static or an instance method. Its parameters say what it runs over:

ParameterMeaning
ref T / in T / ref readonly T, T : IComponent1 to 9 components: ref to write, in to read
ref T / in T, T : ISingletonComponentthe world's singleton, resolved once per pass; throws if it was not added
Entitythe current entity, for structural changes and lookups
Worldthe world (for creating entities, other singletons)
Maybe<T>a component the entity may lack
Span<T> / ReadOnlySpan<T>, EntitySpana batch method: runs of rows at once
AttributeMeaning
[ForEach]run the method for every matching entity; Parallel = true for several threads
[With<T>]the entity must have T, not passed in; repeatable
[Without<T>]the entity must not have T; repeatable
[WithAny<T>]the entity must have at least one of the method's [WithAny<T>] components
[Changed<T>]T (ITrackChanges) was written since the system last ran (change tracking)
[Removed<T>]the entity lost T (ITrackChanges) since the system last ran (removal detection)

With no component parameter, the first [With<T>] (else the first [Changed<T>]) names the queried component:

public class CorpseCleanup : EcsSystem
{
    [ForEach, With<Dead>]
    static void Remove(Entity corpse) => corpse.Destroy();
}

A method that is static, takes no World and uses its Entity (if any) only to read (Id, IsAlive, Has, Get, Read, TryGet, TryGetRef) cannot change structure: its job implements INoStructuralChanges, walks each table with no per-entity check, and may share a parallel stage with other systems. A method that may change structure runs alone, and each entity is still visited at most once per pass (Structural changes).

Methods run in source order, and a derived system runs its base class's [ForEach] methods first. Keep a system's methods in one file: across the files of a partial class the order is per file.

Optional components: Maybe<T>

Maybe<T> takes a component the entity may lack: the method visits every entity with its other components, and HasValue says whether this one also has T. Writing through Value writes T (a tracked one is stamped); reading only is a read.

public record struct Shield(int Bonus) : IComponent;
public record struct Stamina(int Value) : IComponent;

public class Regeneration : EcsSystem
{
    [ForEach]
    static void Regenerate(ref Stamina stamina, Maybe<Shield> shield) =>
        stamina.Value += shield.HasValue ? 1 + shield.Value.Bonus : 1;
}

It saves writing two methods when the optional part is small. In the hottest loops, two methods split by [With<Shield>] and [Without<Shield>] are faster: no test per row (see the numbers below). A method that changes no structure finds the optional column once per run of rows; one that changes structure looks it up per entity.

Batch methods

A method whose component parameters are spans receives runs of consecutive matching rows: element i of every span belongs to the same entity, and a table where every row matches is one call. Its other parameters can be singletons and an EntitySpan (entities[i] is built only when indexed), nothing else (EECS009). The spans point into the tables, so the structure is frozen while it runs: a change throws, and EECS013 reports it at compile time.

using System.Numerics;
using System.Runtime.InteropServices;

public class DriftSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Drift(Span<Position> positions, ReadOnlySpan<Velocity> velocities)
    {
        // The JIT does not vectorize loops on its own. Two floats each: as Vector<float>, every lane is a coordinate
        var p = MemoryMarshal.Cast<Position, Vector<float>>(positions);
        var v = MemoryMarshal.Cast<Velocity, Vector<float>>(velocities);
        for (int i = 0; i < p.Length; i++) p[i] += v[i];
        var pf = MemoryMarshal.Cast<Position, float>(positions);
        var vf = MemoryMarshal.Cast<Velocity, float>(velocities);
        for (int i = p.Length * Vector<float>.Count; i < pf.Length; i++) pf[i] += vf[i];   // the rows left over
    }
}

A scalar loop over spans gains little over a per-entity method; write a batch method to vectorize.

Parallel methods

[ForEach(Parallel = true)] cuts the matching rows into chunks (about four per thread, a multiple of 64 rows, between 1,024 and World.ParallelChunkRows = 16,384) and runs them on the calling thread plus up to WorldOptions.MaxDegreeOfParallelism - 1 thread-pool threads. It is for heavy per-entity work (path finding, steering, AI scoring) over tens of thousands of entities; for light work the hand-off costs more than it saves.

public record struct Clock(float Time) : ISingletonComponent;

public class SteeringSystem : EcsSystem
{
    [ForEach(Parallel = true), Without<Dead>]
    static void Steer(ref Velocity velocity, in Position position, in Clock clock) =>
        velocity = new Velocity(MathF.Cos(clock.Time + position.X), MathF.Sin(clock.Time + position.Y));
}

The method must be able to run on several threads at once (EECS010): no structural change, per entity (not a batch method), singletons only as in. It also must not write what another row's run reads, such as another entity through Get. Fewer than two chunks run on the calling thread. It allocates nothing after its first update.

System groups

world.Update() runs the default group. A system marked [UpdateInGroup<TGroup>] (TGroup a struct : ISystemGroup) runs only when world.Update<TGroup>() is called. Use groups for different cadences: a server can apply input whenever it arrives and simulate at a fixed tick.

public struct InputGroup : ISystemGroup;

[UpdateInGroup<InputGroup>]
public class ApplyInputSystem : EcsSystem
{
    [ForEach, With<Player>]
    static void Apply(ref Velocity velocity) => velocity = new Velocity(velocity.X * 0.9f, velocity.Y * 0.9f);
}
world.AddSystem<ApplyInputSystem>();
world.Update<InputGroup>();   // whenever input arrives
world.Update();               // fixed tick: the default group

Ordering, UpdateInterval, UpdatePhase and Enabled apply within each group, and the attribute is inherited. Updating a group with no systems does nothing.

Group filters

[With<T>], [Without<T>] and [WithAny<T>] on the group struct join every [ForEach] method of its systems: a whole group can leave frozen or inactive entities out without repeating the filter on each method. A group's [WithAny<T>] joins the method's own [WithAny<T>] set, so it widens the "at least one of" test: a group with [WithAny<A>] and a method with [WithAny<B>] select entities with A or B. Queries a system makes in OnUpdate are its own, and [ForEach] runners belong to no group, so no group filter applies to them. A filter attribute on a struct that is not a group is a compile error (EECS023).

[Without<Frozen>]
public struct Gameplay : ISystemGroup;              // no method of the group sees a frozen entity

[UpdateInGroup<Gameplay>]
public class MoveSystem : EcsSystem
{
    [ForEach]
    static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y);
}

A group that a generic interface describes cannot name its filter in an attribute: C# refuses a type parameter as the type argument of an attribute ([With<In<TActor>>] on IActor<TActor> is CS8968). The group implements IGroupWith<T> or IGroupWithout<T> instead, here or through an interface, and gets the same filter: one interface then gives every actor type its group.

The actor pattern goes one step further: one type per kind of actor is at once its key component (indexed, so a message finds its actor), its system group and, through the interface, the group's filter:

public struct In<TActor> : IComponent;             // the tag of one kind of actor

public interface IActor<TSelf> : IComponent, IIndexed<TSelf>, ISystemGroup, IGroupWith<In<TSelf>>
    where TSelf : struct, IActor<TSelf>, IEquatable<TSelf>;   // IIndexed requires IEquatable

// Key component, index key and system group in one type. Key is implemented explicitly: a public
// Key property would be printed by the record's ToString(), which would print Key again, forever.
public readonly record struct Shop(long Id) : IActor<Shop>
{
    Shop IIndexed<Shop>.Key => this;
}

public record struct Stock(int Items) : IComponent;

[UpdateInGroup<Shop>]
public class RestockSystem : EcsSystem
{
    [ForEach]                                       // only entities tagged In<Shop>
    static void Restock(ref Stock stock) => stock.Items = Math.Max(stock.Items, 10);
}
world.AddSystem<RestockSystem>();
world.CreateEntity(new Shop(7), new In<Shop>(), new Stock(0));
world.Update<Shop>();                               // the shop systems, over the shop actors only
bool open = world.ShopIndex.TryFind(new Shop(7), out var shop);   // a message finds its actor

The Actors sample is the whole program: two kinds of actors, messages handled with entity.Run, activation and saving.

Generic systems

A system can be generic. Each closed type is a system of its own, with its own generated job and access set, so CountOf<Position> and CountOf<Health> are added, ordered and scheduled independently. A closed generic system can be a base class: its [ForEach] methods run before the subclass's. A closed type the code never names (built by reflection) has its code closed on first use.

public record struct Tally(int Count) : ISingletonComponent;

public class CountOf<T> : EcsSystem where T : struct, IComponent   // world.AddSystem<CountOf<Position>>()
{
    [ForEach] static void Count(in T component, ref Tally tally) => tally.Count++;
}

A system's [ForEach] method itself cannot be generic: nothing would supply its type arguments (EECS004). Attribute type arguments cannot name type parameters (C# rule CS8968), so filters such as [With<T>] name concrete types.

[ForEach] outside systems

A [ForEach] method in a type that is not an EcsSystem is a runner: a pass the host runs itself, for example between ticks to answer a request. The generator writes an entry point for it, a static method of the type with the same name that takes the World and then the method's other values, and runs the job once over the world.

Besides components, singletons, Entity and World, a runner may take values of any other type; the entry point takes them from the caller, ref ones included, so a runner can return results through them.

public record struct Gold(int Amount) : IComponent, ITrackChanges;

public static class Reports
{
    [ForEach, Without<Dead>]
    static void SumHealth(in Health hp, ref long total) => total += hp.Value;

    [ForEach, Changed<Gold>]
    static void Rich(in Gold gold, ref int count, int threshold) { if (gold.Amount >= threshold) count++; }
}

A generic runner counts the living entities that have any component:

public static class Census
{
    [ForEach, Without<Dead>]
    static void CountAlive<T>(in T component, ref int count) where T : struct, IComponent => count++;
}
long total = 0;
Reports.SumHealth(world, ref total);              // the generated entry point
ulong mark = world.ChangeTick;
int rich = 0;
Reports.Rich(world, mark, ref rich, 1_000);       // [Changed<T>]: the tick comes after the world
int alive = 0;
Census.CountAlive<Health>(world, ref alive);      // a generic runner: the type arguments first
  • The method must be static (EECS005); it may be private, and the entry point is public when the types it names are public.
  • With [Changed<T>] or [Removed<T>] the entry point takes the tick to look back from, since a runner has no last run of its own.
  • Runners may be generic, or members of a generic type: the entry point takes the type arguments.
  • No group filter applies to a runner: it belongs to no group.
  • Batch and parallel runners follow the rules of batch methods and parallel methods.
  • The entry point must not collide with another method of the type (EECS021), and a local function cannot be a runner (EECS024).
  • Call it on the world's owner thread, like any structural code.

Measuring systems

With WorldOptions.MeasureSystems, every run of a system (its OnUpdate plus its [ForEach] methods) is timed, and system.Stats holds Runs, Last, Total and Average. It costs two timestamp reads per system run, and nothing when off. Read it between updates, for example from a diagnostics endpoint:

var measured = new World(new WorldOptions { MeasureSystems = true });
measured.AddSingleton<BurnTotals>();
measured.AddSystem<BurnSystem>();
measured.Update();
var stats = measured.GetSystem<BurnSystem>().Stats;
Console.WriteLine($"burn: {stats.Last.TotalMicroseconds} μs, average {stats.Average.TotalMicroseconds} μs over {stats.Runs} runs");

Errors

By default an exception thrown by a system propagates out of Update() (and out of Dispose() for OnDestroy). With SystemErrors = SystemErrorPolicy.Disable, the failing system is switched off, its exception is kept in system.Error, and the update goes on with the next system. A failure is data: read it between updates. Setting Enabled = true clears Error and retries the system. A system that failed still counts as run: its LastRunTick moves on, so its [Changed<T>] methods do not visit again the rows written before the failed run.

var guarded = new World(new WorldOptions { SystemErrors = SystemErrorPolicy.Disable });
guarded.AddSingleton<BurnTotals>();
guarded.AddSystem<BurnSystem>();
guarded.Update();
foreach (var system in guarded.Systems)                   // a health check, between updates
    if (system.Error is { } error) Console.Error.WriteLine($"{system.GetType().Name} is off: {error.Message}");

Update() after Dispose() throws ObjectDisposedException.

What else a running world can tell you (its tables, an entity's components, memory): Debugging and diagnostics.

Full example

A group with a filter, two systems ordered inside it, and a method filter: three units move, one of them on the ground and one frozen. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

tick 1: flying at 8, walking at 4, frozen at 0
tick 2: flying at 16, walking at 6, frozen at 0
run order: FrictionSystem
run order: MoveSystem

The frozen unit never moves: the group's [Without<Frozen>] keeps it out of every method. Friction runs before the move although it was added second, so the grounded unit loses half its speed before each step.

How to use it fast

Instead ofDoWhy
ref on a component the method only readsin (EECS025)The system can share a stage; a tracked component is not stamped
An Entity or World parameter the method does not needDrop it (EECS026)The job skips structural bookkeeping and may run in parallel
An instance [ForEach] methodA static one (EECS029)Proven not to change structure: may share a stage, no per-row checks
A scalar loop over many rowsA batch method with Vector<T>SIMD over whole runs of rows
Maybe<T> in the hottest loopTwo methods with [With<T>] / [Without<T>]No presence test per row
Parallel = true on light workA plain [ForEach]The hand-off costs more than it saves
A filter repeated on every method of a cadenceA group filterWritten once
Work every tick that could waitUpdateInterval and UpdatePhaseSpread over ticks

A [ForEach] system against two plain arrays, Position += Velocity over 10,000 entities (MicroBenchmarks):

CaseMeanvs baselineAllocated
RawArrayWrite12.8 μs1.01×0 B
ForEachSystemWrite9.13 μs0.72×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

An optional component, 100,000 units of which half have a shield: one method with Maybe<Shield> against two methods split by With / Without (MaybeBenchmark):

CaseMeanvs baselineAllocated
OneMethod130 μs1.01×0 B
TwoMethods41.8 μs0.32×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Heavy steering over 100,000 entities, [ForEach] and [ForEach(Parallel = true)], and the same work as an ad-hoc entity job (ParallelForEachBenchmark):

CaseParallelMeanvs baselineAllocated
TickFalse1.68 ms—0 B
EntityJobFalse1.92 ms—0 B
TickTrue884 μs—0 B
EntityJobTrue896 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Four systems registered in run order, against the same four registered backwards and ordered by [UpdateAfter<T>]: the order is resolved when they are added (OrderingBenchmark):

CaseMeanvs baselineAllocated
Registered20.9 μs1.01×0 B
Ordered20.8 μs1.01×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Against Friflo.Engine.ECS: a method that takes the Entity per row, a batch method that builds handles only where needed, and a method that writes a singleton:

Per pass, 100,000 entities

  • EasyEcs
  • Friflo.Engine.ECS
EntityFriflo.Engine.ECS 1.37×49.0 μs · 0 B67.2 μs · 0 BEntityBatchFriflo.Engine.ECS 0.96×38.5 μs · 0 B37.0 μs · 0 BSingletonFriflo.Engine.ECS 1.05×212 μs · 0 B222 μs · 0 B0.00 ns50.0 μs100 μs150 μs200 μsTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsEntity49.0 μs1.00×0 B
Friflo.Engine.ECSEntity67.2 μs1.37×0 B
EasyEcsEntityBatch38.5 μs1.00×0 B
Friflo.Engine.ECSEntityBatch37.0 μs0.96×0 B
EasyEcsSingleton212 μs1.00×0 B
Friflo.Engine.ECSSingleton222 μs1.05×0 B

What it costs

  • A [ForEach] method is a struct job the JIT inlines into the row loop: no delegate, no allocation.
  • Per system and update: the OnUpdate call, one call per generated job, and one query-cache lookup per method.
  • A group's filters ([With<T>], [Without<T>], [WithAny<T>] on the group type, IGroupWith<T>, IGroupWithout<T>) are read by the generator, so they cost nothing at run time. The tables they exclude cost nothing per update: a query's cache holds only the tables that match, so the tables of other kinds of entities in the world (other actor types) are never walked by the group's systems.
  • Singleton parameters are resolved once per pass, not per entity.
  • Ordering is resolved when systems are added: an update pays nothing for it.
  • MeasureSystems costs two timestamp reads per system run; nothing when off.
  • Parallel methods allocate nothing after their first update; the runner's work items are reused.
  • Generated code is registered by a module initializer: systems need no partial, no registration call and no reflection at update time.

Pitfalls

MistakeWhat happensCaught by
A mutable field in a systemState nothing else can see, save or restoreEECS007
A system referencing another systemThe two can no longer change apartEECS008
A parameter of another type in a system's methodNothing can supply itEECS002
No component and no [With<T>]Nothing names what to iterateEECS003
A generic [ForEach] method in a systemNo type argumentsEECS004; make the system generic
Spans mixed with per-entity parametersNo single value per runEECS009
A parallel method that changes structure or writes a singletonRaces between chunksEECS010
Writing a collection through an in parameterScheduled as a read, never stampedEECS011
A structural change through a component's link in a method without Entity / WorldThe pass keeps refs into moved rowsEECS013
UpdateInterval that changesSkipped or repeated runsEECS018
Orderings in a cycle, or across groupsThrows on AddSystem; never appliesEECS019, EECS020
A private type in a method's parametersThe generated job cannot name itEECS022
[With<T>], [Without<T>] or [WithAny<T>] on a struct that is not a groupCompile error: the filter would do nothingEECS023
A group's [With<T>] or IGroupWith<T> with a method's [Removed<T>]Asks for rows that have and lack T: the method never runsEECS016
A group's [With<X>] with a method's [Without<X>]No entity matches: the method never runsNothing reports it: code review
A group's [WithAny<A>] with a method's [WithAny<B>], read as "A and B"The sets merge: entities with A or BCode review
A public Key => this on a record struct actor keyToString() prints Key forever: stack overflowCode review: implement IIndexed<T>.Key explicitly
ref on a component the method only readsStamps a tracked component, keeps the system out of shared stagesEECS025
An Entity or World parameter the method never usesThe job keeps its structural bookkeepingEECS026
An allocation in OnUpdate or a [ForEach] methodGarbage every updateEECS028
An instance [ForEach] method that uses nothing of its systemTreated as one that may change structure: runs alone, with per-row checksEECS029
World.Update() called from a systemThe system runs again inside its own runEECS034
Edit on GitHub

Last updated on

How is this guide?

On this page