Skip to content
Proyectos

genaray/Arch.Extended

Ver en GitHub

Acerca de

Extensions for Arch with some useful features like Systems, Source Generator and Utils.

Juegos y emulación

Cómo se miden estas cifras

What you can do

  • Systems with groups, ordering, fixed steps and command buffers
  • Systems that run in parallel when they do not touch the same components
  • Queries generated from attributes, with phases, order and diagnostics
  • A source generated EventBus

Crecimiento de estrellas medido

in 24h
0
in 7 days
+1
in 15 days
+1
in 1 month
Recopilando historial

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

Arch.Extended Maintenance Nuget License C#

Extensions for Arch, the high-performance C# Archetype & Chunks Entity Component System (ECS). Systems, a source generator, persistence, an inspector and more, so you write game logic instead of boilerplate.

  • 🛠️ PRODUCTIVE > Adds the tools and features you would write yourself anyway, and writes the repetitive parts for you!
  • 🏎️ FAST > Generated queries without delegates, allocation-free systems and groups, and a persistence that copies memory instead of boxing every component!
  • ☕️ SIMPLE > Works easily, reliably and understandably. Every tool can be used on its own!
  • 💪 MAINTAINED > It's actively being worked on, maintained, and supported!
  • 🚢 SUPPORT > Built for Arch 3.0.0. Supports .NetStandard 2.1 and .Net 6 or newer and therefore you may use it with Unity or Godot!

Download the packages and get started today!

dotnet add package Arch.System --version 1.2.0
dotnet add package Arch.System.SourceGenerator --version 2.2.0
dotnet add package Arch.EventBus --version 1.0.2
dotnet add package Arch.LowLevel --version 1.1.5
dotnet add package Arch.Relationships --version 2.1.0
dotnet add package Arch.Persistence --version 3.0.0
dotnet add package Arch.AOT.SourceGenerator --version 1.0.1

⏩ Quickstart

You have a world, and you want things to move. Write what should happen to which components, the rest is generated.

using Arch.Core;
using Arch.System;

// Components
public record struct Position(float X, float Y);
public record struct Velocity(float Dx, float Dy);

// A system. The query is generated, there is no lambda and nothing is allocated.
public partial class MovementSystem : BaseSystem<World, float>
{
    public MovementSystem(World world) : base(world) {}

    [Query]
    public void Move([Data] in float time, ref Position pos, in Velocity vel)
    {
        pos.X += time * vel.Dx;
        pos.Y += time * vel.Dy;
    }
}

using var world = World.Create();
world.Create(new Position(0, 0), new Velocity(1, 1));

var systems = new Group<float>("Systems", new MovementSystem(world));
systems.Initialize();
systems.Update(0.016f);

[!NOTE] The tools can be used independently of each other. Check the Wiki for each of them!

💡 Highlights

🤝 Our promise

  • Stays out of your way - every tool is optional, nothing is forced on your architecture
  • Fast by design - no hidden allocations on the paths that run every frame
  • Errors that explain themselves - the generator, the persistence and the inspector tell you what is wrong and how to fix it
  • Is actively maintained and developed
  • Grateful for every contribution

🚀 Features

  • Systems with groups, ordering, fixed steps and command buffers
  • Systems that run in parallel when they do not touch the same components
  • Queries generated from attributes, with phases, order and diagnostics
  • A source generated EventBus
  • Low-level collections to get rid of GC pressure
  • Relationships between entities
  • Binary and JSON persistence for worlds and entities, that is fast and keeps entities alive
  • A live dashboard that shows memory, systems, timings and entities of a running game
  • AOT friendly
  • And much more...

🧩 Packages

  • ⚙️ Systems > By means of systems, it is now easy to organize, reuse and arrange queries.
  • ✍️ Source Generator > Declarative syntax using attributes and source generator, let your queries write themselves!
  • ✉️ EventBus > A source generated EventBus, send Events with high-performance!
  • 👾 LowLevel > Low-level utils and data structures to get rid of GC pressure!
  • 💑 Relationships > Adds simple relationships between entities to arch!
  • 💾 Persistence > JSON and Binary (de)serialization to persist your Worlds! See below.
  • ⌛ AOT Source Generator > Helps with AOT compatibility and reduces boilerplate code!
  • 🔎 Inspector > Analysis, profiling and a dashboard served from inside your game. Not published as packages yet, build it from this repository!

Check the links and the Wiki!

🔎 Inspector

Inspector dashboard The dashboard watching a demo game with a system that allocates on purpose.

Open http://localhost:5180 while your game runs and see the memory of the world, every archetype and chunk, what each system costs and allocates, which systems run in parallel, a timeline of the threads, and every entity with its live values. Findings tell you what to change, for example components with padding, archetypes that waste chunks or systems that allocate. It needs no build step, no Node and no internet, and costs the frame nothing while nobody looks.

using var session = new InspectorSession<float>(world, new[] { systems });
using var server = new InspectorServer(session);
server.Start();                                      // http://localhost:5180

session.Tick();                                      // once per frame, on the game thread

The Arch.Extended.Sample does exactly this. Read the Inspector documentation for everything it shows, the performance budgets for your tests, and the metrics for Prometheus and Grafana.

💾 Persistence

Arch.Persistence saves and loads worlds and single entities, as compact binary or as readable JSON.

var serializer = new ArchBinarySerializer();         // or new ArchJsonSerializer()

using (var file = File.Create("save.arch"))
{
    serializer.Serialize(file, world);               // also to byte[] or an IBufferWriter<byte>
}

using var stream = File.OpenRead("save.arch");
var loaded = serializer.Deserialize(stream);         // a new world, its entities are alive and keep their ids and versions
var bytes = serializer.Serialize(world, entity);     // a single entity ...
var copy = serializer.Deserialize(otherWorld, bytes);// ... which gets a new id in the world it is loaded into
Fast Components without references are written and read as the block of memory they are. A million entities with two components take about 50 ms to save and 80-120 ms to load.
No garbage when saving Saving to a Stream or an IBufferWriter<byte> allocates a few kilobytes, no matter how many entities the world has. Loading allocates the world itself and nothing beyond it. Components with references, for example strings, go through MessagePack one by one. JSON is meant for people and tools and allocates, it is several times slower and larger.
Safe to load Component types are saved by name, so a save loads in a new process no matter in which order the program used its components, and tells you which type is missing or changed its size. Use PersistenceOptions.ResolveType for renamed types. Damaged or cut off data throws a PersistenceException, it never crashes or exhausts memory.
Correct Entity ids, versions and the ids that are free again are restored, so World.IsAlive works, destroyed entities stay dead and handles you saved stay valid.
Yours to extend new ArchBinarySerializer(formatters) and new ArchJsonSerializer(formatters) take MessagePack and Utf8Json formatters for component types they can not handle. One serializer is safe to use from several threads.

[!WARNING] Version 3.0.0 changed the file format, files of older versions can not be read. Binary data starts with ARCH and a format version, so later versions can tell old data from new.

Is it suitable for networking?

For sending a state once: yes, with limits. A lobby that joins a running game, a reconnect, a replay start, or a spawn message for one entity work well, as long as both sides run the same build. It checks the sizes of components but does not translate between layouts: components without references are copied as memory, so a changed struct, or another runtime that lays structs out differently, must not meet old data. For replicating a game every tick: no. It always writes the whole world, has no deltas and no compression, and a single entity goes through boxing. Use a networking library with snapshots and deltas for that, and Arch.Persistence for the first full state and for save games. For data from strangers: only with care. Damaged data is detected, but names in the data decide which types are loaded and handed to MessagePack. Set PersistenceOptions.OnlyResolvedTypes and list the allowed types in ResolveType, and do not accept data you did not write without that.

Full code sample

With this package you are able to write and group queries and systems for Arch automatically. And all this with the best possible performance.

The tools can be used independently of each other.

// Components ( ignore the formatting, this saves space )
public struct Position{ float X, Y };
public struct Velocity{ float Dx, Dy };

// BaseSystem provides several useful methods for interacting and structuring systems
public class MovementSystem : BaseSystem<World, float>
{
    public MovementSystem(World world) : base(world) {}
    
    // Generates a query and calls that one automatically on BaseSystem.Update
    [Query]
    public void Move([Data] in float time, ref Position pos, ref Velocity vel)
    {
        pos.X += time * vel.X;
        pos.Y += time * vel.Y;
    }
    
    // Generates and filters a query and calls that one automatically on BaseSystem.Update in order
    [Query]
    [All<Player, Mob>, Any<Idle, Moving>, None<Alive>]  // Attributes also accept non generics :) 
    public void ResetVelocity(ref Velocity vel)
    {
        vel = new Velocity{ X = 0, Y = 0 };
    }
}

public class Game 
{
    public static void Main(string[] args) 
    {     
        var deltaTime = 0.05f; // This is mostly given by engines, frameworks
        
        // Create a world and a group of systems which will be controlled 
        var world = World.Create();
        var _systems = new Group<float>(
            "Systems",
            new MovementSystem(world),   // Run in order
            new MyOtherSystem(...),
            ...
        );
      
        _systems.Initialize();                  // Inits all registered systems
        _systems.BeforeUpdate(in deltaTime);    // Calls .BeforeUpdate on all systems ( can be overriden )
        _systems.Update(in deltaTime);          // Calls .Update on all systems ( can be overriden )
        _systems.AfterUpdate(in deltaTime);     // Calls .AfterUpdate on all System ( can be overriden )
        _systems.Dispose();                     // Calls .Dispose on all systems ( can be overriden )
    }
}

Systems in depth

Arch.System.SourceGenerator 2.2.0 needs Arch.System 1.2.0 or newer, since the generated code uses types of it.

Query phases and order

A generated system runs its queries automatically. Which phase they run in and in which order is up to you:

public partial class MovementSystem : BaseSystem<World, float>
{
    public MovementSystem(World world) : base(world) {}

    [Query(Phase = SystemPhase.BeforeUpdate)]       // Update is the default phase
    public void ResetForces(ref Force force) { ... }

    [Query(Order = 1)]                              // Lower orders run first, same orders run in declaration order
    public void Move([Data] in float time, ref Position pos, in Velocity vel) { ... }

    [Query(AutoRun = false)]                        // Only generated, call MoveOnceQuery(World, ...) yourself
    public void MoveOnce(ref Position pos) { ... }
}

If you override Update, BeforeUpdate or AfterUpdate yourself, the generator leaves it alone. The queries of the phase are still available through the generated RunQueries(SystemPhase.Update, in data). Derived systems with their own queries run together with the queries of their base systems.

A query is only run automatically if its [Data] parameters are of the type the system passes to its phases (T of BaseSystem<World, T>) and are passed by value or in. Otherwise the generator warns (ARCHSYS006) and you call the generated method yourself.

Diagnostics

Id Severity Meaning
ARCHSYS001 Error The type of a query method, or a type around it, is not partial.
ARCHSYS002 Error Unsupported parameter modifier, for example an out component or a ref Entity.
ARCHSYS003 Error A parallel query method is not static.
ARCHSYS004 Error A [Data] parameter of a parallel query is passed by reference, it is copied into the job.
ARCHSYS005 Error Two query methods would generate the same method.
ARCHSYS006 Warning A query is not run automatically, because its data does not match the system.
ARCHSYS007 Error A parameter is named world, which the generated method uses.
ARCHSYS008 Warning A query changes the structure of the world while it iterates, use a CommandBuffer parameter.

Structural changes in queries

Creating or destroying entities, or adding and removing components, while a query iterates is not safe. Add a CommandBuffer parameter to an instance query method of a system and record the changes into it:

[Query]
public void Kill(in Entity entity, in Health health, CommandBuffer buffer)
{
    if (health.Value <= 0)
        buffer.Destroy(in entity);                  // recorded now, applied right after the query
}

The generated code gives every system one buffer (CommandBuffer property) and plays it back after the query. In a ParallelGroup the playback of systems that run at the same time waits until nothing else runs: right before a system that runs alone and when the phase ends, always in the order the systems were added in (see below). Static query methods, and methods of classes that are no BaseSystem, receive the buffer like any other data, you pass it to the generated method yourself.

The generator also looks for direct structural calls in query methods and the methods they call in the same project (World.Destroy, entity.Add<T>(), anything Arch marks with [StructuralChange]). It warns with ARCHSYS008 and makes the system run alone in a ParallelGroup. Calls through delegates, virtual methods and other assemblies are not found.

Groups

var group = new Group<float>("Systems", new InputSystem(world), new MovementSystem(world), new RenderSystem(world));

// Ordering is resolved once, during Initialize. Without it systems run in the order they were added in.
group.Order<MovementSystem>().After<InputSystem>().Before<RenderSystem>();

[UpdateAfter(typeof(InputSystem))]                  // Or use attributes on the systems
public partial class MovementSystem : BaseSystem<World, float> { ... }

group.Initialize();                                  // Orders and initializes all systems, a cycle throws
group.Add(new LateSystem(world));                    // Systems added afterwards are ordered and initialized immediately

movementSystem.Enabled = false;                      // Disabled systems (and groups) skip their updates
group.Get<MovementSystem>();                         // Finds systems in nested groups as well

group.Observer = new MyProfiler();                   // ISystemObserver<T> is told how long each system took, null measures nothing
  • FixedStepGroup<T> runs its systems in fixed time steps, no matter how often it is updated. Alpha helps interpolating between steps.
  • CommandBufferSystem<T> plays back a CommandBuffer at the place it sits at in a group. Systems record structural changes into its Buffer while they iterate.
var playback = new CommandBufferSystem<float>(world);
var group = new Group<float>("Systems", new SpawnSystem(world, playback.Buffer), playback);

Running systems in parallel

A ParallelGroup<T> runs systems at the same time if they do not touch the same components. The generator tells it what a system touches: ref components are written, in and by-value components are read.

World.SharedJobScheduler = new JobScheduler();       // The scheduler of Arch, which parallel queries use as well

var group = new ParallelGroup<float>("Systems", new MovementSystem(world), new AiSystem(world), new CommandBufferSystem<float>(world));
Console.WriteLine(group.DescribePlan());             // Shows which system waits for which, group.GetSchedule() gives the same as data
  • Every system starts as soon as the earlier systems it conflicts with, or has to run after (Order, UpdateAfter), are done. It does not wait for the others, so a slow system only holds back the systems that depend on it. Systems that conflict keep the order they were added in, so the result is the same as running the group sequentially.
  • Systems that do not declare what they touch run alone, they wait for all earlier systems and all later systems wait for them: hand written Update overrides, queries without components, [Query(Parallel = true)] queries and queries with direct structural changes. Implement DescribeAccess yourself to declare them (access.Write<Position>()).
  • Query methods must only touch the components passed to them. Systems running at the same time must not create or destroy entities or add components, record this in the CommandBuffer parameter instead. The commands are applied at the next point where nothing else runs: right before a system that runs alone (for example a CommandBufferSystem) and when the phase ends, in the order the systems were added in. They are not applied after each group of systems that ran together. A system that runs alone applies its own commands after each query, as in a plain Group.
  • The systems run on the job scheduler of Arch (JobSchedulerExecutor) without allocating, the calling thread works on them while it waits. If every system waits for the one before it, they simply run one after another on the calling thread.
  • Use new ParallelGroup<float>(name, executor, systems) to choose how the systems run: new JobSchedulerExecutor(scheduler) for a scheduler of your own, ParallelForExecutor for the .NET thread pool without any setup, or your own IParallelExecutor.

Contributing

Build and test against the released Arch package, or against a local checkout of an upcoming Arch version:

dotnet test
dotnet test -p:ArchSource=local                                                  # Uses ../Arch/src/Arch/Arch.csproj
dotnet test -p:ArchSource=local -p:ArchLocalPath=/path/to/Arch/src/Arch/Arch.csproj

Every push and pull request is built with warnings as errors and tested in Debug and Release, including the tests of the inspector and its dashboard. The packages have their own versions. A release is made by starting the Release workflow by hand: choose the package, enter its version and the release notes, and choose whether to publish. It builds and tests everything first, packs the package, and pushes it to NuGet and GitHub Packages. It creates the GitHub release <package>-v<version>, except for alpha and beta versions.

Arch.Extended.Benchmarks contains BenchmarkDotNet benchmarks for the dispatch of groups and the generated queries: dotnet run -c Release --project Arch.Extended.Benchmarks.

Explorar proyectos relacionados

Cargando…