@ste_tisci/ecs 0.1.0 → 0.1.2

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.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Interface used for fast entity lookups, insertion and removal.
3
+ *
4
+ * Maintain two parallel arrays:
5
+ *
6
+ * - sparse: a direct lookup table that maps an entity ID (eid) to its index in the dense array.
7
+ * - dense: a compact array that stores all active entity IDs contiguously.
8
+ */
9
+ export interface ISparseSet {
10
+ /**
11
+ * Check if an entity ID exists in the set
12
+ * @param eid The entity ID to check
13
+ * @returns True if the entity ID exists, false otherwise
14
+ */
15
+ has: (eid: number) => boolean;
16
+
17
+ /**
18
+ * Add the entity ID to the set
19
+ * @param eid The entity ID to add
20
+ * @thows Error if the entity ID is already been added
21
+ */
22
+ add: (eid: number) => void;
23
+
24
+ /**
25
+ * Remove an Entity ID from the set
26
+ * @param eid The entity ID to remove
27
+ * @throws Error if the ID does not exists in the set
28
+ */
29
+ remove: (eid: number) => void;
30
+
31
+ /**
32
+ * Retrive the index of the entity ID in the set
33
+ * @param eid The entity ID
34
+ * @returns The index corresponding to an entity ID in the set
35
+ */
36
+ getIndex: (eid: number) => number;
37
+
38
+ /**
39
+ * Retrive the full dense array that contain all the entity IDs of the set
40
+ * @returns an Array with all the current entity IDs
41
+ */
42
+ getDense: () => number[];
43
+
44
+ /**
45
+ * Retrive the size representing the number of active entities in the set.
46
+ * @returns The current size of the Dense array
47
+ */
48
+ getSize: () => number;
49
+ }
@@ -0,0 +1,42 @@
1
+ import type { IComponentStore } from './IComponentStore.js';
2
+
3
+ /**
4
+ * Represents component data in Structure of Arrays (SoA) format.
5
+ * Each property of the component is stored in a separate array,
6
+ * enabling cache-efficient iteration and SIMD operations.
7
+ * @template T - The component data type
8
+ * @example
9
+ * // For Position component: { x: number, y: number }
10
+ * // ComponentDataArrays would be: { x: number[], y: number[] }
11
+ */
12
+ export type ComponentDataArrays<T> = {
13
+ [K in keyof T]: T[K][];
14
+ };
15
+
16
+ /**
17
+ * Maps component names to their corresponding ComponentStore instances.
18
+ * Used internally by CreateWorld to manage all component stores.
19
+ * @template T - Record type defining all component types
20
+ */
21
+ export type StoreMap<T> = {
22
+ [K in keyof T]: IComponentStore<T[K]>;
23
+ };
24
+
25
+ /**
26
+ * Maps component names to their data arrays for direct access.
27
+ * Used to expose component data to the user without store methods.
28
+ * @template T - Record type defining all component types
29
+ */
30
+ export type StoreDataMap<T> = {
31
+ [K in keyof T]: ComponentDataArrays<T[K]>;
32
+ };
33
+
34
+ /**
35
+ * Type helper for the query result.
36
+ * Creates an object with eid and all required components typed correctly.
37
+ * @template T - Record type with all component types.
38
+ * @template C - Array of the component names requested in the query.
39
+ */
40
+ export type QueryResult<T, C extends (keyof T)[]> = {
41
+ [K in C[number]]: { id: number };
42
+ };
@@ -0,0 +1,32 @@
1
+ import type { IComponentRegistry } from '../types/IComponentRegistry.js';
2
+
3
+ export function createComponentRegistry<K extends string>(): IComponentRegistry<K> {
4
+ const nameToID = new Map<K, number>();
5
+ const IDtoName = new Map<number, K>();
6
+ let nextID: number = 0;
7
+
8
+ function register(name: K): void {
9
+ if (!nameToID.has(name)) {
10
+ const eid = nextID++;
11
+
12
+ nameToID.set(name, eid);
13
+ IDtoName.set(eid, name);
14
+ }
15
+ }
16
+
17
+ function getID(name: K): number {
18
+ const eid = nameToID.get(name);
19
+ if (eid === undefined) throw new Error(`Component ${name} not registered`);
20
+
21
+ return eid;
22
+ }
23
+
24
+ function getName(cid: number): K {
25
+ const name = IDtoName.get(cid);
26
+ if (!name) throw new Error(`Component ID ${cid} not registered`);
27
+
28
+ return name;
29
+ }
30
+
31
+ return { register, getID, getName };
32
+ }
@@ -0,0 +1,54 @@
1
+ import type { ISparseSet } from '../types/ISparseSet.js';
2
+
3
+ export function SparseSet(): ISparseSet {
4
+ const sparse: number[] = [];
5
+ const dense: number[] = [];
6
+ let size = 0;
7
+
8
+ function has(eid: number): boolean {
9
+ const ID = getIndex(eid);
10
+
11
+ const exist = ID !== undefined && dense[ID] === eid;
12
+ const isWhitinBounds = ID >= 0 && ID < size;
13
+
14
+ return exist && isWhitinBounds;
15
+ }
16
+
17
+ function add(eid: number): void {
18
+ if (has(eid)) throw new Error(`ID ${eid} already present in the set`);
19
+
20
+ sparse[eid] = size;
21
+ dense[size] = eid;
22
+ size++;
23
+ }
24
+
25
+ function remove(eid: number): void {
26
+ if (!has(eid)) throw new Error(`Cannot remove ID ${eid} because does not exists`);
27
+
28
+ const ID = getIndex(eid);
29
+ const last = dense[size - 1];
30
+
31
+ // Swap with the last element inserted
32
+ dense[ID] = last;
33
+ sparse[last] = ID;
34
+
35
+ // Remove the element
36
+ dense.pop();
37
+ size--;
38
+ delete sparse[eid];
39
+ }
40
+
41
+ function getIndex(eid: number): number {
42
+ return sparse[eid];
43
+ }
44
+
45
+ function getDense(): number[] {
46
+ return dense;
47
+ }
48
+
49
+ function getSize(): number {
50
+ return size;
51
+ }
52
+
53
+ return { has, add, remove, getIndex, getDense, getSize };
54
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2024",
4
+ "allowSyntheticDefaultImports": true,
5
+ "esModuleInterop": true,
6
+ "outDir": "dist",
7
+ "forceConsistentCasingInFileNames": true,
8
+ "resolveJsonModule": true,
9
+ "strict": true,
10
+ "sourceMap": true,
11
+ "rootDir": "src",
12
+ "moduleResolution": "nodenext",
13
+ "module": "node20"
14
+ },
15
+ "exclude": ["node_modules/"],
16
+ "include": ["src"]
17
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ format: ['cjs', 'esm'],
5
+ entry: ['./src/index.ts'],
6
+ dts: true,
7
+ shims: true,
8
+ skipNodeModulesBundle: true,
9
+ clean: true,
10
+ });
package/dist/index.cjs DELETED
@@ -1,247 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- ECS: () => ECS
24
- });
25
- module.exports = __toCommonJS(index_exports);
26
-
27
- // src/utils/SparseSet.ts
28
- function SparseSet() {
29
- const sparse = [];
30
- const dense = [];
31
- let size = 0;
32
- function has(eid) {
33
- const ID = getIndex(eid);
34
- const exist = ID !== void 0 && dense[ID] === eid;
35
- const isWhitinBounds = ID >= 0 && ID < size;
36
- return exist && isWhitinBounds;
37
- }
38
- function add(eid) {
39
- if (has(eid)) throw new Error(`ID ${eid} already present in the set`);
40
- sparse[eid] = size;
41
- dense[size] = eid;
42
- size++;
43
- }
44
- function remove(eid) {
45
- if (!has(eid)) throw new Error(`Cannot remove ID ${eid} because does not exists`);
46
- const ID = getIndex(eid);
47
- const last = dense[size - 1];
48
- dense[ID] = last;
49
- sparse[last] = ID;
50
- dense.pop();
51
- size--;
52
- delete sparse[eid];
53
- }
54
- function getIndex(eid) {
55
- return sparse[eid];
56
- }
57
- function getDense() {
58
- return dense;
59
- }
60
- function getSize() {
61
- return size;
62
- }
63
- return { has, add, remove, getIndex, getDense, getSize };
64
- }
65
-
66
- // src/ComponentStore.ts
67
- function ComponentStore() {
68
- const componentSet = SparseSet();
69
- const componentData = {};
70
- function add(eid, data) {
71
- if (componentSet.has(eid)) throw new Error(`Entity ${eid} already has this component`);
72
- const ID = componentSet.getSize();
73
- componentSet.add(eid);
74
- for (const key in data) {
75
- if (!componentData[key]) {
76
- componentData[key] = [];
77
- }
78
- componentData[key][ID] = data[key];
79
- }
80
- }
81
- function remove(eid) {
82
- if (!componentSet.has(eid)) throw new Error(`Entity ${eid} does not have this component`);
83
- const ID = componentSet.getIndex(eid);
84
- const lastID = componentSet.getSize() - 1;
85
- if (ID !== lastID) {
86
- for (const key of Object.keys(componentData)) {
87
- componentData[key][ID] = componentData[key][lastID];
88
- }
89
- }
90
- componentSet.remove(eid);
91
- for (const key in componentData) {
92
- componentData[key].pop();
93
- }
94
- }
95
- function getDense() {
96
- return componentSet.getDense();
97
- }
98
- function getData() {
99
- return componentData;
100
- }
101
- function getIndex(eid) {
102
- return componentSet.getIndex(eid);
103
- }
104
- function getSize() {
105
- return componentSet.getSize();
106
- }
107
- return { add, remove, getIndex, getDense, getData, getSize };
108
- }
109
-
110
- // src/EntityManager.ts
111
- function EntityManager(registry) {
112
- let nextID = 0;
113
- const recycledIDs = [];
114
- const bitMasks = [];
115
- function exists(eid) {
116
- const isWithinBounds = eid >= 0 && eid < nextID;
117
- const hasMask = bitMasks[eid] !== void 0;
118
- return isWithinBounds && hasMask;
119
- }
120
- function hasComponent(eid, name) {
121
- if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
122
- const cid = registry.getID(name);
123
- return (bitMasks[eid] & 1n << BigInt(cid)) !== 0n;
124
- }
125
- function create() {
126
- const ID = recycledIDs.length > 0 ? recycledIDs.pop() : nextID++;
127
- bitMasks[ID] = 0n;
128
- return ID;
129
- }
130
- function remove(eid) {
131
- if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
132
- bitMasks[eid] = void 0;
133
- recycledIDs.push(eid);
134
- }
135
- function addComponent(eid, name) {
136
- if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
137
- if (hasComponent(eid, name)) throw new Error(`Entity ${eid} already has component ${name}`);
138
- const cid = registry.getID(name);
139
- bitMasks[eid] |= 1n << BigInt(cid);
140
- }
141
- function removeComponent(eid, name) {
142
- if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
143
- if (!hasComponent(eid, name)) throw new Error(`Entity ${eid} does not have component ${name}`);
144
- const cid = registry.getID(name);
145
- bitMasks[eid] &= ~(1n << BigInt(cid));
146
- }
147
- function getMask(eid) {
148
- return bitMasks[eid];
149
- }
150
- return { exists, hasComponent, create, remove, addComponent, removeComponent, getMask };
151
- }
152
-
153
- // src/utils/ComponentRegistry.ts
154
- function createComponentRegistry() {
155
- const nameToID = /* @__PURE__ */ new Map();
156
- const IDtoName = /* @__PURE__ */ new Map();
157
- let nextID = 0;
158
- function register(name) {
159
- if (!nameToID.has(name)) {
160
- const eid = nextID++;
161
- nameToID.set(name, eid);
162
- IDtoName.set(eid, name);
163
- }
164
- }
165
- function getID(name) {
166
- const eid = nameToID.get(name);
167
- if (eid === void 0) throw new Error(`Component ${name} not registered`);
168
- return eid;
169
- }
170
- function getName(cid) {
171
- const name = IDtoName.get(cid);
172
- if (!name) throw new Error(`Component ID ${cid} not registered`);
173
- return name;
174
- }
175
- return { register, getID, getName };
176
- }
177
-
178
- // src/Ecs.ts
179
- function ECS() {
180
- const ComponentRegistry = createComponentRegistry();
181
- const Entities = EntityManager(ComponentRegistry);
182
- const internalStores = {};
183
- const components = {};
184
- function defineComponents(data) {
185
- for (const key in data) {
186
- ComponentRegistry.register(key);
187
- internalStores[key] = ComponentStore();
188
- components[key] = internalStores[key].getData();
189
- }
190
- }
191
- function createEntity() {
192
- return Entities.create();
193
- }
194
- function destroyEntity(eid) {
195
- const entityMask = Entities.getMask(eid);
196
- let cid = 0;
197
- let tempMask = entityMask;
198
- while (tempMask !== 0n) {
199
- if ((tempMask & 1n) !== 0n) {
200
- const name = ComponentRegistry.getName(cid);
201
- internalStores[name].remove(eid);
202
- }
203
- tempMask >>= 1n;
204
- cid++;
205
- }
206
- Entities.remove(eid);
207
- }
208
- function addComponent(eid, name, data) {
209
- Entities.addComponent(eid, name);
210
- internalStores[name].add(eid, data);
211
- }
212
- function removeComponent(eid, name) {
213
- Entities.removeComponent(eid, name);
214
- internalStores[name].remove(eid);
215
- }
216
- function* query(...componentName) {
217
- if (componentName.length === 0) return;
218
- let smallestStore = internalStores[componentName[0]];
219
- let smallestSize = smallestStore.getSize();
220
- for (let i = 1; i < componentName.length; i++) {
221
- const store = internalStores[componentName[i]];
222
- const size = store.getSize();
223
- if (size < smallestSize) {
224
- smallestStore = store;
225
- smallestSize = size;
226
- }
227
- }
228
- let targetMask = 0n;
229
- for (const name of componentName) {
230
- targetMask |= 1n << BigInt(ComponentRegistry.getID(name));
231
- }
232
- for (const eid of smallestStore.getDense()) {
233
- if ((Entities.getMask(eid) & targetMask) !== targetMask) continue;
234
- const result = {};
235
- for (const name of componentName) {
236
- const id = internalStores[name].getIndex(eid);
237
- result[name] = { id };
238
- }
239
- yield result;
240
- }
241
- }
242
- return { defineComponents, createEntity, destroyEntity, addComponent, removeComponent, query, components };
243
- }
244
- // Annotate the CommonJS export names for ESM import in node:
245
- 0 && (module.exports = {
246
- ECS
247
- });
package/dist/index.d.ts DELETED
@@ -1,103 +0,0 @@
1
- /**
2
- * Represents component data in Structure of Arrays (SoA) format.
3
- * Each property of the component is stored in a separate array,
4
- * enabling cache-efficient iteration and SIMD operations.
5
- * @template T - The component data type
6
- * @example
7
- * // For Position component: { x: number, y: number }
8
- * // ComponentDataArrays would be: { x: number[], y: number[] }
9
- */
10
- type ComponentDataArrays<T> = {
11
- [K in keyof T]: T[K][];
12
- };
13
-
14
- /**
15
- * Maps component names to their data arrays for direct access.
16
- * Used to expose component data to the user without store methods.
17
- * @template T - Record type defining all component types
18
- */
19
- type StoreDataMap<T> = {
20
- [K in keyof T]: ComponentDataArrays<T[K]>;
21
- };
22
-
23
- /**
24
- * Type helper for the query result.
25
- * Creates an object with eid and all required components typed correctly.
26
- * @template T - Record type with all component types.
27
- * @template C - Array of the component names requested in the query.
28
- */
29
- type QueryResult<T, C extends (keyof T)[]> = {
30
- [K in C[number]]: { id: number };
31
- };
32
-
33
- type StoreInit<T> = {
34
- [K in keyof T]: {
35
- [P in keyof T[K]]: T[K][P][];
36
- };
37
- };
38
-
39
- /**
40
- * Interface for the main ECS registry.
41
- * Provides high-level API for entity-component management,
42
- * coordinating between EntityManager and ComponentStores.
43
- * @template T - Record type defining all component types in the ECS
44
- */
45
- interface IECS<T> {
46
- /**
47
- * Initializes the ECS with component definitions.
48
- * Registers all components and creates their corresponding stores.
49
- * Must be called before any other operations.
50
- * @param components - Object mapping component names to their structure
51
- */
52
- defineComponents: (data: StoreInit<T>) => void;
53
-
54
- /**
55
- * Creates a new entity in the ECS.
56
- * @returns The ID of the newly created entity
57
- */
58
- createEntity: () => number;
59
-
60
- /**
61
- * Completely removes an entity and all its components from the ECS.
62
- * Cleans up all component data and entity records.
63
- * @param eid - The entity ID to destroy
64
- */
65
- destroyEntity: (eid: number) => void;
66
-
67
- /**
68
- * Adds a component to an entity with the provided data.
69
- * Updates both the entity's bitmask and the component store.
70
- * @template K - The component name type (key of T)
71
- * @param eid - The entity ID
72
- * @param name - The component name
73
- * @param data - The component data to store
74
- */
75
- addComponent: <K extends keyof T>(eid: number, name: K, data: T[K]) => void;
76
-
77
- /**
78
- * Removes a component from an entity.
79
- * Updates both the entity's bitmask and the component store.
80
- * @template K - The component name type (key of T)
81
- * @param eid - The entity ID
82
- * @param name - The component name
83
- */
84
- removeComponent: <K extends keyof T>(eid: number, name: K) => void;
85
-
86
- /**
87
- * Retrieves all entities that contain the specified set of components.
88
- * Performs a filtered search across component stores and yields each matching entity.
89
- * The returned generator allows efficient iteration without allocating large arrays.
90
- *
91
- * @template C - Array of component names to query for
92
- * @param components - List of component names that the entity must include
93
- * @returns A generator that yields an object for each matching entity,
94
- * containing the entity ID and the related component data
95
- */
96
- query: <C extends (keyof T)[]>(...componentName: C) => Generator<QueryResult<T, C>>;
97
-
98
- components: StoreDataMap<T>;
99
- }
100
-
101
- declare function ECS<T extends Record<string, Record<string, any>>>(): IECS<T>;
102
-
103
- export { ECS };