EasyEcs

Migrate from Friflo.Engine.ECS

Port a Friflo.Engine.ECS codebase to EasyEcs: concepts and API mapped old to new, chunk loops and command buffers turned into [ForEach] methods, pitfalls.

Friflo.Engine.ECS and EasyEcs are both archetype libraries that allocate nothing per tick, so the data model ports one to one: components stay structs, tags stay empty structs, an EntityStore becomes a World. What changes is how a system is written. A cached ArchetypeQuery iterated chunk by chunk becomes a [ForEach] method whose parameters are the components; changes recorded in a CommandBuffer become direct calls; OnComponentRemoved subscriptions become [Removed<T>] methods. The worked example is the real port in the repository: FrifloSimulation.cs and the EasyEcs world it was ported from, WorldSimulation.cs.

Before you start

Requirements

EasyEcs targets net10.0 only. Code that must also run in Unity or on netstandard2.1 / .NET 6-8 stays on Friflo.

dotnet add package EasyEcs

Both libraries name their component interface IComponent. During a port, alias one of them (using F = Friflo.Engine.ECS;), as the comparison project does.

Concepts

Friflo.Engine.ECSEasyEcsWhat changes
EntityStoreWorldOne owner thread per world.
IComponent structIComponent structNothing but the namespace.
ITagAn empty IComponent structTags are components; removing one flips a bit.
ArchetypeQuery<A, B> + Chunks loopsA [ForEach] method in an EcsSystemThe generator writes the loop.
CommandBuffer + Playback()Direct callsChanges apply at once, also mid-pass.
UniqueEntityISingletonComponentPer-world data, a ref parameter.
SystemRoot, SystemGroup, QuerySystemWorld.AddSystem<T>(), ISystemGroup, EcsSystem
OnComponentRemoved / OnComponentAdded events[Removed<T>], [Changed<T>]State changes are data.
entity.EnabledA tag and [Without<T>], or entity.Disable<T>()EasyEcs disables components, not whole entities (D8).

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).

Entities and components

Friflo.Engine.ECSEasyEcs
var store = new EntityStore();var world = new World();
store.EnsureCapacity(n)world.EnsureEntityCapacity(n)
archetype.EnsureCapacity(n)world.EnsureCapacity<T1, …, Tn>(n) (the entity storage too)
store.CreateEntity(a, b, c)world.CreateEntity(a, b, c)
store.Countworld.EntityCount
entity.AddComponent(c)entity.SetHealth(100, 100), entity.Set(c)
entity.RemoveComponent<Health>()entity.RemoveHealth(), entity.Remove<T>()
ref var c = ref entity.GetComponent<Health>()ref var hp = ref entity.Health, entity.Get<T>()
entity.HasComponent<Health>()entity.HasHealth, entity.Has<T>()
entity.AddTag<Dead>() / RemoveTag<Dead>()entity.SetDead() / entity.RemoveDead()
entity.Tags.Has<Dead>()entity.IsDead
entity.DeleteEntity()entity.Destroy()
store.GetEntityById(id)world.TryGetEntity(entityId, out var entity)
store.CloneEntity(template)world.Instantiate(prefab), entity.Clone()

Queries and iteration

Friflo.Engine.ECSEasyEcs
store.Query<A, B>()the method's parameters: static void M(ref A a, in B b)
.AllComponents(ComponentTypes.Get<C>())[With<C>]
.WithoutAnyComponents(ComponentTypes.Get<C>())[Without<C>]
.AllTags(Tags.Get<Dead>()) / .WithoutAnyTags(...)[With<Dead>] / [Without<Dead>]
foreach (var (as, bs, entities) in query.Chunks)a batch method static void M(Span<A> a, ReadOnlySpan<B> b), or a per-entity method
entities.Ids[i], entities.EntityAt(i)an Entity parameter, or an EntitySpan in a batch method
query.ForEachEntity((ref A a, Entity e) => ...)static void M(Entity e, ref A a)
query.Countworld.Count<A>(filter)
query.ForEach(...) + RunParallel()[ForEach(Parallel = true)]

Changes, events and features

Friflo.Engine.ECSEasyEcs
buffer.AddComponent(id, c) + Playback()entity.Set(c)
buffer.RemoveComponent<T>(id), RemoveTag<T>(id)entity.Remove<T>()
buffer.DeleteEntity(id)entity.Destroy()
buffer.CreateEntity() + AddComponent per componentworld.CreateEntity(a, b, c)
EntityBatch + query.Entities.ApplyBatch(batch)world.SetAll(value, filter), world.RemoveAll<T>(filter)
store.OnComponentRemoved += ...[ForEach, Removed<T>] (with T : ITrackChanges)
A dirty tag added on writeT : ITrackChanges + [ForEach, Changed<T>]
IIndexedComponent<K>, store.ComponentIndex<T, K>()[key]IIndexed<K>, world.Index<T, K>().Find(key)
query.ValueInRange<T, K>(min, max)world.Index<T, K>().Range(min, max)
ILinkComponent, GetIncomingLinks<T>()an EntityId key: IIndexed<EntityId>, index.Find(target)
ILinkRelation, AddRelation, GetRelations<T>()IRelation, entity.AddRelation(...), world.Relations<T>()
AddChild, ChildEntitiesChildOf(parent), world.Children(parent)
EntitySerializer (JSON)world.Save(writer) / world.Load(bytes) (binary)

A worked example: the headline simulation

Components and tags

The structs keep their fields. Dead : ITag becomes an empty component; the counters 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 AoiCell : IComponent { public int Cell; }
public struct Player : IComponent { public long AccountId; }
public struct Npc : IComponent { public int TemplateId; }
public struct Dead : IComponent;

public struct WorldStats : ISingletonComponent
{
    public int CellChanges, Deaths, NpcKills;
}

A chunk loop becomes a method

Friflo:

_cells = _store.Query<Position, AoiCell>().WithoutAnyTags(Tags.Get<Dead>());

foreach (var (positions, cells, _) in _cells.Chunks)
{
    var ps = positions.Span;
    var cs = cells.Span;
    for (int i = 0; i < ps.Length; i++)
    {
        int cell = Rules.Cell(ps[i].X, ps[i].Y);
        if (cell == cs[i].Cell) continue;
        cs[i].Cell = cell;
        _c.CellChanges++;
    }
}

EasyEcs: one method per row; the counters are a ref singleton parameter, resolved once per pass.

AoiSystem.cs
public class AoiSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void UpdateCell(in Position p, ref AoiCell aoi, ref WorldStats stats)
    {
        int cell = (int)(p.Y * (1f / 64f)) * 64 + (int)(p.X * (1f / 64f));
        if (cell == aoi.Cell) return;
        aoi.Cell = cell;
        stats.CellChanges++;
    }
}

The command buffer goes

Friflo records the tag and plays the buffer back after the loop:

foreach (var (healths, entities) in _alive.Chunks)
{
    var health = healths.Span;
    for (int i = 0; i < health.Length; i++)
    {
        if (health[i].Value > 0) continue;
        _buffer.AddTag<Dead>(entities.Ids[i]);
        _c.Deaths++;
        if (entities.EntityAt(i).HasComponent<Npc>()) _c.NpcKills++;
    }
}
_buffer.Playback();

EasyEcs adds it where it is decided, and the respawn system after it already sees the dead:

DeathSystem.cs
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++;
    }
}

public class RespawnSystem : EcsSystem
{
    [ForEach, With<Dead>, With<Player>]
    static void Respawn(Entity entity, ref Health health)
    {
        health.Value = health.Max;
        entity.RemoveDead();
    }
}

Clones become prefabs

Friflo spawns NPCs by cloning a template entity of the store, which queries see like any other. A Prefab lives outside every world, and a wave is one call:

private static readonly Prefab Grunt = new Prefab()
    .SetPosition(0, 0).SetVelocity(0, 0).SetHealth(value: 100, max: 100)
    .SetAoiCell(cell: -1).SetNpc(templateId: 7);
var wave = new Entity[5_000];
world.Instantiate(Grunt, wave);

An event becomes a [Removed<T>] method

A subscription that collects the entities which lost a component, read once per tick, becomes a method. The component must be tracked:

BuffReplication.cs
public record struct Buff(int Ticks) : IComponent, ITrackChanges;
public record struct Expired(int Count) : IComponent;

public class BuffReplication : EcsSystem
{
    [ForEach, Removed<Buff>]
    static void Send(ref Expired expired) => expired.Count++;
}

The tick

Friflo's Tick() calls every loop and every playback in order. EasyEcs runs the systems in the order they were added:

Program.cs
world.AddSingleton<WorldStats>();
world.AddSystem<AoiSystem>();
world.AddSystem<DeathSystem>();
world.AddSystem<RespawnSystem>();
world.AddSystem<BuffReplication>();
world.Update();

The two versions of the whole tick, on the same machine:

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
Both IComponents importedAmbiguous referencesCompiler error: alias one namespace
Keeping a [Removed<T>] component untrackedRemovals are not recordedAdd ITrackChanges to T
Taking T as a parameter of a [Removed<T>] methodNo row can both have and lack TEECS016
Storing an Entity in a component (Friflo's link components do)The column holds referencesEECS017 (warning): store EntityId
Writing an indexed component through ref (Friflo re-indexes on AddComponent)The index cannot see the new keyEECS015: use Set
Expecting Enabled = false on a whole entityNo such switchUse a tag and [Without<T>]
A static method without Entity or World that adds a tagIt promised no structural changeEECS013
Edit on GitHub

Last updated on

How is this guide?

On this page