> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nanoforge.eu/llms.txt
> Use this file to discover all available pages before exploring further.

# ECS

> Store the game state as entities and components, and update it with systems

The ECS (entity component system) holds the state of your game. It comes from `@nanoforge-dev/ecs`, a registry written in C++ and compiled to WebAssembly.

* An **entity** is an id. It has no data of its own.
* A **component** is a data object attached to an entity: a position, a velocity, a health value.
* A **system** is a function called on every tick. It finds the entities that have some components and updates them.

## Register the library

Import `EcsLibrary` from the entry point of your side of the game:

```ts theme={null}
import { EcsLibrary } from "@nanoforge-dev/ecs/client";

// or "@nanoforge-dev/ecs/server"

const ecs = new EcsLibrary();
app.use(ecs);
await app.init(options);

const registry = ecs.registry; // also ctx.ecs.registry in systems
```

`ecs.registry` throws before `app.init` has resolved. The types `Registry`, `Entity`, `Component` and `System` come from the same entry point.

## Components

A component is an instance of a class with a `name` field equal to its class name:

```ts theme={null}
export class Position {
  name = this.constructor.name;

  constructor(
    public x: number,
    public y: number,
  ) {}
}
```

The registry files each component under its `name`. When you add a component it reads `name` on the instance; when you query, it reads `name` on the class you pass. The two must match.

> [!WARNING]
>
> Don't give a component class the name of another class in your game's bundle. When two classes
> share a name, the bundler renames one (`Position2`), and the results of `getZipper` are then keyed
> by that new name: destructuring `({Position})` gives `undefined`. Three.js and Konva export many
> classes (`Sphere`, `Plane`, `Box3`, `Text`, `Image`, `Line`...), so prefer names that are clearly
> yours, such as `Hitbox` or `PlayerSprite`.

An entity has at most one component of each type: adding a second `Position` replaces the first.

## Entities

```ts theme={null}
const enemy = registry.spawnEntity();
registry.addComponent(enemy, new Health(3));
registry.addComponent(enemy, new Poisoned());

const health = registry.getEntityComponent(enemy, Health); // the Health instance, or undefined
registry.removeComponent(enemy, Poisoned);
registry.killEntity(enemy);
```

`killEntity` removes every component of the entity.

## Systems

A system has the type `(registry, ctx) => void`. Add it with `registry.addSystem(system)`. Systems run on every tick, in the order you added them, unless the game is paused.

`registry.getZipper([A, B])` returns one object per entity that has every listed component, keyed by component name:

```ts theme={null}
export const move = (registry: Registry, ctx: Context) => {
  const seconds = ctx.app.delta / 1000;
  registry.getZipper([Position, Velocity]).forEach(({ Position, Velocity }) => {
    Position.x += Velocity.x * seconds;
    Position.y += Velocity.y * seconds;
  });
};
```

The objects in the result are your component instances: changing them changes the game state.

To know which entity a result belongs to, use `getIndexedZipper`. Each object also has an `id`, which `entityFromIndex` turns back into an entity:

```ts theme={null}
export const poison = (registry: Registry) => {
  registry.getIndexedZipper([Health, Poisoned]).forEach(({ id, Health }) => {
    Health.value -= 1;
    if (Health.value <= 0) registry.killEntity(registry.entityFromIndex(id));
  });
};
```

Other registry methods:

| Method | What it does |
| - | - |
| `removeSystem(index)` | Removes the system at that position in the list. |
| `clearSystems()` | Removes every system. |
| `clearEntities()` | Removes every entity and component. |
| `getComponents(Component)` | The sparse array of one component type, indexed by entity id. |
| `maxEntities()` | The number of entity ids used so far. |

To add and remove a group of entities and systems together, such as a level, use a scene: see [Scenes](https://docs.nanoforge.eu/docs/engine/scene/index.md).

## Errors

An error thrown in the C++ registry reaches JavaScript as a runtime error, with less detail than a JavaScript error. For example, `entityFromIndex` throws for an id that was never spawned or was killed: check your ids before calling it.

## Editor manifests

Projects generated by `nf new` export an `EDITOR_COMPONENT_MANIFEST` next to each component and an `EDITOR_SYSTEM_MANIFEST` next to each system. The NanoForge editor reads them to show and generate your components and systems. The types are `EditorComponentManifest` and `EditorSystemManifest`. To generate a new component or system with its manifest, see the CLI [component](https://docs.nanoforge.eu/docs/cli/schematics/component.md) and [system](https://docs.nanoforge.eu/docs/cli/schematics/system.md) schematics.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.