assassin-bug/framework/ecs/query.js

35 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2022-11-26 01:22:02 +00:00
export class Query {
constructor(include, exclude, world) {
this.include = include;
this.exclude = exclude;
this.world = world;
this.isDirty = true;
this.results = new Array();
this.includeComponentIds = include.map((component) => component.id);
this.excludeComponentIds = exclude.map((component) => component.id);
this.id = 0;
}
execute() {
if (!this.isDirty && this.results) {
return this.results;
}
let filtered;
this.includeComponentIds = this.include.map((component) => this.world.componentNamesToIDs.get(component.name));
this.excludeComponentIds = this.exclude.map((component) => this.world.componentNamesToIDs.get(component.name));
const entities = this.world.entities.filter((entity) => {
let ids = entity.getComponentIDs();
// let includes = ids.map(id => this.includeComponentIds.includes(id)).includes(true);
let excludes = ids
.map((id) => this.excludeComponentIds.includes(id))
.includes(true);
let includes = ids.filter((id) => this.includeComponentIds.includes(id));
return includes.length === this.includeComponentIds.length && !excludes;
});
if (entities.length > 0) {
this.isDirty = false;
this.results = entities;
}
return entities;
}
}