Skip to main content

Quick Start

This document provides a quick overview of the different features and concepts in Flecs with short examples. This is a good resource if you're just getting started or just want to get a better idea of what kind of features are available in Flecs!

Nuget

You can download the nuget package and use Flecs.NET right away!

Flecs.NET (Wrapper + bindings + native libraries): Release | Debug

dotnet add PROJECT package Flecs.NET.Release --version *-*

Flecs.NET.Bindings (Bindings + native libraries): Release | Debug

dotnet add PROJECT package Flecs.NET.Bindings.Release --version *-*

Flecs.NET.Native (Native libraries): Release | Debug

dotnet add PROJECT package Flecs.NET.Native.Release --version *-*

Flecs.NET provides both release and debug packages for nuget. To include both of them in your project based on your build configuration, use the packages references below. The latest stable or prerelease versions will be added to your project.

<ItemGroup>
<PackageReference Include="Flecs.NET.Debug" Version="*-*" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="Flecs.NET.Release" Version="*-*" Condition="'$(Configuration)' == 'Release'" />
</ItemGroup>

Concepts

This section contains an overview of all the different concepts in Flecs and how they wire together. The sections in the quickstart go over them in more detail and with code examples.

Flecs Overview

World

The world is the container for all ECS data. It stores the entities and their components, does queries and runs systems. Typically there is only a single world, but there is no limit on the number of worlds an application can create.

C#
using Flecs.NET.Core;

using World world = World.Create();

// Do the ECS stuff

Entity

An entity is a unique thing in the world, and is represented by a 64 bit id. Entities can be created and deleted. If an entity is deleted it is no longer considered "alive". A world can contain up to 4 billion(!) alive entities. Entity identifiers contain a few bits that make it possible to check whether an entity is alive or not.

C#
Entity e = world.Entity();
e.IsAlive(); // true!

e.Destruct();
e.IsAlive(); // false!

Entities can have names which makes it easier to identify them in an application. In C++ and .NET the name can be passed to the constructor. In C a name can be assigned with the ecs_entity_init function/ecs_entity macro. If a name is provided during entity creation time and an entity with that name already exists, the existing entity will be returned.

C#
Entity e = world.Entity("Bob");

Console.WriteLine($"Entity name: {e.Name()}");

Entities can be looked up by name with the Lookup function:

C#
Entity e = world.Lookup("Bob");

Id

An id is a 64 bit number that can encode anything that can be added to an entity. In flecs this can be either a component, tag or a pair. A component is data that can be added to an entity. A tag is an "empty" component. A pair is a combination of two component/tag ids which is used to encode entity relationships. All entity/component/tag identifiers are valid ids, but not all ids are valid entity identifier.

The following sections describe components, tags and pairs in more detail.

Component

A component is a type of which instances can be added and removed to entities. Each component can be added only once to an entity (though not really, see Pair). In C applications components must be registered before use. In C++ and .NET this happens automatically.

C#
Entity e = world.Entity();

// Add a component. This creates the component in the ECS storage, but does not
// assign it with a value.
e.Add<Velocity>();

// Set the value for the Position & Velocity components. A component will be
// added if the entity doesn't have it yet.
e.Set(new Position { X = 10, Y = 20 })
.Set(new Velocity { X = 1, Y = 2 });

// Get a component
ref readonly Position p = ref e.Get<Position>();

// Remove component
e.Remove<Position>();

Each component is associated by a unique entity identifier by Flecs. This makes it possible to inspect component data, or attach your own data to components. C applications can use the ecs_id macro to get the entity id for a component. C++ applications can use the world::entity function and .NET applications can use the world.Entity function:

C#
Entity posE = world.Entity<Position>();
Console.WriteLine($"Name: {posE.Name()}); // outputs 'Name: Position'

// It's possible to add components like you would for any entity
posE.Add<Serializable>();

The thing that makes an ordinary entity a component is the EcsComponent (or flecs::Component, in C++) component. This is a builtin component that tells Flecs how much space is needed to store a component, and can be inspected by applications:

C#
Entity posE = world.Entity<Position>();

ref readonly EcsComponent c = ref posE.Get<EcsComponent>();
Console.WriteLine($"Component size: {c.size}");

Because components are stored as regular entities, they can in theory also be deleted. To prevent unexpected accidents however, by default components are registered with a tag that prevents them from being deleted. If this tag were to be removed, deleting a component would cause it to be removed from all entities. For more information on these policies, see Relationship cleanup properties.

Tag

A tag is a component that does not have any data. In Flecs tags can be either empty types (in C++ and .NET) or regular entities that do not have the EcsComponent component (or have an EcsComponent component with size 0). Tags can be added & removed using the same APIs as adding & removing components, but because tags have no data, they cannot be assigned a value. Because tags (like components) are regular entities, they can be created & deleted at runtime.

C#
// Option 1: create Tag as empty struct
public struct Enemy { }

// Create entity, add Enemy tag
Entity e = world.Entity().Add<Enemy>();
e.Has<Enemy>(); // true!

e.Remove<Enemy>();
e.Has<Enemy>(); // false!


// Option 2: create Tag as entity
Entity Enemy = world.Entity();

// Create entity, add Enemy tag
Entity e = world.Entity().Add(Enemy);
e.Has(Enemy); // true!

e.Remove(Enemy);
e.Has(Enemy); // false!

Note that both options in the C++ and .NET examples achieve the same effect. The only difference is that in option 1 the tag is fixed at compile time, whereas in option 2 the tag can be created dynamically at runtime.

When a tag is deleted, the same rules apply as for components (see Relationship cleanup properties).

Pair

A pair is a combination of two entity ids. Pairs can be used to store entity relationships, where the first id represents the relationship kind and the second id represents the relationship target (called "object"). This is best explained by an example:

C#
// Create Likes relationship as empty type (tag)
public struct Likes { }

// Create a small graph with two entities that like each other
Entity Bob = world.Entity();
Entity Alice = world.Entity();

Bob.Add<Likes>(Alice); // Bob likes Alice
Alice.Add<Likes>(Bob); // Alice likes Bob
Bob.Has<Likes>(Alice); // true!

Bob.Remove<Likes>(Alice);
Bob.Has<Likes>(Alice); // false!

A pair can be encoded in a single 64 bit identifier by using the ecs_pair macro in C, or the world.pair function in C++ and .NET:

C#
Id id = world.Pair<Likes>(Bob);

The following examples show how to get back the elements from a pair:

C#
if (id.IsPair())
{
Entity relationship = id.First();
Entity target = id.Second();
}

A component or tag can be added multiple times to the same entity as long as it is part of a pair, and the pair itself is unique:

C#
Bob.Add(Eats, Apples);
Bob.Add(Eats, Pears);
Bob.Add(Grows, Pears);

Bob.Has(Eats, Apples); // true!
Bob.Has(Eats, Pears); // true!
Bob.Has(Grows, Pears); // true!

The target function can be used to get the object for a relationship:

C#
Entity o = Alice.Target<Likes>(); // Returns Bob

Entity relationships enable lots of interesting patterns and possibilities. Make sure to check out the Relationships manual.

Hierarchies

Flecs has builtin support for hierarchies with the builtin EcsChildOf (or flecs::ChildOf, in C++) relationship. A hierarchy can be created with the regular relationship API, or with the child_of/ChildOf shortcut in C++ and .NET:

C#
Entity parent = world.Entity();
Entity child = world.Entity().ChildOf(parent);

// Deleting the parent also deletes its children
parent.Destruct();

When entities have names, they can be used together with hierarchies to generate path names or do relative lookups:

C#
Entity parent = world.Entity("parent");
Entity child = world.Entity("child").ChildOf(parent);
Console.WriteLine(child.Path());// output: 'parent::child'

world.Lookup("parent.child"); // returns child
parent.Lookup("child"); // returns child

Queries (see below) can use hierarchies to order data breadth-first, which can come in handy when you're implementing a transform system:

C#
Query q = world.Query(
filter: world.FilterBuilder<Position, Position>()
.TermAt(2).Parent().Cascade()
);

q.Each((ref Position p, ref Position pParent) =>
{
// Do the thing
});

Instancing

Flecs has builtin support for instancing (sharing a single component with multiple entities) through the builtin EcsIsA relationship (flecs::IsA in C++). An entity with an IsA relationship to a base entity "inherits" all entities from that base:

C#
Entity baseEntity = world.Entity().Set(new Triangle(new(0, 0), new(1, 1), new(-1, -1)));

// Create entity that shares components with base
Entity e = world.Entity().IsA(baseEntity);
ref readonly Triangle t = ref e.Get<Triangle>(); // gets Triangle from base

Entities can override components from their base:

C#
// Add private instance of Triangle to e, copy value from base
e.Add<Triangle>();

Instancing can be used to build modular prefab hierarchies, as the foundation of a batched renderer with instancing support, or just to reduce memory footprint by sharing common data across entities.

Type

The type (often referred to as "archetype") is the list of ids an entity has. Types can be used for introspection which is useful when debugging, or when for example building an entity editor. The most common thing to do with a type is to convert it to text and print it:

C#
Entity e = ecs.Entity()
.Add<Position>()
.Add<Velocity>();

Console.WriteLine(e.Type().Str()); // output: 'Position,Velocity'

A type can also be iterated by an application:

C#
e.Each((Id id) =>
{
if (id == world.Id<Position>())
// Found Position component!
});

Singleton

A singleton is a single instance of a component that can be retrieved without an entity. The functions for singletons are very similar to the regular API:

C#
world.Set(new Gravity { Value = 9.81 });

Singleton components are created by adding the component to its own entity id. The above code examples are shortcuts for these regular API calls:

C#
Entity gravE = world.Entity<Gravity>();

gravE.Set(new Gravity { X = 10, Y = 20 });

ref readonly Gravity g = ref gravE.Get<Gravity>();

The following examples show how to query for a singleton component:

C#
world.Query(
filter: world.FilterBuilder<Velocity, Gravity>()
.TermAt(2).Singleton()
);

Filter

Filters are a kind of uncached query that are cheap to create. This makes them a good fit for scenarios where an application doesn't know in advance what it has to query for, like when finding the children for a parent. The following example shows a simple filter:

C#
// For simple queries the each function can be used
world.Each((ref Position p, ref Velocity v) => // Entity argument is optional
{
p.x += v.x;
p.y += v.y;
});

// More complex filters can first be created, then iterated
Filter f = world.Filter(
filter: world.FilterBuilder<Position>()
.Term(Ecs.ChildOf, parent)
);

// Option 1: Each() function that iterates each entity
f.Each((Entity e, ref Position p) =>
{
Console.WriteLine($"{e}: ({p.x}, {p.y})");
});

// Option 2: Iter() function that iterates each archetype
f.Iter((Iter it, Column<Position> p) =>
{
foreach (int i in it)
Console.WriteLine($"{it.Entity(i)}: ({p[i].X}, {p[i].Y})");
});

Filters can use operators to exclude components, optionally match components or match one out of a list of components. Additionally filters may contain wildcards for terms which is especially useful when combined with pairs.

The following example shows a filter that matches all entities with a parent that do not have Position:

C#
Filter f = world.Filter(
filter: world.FilterBuilder()
.Term(Ecs.ChildOf, Ecs.Wildcard)
.Term<Position>().Not()
);

// Iteration code is the same

Query

Queries are cached versions of filters. They are slower to create than filters, but much faster to iterate since this just means iterating their cache.

The API for queries is similar to filters:

C#
// Create a query with two terms
Query q = world.Query(
filter: world.FilterBuilder<Position>()
.Term(Ecs.ChildOf, Ecs.Wildcard)
);

// Iteration is the same as filters

When using queries, make sure to reuse a query object instead of creating a new one each time you need it. Query creation is expensive, and many of the performance benefits of queries are lost when they are created in loops.

See the query manual for more details.

System

A system is a query combined with a callback. Systems can be either ran manually or ran as part of an ECS-managed main loop (see Pipeline). The system API looks similar to queries:

C#
// Systems are called routines in Flecs.NET
Routine moveRoutine = world.Routine(
filter: world.FilterBuilder<Position, Velocity>(),
callback: (Iter it, Column<Position> p, Column<Velocity> v) =>
{
foreach (int i in it)
{
p[i].X += v[i].X * it.DeltaTime();
p[i].Y += v[i].Y * it.DeltaTime();
}
}
);

moveRoutine.Run();

Systems are stored as entities with an EcsSystem component (flecs::System in C++), similar to components. That means that an application can use a system as a regular entity:

C#
Console.WriteLine($"Routine: {moveRoutine}");
moveRoutine.Entity.Add(Ecs.OnUpdate);
moveRoutine.Entity.Destruct();

Pipeline

A pipeline is a list of tags that when matched, produces a list of systems to run. These tags are also referred to as a system "phase". Flecs comes with a default pipeline that has the following phases:

C#
Ecs.OnLoad
Ecs.PostLoad
Ecs.PreUpdate
Ecs.OnUpdate
Ecs.OnValidate
Ecs.PostUpdate
Ecs.PreStore
Ecs.OnStore

When a pipeline is executed, systems are ran in the order of the phases. This makes pipelines and phases the primary mechanism for defining ordering between systems. The following code shows how to assign systems to a pipeline, and how to run the pipeline with the progress() function:

C#
world.Routine(
name: "Move",
filter: world.FilterBuilder<Position, Velocity>(),
routine: world.RoutineBuilder().Kind(Ecs.OnUpdate),
callback: (Iter it) => { ... }
);

world.Routine(
name: "Transform",
filter: world.FilterBuilder<Position, Transform>(),
routine: world.RoutineBuilder().Kind(Ecs.PostUpdate),
callback: (Iter it) => { ... }
);

world.Routine(
name: "Render",
filter: world.FilterBuilder<Transform, Mesh>(),
routine: world.RoutineBuilder().Kind(Ecs.OnStore),
callback: (Iter it) => { ... }
);

world.Progress();

Because phases are just tags that are added to systems, applications can use the regular API to add/remove systems to a phase:

C#
moveRoutine.Entity.Add(Ecs.OnUpdate);
moveRoutine.Entity.Remove(Ecs.PostUpdate);

Inside a phase, systems are guaranteed to be ran in their declaration order.

Observer

Observers are callbacks that are invoked when one or more events matches the query of an observer. Events can be either user defined or builtin. Examples of builtin events are OnAdd, OnRemove and OnSet.

When an observer has a query with more than one component, the observer will not be invoked until the entity for which the event is emitted satisfies the entire query.

An example of an observer with two components:

C#
world.Observer(
name: "OnSetPosition",
filter: world.FilterBuilder<Position, Velocity>(),
observer: world.ObserverBuilder().Event(Ecs.OnSet),
callback: (Iter it) => { ... }
);

Entity e = world.Entity();
e.Set(new Position { X = 10, Y = 20 });
e.Set(new Velocity { X = 1, Y = 2 });
e.Set(new Position { X = 20, Y = 30 });

Module

A module is a function that imports and organizes components, systems, triggers, observers, prefabs into the world as reusable units of code. A well designed module has no code that directly relies on code of another module, except for components definitions. All module contents are stored as child entities inside the module scope with the ChildOf relationship. The following examples show how to define a module in different languages:

C#
public struct MyModule : IFlecsModule
{
public void InitModule(ref World world)
{
world.Module<MyModule>();

// Define components, systems, triggers, ... as usual. They will be
// automatically created inside the scope of the module.
}
};

// Import code
world.Import<MyModule>();