BorrowedTorch.ECS
1.2.0
Prefix Reserved
dotnet add package BorrowedTorch.ECS --version 1.2.0
NuGet\Install-Package BorrowedTorch.ECS -Version 1.2.0
<PackageReference Include="BorrowedTorch.ECS" Version="1.2.0" />
<PackageVersion Include="BorrowedTorch.ECS" Version="1.2.0" />
<PackageReference Include="BorrowedTorch.ECS" />
paket add BorrowedTorch.ECS --version 1.2.0
#r "nuget: BorrowedTorch.ECS, 1.2.0"
#:package BorrowedTorch.ECS@1.2.0
#addin nuget:?package=BorrowedTorch.ECS&version=1.2.0
#tool nuget:?package=BorrowedTorch.ECS&version=1.2.0
BorrowedTorch.ECS
A small entity component system for .NET games. Entities are generational handles, components are plain structs kept in sparse-set stores packed for cache-friendly iteration, and systems walk them through by-reference queries. It has no dependencies: it knows nothing about MonoGame, and sits next to it (or any other framework) without friction.
What you get:
- Generational entity handles: ids of destroyed entities are recycled, and a handle kept past its entity's destruction stays dead even after its id has been given to a new entity.
- Packed component storage: one sparse set per component type. Add, get, has and remove are O(1), and queries iterate dense arrays with no holes.
- By-reference queries over one, two or three component types. Components are handed over as
ref, so a system changes them in place, and a join walks the smallest of the stores involved. - Type-erased access: list every live entity, add, get, has and remove by
Type, list an entity's component types, and give components a declared default. Everything an inspector, an editor or a serializer needs. - Component types that can go: list the types a world keeps stores for, and drop one with all its components, so an assembly of component types - a game's code reloaded - can be unloaded.
It does not schedule or order systems, track changes, raise events, serialize, or run anything on more than one thread: it stores components and answers queries, and the game loop around it stays yours.
Requirements
- .NET 8 or later. No other dependencies.
Installing
dotnet add package BorrowedTorch.ECS
Concepts
| Type | Namespace | What it is |
|---|---|---|
ECSWorld |
BorrowedTorch.ECS |
Owns entities and component stores, and runs queries. Systems talk only to the world. |
Entity |
BorrowedTorch.ECS.Entities |
A handle: an id plus the generation that id had when the entity was created. |
IComponent |
BorrowedTorch.ECS.Components.Base |
Marks a type as a component. Components are data only. |
ISystem |
BorrowedTorch.ECS.Systems.Base |
Marks a type as a system. How and when it runs is up to you. |
ComponentStore<T> |
BorrowedTorch.ECS.Components.Store |
The sparse set behind one component type. The world creates them; you rarely touch one directly. |
ComponentDefaults |
BorrowedTorch.ECS.Components.Store |
The starting value of a component added by Type without a value. |
1. Define components
Components are plain data. Make them structs: the stores keep them packed side by side, and queries hand them over by reference without copying. Classes work too, but are stored as references to objects scattered on the heap.
using BorrowedTorch.ECS.Components.Base;
public struct Position : IComponent
{
public float X;
public float Y;
}
public struct Velocity : IComponent
{
public float X;
public float Y;
}
public struct Health : IComponent
{
public int Value;
// Used when a Health is added by type without a value (see "Type-erased access" below).
public static readonly Health Default = new() { Value = 100 };
}
IComponent shares its name with System.ComponentModel.IComponent. If a file imports both namespaces (WPF and
WinForms projects do by default), settle it with an alias:
global using IComponent = BorrowedTorch.ECS.Components.Base.IComponent;
2. Create entities and attach components
using BorrowedTorch.ECS;
var world = new ECSWorld();
var player = world.CreateEntity();
world.AddComponent(player, new Position { X = 0, Y = 0 });
world.AddComponent(player, new Velocity { X = 1, Y = 0 });
world.AddComponent(player, new Health { Value = 100 });
// GetComponent returns a reference: changes go straight into the store.
ref var health = ref world.GetComponent<Health>(player);
health.Value -= 25;
if (world.HasComponent<Velocity>(player)) world.RemoveComponent<Velocity>(player);
Adding a component the entity already has overwrites it: an entity has at most one component of each type.
The reference GetComponent returns points straight into the store. Like a reference handed to a query callback, it
is valid until the next add or remove of that component type on any entity, which may move the store's contents. Use
it on the spot rather than keeping it across those calls.
3. Write systems
A system queries the world for the entities that have the components it works on. Keep the query callback in a field: a lambda that captures state allocates a new delegate every time it is passed in, and systems run every frame.
using BorrowedTorch.ECS;
using BorrowedTorch.ECS.Entities;
using BorrowedTorch.ECS.Systems.Base;
public sealed class MovementSystem : ISystem
{
private readonly ECSWorld _world;
private readonly ECSWorld.QueryAction<Position, Velocity> _move;
private float _deltaTime;
public MovementSystem(ECSWorld world)
{
_world = world;
_move = Move;
}
public void Update(float deltaTime)
{
_deltaTime = deltaTime;
_world.Query(_move);
}
private void Move(Entity entity, ref Position position, ref Velocity velocity)
{
position.X += velocity.X * _deltaTime;
position.Y += velocity.Y * _deltaTime;
}
}
ISystem is only a marker: the world does not run systems. Call them from your game loop, in the order you need:
var movement = new MovementSystem(world);
// every frame
movement.Update(deltaTime);
There are queries over one, two and three component types. For a fourth, filter inside the callback with
world.HasComponent<T>(entity). Entities come in no particular order: removing a component moves the store's last
one into the hole it leaves.
Structural changes wait until the query returns
A query walks the stores' arrays directly, so adding or removing a component of a queried type - or destroying an entity that has one - from inside the callback reshapes the arrays under it. Changing component values through the references is fine, and so is adding or removing components of other types. For the rest, collect what has to change and apply it afterwards:
var dead = new List<Entity>();
world.Query((Entity entity, ref Health health) =>
{
if (health.Value <= 0) dead.Add(entity);
});
foreach (var entity in dead) world.DestroyEntity(entity);
4. Entity lifetime
var enemy = world.CreateEntity();
world.DestroyEntity(enemy); // removes all its components and recycles its id
var next = world.CreateEntity(); // may get enemy's id back, under a new generation
world.IsEntityAlive(enemy); // false: enemy != next
world.IsEntityAlive(next); // true
An entity is alive from CreateEntity until DestroyEntity, and only the exact handle CreateEntity returned refers
to it. A handle the world never handed out is not alive, whatever id and generation it is made of.
GetAliveEntities lists every live entity in ascending id order, under its current generation, whether it has
components or not. It builds a new list on every call, so entities can be created and destroyed while walking it:
foreach (var entity in world.GetAliveEntities())
if (world.GetComponentTypes(entity).Count == 0) world.DestroyEntity(entity); // drop the bare ones
Entity handles can be stored anywhere - in a component that points at a target or a parent, in a dictionary, in a list. Before following one, ask the world whether it is still alive. Every world accessor checks this on its own, so a stale handle never reaches the component of whatever entity owns its id now:
| Call on a handle that is not alive | Result |
|---|---|
HasComponent |
false |
GetComponent |
throws KeyNotFoundException |
AddComponent |
throws InvalidOperationException |
RemoveComponent, DestroyEntity |
do nothing |
GetComponentTypes |
an empty list |
Use Entity.Invalid for "no entity": it is never alive. default(Entity) cannot stand in for it. It is id 0 at
generation 0, which is not alive in an empty world, but it is exactly the handle the world's first entity gets. From
then on, an Entity field that was never set points at that entity. Initialise Entity fields with Entity.Invalid.
5. Type-erased access
For code that only knows a component's type at run time: inspectors, editors, serializers, scripting bridges.
foreach (var type in world.GetComponentTypes(player))
{
var value = world.GetComponent(player, type); // boxed copy
// ... display, edit or serialize it ...
world.AddComponent(player, type, value); // write the edited copy back
}
world.AddComponent(player, typeof(Health)); // no value: Health.Default is used
world.HasComponent(player, typeof(Health));
world.RemoveComponent(player, typeof(Health));
The typed and the type-erased calls share the same stores, so a component added one way is seen by the other.
A component added by type without a value starts at its declared default (ComponentDefaults): a public static field
or property named Default or Identity whose type is the component itself, Default first. A struct that declares
neither starts zeroed. Declare one wherever zero is the wrong start, such as a scale of zero or a transparent colour. A
class that declares neither cannot be added without a value.
Dropping a component type
A world keeps the store of every component type it was ever given, empty or not, so a store holds on to its type for
the world's life. Where a type is done with - one from an assembly loaded into a collectible AssemblyLoadContext, a
game's code about to be reloaded - drop its store, and every entity's component of it with it:
foreach (var type in world.ComponentTypes.Where(type => type.IsCollectible).ToList()) // a copy: the view is live
world.RemoveComponentType(type);
The entities stay alive with their other components. A component of the type added afterwards starts a new, empty store, so give the world only the types that are still in use from then on.
Performance notes
- Each
ComponentStore<T>holds a dense array of components, a dense array of the entities that own them, and a sparse array mapping entity id to dense index. The sparse array grows to cover the highest entity id that ever had that component, so even a rare component on a large world costs oneintper id. No store ever shrinks. A store is created by the first add of its type: asking about, or querying, a type nothing has been given costs no store. It stays untilRemoveComponentTypedrops it. - The typed calls (
AddComponent<T>,GetComponent<T>,HasComponent<T>,RemoveComponent<T>and the queries) find a type's store through a static per-type index into an array: a field read and an array index, with noTypeto hash. Only the type-erased calls go through a dictionary keyed onType. - A query over one type is a straight loop over a dense array. A query over two or three walks the smallest store and looks each entity up in the others with one sparse lookup per store, so its cost follows the rarest component.
- A world is not thread-safe. Give each thread its own, or synchronise around it.
Measured with the benchmarks described under "Building and testing", on a Ryzen 7 5800H under .NET 10, on a world of 100,000 entities with ten component types, at entities picked at random. Expect the same order of magnitude on other hardware, not the same digits. The typed calls allocate nothing.
| Operation | Cost |
|---|---|
IsEntityAlive |
~1.4 ns |
HasComponent<T> |
~2.6 ns, or ~5 ns for a type that has no store |
GetComponent<T> |
~4.5 ns for a struct, ~8 ns for a class |
GetComponent(entity, Type) |
~13 ns, plus a 24-byte box |
AddComponent<T> then RemoveComponent<T> |
~9.5 ns for the pair; ~23 ns and a box by Type |
DestroyEntity then CreateEntity, no components |
~35 ns |
DestroyEntity then CreateEntity and ten adds |
~180 ns |
Query<T1>, per entity visited |
under 2 ns |
Query<T1, T2>, per entity visited |
~2.5 ns |
Query<T1, T2, T3>, per entity visited |
~4 ns |
Building and testing
dotnet test BorrowedTorch.ECS.Tests
dotnet pack BorrowedTorch.ECS --configuration Release
The package lands in BorrowedTorch.ECS/bin/Release.
Benchmarks
BorrowedTorch.ECS.Benchmarks measures the hot paths with BenchmarkDotNet, on a world of 100,000 entities with ten
component types: what one GetComponent, HasComponent or IsEntityAlive call costs at a random entity
(AccessBenchmarks), one full pass of each query with the stores overlapping at 100%, 50% and 1% (QueryBenchmarks),
and add/remove and destroy/create churn (ChurnBenchmarks). The access and churn benchmarks time the type-erased
calls next to the typed ones.
dotnet run -c Release --project BorrowedTorch.ECS.Benchmarks
dotnet run -c Release --project BorrowedTorch.ECS.Benchmarks -- --filter *Query*
A full run takes a few minutes. The reports land in BenchmarkDotNet.Artifacts/results.
License
MIT.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on BorrowedTorch.ECS:
| Package | Downloads |
|---|---|
|
BorrowedTorch.Engine
Kindling, Borrowed Torch's game engine: what a game's own code builds against - its features registering components, systems, keys and UI handlers - for the Kindling editor and player to run |
GitHub repositories
This package is not used by any popular GitHub repositories.