EasyEcs

Migrate from Arch

Port an Arch ECS codebase to EasyEcs step by step: concepts and API mapped old to new, a server simulation ported from the benchmarks, and the pitfalls.

Arch and EasyEcs share the archetype model, so most of a port is mechanical: a QueryDescription becomes filter attributes, a struct job's Update becomes a [ForEach] method, and world.Add / Remove / Destroy on an entity become calls on its handle. The one change of habit is the command buffer: EasyEcs has none, because structural changes apply at once, also in the middle of a query. The worked example below is the real port in the repository: ArchSimulation.cs and the EasyEcs world it was ported from, WorldSimulation.cs, checked by the comparison project to produce the same counters.

Before you start

Requirements

EasyEcs targets net10.0 only. A project that must also build for Unity, netstandard2.1 or .NET 8 cannot move its ECS code to EasyEcs.

dotnet add package EasyEcs

The package carries the source generator and the analyzer: [ForEach] systems, the generated members (entity.Position, world.Clock) and the EECS rules work with nothing else to install.

Concepts

ArchEasyEcsWhat changes
World.Create()new World(options)A world has one owner thread; run one world per thread.
Any struct is a componentA struct implementing IComponentAdd the interface; the analyzer rejects classes (EECS006).
QueryDescriptionFilter attributes on a [ForEach] method, or a QueryFilterWritten once, on the method; the generator keeps the filter in a static field.
IForEach<T...> + InlineQueryA [ForEach] method in an EcsSystemThe generator writes the struct job and the call.
CommandBuffer + PlaybackDirect callsChanges apply at once; later systems see them.
A counters object passed to jobsA singleton (ISingletonComponent)Taken as a ref parameter, resolved once per pass.
Arch.Extended systemsEcsSystem, ISystemGroup, [UpdateBefore<T>] / [UpdateAfter<T>]Built in.
Events[Changed<T>], [Removed<T>], tags queried laterState changes are data.

API mapping

The rows name the components of the example below (Health, the tag Dead). For each component the generator writes named members (entity.Health, HasHealth, SetHealth(…), IsDead): use them in your code. The generic calls after them (Get<T>(), Set(c), Remove<T>()) are for generic code (generated members).

World and entities

ArchEasyEcs
var world = World.Create();var world = new World(new WorldOptions { InitialEntityCapacity = n });
World.Destroy(world);world.Dispose();
world.Create(a, b, c)world.CreateEntity(a, b, c)
world.Destroy(entity)entity.Destroy()
world.Add(entity, c)entity.SetHealth(100, 100), entity.Set(c)
world.Add<Dead>(entity)entity.SetDead()
world.Remove<Health>(entity)entity.RemoveHealth(), entity.Remove<T>()
world.Has<Health>(entity)entity.HasHealth, entity.IsDead for a tag, entity.Has<T>()
ref var c = ref world.Get<Health>(entity)ref var hp = ref entity.Health, entity.Get<T>()
world.Sizeworld.EntityCount
entity.Identity.Id.Index; store entity.Id (an EntityId) in data
world.EnsureCapacity(in signature, n)world.EnsureCapacity<T1, …, Tn>(n), world.EnsureCapacity(prefab, n)

Queries and iteration

ArchEasyEcs
new QueryDescription().WithAll<A, B>()the method's component parameters: static void M(ref A a, in B b)
.WithAll<Tag>() (a tag the job does not read)[With<Tag>]
.WithNone<C>()[Without<C>]
.WithAny<C, D>()[WithAny<C>, WithAny<D>]
struct J : IForEach<A> + world.InlineQuery<J, A>(in q, ref job)[ForEach] method; outside systems world.ForEach<A, J>(ref job, in filter) with IForEach<A>.Execute
IForEachWithEntity<A> + InlineEntityQueryan Entity parameter: static void M(Entity e, ref A a)
Chunk iteration (GetChunkIterator, chunk.GetSpan<T>())a batch method: static void M(Span<A> a, ReadOnlySpan<B> b)
world.CountEntities(in q)world.Count<A>(filter)
world.InlineParallelQuery<J, A>(in q, ref job)[ForEach(Parallel = true)]

Structural changes

ArchEasyEcs
buffer.Add(e, c) then buffer.Playback(world)e.SetBurning(10, 3), e.Set(c)
buffer.Remove<Burning>(e)e.RemoveBurning()
buffer.Destroy(e)e.Destroy()
var n = buffer.Create(types); buffer.Set(n, c);world.CreateEntity(a, b, c) (a World parameter in a [ForEach] method)
world.Add(in q, value)world.SetAll(value, filter)
world.Remove<T>(in q)world.RemoveAll<T>(filter)
world.Destroy(in q)world.DestroyEntities<T>(filter)

A worked example: the headline simulation

Components

Add IComponent. A tag stays an empty struct. Counters that Arch kept in an object passed to every job become a singleton.

Components.cs
public struct Position : IComponent { public float X, Y; }
public struct Velocity : IComponent { public float X, Y; }
public struct Health : IComponent { public int Value, Max; }
public struct Attack : IComponent { public int Damage, Cooldown, Interval; }
public struct Lifetime : IComponent { public int Ticks; }
public struct Burning : IComponent { public int Ticks, DamagePerTick; }
public struct Player : IComponent { public long AccountId; }
public struct Npc : IComponent { public int TemplateId; }
public struct Projectile : IComponent { public int OwnerId; }
public struct Stunned : IComponent { public int Ticks; }
public struct Dead : IComponent;

public struct WorldStats : ISingletonComponent
{
    public long Tick;
    public int Hits, Deaths, NpcKills, Spawns;
}

A query and its job become one method

Arch:

private static readonly QueryDescription Moving =
    new QueryDescription().WithAll<Position, Velocity>().WithNone<Stunned, Dead>();

private struct Move : IForEach<Position, Velocity>
{
    public void Update(ref Position p, ref Velocity v) { /* ... */ }
}

var move = new Move();
world.InlineQuery<Move, Position, Velocity>(in Moving, ref move);

EasyEcs: the filter goes on the method, the parameters are the components.

MovementSystem.cs
public class MovementSystem : EcsSystem
{
    [ForEach, Without<Stunned>, Without<Dead>]
    static void Move(ref Position p, ref Velocity v)
    {
        p.X += v.X;
        p.Y += v.Y;
        if (p.X < 0 || p.X > 4096) v.X = -v.X;
        if (p.Y < 0 || p.Y > 4096) v.Y = -v.Y;
    }
}

The command buffer goes

Arch records the status change and plays it back after the query:

public void Update(Entity e, ref Attack attack, ref Health health)
{
    if (--attack.Cooldown > 0) return;
    attack.Cooldown = attack.Interval;
    C.Hits++;
    health.Value -= attack.Damage;
    if (Rng.Chance(C.Tick, e.Id, 1, 50) && !W.Has<Burning>(e))
        B.Add(e, new Burning { Ticks = 10, DamagePerTick = 3 });
}
// ...
_buffer.Playback(_world);

EasyEcs applies it on the spot. The counters are a ref singleton parameter.

CombatSystem.cs
public class CombatSystem : EcsSystem
{
    [ForEach, Without<Dead>, Without<Stunned>]
    static void Fight(Entity entity, ref Attack attack, ref Health health, ref WorldStats stats)
    {
        if (--attack.Cooldown > 0) return;
        attack.Cooldown = attack.Interval;
        stats.Hits++;
        health.Value -= attack.Damage;
        if (entity.Id.Index % 20 == 0 && !entity.HasBurning)
            entity.SetBurning(ticks: 10, damagePerTick: 3);
    }
}

public class StatusSystem : EcsSystem
{
    [ForEach]
    static void Burn(Entity entity, ref Burning burning, ref Health health)
    {
        health.Value -= burning.DamagePerTick;
        if (--burning.Ticks <= 0) entity.RemoveBurning();
    }
}

public class DeathSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void CheckDeath(Entity entity, in Health health, ref WorldStats stats)
    {
        if (health.Value > 0) return;
        entity.SetDead();
        stats.Deaths++;
        if (entity.HasNpc) stats.NpcKills++;
    }
}

Creating and destroying

Arch creates projectiles through the buffer with a signature and one Set per component. EasyEcs creates the entity with its components in one call, placed in its final table; a method that creates or destroys takes World or Entity.

ShootingSystem.cs
public class ShootingSystem : EcsSystem
{
    [ForEach, With<Player>, Without<Dead>]
    static void Shoot(Entity shooter, in Position p, in Velocity v, ref WorldStats stats, World world)
    {
        if ((stats.Tick + shooter.Id.Index) % 20 != 0) return;
        stats.Spawns++;
        world.CreateEntity(p, new Velocity { X = v.X * 4, Y = v.Y * 4 }, new Lifetime { Ticks = 20 },
            new Projectile { OwnerId = shooter.Id.Index });
    }
}

public class LifetimeSystem : EcsSystem
{
    [ForEach]
    static void Expire(Entity entity, ref Lifetime lifetime)
    {
        if (--lifetime.Ticks <= 0) entity.Destroy();
    }
}

public sealed class ClockSystem : EcsSystem
{
    protected override void OnUpdate() => World.WorldStats.Tick++;
}

The tick

Arch's Tick() calls every query and every playback in order. EasyEcs runs the systems in the order they were added (or as [UpdateBefore<T>] / [UpdateAfter<T>] say) with one call.

Program.cs
using var sim = new World(new WorldOptions { InitialEntityCapacity = 200_000 });
sim.AddSingleton<WorldStats>();
sim.AddSystem<MovementSystem>();
sim.AddSystem<CombatSystem>();
sim.AddSystem<StatusSystem>();
sim.AddSystem<DeathSystem>();
sim.AddSystem<LifetimeSystem>();
sim.AddSystem<ShootingSystem>();
sim.AddSystem<ClockSystem>();

sim.EnsureCapacity<Position, Velocity, Health, Attack, Player>(100_000);
for (int i = 0; i < 100_000; i++)
    sim.CreateEntity(new Position { X = i % 4096, Y = i / 25 }, new Velocity { X = 1, Y = -1 },
        new Health { Value = 150, Max = 150 }, new Attack { Damage = 5, Cooldown = i % 10, Interval = 8 },
        new Player { AccountId = i });

sim.Update();   // one tick

The whole port, with the area-of-interest grid and respawns, is the pair of files linked at the top. On the same machine the EasyEcs version runs the tick in 1.68 ms against 5.76 ms for Arch, at 100,000 entities:

One server tick of 100,000 entities: EasyEcs vs Friflo, Arch and DefaultEcs

The same simulation ported to each library's fast path, with identical results checked in setup. Shorter is faster; the badge is the time relative to EasyEcs and the memory allocated per tick.

  • EasyEcs
  • Other libraries
EasyEcs 4.60 B per tick1.68 msFriflo.Engine.ECS 3.61.08× · 0 B per tick1.83 msArch 2.13.4× · 535 KB per tick5.76 msDefaultEcs 0.173.7× · 60.9 KB per tick6.24 ms0.00 ns1.00 ms2.00 ms3.00 ms4.00 ms5.00 ms6.00 msTime per tick

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

Data table
LibraryTimevs EasyEcsAllocated
EasyEcs 4.61.68 ms1.00×0 B
Friflo.Engine.ECS 3.61.83 ms1.08×0 B
Arch 2.15.76 ms3.4×535 KB
DefaultEcs 0.176.24 ms3.7×60.9 KB

Pitfalls

MistakeWhat happensCaught by
Keeping a component as a plain struct without IComponentIt cannot be a parameter or a columnCompiler error: the constraint IComponent
A class as a componentRejectedEECS006
Porting the counters object as a field of the systemSystems are statelessEECS007: use a singleton
Storing an Entity in a component (Arch's Entity was a plain struct)The column holds referencesEECS017 (warning): store EntityId
A static method without Entity or World that adds a componentIt promised no structural changeEECS013: take the Entity
Keeping a "pending changes" list to apply after the loopWorks, but costs a second passCode review: apply the change where it is decided
A parallel method that changes structure or writes a singletonData racesEECS010
Edit on GitHub

Last updated on

How is this guide?

On this page