aiecsjs: Entity Component System
aiecsjs is a TypeScript-first archetype ECS (Entity Component System). Its core feature is the archetype table: entities with the same component combination are stored in the same contiguous arrays, and a query walks the TypedArrays with a plain for loop, which is cache friendly.
Install
Section titled “Install”npm install aiecsjsQuick Start
Section titled “Quick Start”import { createWorld, createEntity, addComponent, defineComponent, defineQuery, pipe, forEachEntityIndexed, Types,} from "aiecsjs";
// 1. Define components (SoA columns)const Position = defineComponent({ x: Types.f32, y: Types.f32 });const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });
// 2. Create a world and an entityconst world = createWorld();const eid = createEntity(world);addComponent(world, eid, Position, { x: 0, y: 0 });addComponent(world, eid, Velocity, { x: 1, y: 2 });
// 3. Define a query: every entity that has Position + Velocityconst movers = defineQuery([Position, Velocity]);
// 4. A system is a pure function, chained with pipeconst movement = (w: typeof world, dt: number) => { forEachEntityIndexed(w, movers, (e, i, pos, vel) => { // i is the safe column index; do not use e (entity id ≠ column index) pos.x[i] += vel.x[i] * dt; pos.y[i] += vel.y[i] * dt; }); return w;};
// Every framepipe(movement)(world, 1 / 60);Interactive Demo
Section titled “Interactive Demo”Bullets, particle clouds and RTS unit crowds, many entities of the same shape, are where SoA columns pay off. The demo below runs 2,000 entities with Position and Velocity through one pipe of three systems every frame: steer, move (wrapping around the edges) and draw, which writes the Position columns straight into a PixiJS ParticleContainer. The status line shows the entity count and the time the systems take per frame.
Demo source
/** * SwarmSimulation: a movement system over 2,000 entities with aiecsjs. * * Every entity has two SoA components, Position and Velocity: aiecsjs stores each field as one * TypedArray column, and a system walks those columns in a plain loop. Every frame one pipeline * of plain-function systems runs: * 1. steer: a slowly drifting flow field turns each velocity, so the swarm moves in bands; * 2. move: integrate the position and wrap it around the arena edges; * 3. draw: copy the Position columns straight into the matching PixiJS particles. * * The readout shows the live entity count and the average time the pipeline takes per frame. */import { Types, addComponent, createEntity, createWorld, defineComponent, defineQuery, destroyWorld, forEachEntityIndexed, getWorldSize, pipe, type World,} from 'aiecsjs';import { Container, Graphics, Particle, ParticleContainer, type Application } from 'pixi.js';import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };const ENTITY_COUNT = 2000;const TURN_RATE = 1.5; // how fast a velocity turns toward the flow field, per secondconst MAX_STEP_MS = 50; // clamp long frames (tab switches, hiccups) so entities do not jumpconst REPORT_EVERY_MS = 250;
// Components and queries are defined once per module: aiecsjs keeps them in a process-wide// registry, and a world allocates the columns when an entity first gets the component.const Position = defineComponent({ x: Types.f32, y: Types.f32 });const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });const movers = defineQuery([Position, Velocity]);const positioned = defineQuery([Position]);
/** What every system receives besides the world: the frame step and the elapsed time. */interface Tick { seconds: number; time: number;}
/** Direction of the flow field at (x, y), in radians. Two sine waves that drift over time. */function flowAngle(x: number, y: number, time: number): number { return Math.sin(x * 0.009 + time * 0.35) * Math.PI + Math.cos(y * 0.014 - time * 0.25);}
function wrap(value: number, size: number): number { return ((value % size) + size) % size;}
/** System 1: turn every velocity toward the flow field, keeping its speed. */function steer(world: World, { seconds, time }: Tick): World { const blend = Math.min(1, TURN_RATE * seconds); forEachEntityIndexed(world, movers, (_e, i, pos, vel) => { // `i` is the column index. `_e` is the packed EntityId and must never index a column. const speed = Math.hypot(vel.x[i], vel.y[i]); const heading = Math.atan2(vel.y[i], vel.x[i]); const delta = flowAngle(pos.x[i], pos.y[i], time) - heading; const next = heading + Math.atan2(Math.sin(delta), Math.cos(delta)) * blend; // shortest turn vel.x[i] = Math.cos(next) * speed; vel.y[i] = Math.sin(next) * speed; }); return world;}
/** System 2: integrate and wrap around the arena bounds. */function move(world: World, { seconds }: Tick): World { forEachEntityIndexed(world, movers, (_e, i, pos, vel) => { pos.x[i] = wrap(pos.x[i] + vel.x[i] * seconds, ARENA.width); pos.y[i] = wrap(pos.y[i] + vel.y[i] * seconds, ARENA.height); }); return world;}
function readColors(cssColor: DemoContext['cssColor']) { return { border: cssColor('--sl-color-gray-4'), swarm: cssColor('--sl-color-accent'), scout: cssColor('--sl-color-text'), };}
const READOUT = { 'zh-TW': (count: string, ms: string) => `entity:${count} 個|3 個 system 每幀共 ${ms} ms`, en: (count: string, ms: string) => `Entities: ${count} | 3 systems per frame: ${ms} ms`,};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle { const world = createWorld({ initialCapacity: ENTITY_COUNT + 1 }); // slot 0 is reserved for (let n = 0; n < ENTITY_COUNT; n++) { const eid = createEntity(world); const angle = Math.random() * Math.PI * 2; const speed = 30 + Math.random() * 60; // px per second addComponent(world, eid, Position, { x: Math.random() * ARENA.width, y: Math.random() * ARENA.height }); addComponent(world, eid, Velocity, { x: Math.cos(angle) * speed, y: Math.sin(angle) * speed }); }
// One small white dot, rendered to a texture once and shared by every particle (tinted). const dot = new Graphics().circle(0, 0, 2.5).fill(0xffffff); const texture = app.renderer.generateTexture({ target: dot, resolution: 2, antialias: true }); dot.destroy();
// Only `position` is uploaded every frame; tint and scale are static until update() is called. const layer = new ParticleContainer({ texture, dynamicProperties: { position: true } }); const border = new Graphics(); const arena = new Container(); arena.addChild(border, layer); app.stage.addChild(arena);
// particles[i] belongs to the entity in column slot i, so the draw system needs no lookup. const particles: Particle[] = []; forEachEntityIndexed(world, positioned, (_e, i) => { const scale = 0.6 + Math.random() * 0.6; particles[i] = new Particle({ texture, anchorX: 0.5, anchorY: 0.5, scaleX: scale, scaleY: scale, alpha: 0.85 }); layer.addParticle(particles[i]); });
/** System 3: copy the Position columns into the particles. */ const draw = (w: World): World => { forEachEntityIndexed(w, positioned, (_e, i, pos) => { const particle = particles[i]; particle.x = pos.x[i]; particle.y = pos.y[i]; }); return w; }; const systems = pipe<World, Tick>(steer, move, draw);
let colors = readColors(cssColor); const paint = () => { border.clear().rect(0, 0, ARENA.width, ARENA.height).stroke({ width: 1, color: colors.border, alpha: 0.6 }); particles.forEach((particle, i) => { particle.tint = i % 10 === 0 ? colors.scout : colors.swarm; }); layer.update(); // re-upload the static tint };
const fit = () => { const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height); arena.scale.set(scale); arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2); }; fit(); app.renderer.on('resize', fit);
const tick: Tick = { seconds: 0, time: 0 }; let systemMs = 0; let frames = 0; let sinceReport = 0; const frame = (seconds: number) => { tick.seconds = seconds; tick.time += seconds; const started = performance.now(); systems(world, tick); systemMs += performance.now() - started; frames++; }; const report = () => { const ms = frames > 0 ? systemMs / frames : 0; setStatus(READOUT[lang](getWorldSize(world).toLocaleString(lang), ms.toFixed(2))); systemMs = 0; frames = 0; };
paint(); frame(0); // the first frame is drawn even if the demo never plays (reduced motion) report();
return { update(deltaMS) { frame(Math.min(deltaMS, MAX_STEP_MS) / 1000); sinceReport += deltaMS; if (sinceReport >= REPORT_EVERY_MS) { sinceReport = 0; report(); } }, onThemeChange() { colors = readColors(cssColor); paint(); }, dispose() { app.renderer.off('resize', fit); destroyWorld(world); arena.destroy({ children: true }); texture.destroy(true); }, };}Core Concepts
Section titled “Core Concepts”World└── Archetype Table (one table per component combination) └── TypedArray columns (SoA: data of the same type stored contiguously) Entities reuse the generation bits of EntityId (ABA safe)defineComponent: defines an SoA component; field types useTypes.f32 / i32 / u32 / f64and so ondefineQuery: declares a query and returns a query object usable inforEachEntityIndexedpipe: chains several systems into one execution pipelineforEachEntityIndexed: the recommended column-walking API; the callback provides bothe(EntityId) andi(column index)
Subpath Exports
Section titled “Subpath Exports”| Subpath | Purpose |
|---|---|
aiecsjs |
Core API |
aiecsjs/loop |
createLoop() fixed-timestep loop |
aiecsjs/commands |
createCommandBuffer(), flush(), withCommandBuffer(), deferred structural changes |
aiecsjs/observers |
onAdd / onRemove / onSet / observe to observe component changes (enterQuery / exitQuery are in the core entry) |
aiecsjs/serialize |
toJSON / fromJSON, serializeWorld / deserializeWorld and the delta serialiser (snapshot format 2) |
aiecsjs/worker |
SAB snapshot transport, for passing data across Workers |
aiecsjs/relations |
defineRelation, ChildOf and helpers for entity relations such as addRelation |
Snapshot Format 2 and Stable Keys
Section titled “Snapshot Format 2 and Stable Keys”Since 0.6.0, toJSON / serializeWorld and delta capture write format 2: entity data plus a component table (key, kind, SoA columns). All loaders (fromJSON, deserializeWorld, delta apply(), adoptSnapshot, attachWorld) resolve components by stable key (by creation-order id when there is no key), and throw EcsError on a component that this process has not defined, or whose kind or columns do not match. Give every component you want to save a key:
import { defineComponent, defineTag, Types } from "aiecsjs";import { serializeWorld, deserializeWorld } from "aiecsjs/serialize";
const Position = defineComponent({ x: Types.f32, y: Types.f32 }, { key: "position" });const Player = defineTag({ key: "player" });
const bytes = serializeWorld(world);const restored = deserializeWorld(bytes); // or fromJSON(toJSON(world))- A key must be a non-empty string;
defineObjectComponent(factory, { key })works too. Defining the same key again with the same kind and column layout (HMR, an editor reloading scripts) returns the existing component, andEcsErroris thrown only when the layout differs. - 0.5.x snapshots are rejected by default. Load an old save once with
{ onUnknownVersion: "best-effort" }and save it again; pass{ onUnknownComponent: "skip" }when you are sure you want to drop the data of unknown components. Seedocs/MIGRATION.mdin the repo for the full steps. - Snapshots from outside should still be treated as untrusted input.
Errors and Validation
Section titled “Errors and Validation”- Misuse and invariant errors throw
EcsErrorbefore any mutation (the message starts withaiecsjs:, and the constructor supports{ cause }): non-integerinitialCapacity/maxEntities/indexBits/generationBits, a dead entity, an unregistered component, an invalid component key, and an observer handler,forEachEntity/withCommandBuffercallback,pipesystem or AoS factory that is not a function. An AoS factory that returnsnull/undefinedalso throws. addRelationthrowsEcsErrorwhen its source or target no longer exists; check withentityExistsfirst when an endpoint may be stale.- A read-only world obtained from
attachWorld(buffer, { readOnly: true })rejects all mutators, includingresetWorld. createLoopthrowsTypeErrorwhen options are missing oronUpdate/onRenderis not a function, andRangeErrorwhenfixed/maxSubStepsis invalid.
Common Pairings
Section titled “Common Pairings”- With
aipooljs: Pool manages PixiJS Sprite objects, ECS manages the data logic - With
aiquadtreejs: an entity’s AABB columns are inserted directly into the quadtree for broadphase collision queries - With
aifsmjs: an entity’s behaviour state (idle/walk/attack) is stored as an FSM snapshot component - With
aibridgejs: serialise the world snapshot withaiecsjs/serialize, then send it through the bridge to another context