@ste_tisci/ecs 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.prettierrc CHANGED
@@ -1,12 +1,12 @@
1
- {
2
- "singleQuote": true,
3
- "printWidth": 150,
4
- "proseWrap": "always",
5
- "tabWidth": 2,
6
- "useTabs": false,
7
- "trailingComma": "all",
8
- "bracketSpacing": true,
9
- "arrowParens": "avoid",
10
- "singleAttributePerLine": false,
11
- "semi": true
12
- }
1
+ {
2
+ "singleQuote": true,
3
+ "printWidth": 150,
4
+ "proseWrap": "always",
5
+ "tabWidth": 2,
6
+ "useTabs": false,
7
+ "trailingComma": "all",
8
+ "bracketSpacing": true,
9
+ "arrowParens": "avoid",
10
+ "singleAttributePerLine": false,
11
+ "semi": true
12
+ }
package/README.md CHANGED
@@ -1,84 +1,89 @@
1
- > [!IMPORTANT]
2
- > Work in progress.
3
-
4
- # ECS in TypeScript
5
-
6
- A minimalistic game engine with zero dependencies based on the **Entity Component System (ECS)** architecture implemented in **TypeScript**
7
-
8
- ## Features
9
-
10
- - **ECS architecture** with single responsability principles (SRP)
11
-
12
- - **SparSet** for ultra-fast entities lookup
13
-
14
- - **Structure of Arrays(SoA)** for optimized memory storage and access
15
-
16
- - **Bitmask** for efficient component queries
17
-
18
- ## Core Components
19
-
20
- - **EntityManager**: Manage creation, destruction and entity recycle. Uses a bitmask to track components of every entity.
21
-
22
- - **ComponentStore**: Generic store that maintains components data in SoA format to maximise cache locality.
23
-
24
- - **ECS**: Central Orchestator that coordinates entity and components, expose an API for queries and CRUD operations
25
-
26
- - **SparseSet**: Data structure that grants O(1) for insertion, removal and lookups of entities.
27
-
28
- ## Technologies
29
-
30
- - TypeScript for type safety
31
- - Data oriented architecture for optimal performance
32
- - Functional pattern without classes
33
-
34
- ```typescript
35
- import { ECS } from '@ste_tisci/ecs';
36
-
37
- // Define the type of the components
38
- const World = ECS<{
39
- Position: { x: number; y: number };
40
- Velocity: { x: number; y: number };
41
- Size: { width: number; height: number };
42
- Sprite: { src: HTMLImageElement };
43
- }>();
44
-
45
- // Define the structure of components that will be converted in SoA Arrays with the types previously defined
46
- // Position = { x: number[], y: number[] }
47
- // Size = { src: HTMLImageElement[] }
48
- // etc.
49
- World.defineComponents({
50
- Position: {},
51
- Size: {},
52
- Velocity: {},
53
- Sprite: {},
54
- });
55
-
56
- const ent = World.createEntity();
57
-
58
- World.addComponent(ent, 'Position', { x: 100, y: 20 });
59
- World.addComponent(ent, 'Velocity', { x: 2, y: 1 });
60
- World.addComponent(ent, 'Size', { width: 20, height: 20 });
61
-
62
- function movementSystem(World) {
63
- const { Position, Velocity } = World.components;
64
-
65
- for (const entity of World.query('Position', 'Velocity')) {
66
- const posID = entity.Position.id;
67
- const velID = entity.Velocity.id;
68
-
69
- Position.x[posID] += Velocity.x[velID];
70
- Position.y[posID] += Velocity.y[velID];
71
- }
72
- }
73
-
74
- function gameLoop() {
75
- movementSystem(World);
76
- requestAnimationFrame(gameLoop);
77
- }
78
-
79
- gameLoop();
80
- ```
81
-
82
- ## ⚖️ License
83
-
84
- MIT © 2025 SteTisci
1
+ > [!IMPORTANT]
2
+ > Work in progress.
3
+
4
+ # ECS in TypeScript
5
+
6
+ A minimalistic game engine with zero dependencies based on the **Entity Component System (ECS)** architecture implemented in **TypeScript**
7
+
8
+ ## Features
9
+
10
+ - **ECS architecture** with single responsability principles (SRP)
11
+
12
+ - **SparSet** for ultra-fast entities lookup
13
+
14
+ - **Structure of Arrays(SoA)** for optimized memory storage and access — numeric fields are backed by `Float32Array`, non-numeric fields by plain arrays
15
+
16
+ - **Bitmask** for efficient component queries
17
+
18
+ ## Core Components
19
+
20
+ - **EntityManager**: Manage creation, destruction and entity recycle. Uses a bitmask to track components of every entity.
21
+
22
+ - **ComponentStore**: Generic store that maintains component data in SoA format to maximise cache locality — numeric fields in a growable `Float32Array`, non-numeric fields (e.g. `HTMLImageElement`) in a plain array.
23
+
24
+ - **ECS**: Central Orchestator that coordinates entity and components, expose an API for queries and CRUD operations
25
+
26
+ - **SparseSet**: Data structure that grants O(1) for insertion, removal and lookups of entities.
27
+
28
+ ## Technologies
29
+
30
+ - TypeScript for type safety
31
+ - Data oriented architecture for optimal performance
32
+ - Functional pattern without classes
33
+
34
+ ```typescript
35
+ import { ECS } from '@ste_tisci/ecs';
36
+
37
+ // Define the type of the components
38
+ const World = ECS<{
39
+ Position: { x: number; y: number };
40
+ Velocity: { x: number; y: number };
41
+ Size: { width: number; height: number };
42
+ Sprite: { src: HTMLImageElement };
43
+ }>();
44
+
45
+ // Define the structure of components that will be converted to SoA storage.
46
+ // Numeric fields become Float32Array, everything else stays a plain array.
47
+ // Position = { x: Float32Array, y: Float32Array }
48
+ // Sprite = { src: HTMLImageElement[] }
49
+ // etc.
50
+ World.defineComponents('Position', 'Velocity', 'Size', 'Sprite');
51
+
52
+ const ent = World.createEntity();
53
+
54
+ World.addComponent(ent, 'Position', { x: 100, y: 20 });
55
+ World.addComponent(ent, 'Velocity', { x: 2, y: 1 });
56
+ World.addComponent(ent, 'Size', { width: 20, height: 20 });
57
+
58
+ function movementSystem(World) {
59
+ const { Position, Velocity } = World.components;
60
+
61
+ for (const entity of World.query('Position', 'Velocity')) {
62
+ const posID = entity.Position.id;
63
+ const velID = entity.Velocity.id;
64
+
65
+ Position.x[posID] += Velocity.x[velID];
66
+ Position.y[posID] += Velocity.y[velID];
67
+ }
68
+ }
69
+
70
+ function gameLoop() {
71
+ movementSystem(World);
72
+ requestAnimationFrame(gameLoop);
73
+ }
74
+
75
+ gameLoop();
76
+ ```
77
+
78
+ ## Error Handling
79
+
80
+ Every operation validates its inputs and throws a descriptive `Error` instead of failing silently or corrupting state:
81
+
82
+ - `addComponent` / `removeComponent` / `destroyEntity` throw if the entity does not exist
83
+ - `addComponent` throws if the entity already has the component; `removeComponent` throws if it doesn't
84
+ - `query`, `addComponent` and `removeComponent` throw if the component name was never registered via `defineComponents`
85
+ - `defineComponents` throws if a component name is already defined
86
+
87
+ ## ⚖️ License
88
+
89
+ MIT © 2025 SteTisci
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "@ste_tisci/ecs",
3
- "version": "0.1.5",
4
- "description": "A minimalistic game engine with zero dependencies based on the Entity Component System (ECS) architecture implemented in TypeScript",
5
- "main": "./dist/index.cjs",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "scripts": {
9
- "build": "tsup"
10
- },
11
- "keywords": [],
12
- "author": "",
13
- "license": "MIT",
14
- "repository": {
15
- "type": "git",
16
- "url": "https://github.com/SteTisci/ecs"
17
- },
18
- "type": "module",
19
- "devDependencies": {
20
- "tsup": "^8.5.1",
21
- "typescript": "^5.9.3"
22
- }
23
- }
1
+ {
2
+ "name": "@ste_tisci/ecs",
3
+ "version": "0.1.6",
4
+ "description": "A minimalistic game engine with zero dependencies based on the Entity Component System (ECS) architecture implemented in TypeScript",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsup"
10
+ },
11
+ "keywords": [],
12
+ "author": "",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/SteTisci/ecs"
17
+ },
18
+ "type": "module",
19
+ "devDependencies": {
20
+ "tsup": "^8.5.1",
21
+ "typescript": "^5.9.3"
22
+ }
23
+ }
@@ -0,0 +1,96 @@
1
+ import type { IComponentStore } from './types/IComponentStore.js';
2
+ import type { ComponentDataArrays } from './types/index.js';
3
+ import { SparseSet } from './utils/SparseSet.js';
4
+
5
+ const INITIAL_CAPACITY = 8;
6
+
7
+ // Float32Array has a fixed length, so numeric fields grow by doubling capacity
8
+ // (like a dynamic array reallocation) instead of relying on push/pop.
9
+ function grow(buffer: Float32Array, requiredIndex: number): Float32Array {
10
+ let capacity = buffer.length;
11
+ while (capacity <= requiredIndex) capacity *= 2;
12
+
13
+ const grown = new Float32Array(capacity);
14
+ grown.set(buffer);
15
+ return grown;
16
+ }
17
+
18
+ // Internally every field is either a Float32Array (numeric) or a plain array (anything else).
19
+ // The precise, per-field ComponentDataArrays<T> type is only applied at the public getData() boundary.
20
+ type FieldStore = Float32Array | unknown[];
21
+
22
+ export function ComponentStore<T extends Record<string, any>>(): IComponentStore<T> {
23
+ const componentSet = SparseSet();
24
+ const componentData: Record<string, FieldStore> = {};
25
+
26
+ // Tracks which fields are numeric (Float32Array-backed) vs plain arrays, keyed by field name
27
+ const isNumeric: Record<string, boolean> = {};
28
+
29
+ function add(eid: number, data: T): void {
30
+ if (componentSet.has(eid)) throw new Error(`Entity ${eid} already has this component`);
31
+
32
+ // Use the current size (next index) to maintain data coherence with the dense array
33
+ const ID = componentSet.getSize();
34
+
35
+ componentSet.add(eid);
36
+
37
+ // Store each property of the component into its corresponding array
38
+ for (const key in data) {
39
+ const value = data[key];
40
+
41
+ if (!(key in componentData)) {
42
+ isNumeric[key] = typeof value === 'number';
43
+ componentData[key] = isNumeric[key] ? new Float32Array(INITIAL_CAPACITY) : [];
44
+ }
45
+
46
+ if (isNumeric[key] && ID >= componentData[key].length) {
47
+ componentData[key] = grow(componentData[key] as Float32Array, ID);
48
+ }
49
+
50
+ (componentData[key] as unknown[])[ID] = value;
51
+ }
52
+ }
53
+
54
+ function remove(eid: number): void {
55
+ if (!componentSet.has(eid)) throw new Error(`Entity ${eid} does not have this component`);
56
+
57
+ const ID = componentSet.getIndex(eid);
58
+ const lastID = componentSet.getSize() - 1;
59
+
60
+ // Swap the component data only if is not the last one inserted
61
+ if (ID !== lastID) {
62
+ for (const key of Object.keys(componentData)) {
63
+ (componentData[key] as unknown[])[ID] = componentData[key][lastID];
64
+ }
65
+ }
66
+
67
+ componentSet.remove(eid);
68
+
69
+ // Plain arrays are trimmed to release references and stay in sync with the dense array.
70
+ // Float32Array slots beyond the current size are simply unused (unreachable via query/getIndex),
71
+ // so there's nothing to release and the capacity is kept as-is.
72
+ for (const key in componentData) {
73
+ if (!isNumeric[key]) {
74
+ (componentData[key] as unknown[]).pop();
75
+ }
76
+ }
77
+ }
78
+
79
+ function getDense(): number[] {
80
+ return componentSet.getDense();
81
+ }
82
+
83
+ function getData(): ComponentDataArrays<T> {
84
+ return componentData as ComponentDataArrays<T>;
85
+ }
86
+
87
+ function getIndex(eid: number): number {
88
+ return componentSet.getIndex(eid);
89
+ }
90
+
91
+ function getSize(): number {
92
+ return componentSet.getSize();
93
+ }
94
+
95
+ return { add, remove, getIndex, getDense, getData, getSize };
96
+ }
package/src/Ecs.ts ADDED
@@ -0,0 +1,98 @@
1
+ import type { QueryResult, StoreDataMap, StoreMap } from './types/index.js';
2
+ import type { IECS } from './types/IEcs.js';
3
+ import { ComponentStore } from './ComponentStore.js';
4
+ import { EntityManager } from './EntityManager.js';
5
+ import { createComponentRegistry } from './utils/ComponentRegistry.js';
6
+
7
+ export function ECS<T extends Record<string, Record<string, any>>>(): IECS<T> {
8
+ const ComponentRegistry = createComponentRegistry<keyof T & string>();
9
+ const Entities = EntityManager(ComponentRegistry);
10
+ const internalStores = {} as StoreMap<T>;
11
+ const components = {} as StoreDataMap<T>;
12
+
13
+ // Initialize the structure of the components used
14
+ function defineComponents<K extends readonly (keyof T)[]>(...names: K): void {
15
+ for (const name of names) {
16
+ if (name in internalStores) throw new Error(`Component ${String(name)} is already defined`);
17
+
18
+ ComponentRegistry.register(name as string);
19
+ internalStores[name] = ComponentStore<T[typeof name]>();
20
+ components[name] = internalStores[name].getData();
21
+ }
22
+ }
23
+
24
+ function createEntity(): number {
25
+ return Entities.create();
26
+ }
27
+
28
+ function destroyEntity(eid: number): void {
29
+ const entityMask = Entities.getMask(eid);
30
+
31
+ let cid = 0;
32
+ let tempMask = entityMask;
33
+
34
+ // Bit operation on the entity mask to track the corresponding components and remove them
35
+ while (tempMask !== 0n) {
36
+ if ((tempMask & 1n) !== 0n) {
37
+ const name = ComponentRegistry.getName(cid);
38
+ internalStores[name].remove(eid);
39
+ }
40
+
41
+ tempMask >>= 1n;
42
+ cid++;
43
+ }
44
+
45
+ Entities.remove(eid);
46
+ }
47
+
48
+ function addComponent<K extends keyof T>(eid: number, name: K, data: T[K]): void {
49
+ Entities.addComponent(eid, name as keyof T & string);
50
+ internalStores[name].add(eid, data);
51
+ }
52
+
53
+ function removeComponent<K extends keyof T>(eid: number, name: K): void {
54
+ Entities.removeComponent(eid, name as keyof T & string);
55
+ internalStores[name].remove(eid);
56
+ }
57
+
58
+ // Generator function to retrive the indexes of the entity components searched
59
+ function* query<C extends (keyof T)[]>(...componentName: C): Generator<QueryResult<C>> {
60
+ if (componentName.length === 0) return;
61
+
62
+ // Validate that every requested component is registered before touching internalStores,
63
+ // so an unknown name throws a clear error instead of a raw "undefined" access below.
64
+ let targetMask = 0n;
65
+ for (const name of componentName) {
66
+ targetMask |= 1n << BigInt(ComponentRegistry.getID(name as keyof T & string));
67
+ }
68
+
69
+ let smallestStore = internalStores[componentName[0]];
70
+ let smallestSize = smallestStore.getSize();
71
+
72
+ for (let i = 1; i < componentName.length; i++) {
73
+ const store = internalStores[componentName[i]];
74
+ const size = store.getSize();
75
+
76
+ if (size < smallestSize) {
77
+ smallestStore = store;
78
+ smallestSize = size;
79
+ }
80
+ }
81
+
82
+ for (const eid of smallestStore.getDense()) {
83
+ if ((Entities.getMask(eid) & targetMask) !== targetMask) continue;
84
+
85
+ const result = {} as any;
86
+
87
+ for (const name of componentName) {
88
+ const id = internalStores[name].getIndex(eid);
89
+
90
+ result[name] = { id };
91
+ }
92
+
93
+ yield result as QueryResult<C>;
94
+ }
95
+ }
96
+
97
+ return { defineComponents, createEntity, destroyEntity, addComponent, removeComponent, query, components };
98
+ }
@@ -0,0 +1,60 @@
1
+ import type { IComponentRegistry } from './types/IComponentRegistry.js';
2
+ import type { IEntityManager } from './types/IEntityManager.js';
3
+
4
+ export function EntityManager<K extends string>(registry: IComponentRegistry<K>): IEntityManager<K> {
5
+ let nextID: number = 0;
6
+ const recycledIDs: number[] = [];
7
+ const bitMasks: bigint[] = [];
8
+
9
+ function exists(eid: number): boolean {
10
+ const isWithinBounds = eid >= 0 && eid < nextID;
11
+ const hasMask = bitMasks[eid] !== undefined;
12
+
13
+ return isWithinBounds && hasMask;
14
+ }
15
+
16
+ function hasComponent(eid: number, name: K): boolean {
17
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
18
+
19
+ const cid = registry.getID(name);
20
+ return (bitMasks[eid] & (1n << BigInt(cid))) !== 0n;
21
+ }
22
+
23
+ function create(): number {
24
+ const ID = recycledIDs.length > 0 ? recycledIDs.pop()! : nextID++;
25
+ bitMasks[ID] = 0n;
26
+
27
+ return ID;
28
+ }
29
+
30
+ function remove(eid: number): void {
31
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
32
+
33
+ bitMasks[eid] = undefined as any;
34
+ recycledIDs.push(eid);
35
+ }
36
+
37
+ function addComponent(eid: number, name: K): void {
38
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
39
+ if (hasComponent(eid, name)) throw new Error(`Entity ${eid} already has component ${name}`);
40
+
41
+ const cid = registry.getID(name);
42
+ bitMasks[eid] |= 1n << BigInt(cid);
43
+ }
44
+
45
+ function removeComponent(eid: number, name: K): void {
46
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
47
+ if (!hasComponent(eid, name)) throw new Error(`Entity ${eid} does not have component ${name}`);
48
+
49
+ const cid = registry.getID(name);
50
+ bitMasks[eid] &= ~(1n << BigInt(cid));
51
+ }
52
+
53
+ function getMask(eid: number): bigint {
54
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
55
+
56
+ return bitMasks[eid];
57
+ }
58
+
59
+ return { exists, hasComponent, create, remove, addComponent, removeComponent, getMask };
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { ECS } from './Ecs.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Interface for managing component registration and ID mapping.
3
+ * Provides a centralized registry that maps component names to unique IDs
4
+ * and vice versa, used for efficient bitmask operations in the ECS.
5
+ */
6
+ export interface IComponentRegistry<K extends string> {
7
+ /**
8
+ * Registers a new component by name.
9
+ * Assigns a unique incremental ID to the component if not already registered.
10
+ * @param name - The name of the component to register
11
+ */
12
+ register: (name: K) => void;
13
+
14
+ /**
15
+ * Retrieves the unique ID associated with a component name.
16
+ * @param name - The name of the component
17
+ * @returns The unique ID assigned to the component
18
+ * @throws Error if the component is not registered
19
+ */
20
+ getID: (name: K) => number;
21
+
22
+ /**
23
+ * Retrieves the component name associated with a given ID.
24
+ * @param cid - The unique ID of the component
25
+ * @returns The name of the component
26
+ * @throws Error if the ID is not registered
27
+ */
28
+ getName: (cid: number) => K;
29
+ }
@@ -0,0 +1,53 @@
1
+ import type { ComponentDataArrays } from './index.js';
2
+
3
+ /**
4
+ * Interface for storing and managing component data using Structure of Arrays (SoA) pattern.
5
+ * Each component type has its own store that maintains entity-component associations
6
+ * and stores component data in separate arrays per property for cache efficiency.
7
+ * @template T - The component data type (object with properties)
8
+ */
9
+ export interface IComponentStore<T> {
10
+ /**
11
+ * Adds a component to an entity with the provided data.
12
+ * Stores each property of the component in separate arrays for efficient iteration.
13
+ * @param eid - The entity ID to add the component to
14
+ * @param data - The component data to store
15
+ * @throws Error if the entity already has this component
16
+ */
17
+ add: (eid: number, data: T) => void;
18
+
19
+ /**
20
+ * Removes a component from an entity.
21
+ * Uses swap-and-pop technique to maintain dense arrays.
22
+ * @param eid - The entity ID to remove the component from
23
+ * @throws Error if the entity doesn't have this component
24
+ */
25
+ remove: (eid: number) => void;
26
+
27
+ /**
28
+ * Gets the index of an entity's component data in the dense arrays.
29
+ * @param eid - The entity ID
30
+ * @returns The index in the data arrays where this entity's component data is stored
31
+ */
32
+ getIndex: (eid: number) => number;
33
+
34
+ /**
35
+ * Returns the dense array of entity IDs that have this component.
36
+ * Useful for efficient iteration over all entities with this component.
37
+ * @returns Array of entity IDs
38
+ */
39
+ getDense: () => number[];
40
+
41
+ /**
42
+ * Returns the component data arrays organized by property.
43
+ * Each property of the component type has its own array.
44
+ * @returns Object mapping property names to their value arrays
45
+ */
46
+ getData: () => ComponentDataArrays<T>;
47
+
48
+ /**
49
+ * Returns the number of entities that have this component.
50
+ * @returns The count of entities with this component
51
+ */
52
+ getSize: () => number;
53
+ }