ecsify
TypeScript icon, indicating that this package has built-in type declarations

0.0.11 • Public • Published

ecsify banner

GitHub License NPM bundle minzipped size NPM total downloads Join Discord

ecsify is a flexible, typesafe, and performance-focused Entity Component System (ECS) library for TypeScript.

  • 🔮 Simple, declarative API: Intuitive component patterns with full type safety
  • 🍃 Lightweight & Tree Shakable: Function-based and modular design
  • ⚡ High Performance: O(1) component checks using bitflags, cache-friendly sparse arrays
  • 🔍 Powerful Querying: Query entities with complex filters and get component data efficiently
  • 📦 Zero Dependencies: Standalone library ensuring ease of use in various environments
  • 🔧 Flexible Storage: Supports AoS, SoA, and marker component patterns
  • 🧵 Change Tracking: Built-in tracking for added, changed, and removed components

📚 Examples

🌟 Motivation

Build a modern, type-safe ECS library that fully leverages TypeScript's type system without compromising performance. While libraries like bitECS offer good speed, they often lack robust TypeScript support and more advanced queries like Added(), Removed(), or Changed(). ecsify bridges this gap - combining high performance, full TypeScript integration, and powerful query capabilities - all while adhering to the KISS principle for a clean, intuitive API.

⚖️ Alternatives

📖 Usage

ecsify offers two approaches: App for better developer experience, and Raw for maximum performance.

  • App: Better DX, type safety, unified API
  • Raw: Maximum performance, direct memory access
  • Both approaches can be mixed in the same codebase

App Approach (Recommended)

Better DX with plugins, systems, and unified API (slower than Raw because of added abstractions):

import { createApp, createDefaultPlugin, TPlugin, With } from 'ecsify';

// Create plugin with components and systems
type TCorePlugin = TPlugin<{
  name: 'Core';
  components: {
    Position: { x: number[]; y: number[] };
    Velocity: { dx: number[]; dy: number[] };
    Health: number[];
  };
}, []>;

function createCorePlugin(): TCorePlugin {
  return {
    name: 'Core',
    deps: [],
    components: {
      Position: { x: [], y: [] },
      Velocity: { dx: [], dy: [] },
      Health: []
    },
    setup(app: TApp<TAppContext<[TCorePlugin]>>) {
      // Initialize entities
      const entity = app.createEntity();
      app.addComponent(entity, app.c.Position, { x: 0, y: 0 });
      app.addComponent(entity, app.c.Velocity, { dx: 1, dy: 1 });
      
      // Register systems
      app.addSystem(movementSystem, { set: 'Update' });
    }
  };
}

function movementSystem(app: TApp<TAppContext<[TCorePlugin]>>) {
    for (const [eid, pos, vel] of app.queryComponents([Entity, app.c.Position, app.c.Velocity] as const)) {
      app.updateComponent(eid, app.c.Position, {
        x: pos.x + vel.dx,
        y: pos.y + vel.dy
      });
    }
}

// Create app with plugins
const app = createApp({
  plugins: [createDefaultPlugin(), createCorePlugin()] as const,
  systemSets: ['First', 'Update', 'Last'] // Execution order of systems
});

// Game loop
function gameLoop() {
  app.update(); // Runs all systems in order: First → Update → Last
  requestAnimationFrame(gameLoop);
}

Raw Approach (Performance Critical)

Direct ECS access for maximum performance:

import { 
  createEntityIndex, 
  createComponentRegistry, 
  createQueryRegistry,
  With, And
} from 'ecsify';

// Create core registries
const entityIndex = createEntityIndex();
const componentRegistry = createComponentRegistry();
const queryRegistry = createQueryRegistry(entityIndex, componentRegistry);

// Define components directly
const Position: { x: number[]; y: number[] } = { x: [], y: [] };
const Velocity: { dx: number[], dy: number[] } = { dx: [], dy: [] };
const Health: number[] = [];

// Create entities and add components
const entity = entityIndex.createEntity();
componentRegistry.addComponent(entity, Position);
Position.x[entity] = 0;
Position.y[entity] = 0;
componentRegistry.addComponent(entity, Velocity);
Velocity.dx[entity] = 1;
Velocity.dy[entity] = 1;

// Systems are just functions
function movementSystem() {
  for (const eid of queryRegistry.queryEntities(And(With(Position), With(Velocity)))) {
    Position.x[eid] += Velocity.dx[eid];
    Position.y[eid] += Velocity.dy[eid];
  }
}

// Manual game loop
function gameLoop() {
  movementSystem();
  componentRegistry.flush(); // Clear change tracking
  requestAnimationFrame(gameLoop);
}

Key Concepts

Entities are numerical IDs representing game objects:

const entity = app.createEntity(); // App approach
const entity = entityIndex.createEntity(); // Raw approach

Components are data containers following different patterns:

// Array of Structures (AoS) 
const Transform: { x: number; y: number }[] = [];

// Structure of Arrays (SoA)
const Position: { x: number[]; y: number[] } = { x: [], y: [] };

// Single arrays
const Health: number[] = [];

// Markers
const Player = {};

Systems are functions that query and process entities:

// App approach - registered systems
app.addSystem(movementSystem);

// Raw approach - manual execution
movementSystem();

Queries filter entities with powerful operators:

import { Added, Changed, Removed, With, Without, And, Or } from 'ecsify';

app.queryEntities(With(Player)); // Has component
app.queryEntities(Without(Dead)); // Lacks component
app.queryEntities(And(With(Position), With(Velocity))); // Has all components
app.queryEntities(Or(With(Player), With(Enemy))); // Has either component

// Reactive queries - track component lifecycle
app.queryEntities(Added(Player)); // Component added this frame
app.queryEntities(Removed(Velocity)); // Component removed this frame
app.queryEntities(Changed(Health)); // Component changed this frame

// Query entities with components
for (const [eid, pos, vel] of app.queryComponents([Entity, app.c.Position, app.c.Velocity] as const, With(Player))) {
  console.log(`Player ${eid} at (${pos.x}, ${pos.y})`);
}

// Query entities
for (const eid of app.queryEntities(With(Enemy))) {
    console.log(`Enemy ${eid} at (${Position.x[eid]}, ${Position.y[eid]})`);
}

// For reactive queries with direct updates, mark changes manually
Position.x[entity] = 110;
app.markComponentChanged(entity, Position); // Required for Changed() queries

Component Operations

// Add components
app.addComponent(entity, Position, { x: 100, y: 50 });
app.addComponent(entity, Health, 100);
app.addComponent(entity, Player); // Marker

// Update components  
app.updateComponent(entity, Position, { x: 110 }); // Partial updates (only possible for SoA)
app.updateComponent(entity, Health, 95);

// Direct updates
Position.x[entity] = 110;
app.markComponentChanged(entity, Position); // Required for Changed() queries
Health[entity] = 95;

// Remove components
app.removeComponent(entity, Velocity);

// Check components
if (app.hasComponent(entity, Player)) {
  // Entity is a player
}

Game Loop

function update(deltaTime: number) {
  // App approach
  app.update(); // Runs all registered systems
  
  // Raw approach  
  movementSystem();
  renderSystem();
  componentRegistry.flush(); // Clear change tracking
}

📐 Architecture

Entity Index (create-entity-index.ts)

Efficient entity ID management using sparse-dense array pattern with optional versioning. Provides O(1) operations while maintaining cache-friendly iteration.

Sparse-Dense Pattern

Sparse Array:  [_, 0, _, 2, 1, _, _]  ← Maps entity ID → dense index
                 1  2  3  4  5  6  7   ← Entity IDs

Dense Array:   [2, 5, 4, 7, 3]        ← Alive entities (cache-friendly)
               [0, 1, 2, 3, 4]        ← Indices
               └─alive─┘ └dead┘

aliveCount: 3  ← First 3 elements are alive

Core Data:

  • Sparse Array: Maps base entity IDs to dense array positions
  • Dense Array: Contiguous alive entities, with dead entities at end
  • Alive Count: Boundary between alive/dead entities

Entity ID Format

32-bit Entity ID = [Version Bits | Entity ID Bits]

Example with 8 version bits:
┌─ Version (8 bits) ─┐┌─── Entity ID (24 bits) ───┐
00000001              000000000000000000000001
│                     │
└─ Version 1          └─ Base Entity ID 1

Why This Design?

Problem: Stale References

const entity = addEntity(); // Returns ID 5
removeEntity(entity); // Removes ID 5
const newEntity = addEntity(); // Might reuse ID 5!
// Bug: old reference to ID 5 now points to wrong entity

Solution: Versioning

const entity = addEntity(); // Returns 5v0 (ID 5, version 0)
removeEntity(entity); // Increments to 5v1
const newEntity = addEntity(); // Reuses base ID 5 but as 5v1
// Safe: old reference (5v0) won't match new entity (5v1)

Swap-and-Pop for O(1) Removal

// Remove entity at index 1:
dense = [1, 2, 3, 4, 5];
// 1. Swap with last: [1, 5, 3, 4, 2]
// 2. Decrease alive count
// Result: [1, 5, 3, 4 | 2] - only alive section matters

Performance: O(1) all operations, ~8 bytes per entity, cache-friendly iteration.

Query Registry (create-query-registry.ts)

Entity filtering with two strategies: bitmask optimization for simple queries, individual evaluation for complex queries.

Query Filters

// Component filters
With(Position); // Entity must have component
Without(Dead); // Entity must not have component

// Change detection
Added(Position); // Component added this frame
Changed(Health); // Component modified this frame
Removed(Velocity); // Component removed this frame

// Logical operators
And(With(Position), With(Velocity)); // All must match
Or(With(Player), With(Enemy)); // Any must match

Evaluation Strategies

Bitmask Strategy - Fast bitwise operations:

// Components get bit positions
Position: bitflag=0b001, Velocity: bitflag=0b010, Health: bitflag=0b100

// Entity masks show what components each entity has
entity1: 0b011  // Has Position + Velocity
entity2: 0b101  // Has Position + Health

// Query: And(With(Position), With(Velocity)) → andMasks.with = 0b011
// Check: (entityMask & 0b011) === 0b011
entity1: (0b011 & 0b011) === 0b011   true
entity2: (0b101 & 0b011) === 0b011   false

Individual Strategy - Per-filter evaluation for complex queries:

// Complex queries like Or(With(Position), Changed(Health))
// Fall back to: filters.some(filter => filter.evaluate(app, eid))

Performance (10,000 entities)

  individual + cached - __tests__/query.bench.ts > Query Performance > With(Position)
    1.04x faster than bitmask + cached
    7.50x faster than bitmask + no cache
    7.83x faster than individual + no cache

  bitmask + cached - __tests__/query.bench.ts > Query Performance > And(With(Position), With(Velocity))
    1.01x faster than individual + cached
    13.58x faster than bitmask + no cache
    13.72x faster than individual + no cache

Key Insight: Caching matters most (7-14x faster than no cache). Bitmask vs individual evaluation shows minimal difference.

Component Registry (create-component-registry.ts)

Component management with direct array access, unlimited components via generations, and flexible storage patterns.

Component Patterns

// Array of Structures (AoS) - good for complete entity data
const Transform = [];
Transform[eid] = { x: 10, y: 20 };

// Structure of Arrays (SoA) - cache-friendly for bulk operations
const Position = { x: [], y: [] };
Position.x[eid] = 10;
Position.y[eid] = 20;

// Single arrays and marker components
const Health = []; // Health[eid] = 100
const Player = {}; // Just presence/absence

Generation System

Unlimited components beyond 31-bit limit:

Why Generations? Bitmasks need one bit per component for fast O(1) checks. JavaScript integers are 32-bit, giving us only 31 usable bits (0 - 30, bit 31 is sign). So we can only track 31 components per bitmask.

// Problem: Only 31 components fit in one integer bitmask
// Bits:  31 30 29 28 ... 3  2  1  0
// Components: ❌ ✓  ✓  ✓ ... ✓  ✓  ✓  ✓  (31 components max)

// Solution: Multiple generations, each with 31 components
// Generation 0: Components 0-30 (bitflags 1, 2, 4, ..., 2^30)
Position: { generationId: 0, bitflag: 0b001 }
Velocity: { generationId: 0, bitflag: 0b010 }

// Generation 1: Components 31+ (bitflags restart)
Armor:    { generationId: 1, bitflag: 0b001 }
Weapon:   { generationId: 1, bitflag: 0b010 }

// Entity masks stored per generation
_entityMasks[0][eid] = 0b011;  // Has Position + Velocity
_entityMasks[1][eid] = 0b001;  // Has Armor

Bitmask Operations

// Adding component: OR with bitflag
entityMask |= 0b010; // Add Velocity

// Removing component: AND with inverted bitflag
entityMask &= ~0b010; // Remove Velocity

// Checking component: AND with bitflag
const hasVelocity = (entityMask & 0b010) !== 0;

Change Tracking

// Separate masks track changes per frame
_addedMasks[0][eid] |= bitflag;    // Component added
_changedMasks[0][eid] |= bitflag;  // Component changed
_removedMasks[0][eid] |= bitflag;  // Component removed

// Clear at frame end
flush() { /* clear all change masks */ }

📚 Good to Know

Sparse vs Dense Arrays

JavaScript sparse arrays store only assigned indices, making them memory-efficient:

const sparse = [];
sparse[1000] = 5; // [<1000 empty items>, 5]

console.log(sparse.length); // 1001
console.log(sparse[500]); // undefined (no memory used)

In contrast, dense arrays allocate memory for every element, even if unused:

const dense = new Array(1001).fill(0); // Allocates 1001 × 4 bytes = ~4KB

console.log(dense.length); // 1001
console.log(dense[500]); // 0

Use sparse arrays for large, mostly empty datasets. Use dense arrays when you need consistent iteration and performance.

💡 Resources / References

Readme

Keywords

none

Package Sidebar

Install

npm i ecsify

Weekly Downloads

14

Version

0.0.11

License

MIT

Unpacked Size

116 kB

Total Files

73

Last publish

Collaborators

  • bennobuilder