entix-ecs
Version:
A Class based ECS Package.
86 lines (85 loc) • 2.77 kB
JavaScript
export class EntityManager {
entityCount = 0; //A counter for id's
entities = []; //A array of entities
componentMap = new Map(); /* A nested map,
contains EntityId with a another map containing components.*/
createEntity() {
const id = this.entityCount;
this.entities.push(id);
this.componentMap.set(id, new Map());
this.entityCount++;
return id;
}
;
addComponent(id, componentClass, componentInstance) {
this.ensureEntityExists(id);
const components = this.componentMap.get(id);
if (!components?.has(componentClass)) {
components?.set(componentClass, componentInstance);
}
}
;
removeComponent(id, componentClass) {
this.ensureEntityExists(id);
const components = this.componentMap.get(id);
if (components?.has(componentClass)) {
components.delete(componentClass);
}
}
;
getComponent(id, componentClass) {
this.ensureEntityExists(id);
const components = this.componentMap.get(id);
const requestedComponent = components?.get(componentClass);
return requestedComponent;
}
;
getAllComponents(id) {
this.ensureEntityExists(id);
const components = this.componentMap.get(id);
if (!components)
return [];
return Array.from(components.values());
}
;
removeEntity(id) {
this.ensureEntityExists(id);
this.entities = this.entities.filter(e => e !== id);
this.componentMap.delete(id);
}
;
query(filterType, componentsToMatch, callback) {
for (const entity of this.entities) {
const matched = {};
const results = [];
for (const key in componentsToMatch) {
const compClass = componentsToMatch[key];
const instance = this.getComponent(entity, compClass);
if (instance)
matched[key] = instance;
results.push(!!instance);
}
let shouldCall = false;
if (filterType === 'All')
shouldCall = results.every(Boolean);
else if (filterType === 'Any')
shouldCall = results.some(Boolean);
else if (filterType === 'None')
shouldCall = results.every(r => !r);
else
throw new Error(`Unknown filter type: ${filterType}`);
if (shouldCall)
callback(entity, matched);
}
}
;
getAllEntities() {
return this.entities;
}
ensureEntityExists(id) {
if (!this.entities.includes(id))
throw new Error(`Entity ${id} does not exist!`);
}
;
}
;