Example: a battle server
A complete battle server built with EasyEcs, section by section: components, prefabs, systems, replication by change tracking, indexes, relations and saves.
A battle server that uses every feature of EasyEcs the way it is meant to be used: plain data, one job per system,
systems that never know about each other, and a host that ticks the world and answers questions between ticks. This
page walks through it section by section. Every code block on it is included from
BattleServer.cs,
the same file that BattleServerBenchmark measures and
BattleServerTests
checks feature by feature, so what you read here is the code that runs.
What the world simulates
A battle of units entities, a third of them players and the rest NPCs, on a 4,096 × 4,096 map split into four
zones:
- NPCs steer towards waypoints; every unit moves, attacks on a cooldown, and may catch fire or freeze.
- A unit whose health reaches zero dies. Players respawn next to a living friend; an NPC drops loot for a player of its zone and comes back later as a new NPC.
- Players spend mana on projectiles that fly for twenty ticks and belong to their shooter.
- Every third tick the server replicates what changed: healths, fires that started or went out, bags of loot.
- Between ticks the host answers questions: a census, the nearest player, the top killers, a save, a rollback.
One call to Tick() runs the default group of systems, in this order, and the Replication group every third tick:
With ParallelSystems on, systems with no order and no conflicting access between them share a stage and run at
once (MovementSystem and ManaSystem touch different components); the result is the same as running them one
after the other.
Where each feature is
Coming from another ECS? Comparison maps their features to EasyEcs; this table maps EasyEcs' features to their place in this file.
| Feature | Where |
|---|---|
| Components, tags, singletons | Position, Health, Player, Dead; singletons Battle, Rules, Waypoints |
| Generated members | players[i].Position = …, SetZone, SetFrozen, RemoveBurning, SetDead, IsDead, TryGetMana, WriteHealth(), World.Battle, KillsIndex; buffers player.Loot, WriteLoot(); DisableAttack / EnableAttack; on prefabs SetHealth, SetNpc |
Systems, filters (With, Without, WithAny) | every system; AfflictionSystem counts burning or frozen units with World.Count |
Parallel [ForEach] | SteeringSystem; Reports.HealFully and Reports.Scatter in NewRound |
Parallel systems (WorldOptions.ParallelSystems) | MovementSystem and ManaSystem: disjoint data |
Batch methods (Span<T>), SIMD | MovementSystem; Reports.SumHealth |
[ForEach] runners outside systems | Reports |
Maybe<T> | RegenerationSystem heals burning players less |
| Disabling components | a frozen unit's Attack and Velocity; NewRound enables them all in bulk |
Cleanup components (ICleanupComponent, Destroyed) | Spawn: a destroyed NPC leaves it behind for RespawnSystem.Revive |
Hierarchy (ChildOf, Children, Descendants) | projectiles are children of their player; Transfer collects the subtree |
| Structural changes during passes | statuses, deaths, respawns, projectiles spawned and destroyed mid-pass |
Prefabs (Prefab, Instantiate, EnsureCapacity), cloning | Hero, Grunt, Brute (a variant of Grunt); Mirror clones a living unit |
| Change tracking and removal detection | ReplicationSystem; WrittenSinceCheckpoint |
| Dynamic buffers | every player's bag of Loot |
Groups (IGroup, GroupBy, InGroup) | Zone: a table per zone |
| Ordered index, relations, target policies | Kills leaderboard; Friend links, dropped when a player leaves |
System groups, UpdateInterval, UpdatePhase, ordering, lifecycle | Replication; ManaSystem, RegenerationSystem; ClockSystem; SteeringSystem.OnCreate |
| Queries, handles and one-entity jobs | NearestPlayer, Census, ShotsLeft; Hit runs the TakeHit job with entity.Run |
| Bulk operations | Instantiate(prefab, span), DestroyEntities, RemoveAll, EnableAll |
| Snapshots, saves and moves | Checkpoint / Rewind, Save / Load, Transfer |
| Introspection, diagnostics, error policy | Tables, Slowest, Failure |
The data
Components
Every component is a plain record struct. Three markers change how the world stores one: ITrackChanges gives it
a hidden column of change ticks (Health and Burning are replicated), IGroup splits tables by its value (one
table set per Zone), and IIndexed<TKey> keeps a value index of it (Kills, the leaderboard). Spawn is a
cleanup component, Loot and Friend are the elements of dynamic buffers, and the empty structs are tags.
public record struct Position(float X, float Y) : IComponent;
public record struct Velocity(float X, float Y) : IComponent;
public record struct Health(int Value, int Max) : IComponent, ITrackChanges; // replicated: writes are tracked
public record struct Replica(int Health, bool Burning) : IComponent; // what clients last received
public record struct Mana(int Value, int Max) : IComponent;
public record struct Attack(int Damage, int Interval, int Cooldown) : IComponent;
public record struct Burning(int Ticks) : IComponent, ITrackChanges; // status effects come and go; clients
// see fires start and go out
public record struct Frozen(int Ticks) : IComponent; // while it lasts, Attack and Velocity
// are disabled: no query sees them
public record struct Lifetime(int Ticks) : IComponent;
public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } // a table per zone
public record struct Kills(int Count) : IComponent, IIndexed<int> { public int Key => Count; } // ordered: a leaderboard
public record struct Spawn(Position At, int Seed) : ICleanupComponent; // outlives its NPC: where the next appears
public record struct Loot(int Item); // players carry a DynamicBuffer<Loot>
public record struct Friend(EntityId Target) : IRelation; // and a DynamicBuffer<Friend> of links
public struct Player : IComponent; // tags: empty components
public struct Npc : IComponent;
public struct Dead : IComponent;Singletons and a system group
State that exists once per battle is a singleton: Battle counts what happened, Rules holds the battle's rules as
data, and Waypoints is a fixed-size array the steering reads. Replication is an empty struct that names a system
group, updated by its own call.
public record struct Battle(long Tick, int Hits, int Deaths, int Shots, int Replicated, int Afflicted) : ISingletonComponent;
public record struct Rules(int ShotCost, int BagSize, bool Ceasefire) : ISingletonComponent; // the battle's rules: data
public struct Waypoints : ISingletonComponent
{
public const int Count = 8;
public WaypointArray Points;
}
[InlineArray(Waypoints.Count)]
public struct WaypointArray { private Position _first; }
public struct Replication : ISystemGroup; // runs when the server sends updatesThe systems
Each system does one job and shares nothing with the others but components and singletons. ref marks what a
[ForEach] method writes and in what it reads; the generator builds the loop and the access set from those two
words.
Moving
SteeringSystem is heavy per-entity math, so it runs on every core (Parallel = true); it creates the Waypoints
singleton it reads in OnCreate and removes it in OnDestroy. MovementSystem takes spans and adds whole runs of
rows as Vector<float>. ManaSystem runs every tenth update, five updates after RegenerationSystem, so their work
falls on different ticks. ZoneSystem writes Zone only when a unit really changes zone, which moves its row to the
zone's table.
public class SteeringSystem : EcsSystem // heavy per-entity math: on all cores
{
protected override void OnCreate() // the system sets up the data it steers by
{
ref var waypoints = ref World.GetOrAddWaypoints();
for (int i = 0; i < Waypoints.Count; i++) waypoints.Points[i] = new Position(512 + i * 400, 512 + i * 1777 % 3000);
}
protected override void OnDestroy() => World.RemoveWaypoints();
[ForEach(Parallel = true), With<Npc>, Without<Dead>, Without<Frozen>]
static void Steer(in Position p, ref Velocity v, in Waypoints waypoints)
{
var target = waypoints.Points[(int)(p.X + p.Y) & (Waypoints.Count - 1)];
float dx = target.X - p.X, dy = target.Y - p.Y, length = MathF.Sqrt(dx * dx + dy * dy) + 1;
v = new Velocity(dx / length * 2, dy / length * 2);
}
}
public class MovementSystem : EcsSystem
{
[ForEach, Without<Dead>] // whole runs of rows, vectorized
static void Move(Span<Position> positions, ReadOnlySpan<Velocity> velocities)
{
// Two floats each, no padding: as Vector<float> spans, every lane is one coordinate (the JIT does not
// vectorize loops by itself)
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
}
}
public class ManaSystem : EcsSystem // other data than MovementSystem: both
{ // run at once
public override int UpdateInterval => 10; // every 10th update, five updates after
public override int UpdatePhase => 5; // RegenerationSystem: their work spreads
[ForEach]
static void Regenerate(ref Mana mana) => mana.Value = Math.Min(mana.Max, mana.Value + 10);
}
public class ZoneSystem : EcsSystem // a new zone moves the row to its table
{
[ForEach]
static void Enter(Entity player, in Position p, in Zone zone) // `in`: reading is not a change
{
int id = Math.Clamp((int)(p.X / 1024), 0, 3);
if (zone.Id != id) player.SetZone(id); // only real moves are writes
}
}Fighting
Combat is split into damage (CombatSystem) and statuses (StatusSystem). Freezing a unit disables its Attack and
Velocity: the values are kept, but no query sees them until Thaw enables them again, so a frozen unit neither
attacks, moves nor shoots without any system checking for Frozen. AfflictionSystem counts burning or frozen
units without a loop: Count reads presence bits 64 rows at a time. DeathSystem marks the dead with a tag that
other systems filter on.
public class CombatSystem : EcsSystem // damage only: statuses are StatusSystem's
{
[ForEach, Without<Dead>] // a frozen unit's Attack is disabled
static void Fight(Entity unit, ref Attack attack, ref Battle battle)
{
if (--attack.Cooldown > 0) return;
attack.Cooldown = attack.Interval;
unit.WriteHealth().Value -= attack.Damage; // a hit is a change of Health
battle.Hits++;
}
}
public class StatusSystem : EcsSystem
{
[ForEach, Without<Dead>] // the units that attacked this tick
static void Afflict(Entity unit, in Attack attack, in Battle battle)
{
if (attack.Cooldown != attack.Interval) return; // CombatSystem just reset it
uint roll = Dice.Roll(battle.Tick, unit.Id.Index);
if (roll % 50 == 0) unit.GetOrAddBurning() = new Burning(10); // applied at once; a new fire restarts it
else if (roll % 70 == 1)
{
unit.SetFrozen(4);
unit.DisableAttack(); // kept, but no query sees them: no attacks,
unit.DisableVelocity(); // no steering, no moves, no shots
}
}
[ForEach]
static void Burn(Entity unit, ref Burning burning, ref Health hp)
{
hp.Value -= 3;
if (--burning.Ticks == 0) unit.RemoveBurning(); // flips a bit: the row stays
}
[ForEach]
static void Thaw(Entity unit, ref Frozen frozen)
{
if (--frozen.Ticks > 0) return;
unit.RemoveFrozen();
unit.EnableAttack(); // back with the values they had
unit.EnableVelocity();
}
}
public sealed class AfflictionSystem : EcsSystem // registered after StatusSystem
{
// A count, not a loop: Count reads presence bits, 64 rows per load
protected override void OnUpdate() =>
World.Battle.Afflicted += World.Count<Health>(BattleServer.Afflicted);
}
public class DeathSystem : EcsSystem
{
[ForEach, Without<Dead>] // a plain scan: most healths change often
static void Die(Entity unit, in Health hp, ref Battle battle)
{
if (hp.Value > 0) return;
unit.SetDead(); // whoever cares queries Dead
battle.Deaths++;
}
}Death and respawn
RespawnSystem reacts to the Dead tag; DeathSystem does not know it exists. A player recalls its projectiles
(its children), empties its bag, comes back next to a living friend found through its Friend links, and loses its
statuses in one Remove<Dead, Burning, Frozen>(). An NPC writes where the next one should appear into its Spawn
cleanup component, gives its loot to a player of its zone (one group's table to look at) and is destroyed: its
Spawn stays behind with the Destroyed tag until Revive spawns the next NPC and removes it, which frees the old
entity.
public class RespawnSystem : EcsSystem // DeathSystem does not know it exists
{
[ForEach, With<Player>, With<Dead>]
static void Respawn(Entity player, ref Health hp, ref DynamicBuffer<Loot> bag, World world)
{
foreach (var shot in world.Children(player)) shot.Destroy(); // recall its projectiles
hp.Value = hp.Max;
bag.Clear(); // a death empties the bag
var at = new Position(2048, 2048);
foreach (var link in player.Friend) // next to a living friend, if any
if (world.TryGetEntity(link.Target, out var friend) && !friend.IsDead)
{
at = friend.Position;
break;
}
player.Set(at, new Mana(0, 100), new Kills(0)); // several components, one call; a death
// ends the kill streak
player.Remove<Dead, Burning, Frozen>(); // back without statuses: one transition
player.EnableAttack(); // false when it was not frozen
player.EnableVelocity();
}
[ForEach, With<Npc>, With<Dead>]
static void Despawn(Entity npc, in Position p, ref Spawn spawn, in Rules rules, World world)
{
spawn = new Spawn(new Position(p.Y, p.X), npc.Id.Index); // where the next one appears
Entity hunter = default;
foreach (var item in world.Query<Position>(BattleServer.Zones[npc.Id.Index & 3])) // a player of some zone:
{ // one table to look at
hunter = item.Entity;
spawn.At = item.Position;
break;
}
if (hunter.IsAlive)
{
ref var bag = ref hunter.WriteLoot(); // the hunter gets the loot
if (bag.Count == rules.BagSize) bag.RemoveAt(0); // a full bag drops its oldest item
bag.Add(new Loot(npc.Id.Index & 15));
hunter.SetKills(hunter.Kills.Count + 1); // the leaderboard follows
}
npc.Destroy(); // Spawn stays, with the Destroyed tag
}
[ForEach, With<Destroyed>] // what destroyed NPCs left behind
static void Revive(Entity old, in Spawn spawn, World world)
{
BattleServer.SpawnNpc(world, spawn.At, spawn.Seed);
old.RemoveSpawn(); // its last cleanup component: freed
}
}Projectiles, regeneration and the clock
A projectile is an entity with a ChildOf link to its player, so destroying the player destroys its shots.
RegenerationSystem heals burning players less with one method: Maybe<Burning> tells whether this entity has the
component. ClockSystem is registered first but runs last, because [UpdateAfter<RegenerationSystem>] moves it.
public class ProjectileSystem : EcsSystem
{
[ForEach, With<Player>, Without<Dead>] // a frozen player's Velocity is disabled
static void Shoot(Entity player, in Position p, in Velocity v, ref Mana mana, ref Battle battle, in Rules rules, World world)
{
if (rules.Ceasefire || mana.Value < rules.ShotCost || Dice.Roll(battle.Tick, player.Id.Index) % 20 != 0) return;
mana.Value -= rules.ShotCost;
battle.Shots++;
world.CreateEntity(p, new Velocity(v.X * 4, v.Y * 4), new Lifetime(20), new ChildOf(player)); // a child: gone
} // with its player
[ForEach]
static void Expire(Entity shot, ref Lifetime life)
{
if (--life.Ticks == 0) shot.Destroy();
}
}
public class RegenerationSystem : EcsSystem
{
public override int UpdateInterval => 10; // every 10th update
[ForEach, With<Player>, Without<Dead>]
static void Regenerate(Entity player, in Health hp, Maybe<Burning> burning) // burning or not: one method
{
if (hp.Value < hp.Max) player.WriteHealth().Value = Math.Min(hp.Max, hp.Value + (burning.HasValue ? 5 : 20));
}
}
[UpdateAfter<RegenerationSystem>] // registered first, runs last
public sealed class ClockSystem : EcsSystem
{
protected override void OnCreate() => World.GetOrAddBattle();
protected override void OnUpdate() => World.Battle.Tick++;
}Replication by change tracking
ReplicationSystem belongs to the Replication group, which the host updates every third tick. Each method visits
only what changed since the system last ran: the healths written ([Changed<Health>]), the units set on fire
([Changed<Burning>]), the fires that went out ([Removed<Burning>], the entities that lost the component and
still lack it) and the bags written through a ref ([Changed<DynamicBuffer<Loot>>]). Nothing marks rows dirty by
hand: a write through a ref is the mark.
[UpdateInGroup<Replication>]
public class ReplicationSystem : EcsSystem // only what changed since the last send
{
[ForEach, Changed<Health>]
static void Send(in Health hp, ref Replica replica, ref Battle battle)
{
replica.Health = hp.Value;
battle.Replicated++;
}
[ForEach, Changed<Burning>] // set on fire, or burning on
static void SendFire(ref Replica replica, ref Battle battle)
{
if (replica.Burning) return;
replica.Burning = true;
battle.Replicated++;
}
[ForEach, Removed<Burning>] // the fire went out: the row lacks it now
static void SendFireOut(ref Replica replica, ref Battle battle)
{
if (!replica.Burning) return; // lit and out between two sends
replica.Burning = false;
battle.Replicated++;
}
[ForEach, Changed<DynamicBuffer<Loot>>] // bags changed by a ref write
static void SendBag(in DynamicBuffer<Loot> bag, ref Battle battle) => battle.Replicated += 1 + bag.Count;
}Why it pays and what counts as a write: Change tracking and removal detection.
Passes outside the tick
A static [ForEach] method of an ordinary static class is a runner: the generator writes an entry point that takes
the world and the method's other arguments (Reports.SumMana(world, ref total)). The host calls them between ticks.
SumHealth reads whole runs of rows as Vector<int> lanes; HealFully and Scatter run in parallel chunks.
Dice is a pure function of the tick and the entity, so a roll is the same on any thread.
public static class Dice
{
public static uint Roll(long tick, int id)
{
ulong x = (ulong)tick * 0x9E3779B97F4A7C15UL ^ (uint)id * 0xBF58476D1CE4E5B9UL;
x ^= x >> 31;
x *= 0x94D049BB133111EBUL;
return (uint)(x ^ (x >> 29));
}
}
/// <summary>
/// [ForEach] methods outside systems: the generator writes the job and an entry point taking the world and the
/// caller's values (<c>Reports.SumMana(world, ref total)</c>), for passes the host runs between ticks.
/// </summary>
public static class Reports
{
[ForEach, With<Player>, Without<Dead>] // whole runs of rows, read-only
static void SumHealth(ReadOnlySpan<Health> hp, ref long total)
{
// Value, Max, Value, Max, ...: sum every lane, keep the even ones (an int lane holds 4M rows of 500)
var lanes = MemoryMarshal.Cast<Health, Vector<int>>(hp);
var sum = Vector<int>.Zero;
for (int i = 0; i < lanes.Length; i++) sum += lanes[i];
total += Vector.Sum(sum & Vector.Equals(Vector<int>.Indices & Vector<int>.One, Vector<int>.Zero));
for (int i = lanes.Length * Vector<int>.Count / 2; i < hp.Length; i++) total += hp[i].Value; // left over
}
[ForEach]
static void SumMana(in Mana mana, ref long total) => total += mana.Value;
[ForEach, With<Player>, Without<Dead>]
static void FindWeakest(Entity player, in Health hp, ref EntityId weakest, ref int lowest)
{
if (hp.Value < lowest) (lowest, weakest) = (hp.Value, player);
}
[ForEach(Parallel = true)] // chunks on all cores: no shared state
static void HealFully(ref Health hp) => hp.Value = hp.Max;
[ForEach(Parallel = true), With<Npc>] // NPCs start the round anywhere
static void Scatter(Entity npc, ref Position p, long round)
{
uint r = Dice.Roll(round, npc.Id.Index); // per entity, the same on any thread
p = new Position(r % 4096, (r >> 12) % 4096);
}
}
/// <summary>What the server reports: computed by the runners of <see cref="Reports"/>, outside the tick.</summary>
public record struct Census(int Players, int Alive, long Health, long Mana, Entity Weakest, int ReadyToAttack);The host
BattleServer owns one world on one thread, ticks it, and answers questions about it between ticks.
Filters and prefabs
Filters are built once, in static readonly fields; WrittenPlayers takes its tick per call with Since. The
prefabs are recipes that belong to no world, so no query sees them: Hero sets its components several at once or
one by one through the generated writers, and Brute is a variant, a copy of Grunt with three values changed.
public const int ShotCost = 30;
public const int BagSize = 8;
private static readonly QueryFilter Players = QueryFilter.Create().With<Player>(); // build filters once
private static readonly QueryFilter AlivePlayers = Players.Without<Dead>();
private static readonly QueryFilter Alive = QueryFilter.Create().Without<Dead>();
internal static readonly QueryFilter Afflicted = QueryFilter.Create().WithAny<Burning>().WithAny<Frozen>();
private static readonly QueryFilter WrittenPlayers = Players.Changed<Health>(0); // the tick is set per call
internal static readonly QueryFilter[] Zones = // one table each
[Players.InZone(0), Players.InZone(1), Players.InZone(2), Players.InZone(3)];
// Unit kinds: recipes that belong to no world (no query sees them), copied by Instantiate
private static readonly Prefab Hero = new Prefab().Set(new Position(), new Velocity(1, 0)) // several at once
.SetHealth(500, 500).SetReplica(500, false).SetMana(100, 100).SetAttack(8, 6, 0) // or one by name
.SetZone(0).SetKills(0).SetPlayer().Set(new DynamicBuffer<Friend>())
.SetLoot(new Loot(0)); // a starter item: each hero gets a bag of its own
private static readonly Prefab Grunt = new Prefab().Set(new Position(), new Velocity())
.SetHealth(120, 120).SetReplica(120, false).SetAttack(6, 8, 0).SetSpawn(default, 0).SetNpc();
private static readonly Prefab Brute = new Prefab(Grunt) // a variant: a copy
.SetHealth(200, 200).SetReplica(200, false).SetAttack(9, 12, 0);Setting up the world
The constructor configures the world (parallel systems, timings, a failing system switched off instead of thrown),
groups tables by Zone, sets the friend links' target policy, registers the systems in tick order and spawns the
units in bulk: one table growth per wave. EnsureCapacity sizes the NPC tables for respawn waves, so they never grow
during a tick.
public readonly World World;
private readonly SingletonRef<Battle> _battle; // resolved once, no lookup per tick
private readonly List<EntityId> _group = []; // reused by Transfer
private WorldSnapshot _checkpoint;
private ulong _checkpointAt;
/// <summary>A battle of <paramref name="units"/> units, a third of them players.</summary>
public BattleServer(int units)
{
World = new World(new WorldOptions
{
InitialEntityCapacity = units * 2,
ParallelSystems = true, // unordered systems with disjoint data side by side
MeasureSystems = true, // per-system timings in system.Stats
SystemErrors = SystemErrorPolicy.Disable, // a failing system goes off, the battle goes on
});
World.GroupBy<Zone>(); // a zone's players contiguous, in its table
World.FriendIndex.WhenTargetDestroyed(TargetPolicy.Remove); // a player who leaves leaves friend lists
World.SetRules(ShotCost, BagSize, false);
World.AddSystem<ClockSystem>(); // OnCreate adds the Battle singleton
World.AddSystem<SteeringSystem>();
World.AddSystem<MovementSystem>();
World.AddSystem<ManaSystem>();
World.AddSystem<ZoneSystem>();
World.AddSystem<CombatSystem>();
World.AddSystem<StatusSystem>();
World.AddSystem<AfflictionSystem>();
World.AddSystem<DeathSystem>();
World.AddSystem<RespawnSystem>();
World.AddSystem<ProjectileSystem>();
World.AddSystem<RegenerationSystem>();
World.AddSystem<ReplicationSystem>();
_battle = World.SingletonRef<Battle>();
var players = new Entity[units / 3];
World.Instantiate(Hero, players); // in bulk: one table growth
for (int i = 0; i < players.Length; i++)
{
uint r = Dice.Roll(0, i);
players[i].Position = new Position(r % 4096, (r >> 12) % 4096);
players[i].Velocity = new Velocity((int)(r % 5) - 2, (int)((r >> 8) % 5) - 2);
players[i].Attack.Cooldown = (int)(r % 6);
players[i].WriteLoot().EnsureCapacity(BagSize); // room once: a full bag never grows
players[i].AddFriend(players[(i + 1) % players.Length]); // each player has two friends
players[i].AddFriend(players[(i + 7) % players.Length]);
}
var npcs = new Entity[units - players.Length];
World.Instantiate(Grunt, npcs.AsSpan(0, npcs.Length / 2)); // copies of a recipe, in bulk
World.Instantiate(Brute, npcs.AsSpan(npcs.Length / 2));
for (int i = 0; i < npcs.Length; i++)
{
uint r = Dice.Roll(0, players.Length + i);
npcs[i].Position = new Position(r % 4096, (r >> 12) % 4096);
npcs[i].Attack.Cooldown = (int)(r % 10);
}
World.EnsureCapacity(Grunt, npcs.Length / 4); // respawn waves never grow the tables
World.EnsureCapacity(Brute, npcs.Length / 4);
}
public static void SpawnNpc(World world, Position at, int seed)
{
uint r = Dice.Roll(seed, seed);
var npc = world.Instantiate((r & 1) == 0 ? Grunt : Brute); // then only what differs is written
npc.Position = at;
npc.Attack.Cooldown = (int)(r % 10);
}The tick
Tick() is two calls. Battle reads the counters through a SingletonRef, resolved once. Failure finds a system
that threw: under SystemErrorPolicy.Disable the exception is data in system.Error, and the battle goes on.
Ceasefire is a rule, so changing it is a write to a singleton, not a call into a system.
public ref Battle Battle => ref _battle.Value;
/// <summary>A system that threw: it was switched off and the battle went on (its Error is the failure, as data).</summary>
public EcsSystem Failure
{
get
{
foreach (var system in World.Systems)
if (system.Error != null) return system;
return null;
}
}
/// <summary>One server tick: the simulation every tick, replication every third.</summary>
public void Tick()
{
World.Update();
if (Battle.Tick % 3 == 0) World.Update<Replication>();
}
/// <summary>Whether players hold fire: a rule of the battle is data, so shots in flight still expire.</summary>
public bool Ceasefire
{
get => World.Rules.Ceasefire;
set => World.Rules.Ceasefire = value;
}Questions between ticks
PlayersIn counts one group's table. Any stops at the first match. ShotsLeft and Hit start from a handle or an
id a client sent: a stale one answers false. Hit is a request on one unit, so it runs a job with entity.Run: one
lookup for the job's components, and the Alive filter turns a dead unit away. The job declares that it writes
Health, so the hit is stamped for the next replication.
public int PlayersIn(int zone) => World.Count<Player>(Zones[zone]); // one table: its rows, not a scan
public bool AnyoneBurning => World.Any<Burning>();
public bool AnyoneAfflicted => World.Any<Health>(Afflicted); // burning or frozen
public int ShotsLeft(Entity player) => player.IsAlive && player.TryGetMana(out var mana) ? mana.Value / ShotCost : 0;
/// <summary>
/// A client's hit on the unit it names by id: the id turns back into a handle if that unit still lives, and the hit
/// runs as a job on that one unit.
/// </summary>
public bool Hit(EntityId target, int damage)
{
var hit = new TakeHit(damage);
return World.TryGetEntity(target, out var unit)
&& unit.Run<Health, TakeHit>(ref hit, Alive); // false: dead, or no Health
}/// <summary>A hit a client asked for, on one unit (<c>entity.Run</c>): the write is replicated with the next send.</summary>
public readonly record struct TakeHit(int Damage) : IForEachEntity<Health>, INoStructuralChanges
{
public static int Writes => 1;
public void Execute(Entity unit, ref Health hp) => hp.Value -= Damage;
}Bags, clones, leaderboards and friends
Mirror clones a living unit with everything it has; indexes, groups and the next replication learn about the copy.
LootValue reads a bag without counting as a write; Give checks with reads first, then writes both bags.
TopKillers walks the ordered Kills index from the top, and FriendsOf asks the relation index who links to a
player.
/// <summary>
/// A mirror image of a living unit as it is now (health, statuses, bag, zone): a copy of the entity, which the
/// indexes, groups and the next send learn about.
/// </summary>
public Entity Mirror(Entity unit) => unit.IsAlive ? unit.Clone() : default;
/// <summary>The items in a player's bag, summed: a read, never a change.</summary>
public int LootValue(Entity player)
{
int value = 0;
foreach (var loot in player.Loot) value += loot.Item;
return value;
}
/// <summary>A client hands a player's oldest item to another player: two tracked writes, replicated next send.</summary>
public bool Give(Entity from, Entity to)
{
// Check with reads first: a write counts as a change, and an unchanged bag must not be replicated
if (!from.HasLoot || !to.HasLoot || from.Loot.Count == 0 || to.Loot.Count == BagSize) return false;
ref var source = ref from.WriteLoot();
to.WriteLoot().Add(source[0]);
source.RemoveAt(0);
return true;
}
/// <summary>The players with the most kills, best first: an ordered walk of the Kills index.</summary>
public int TopKillers(Span<Entity> top)
{
int count = 0;
foreach (var player in World.KillsIndex.Descending())
{
if (count == top.Length) break;
top[count++] = player;
}
return count;
}
/// <summary>How many players list <paramref name="player"/> as a friend: the relation's index, by target.</summary>
public int FriendsOf(Entity player) => World.FriendIndex.Count(player);Leaving and changing battles
A player who leaves is destroyed: its projectiles go with it (children), and the target policy removes it from every
friend list. Transfer collects the player's whole subtree with Descendants and moves it to another battle of the same
thread with MoveEntities: they arrive as new entities, the shots still its children.
/// <summary>A player leaves: its projectiles go with it (children), and it drops out of friend lists (the policy).</summary>
public bool Leave(Entity player)
{
if (!player.IsAlive || !player.IsPlayer) return false;
player.Destroy();
return true;
}
/// <summary>
/// Move a player and its projectiles to another battle of this thread: they arrive as new entities, the shots
/// still its children; links to entities left behind (friends) become null.
/// </summary>
public Entity Transfer(Entity player, BattleServer to)
{
if (!player.IsAlive || !player.IsPlayer) return default;
_group.Clear();
_group.Add(player);
foreach (var part in World.Descendants(player)) _group.Add(part); // the whole subtree moves together
Entity arrived = default;
World.MoveEntities(to.World, CollectionsMarshal.AsSpan(_group), new Span<Entity>(ref arrived));
return arrived;
}A census
An ad-hoc Query finds the nearest living player; the census adds up runners and counts.
/// <summary>The living player closest to <paramref name="at"/>: an ad-hoc query.</summary>
public Entity NearestPlayer(Position at)
{
Entity nearest = default;
float best = float.MaxValue;
foreach (var item in World.Query<Position>(AlivePlayers)) // Position is not tracked: reads are free
{
float dx = item.Position.X - at.X, dy = item.Position.Y - at.Y, distance = dx * dx + dy * dy;
if (distance < best) (best, nearest) = (distance, item.Entity);
}
return nearest;
}
public Census Census()
{
long health = 0, mana = 0;
Reports.SumHealth(World, ref health);
Reports.SumMana(World, ref mana);
EntityId weakest = default;
int lowest = int.MaxValue;
Reports.FindWeakest(World, ref weakest, ref lowest);
World.TryGetEntity(weakest, out var handle); // none when every player is dead
return new Census(World.Count<Player>(), World.Count<Player>(AlivePlayers), health, mana, handle,
World.Count<Attack>(Alive)); // a frozen unit's Attack is not counted
}A new round
Bulk calls change every match table by table: projectiles destroyed in one pass, statuses removed, disabled components enabled, then two parallel runners heal and scatter.
/// <summary>A new round: projectiles gone, statuses lifted, everyone healed, the NPCs scattered.</summary>
public int NewRound()
{
int cleared = World.DestroyEntities<Lifetime>(); // one pass, however many
World.RemoveAll<Burning>(); // in bulk: table by table, not per entity
World.RemoveAll<Frozen>();
World.EnableAll<Attack>();
World.EnableAll<Velocity>();
Reports.HealFully(World); // on all cores
Reports.Scatter(World, Battle.Tick);
return cleared;
}Snapshots and saves
A checkpoint is an in-memory snapshot plus the change tick it was taken at, so the host can count the players
written since. Save and Load write and read the whole battle as bytes; entities keep their ids, so EntityId
links still point at the right entities.
/// <summary>Keep the battle in memory; <see cref="WrittenSinceCheckpoint"/> counts the players written since.</summary>
public void Checkpoint()
{
_checkpoint = World.Capture();
_checkpointAt = World.ChangeTick;
}
/// <summary>Back to the last checkpoint.</summary>
public void Rewind() => World.Restore(_checkpoint);
public int WrittenSinceCheckpoint => World.Count<Health>(WrittenPlayers.Since(_checkpointAt));
/// <summary>Save the battle (entities, components, singletons) as bytes: to disk, to another process.</summary>
public void Save(IBufferWriter<byte> output) => World.Save(output);
/// <summary>Replace the battle with a saved one: entities keep their ids, so links still point right.</summary>
public void Load(ReadOnlySpan<byte> save) => World.Load(save);Diagnostics
Describe lists every table with its columns, rows and bytes, for a dashboard. With MeasureSystems on, every
system's runs are timed into system.Stats.
/// <summary>The world's tables: their components, rows and bytes, for a dashboard.</summary>
public TableInfo[] Tables() => World.Describe();
/// <summary>The system that took the most time per run so far (<see cref="WorldOptions.MeasureSystems"/>).</summary>
public EcsSystem Slowest()
{
EcsSystem slowest = null;
foreach (var system in World.Systems)
if (slowest == null || system.Stats.Average > slowest.Stats.Average) slowest = system;
return slowest;
}
public void Dispose() => World.Dispose(); // OnDestroy of every systemRunning it
using System.Buffers;
using EasyEcs.Benchmark.Showcase;
using var server = new BattleServer(100_000);
server.Checkpoint(); // e.g. before a risky admin command
while (running)
{
server.Tick(); // allocates nothing once the tables reach their peak
if (server.WrittenSinceCheckpoint > 1_000) server.Checkpoint();
}
var census = server.Census(); // between ticks: runners, Count, groups
Console.WriteLine($"{census.Alive}/{census.Players} alive, {server.PlayersIn(0)} in zone 0, slowest {server.Slowest()}");
server.Ceasefire = true; // a rule as data: players hold fire, shots in flight expire
server.NewRound();
server.Rewind(); // roll the battle back in memory
var save = new ArrayBufferWriter<byte>();
server.Save(save); // to disk, or to another process: Load(save.WrittenSpan)
using var other = new BattleServer(10_000);
server.Transfer(server.NearestPlayer(default), other); // a player and its projectiles change battles
// One world per thread scales across cores: worlds share nothing.
var threads = new Thread[4];
for (int i = 0; i < threads.Length; i++)
(threads[i] = new Thread(() => { using var battle = new BattleServer(25_000); while (running) battle.Tick(); })).Start();Every system can be removed, reordered or tested alone: they share components and singletons, nothing else.
What a tick costs
BattleServerBenchmark ticks a battle of 100,000 units 1,200 times to bring every table to its peak population, then
measures one tick: every system above, with replication every third tick.
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| Tick | 2.97 ms | — | 0 B |
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
The other benchmarks, and how to run them: Performance.
More programs
samples/: complete programs in learning order: hello world, a fixed-tick game loop fed by a network thread, saves and moves between worlds, one world per thread, hot-reloaded game logic.- The guide: the pages of single features have a full example of that feature alone, for instance change tracking.
templates/:dotnet newtemplates for a new project.
Related
Last updated on
How is this guide?
Cheat sheet
The everyday EasyEcs API on one page: entities, generated members, queries, [ForEach] parameters, attributes, singletons, indexes, prefabs, saves, options.
Structuring a real project
Lay out an EasyEcs server the way dotnet new easyecs does: Components/, one system per file, Program.cs as the host, groups for cadence, input, tests and saves.