export class EcsWorld { constructor () { this.nextHandle = 1; this.nextEntityId = 1; this.freeHandles = []; this.alive = new Set(); this.entityIdByHandle = new Map(); this.handleByEntityId = new Map(); this.stores = new Map(); } spawn (entityId = null) { const id = entityId == null ? this.nextEntityId : Number(entityId); if (!Number.isInteger(id) || id < 1) { const error = new Error("Entity id must be a positive integer."); error.userFacing = true; throw error; } if (this.handleByEntityId.has(id)) { const error = new Error(`Entity ${id} already exists.`); error.userFacing = true; throw error; } if (id >= this.nextEntityId) { this.nextEntityId = id + 1; } const handle = this.freeHandles.pop() ?? this.nextHandle++; this.alive.add(handle); this.entityIdByHandle.set(handle, id); this.handleByEntityId.set(id, handle); return handle; } entity () { return this.spawn(); } adopt (entityId) { return this.spawn(entityId); } handleOf (entityId) { return this.handleByEntityId.get(entityId) ?? null; } entityIdOf (handle) { return this.entityIdByHandle.get(handle) ?? null; } hasEntity (entityId) { return this.handleByEntityId.has(entityId); } isAlive (handle) { return this.alive.has(handle); } destroy (handle) { if (!this.alive.has(handle)) { return; } const entityId = this.entityIdByHandle.get(handle); this.alive.delete(handle); this.entityIdByHandle.delete(handle); if (entityId != null) { this.handleByEntityId.delete(entityId); } for (const store of this.stores.values()) { store.delete(handle); } this.freeHandles.push(handle); } destroyEntity (entityId) { const handle = this.handleOf(entityId); if (handle != null) { this.destroy(handle); } } add (handle, name, data) { let store = this.stores.get(name); if (!store) { store = new Map(); this.stores.set(name, store); } store.set(handle, data); return data; } get (handle, name) { return this.stores.get(name)?.get(handle); } has (handle, name) { return this.stores.get(name)?.has(handle) ?? false; } remove (handle, name) { this.stores.get(name)?.delete(handle); } componentsOf (handle) { const components = {}; for (const [name, store] of this.stores) { if (store.has(handle)) { components[name] = store.get(handle); } } return components; } query (...names) { const primary = this.stores.get(names[0]); if (!primary) { return []; } const results = []; for (const [handle, first] of primary) { if (!this.alive.has(handle)) { continue; } const record = { handle, entityId: this.entityIdByHandle.get(handle), [names[0]]: first }; let matched = true; for (let i = 1; i < names.length; i++) { const component = this.get(handle, names[i]); if (!component) { matched = false; break; } record[names[i]] = component; } if (matched) { results.push(record); } } return results; } }