@ste_tisci/ecs 0.1.6 → 0.1.7

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/dist/index.cjs ADDED
@@ -0,0 +1,265 @@
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
+ var INITIAL_CAPACITY = 8;
68
+ function grow(buffer, requiredIndex) {
69
+ let capacity = buffer.length;
70
+ while (capacity <= requiredIndex) capacity *= 2;
71
+ const grown = new Float32Array(capacity);
72
+ grown.set(buffer);
73
+ return grown;
74
+ }
75
+ function ComponentStore() {
76
+ const componentSet = SparseSet();
77
+ const componentData = {};
78
+ const isNumeric = {};
79
+ function add(eid, data) {
80
+ if (componentSet.has(eid)) throw new Error(`Entity ${eid} already has this component`);
81
+ const ID = componentSet.getSize();
82
+ componentSet.add(eid);
83
+ for (const key in data) {
84
+ const value = data[key];
85
+ if (!(key in componentData)) {
86
+ isNumeric[key] = typeof value === "number";
87
+ componentData[key] = isNumeric[key] ? new Float32Array(INITIAL_CAPACITY) : [];
88
+ }
89
+ if (isNumeric[key] && ID >= componentData[key].length) {
90
+ componentData[key] = grow(componentData[key], ID);
91
+ }
92
+ componentData[key][ID] = value;
93
+ }
94
+ }
95
+ function remove(eid) {
96
+ if (!componentSet.has(eid)) throw new Error(`Entity ${eid} does not have this component`);
97
+ const ID = componentSet.getIndex(eid);
98
+ const lastID = componentSet.getSize() - 1;
99
+ if (ID !== lastID) {
100
+ for (const key of Object.keys(componentData)) {
101
+ componentData[key][ID] = componentData[key][lastID];
102
+ }
103
+ }
104
+ componentSet.remove(eid);
105
+ for (const key in componentData) {
106
+ if (!isNumeric[key]) {
107
+ componentData[key].pop();
108
+ }
109
+ }
110
+ }
111
+ function getDense() {
112
+ return componentSet.getDense();
113
+ }
114
+ function getData() {
115
+ return componentData;
116
+ }
117
+ function getIndex(eid) {
118
+ return componentSet.getIndex(eid);
119
+ }
120
+ function getSize() {
121
+ return componentSet.getSize();
122
+ }
123
+ return { add, remove, getIndex, getDense, getData, getSize };
124
+ }
125
+
126
+ // src/EntityManager.ts
127
+ function EntityManager(registry) {
128
+ let nextID = 0;
129
+ const recycledIDs = [];
130
+ const bitMasks = [];
131
+ function exists(eid) {
132
+ const isWithinBounds = eid >= 0 && eid < nextID;
133
+ const hasMask = bitMasks[eid] !== void 0;
134
+ return isWithinBounds && hasMask;
135
+ }
136
+ function hasComponent(eid, name) {
137
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
138
+ const cid = registry.getID(name);
139
+ return (bitMasks[eid] & 1n << BigInt(cid)) !== 0n;
140
+ }
141
+ function create() {
142
+ const ID = recycledIDs.length > 0 ? recycledIDs.pop() : nextID++;
143
+ bitMasks[ID] = 0n;
144
+ return ID;
145
+ }
146
+ function remove(eid) {
147
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
148
+ bitMasks[eid] = void 0;
149
+ recycledIDs.push(eid);
150
+ }
151
+ function addComponent(eid, name) {
152
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
153
+ if (hasComponent(eid, name)) throw new Error(`Entity ${eid} already has component ${name}`);
154
+ const cid = registry.getID(name);
155
+ bitMasks[eid] |= 1n << BigInt(cid);
156
+ }
157
+ function removeComponent(eid, name) {
158
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
159
+ if (!hasComponent(eid, name)) throw new Error(`Entity ${eid} does not have component ${name}`);
160
+ const cid = registry.getID(name);
161
+ bitMasks[eid] &= ~(1n << BigInt(cid));
162
+ }
163
+ function getMask(eid) {
164
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
165
+ return bitMasks[eid];
166
+ }
167
+ return { exists, hasComponent, create, remove, addComponent, removeComponent, getMask };
168
+ }
169
+
170
+ // src/utils/ComponentRegistry.ts
171
+ function createComponentRegistry() {
172
+ const nameToID = /* @__PURE__ */ new Map();
173
+ const IDtoName = /* @__PURE__ */ new Map();
174
+ let nextID = 0;
175
+ function register(name) {
176
+ if (!nameToID.has(name)) {
177
+ const eid = nextID++;
178
+ nameToID.set(name, eid);
179
+ IDtoName.set(eid, name);
180
+ }
181
+ }
182
+ function getID(name) {
183
+ const eid = nameToID.get(name);
184
+ if (eid === void 0) throw new Error(`Component ${name} not registered`);
185
+ return eid;
186
+ }
187
+ function getName(cid) {
188
+ const name = IDtoName.get(cid);
189
+ if (!name) throw new Error(`Component ID ${cid} not registered`);
190
+ return name;
191
+ }
192
+ return { register, getID, getName };
193
+ }
194
+
195
+ // src/Ecs.ts
196
+ function ECS() {
197
+ const ComponentRegistry = createComponentRegistry();
198
+ const Entities = EntityManager(ComponentRegistry);
199
+ const internalStores = {};
200
+ const components = {};
201
+ function defineComponents(...names) {
202
+ for (const name of names) {
203
+ if (name in internalStores) throw new Error(`Component ${String(name)} is already defined`);
204
+ ComponentRegistry.register(name);
205
+ internalStores[name] = ComponentStore();
206
+ components[name] = internalStores[name].getData();
207
+ }
208
+ }
209
+ function createEntity() {
210
+ return Entities.create();
211
+ }
212
+ function destroyEntity(eid) {
213
+ const entityMask = Entities.getMask(eid);
214
+ let cid = 0;
215
+ let tempMask = entityMask;
216
+ while (tempMask !== 0n) {
217
+ if ((tempMask & 1n) !== 0n) {
218
+ const name = ComponentRegistry.getName(cid);
219
+ internalStores[name].remove(eid);
220
+ }
221
+ tempMask >>= 1n;
222
+ cid++;
223
+ }
224
+ Entities.remove(eid);
225
+ }
226
+ function addComponent(eid, name, data) {
227
+ Entities.addComponent(eid, name);
228
+ internalStores[name].add(eid, data);
229
+ }
230
+ function removeComponent(eid, name) {
231
+ Entities.removeComponent(eid, name);
232
+ internalStores[name].remove(eid);
233
+ }
234
+ function* query(...componentName) {
235
+ if (componentName.length === 0) return;
236
+ let targetMask = 0n;
237
+ for (const name of componentName) {
238
+ targetMask |= 1n << BigInt(ComponentRegistry.getID(name));
239
+ }
240
+ let smallestStore = internalStores[componentName[0]];
241
+ let smallestSize = smallestStore.getSize();
242
+ for (let i = 1; i < componentName.length; i++) {
243
+ const store = internalStores[componentName[i]];
244
+ const size = store.getSize();
245
+ if (size < smallestSize) {
246
+ smallestStore = store;
247
+ smallestSize = size;
248
+ }
249
+ }
250
+ for (const eid of smallestStore.getDense()) {
251
+ if ((Entities.getMask(eid) & targetMask) !== targetMask) continue;
252
+ const result = {};
253
+ for (const name of componentName) {
254
+ const id = internalStores[name].getIndex(eid);
255
+ result[name] = { id };
256
+ }
257
+ yield result;
258
+ }
259
+ }
260
+ return { defineComponents, createEntity, destroyEntity, addComponent, removeComponent, query, components };
261
+ }
262
+ // Annotate the CommonJS export names for ESM import in node:
263
+ 0 && (module.exports = {
264
+ ECS
265
+ });
@@ -1,12 +1,43 @@
1
- import type { QueryResult, StoreDataMap } from './index.js';
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
+ * Numeric properties are backed by a Float32Array for a compact, homogeneous
6
+ * memory layout; non-numeric properties fall back to a plain JS array.
7
+ * @template T - The component data type
8
+ * @example
9
+ * // For Position component: { x: number, y: number }
10
+ * // ComponentDataArrays would be: { x: Float32Array, y: Float32Array }
11
+ */
12
+ type ComponentDataArrays<T> = {
13
+ [K in keyof T]: T[K] extends number ? Float32Array : T[K][];
14
+ };
2
15
 
16
+ /**
17
+ * Maps component names to their data arrays for direct access.
18
+ * Used to expose component data to the user without store methods.
19
+ * @template T - Record type defining all component types
20
+ */
21
+ type StoreDataMap<T> = {
22
+ [K in keyof T]: ComponentDataArrays<T[K]>;
23
+ };
24
+
25
+ /**
26
+ * Type helper for the query result.
27
+ * Creates an object with an entry for each requested component, holding its store index.
28
+ * @template C - Array of the component names requested in the query.
29
+ */
30
+ type QueryResult<C extends readonly PropertyKey[]> = {
31
+ [K in C[number]]: { id: number };
32
+ };
33
+
3
34
  /**
4
35
  * Interface for the main ECS registry.
5
36
  * Provides high-level API for entity-component management,
6
37
  * coordinating between EntityManager and ComponentStores.
7
38
  * @template T - Record type defining all component types in the ECS
8
39
  */
9
- export interface IECS<T> {
40
+ interface IECS<T> {
10
41
  /**
11
42
  * Initializes the ECS with component definitions.
12
43
  * Registers all components and creates their corresponding stores.
@@ -61,4 +92,8 @@ export interface IECS<T> {
61
92
  query: <C extends (keyof T)[]>(...componentName: C) => Generator<QueryResult<C>>;
62
93
 
63
94
  components: StoreDataMap<T>;
64
- }
95
+ }
96
+
97
+ declare function ECS<T extends Record<string, Record<string, any>>>(): IECS<T>;
98
+
99
+ export { ECS };
@@ -0,0 +1,99 @@
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
+ * Numeric properties are backed by a Float32Array for a compact, homogeneous
6
+ * memory layout; non-numeric properties fall back to a plain JS array.
7
+ * @template T - The component data type
8
+ * @example
9
+ * // For Position component: { x: number, y: number }
10
+ * // ComponentDataArrays would be: { x: Float32Array, y: Float32Array }
11
+ */
12
+ type ComponentDataArrays<T> = {
13
+ [K in keyof T]: T[K] extends number ? Float32Array : T[K][];
14
+ };
15
+
16
+ /**
17
+ * Maps component names to their data arrays for direct access.
18
+ * Used to expose component data to the user without store methods.
19
+ * @template T - Record type defining all component types
20
+ */
21
+ type StoreDataMap<T> = {
22
+ [K in keyof T]: ComponentDataArrays<T[K]>;
23
+ };
24
+
25
+ /**
26
+ * Type helper for the query result.
27
+ * Creates an object with an entry for each requested component, holding its store index.
28
+ * @template C - Array of the component names requested in the query.
29
+ */
30
+ type QueryResult<C extends readonly PropertyKey[]> = {
31
+ [K in C[number]]: { id: number };
32
+ };
33
+
34
+ /**
35
+ * Interface for the main ECS registry.
36
+ * Provides high-level API for entity-component management,
37
+ * coordinating between EntityManager and ComponentStores.
38
+ * @template T - Record type defining all component types in the ECS
39
+ */
40
+ interface IECS<T> {
41
+ /**
42
+ * Initializes the ECS with component definitions.
43
+ * Registers all components and creates their corresponding stores.
44
+ * Must be called before any other operations.
45
+ * @param names -component names
46
+ * @throws Error if a component name is already defined
47
+ */
48
+ defineComponents<K extends readonly (keyof T)[]>(...names: K): void;
49
+
50
+ /**
51
+ * Creates a new entity in the ECS.
52
+ * @returns The ID of the newly created entity
53
+ */
54
+ createEntity: () => number;
55
+
56
+ /**
57
+ * Completely removes an entity and all its components from the ECS.
58
+ * Cleans up all component data and entity records.
59
+ * @param eid - The entity ID to destroy
60
+ */
61
+ destroyEntity: (eid: number) => void;
62
+
63
+ /**
64
+ * Adds a component to an entity with the provided data.
65
+ * Updates both the entity's bitmask and the component store.
66
+ * @template K - The component name type (key of T)
67
+ * @param eid - The entity ID
68
+ * @param name - The component name
69
+ * @param data - The component data to store
70
+ */
71
+ addComponent: <K extends keyof T>(eid: number, name: K, data: T[K]) => void;
72
+
73
+ /**
74
+ * Removes a component from an entity.
75
+ * Updates both the entity's bitmask and the component store.
76
+ * @template K - The component name type (key of T)
77
+ * @param eid - The entity ID
78
+ * @param name - The component name
79
+ */
80
+ removeComponent: <K extends keyof T>(eid: number, name: K) => void;
81
+
82
+ /**
83
+ * Retrieves all entities that contain the specified set of components.
84
+ * Performs a filtered search across component stores and yields each matching entity.
85
+ * The returned generator allows efficient iteration without allocating large arrays.
86
+ *
87
+ * @template C - Array of component names to query for
88
+ * @param components - List of component names that the entity must include
89
+ * @returns A generator that yields an object for each matching entity,
90
+ * containing the entity ID and the related component data
91
+ */
92
+ query: <C extends (keyof T)[]>(...componentName: C) => Generator<QueryResult<C>>;
93
+
94
+ components: StoreDataMap<T>;
95
+ }
96
+
97
+ declare function ECS<T extends Record<string, Record<string, any>>>(): IECS<T>;
98
+
99
+ export { ECS };
package/dist/index.js ADDED
@@ -0,0 +1,238 @@
1
+ // src/utils/SparseSet.ts
2
+ function SparseSet() {
3
+ const sparse = [];
4
+ const dense = [];
5
+ let size = 0;
6
+ function has(eid) {
7
+ const ID = getIndex(eid);
8
+ const exist = ID !== void 0 && dense[ID] === eid;
9
+ const isWhitinBounds = ID >= 0 && ID < size;
10
+ return exist && isWhitinBounds;
11
+ }
12
+ function add(eid) {
13
+ if (has(eid)) throw new Error(`ID ${eid} already present in the set`);
14
+ sparse[eid] = size;
15
+ dense[size] = eid;
16
+ size++;
17
+ }
18
+ function remove(eid) {
19
+ if (!has(eid)) throw new Error(`Cannot remove ID ${eid} because does not exists`);
20
+ const ID = getIndex(eid);
21
+ const last = dense[size - 1];
22
+ dense[ID] = last;
23
+ sparse[last] = ID;
24
+ dense.pop();
25
+ size--;
26
+ delete sparse[eid];
27
+ }
28
+ function getIndex(eid) {
29
+ return sparse[eid];
30
+ }
31
+ function getDense() {
32
+ return dense;
33
+ }
34
+ function getSize() {
35
+ return size;
36
+ }
37
+ return { has, add, remove, getIndex, getDense, getSize };
38
+ }
39
+
40
+ // src/ComponentStore.ts
41
+ var INITIAL_CAPACITY = 8;
42
+ function grow(buffer, requiredIndex) {
43
+ let capacity = buffer.length;
44
+ while (capacity <= requiredIndex) capacity *= 2;
45
+ const grown = new Float32Array(capacity);
46
+ grown.set(buffer);
47
+ return grown;
48
+ }
49
+ function ComponentStore() {
50
+ const componentSet = SparseSet();
51
+ const componentData = {};
52
+ const isNumeric = {};
53
+ function add(eid, data) {
54
+ if (componentSet.has(eid)) throw new Error(`Entity ${eid} already has this component`);
55
+ const ID = componentSet.getSize();
56
+ componentSet.add(eid);
57
+ for (const key in data) {
58
+ const value = data[key];
59
+ if (!(key in componentData)) {
60
+ isNumeric[key] = typeof value === "number";
61
+ componentData[key] = isNumeric[key] ? new Float32Array(INITIAL_CAPACITY) : [];
62
+ }
63
+ if (isNumeric[key] && ID >= componentData[key].length) {
64
+ componentData[key] = grow(componentData[key], ID);
65
+ }
66
+ componentData[key][ID] = value;
67
+ }
68
+ }
69
+ function remove(eid) {
70
+ if (!componentSet.has(eid)) throw new Error(`Entity ${eid} does not have this component`);
71
+ const ID = componentSet.getIndex(eid);
72
+ const lastID = componentSet.getSize() - 1;
73
+ if (ID !== lastID) {
74
+ for (const key of Object.keys(componentData)) {
75
+ componentData[key][ID] = componentData[key][lastID];
76
+ }
77
+ }
78
+ componentSet.remove(eid);
79
+ for (const key in componentData) {
80
+ if (!isNumeric[key]) {
81
+ componentData[key].pop();
82
+ }
83
+ }
84
+ }
85
+ function getDense() {
86
+ return componentSet.getDense();
87
+ }
88
+ function getData() {
89
+ return componentData;
90
+ }
91
+ function getIndex(eid) {
92
+ return componentSet.getIndex(eid);
93
+ }
94
+ function getSize() {
95
+ return componentSet.getSize();
96
+ }
97
+ return { add, remove, getIndex, getDense, getData, getSize };
98
+ }
99
+
100
+ // src/EntityManager.ts
101
+ function EntityManager(registry) {
102
+ let nextID = 0;
103
+ const recycledIDs = [];
104
+ const bitMasks = [];
105
+ function exists(eid) {
106
+ const isWithinBounds = eid >= 0 && eid < nextID;
107
+ const hasMask = bitMasks[eid] !== void 0;
108
+ return isWithinBounds && hasMask;
109
+ }
110
+ function hasComponent(eid, name) {
111
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
112
+ const cid = registry.getID(name);
113
+ return (bitMasks[eid] & 1n << BigInt(cid)) !== 0n;
114
+ }
115
+ function create() {
116
+ const ID = recycledIDs.length > 0 ? recycledIDs.pop() : nextID++;
117
+ bitMasks[ID] = 0n;
118
+ return ID;
119
+ }
120
+ function remove(eid) {
121
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
122
+ bitMasks[eid] = void 0;
123
+ recycledIDs.push(eid);
124
+ }
125
+ function addComponent(eid, name) {
126
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
127
+ if (hasComponent(eid, name)) throw new Error(`Entity ${eid} already has component ${name}`);
128
+ const cid = registry.getID(name);
129
+ bitMasks[eid] |= 1n << BigInt(cid);
130
+ }
131
+ function removeComponent(eid, name) {
132
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exists`);
133
+ if (!hasComponent(eid, name)) throw new Error(`Entity ${eid} does not have component ${name}`);
134
+ const cid = registry.getID(name);
135
+ bitMasks[eid] &= ~(1n << BigInt(cid));
136
+ }
137
+ function getMask(eid) {
138
+ if (!exists(eid)) throw new Error(`Entity ${eid} does not exist`);
139
+ return bitMasks[eid];
140
+ }
141
+ return { exists, hasComponent, create, remove, addComponent, removeComponent, getMask };
142
+ }
143
+
144
+ // src/utils/ComponentRegistry.ts
145
+ function createComponentRegistry() {
146
+ const nameToID = /* @__PURE__ */ new Map();
147
+ const IDtoName = /* @__PURE__ */ new Map();
148
+ let nextID = 0;
149
+ function register(name) {
150
+ if (!nameToID.has(name)) {
151
+ const eid = nextID++;
152
+ nameToID.set(name, eid);
153
+ IDtoName.set(eid, name);
154
+ }
155
+ }
156
+ function getID(name) {
157
+ const eid = nameToID.get(name);
158
+ if (eid === void 0) throw new Error(`Component ${name} not registered`);
159
+ return eid;
160
+ }
161
+ function getName(cid) {
162
+ const name = IDtoName.get(cid);
163
+ if (!name) throw new Error(`Component ID ${cid} not registered`);
164
+ return name;
165
+ }
166
+ return { register, getID, getName };
167
+ }
168
+
169
+ // src/Ecs.ts
170
+ function ECS() {
171
+ const ComponentRegistry = createComponentRegistry();
172
+ const Entities = EntityManager(ComponentRegistry);
173
+ const internalStores = {};
174
+ const components = {};
175
+ function defineComponents(...names) {
176
+ for (const name of names) {
177
+ if (name in internalStores) throw new Error(`Component ${String(name)} is already defined`);
178
+ ComponentRegistry.register(name);
179
+ internalStores[name] = ComponentStore();
180
+ components[name] = internalStores[name].getData();
181
+ }
182
+ }
183
+ function createEntity() {
184
+ return Entities.create();
185
+ }
186
+ function destroyEntity(eid) {
187
+ const entityMask = Entities.getMask(eid);
188
+ let cid = 0;
189
+ let tempMask = entityMask;
190
+ while (tempMask !== 0n) {
191
+ if ((tempMask & 1n) !== 0n) {
192
+ const name = ComponentRegistry.getName(cid);
193
+ internalStores[name].remove(eid);
194
+ }
195
+ tempMask >>= 1n;
196
+ cid++;
197
+ }
198
+ Entities.remove(eid);
199
+ }
200
+ function addComponent(eid, name, data) {
201
+ Entities.addComponent(eid, name);
202
+ internalStores[name].add(eid, data);
203
+ }
204
+ function removeComponent(eid, name) {
205
+ Entities.removeComponent(eid, name);
206
+ internalStores[name].remove(eid);
207
+ }
208
+ function* query(...componentName) {
209
+ if (componentName.length === 0) return;
210
+ let targetMask = 0n;
211
+ for (const name of componentName) {
212
+ targetMask |= 1n << BigInt(ComponentRegistry.getID(name));
213
+ }
214
+ let smallestStore = internalStores[componentName[0]];
215
+ let smallestSize = smallestStore.getSize();
216
+ for (let i = 1; i < componentName.length; i++) {
217
+ const store = internalStores[componentName[i]];
218
+ const size = store.getSize();
219
+ if (size < smallestSize) {
220
+ smallestStore = store;
221
+ smallestSize = size;
222
+ }
223
+ }
224
+ for (const eid of smallestStore.getDense()) {
225
+ if ((Entities.getMask(eid) & targetMask) !== targetMask) continue;
226
+ const result = {};
227
+ for (const name of componentName) {
228
+ const id = internalStores[name].getIndex(eid);
229
+ result[name] = { id };
230
+ }
231
+ yield result;
232
+ }
233
+ }
234
+ return { defineComponents, createEntity, destroyEntity, addComponent, removeComponent, query, components };
235
+ }
236
+ export {
237
+ ECS
238
+ };
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@ste_tisci/ecs",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "A minimalistic game engine with zero dependencies based on the Entity Component System (ECS) architecture implemented in TypeScript",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
8
11
  "scripts": {
9
- "build": "tsup"
12
+ "build": "tsup",
13
+ "prepublishOnly": "npm run build"
10
14
  },
11
15
  "keywords": [],
12
16
  "author": "",
package/.prettierrc DELETED
@@ -1,12 +0,0 @@
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,96 +0,0 @@
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 DELETED
@@ -1,98 +0,0 @@
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
- }
@@ -1,60 +0,0 @@
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 DELETED
@@ -1 +0,0 @@
1
- export { ECS } from './Ecs.js';
@@ -1,29 +0,0 @@
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
- }
@@ -1,53 +0,0 @@
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
- }
@@ -1,65 +0,0 @@
1
- /**
2
- * Interface for managing entities and their component associations.
3
- * Uses bitmasks to efficiently track which components each entity has,
4
- * enabling fast component checks and queries.
5
- */
6
- export interface IEntityManager<K extends string> {
7
- /**
8
- * Checks if an entity exists in the system.
9
- * @param eid - The entity ID to check
10
- * @returns True if the entity exists, false otherwise
11
- */
12
- exists: (eid: number) => boolean;
13
-
14
- /**
15
- * Checks if an entity has a specific component.
16
- * Uses bitwise operations on the entity's bitmask for fast lookups.
17
- * @param eid - The entity ID
18
- * @param name - The component name
19
- * @returns True if the entity has the component, false otherwise
20
- */
21
- hasComponent: (eid: number, name: K) => boolean;
22
-
23
- /**
24
- * Creates a new entity.
25
- * Recycles entity IDs when possible, otherwise assigns a new incremental ID.
26
- * @returns The ID of the newly created entity
27
- */
28
- create: () => number;
29
-
30
- /**
31
- * Removes an entity from the system.
32
- * Marks the entity ID for recycling.
33
- * @param eid - The entity ID to remove
34
- * @throws Error if the entity doesn't exist
35
- */
36
- remove: (eid: number) => void;
37
-
38
- /**
39
- * Adds a component flag to an entity's bitmask.
40
- * Updates the entity's bitmask to indicate it has the specified component.
41
- * @param eid - The entity ID
42
- * @param name - The component name
43
- * @throws Error if the entity doesn't exist or already has the component
44
- */
45
- addComponent: (eid: number, name: K) => void;
46
-
47
- /**
48
- * Removes a component flag from an entity's bitmask.
49
- * Updates the entity's bitmask to indicate it no longer has the specified component.
50
- * @param eid - The entity ID
51
- * @param name - The component name
52
- * @throws Error if the entity doesn't exist
53
- */
54
- removeComponent: (eid: number, name: K) => void;
55
-
56
- /**
57
- * Retrieves the complete bitmask for an entity.
58
- * The bitmask represents all components the entity has,
59
- * with each bit corresponding to a component ID.
60
- * @param eid - The entity ID
61
- * @returns The entity's component bitmask
62
- * @throws Error if the entity doesn't exist
63
- */
64
- getMask: (eid: number) => bigint;
65
- }
@@ -1,49 +0,0 @@
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
- }
@@ -1,43 +0,0 @@
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
- * Numeric properties are backed by a Float32Array for a compact, homogeneous
8
- * memory layout; non-numeric properties fall back to a plain JS array.
9
- * @template T - The component data type
10
- * @example
11
- * // For Position component: { x: number, y: number }
12
- * // ComponentDataArrays would be: { x: Float32Array, y: Float32Array }
13
- */
14
- export type ComponentDataArrays<T> = {
15
- [K in keyof T]: T[K] extends number ? Float32Array : T[K][];
16
- };
17
-
18
- /**
19
- * Maps component names to their corresponding ComponentStore instances.
20
- * Used internally by CreateWorld to manage all component stores.
21
- * @template T - Record type defining all component types
22
- */
23
- export type StoreMap<T> = {
24
- [K in keyof T]: IComponentStore<T[K]>;
25
- };
26
-
27
- /**
28
- * Maps component names to their data arrays for direct access.
29
- * Used to expose component data to the user without store methods.
30
- * @template T - Record type defining all component types
31
- */
32
- export type StoreDataMap<T> = {
33
- [K in keyof T]: ComponentDataArrays<T[K]>;
34
- };
35
-
36
- /**
37
- * Type helper for the query result.
38
- * Creates an object with an entry for each requested component, holding its store index.
39
- * @template C - Array of the component names requested in the query.
40
- */
41
- export type QueryResult<C extends readonly PropertyKey[]> = {
42
- [K in C[number]]: { id: number };
43
- };
@@ -1,32 +0,0 @@
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
- }
@@ -1,54 +0,0 @@
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 DELETED
@@ -1,17 +0,0 @@
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 DELETED
@@ -1,10 +0,0 @@
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
- });