silphius/app/ecs/query.js

81 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-06-10 22:42:30 -05:00
export default class Query {
$$criteria = {with: [], without: []};
2024-06-26 07:41:07 -05:00
$$ecs;
2024-06-10 22:42:30 -05:00
$$index = new Set();
2024-06-26 07:41:07 -05:00
constructor(parameters, ecs) {
this.$$ecs = ecs;
2024-06-10 22:42:30 -05:00
for (let i = 0; i < parameters.length; ++i) {
const parameter = parameters[i];
switch (parameter.charCodeAt(0)) {
case '!'.charCodeAt(0):
2024-06-26 07:41:07 -05:00
this.$$criteria.without.push(ecs.Components[parameter.slice(1)]);
2024-06-10 22:42:30 -05:00
break;
default:
2024-06-26 07:41:07 -05:00
this.$$criteria.with.push(ecs.Components[parameter]);
2024-06-10 22:42:30 -05:00
break;
}
}
}
get count() {
return this.$$index.size;
}
2024-06-11 19:10:57 -05:00
deindex(entityIds) {
for (let i = 0; i < entityIds.length; ++i) {
this.$$index.delete(entityIds[i]);
2024-06-10 22:42:30 -05:00
}
}
2024-06-11 19:10:57 -05:00
reindex(entityIds) {
2024-06-10 22:42:30 -05:00
if (0 === this.$$criteria.with.length && 0 === this.$$criteria.without.length) {
2024-06-11 19:10:57 -05:00
for (const entityId of entityIds) {
this.$$index.add(entityId);
2024-06-10 22:42:30 -05:00
}
return;
}
2024-06-11 19:10:57 -05:00
for (const entityId of entityIds) {
2024-06-10 22:42:30 -05:00
let should = true;
for (let j = 0; j < this.$$criteria.with.length; ++j) {
2024-06-11 19:10:57 -05:00
if ('undefined' === typeof this.$$criteria.with[j].get(entityId)) {
2024-06-10 22:42:30 -05:00
should = false;
break;
}
}
if (should) {
for (let j = 0; j < this.$$criteria.without.length; ++j) {
2024-06-11 19:10:57 -05:00
if ('undefined' !== typeof this.$$criteria.without[j].get(entityId)) {
2024-06-10 22:42:30 -05:00
should = false;
break;
}
}
}
if (should) {
2024-06-11 19:10:57 -05:00
this.$$index.add(entityId);
2024-06-10 22:42:30 -05:00
}
else if (!should) {
2024-06-11 19:10:57 -05:00
this.$$index.delete(entityId);
2024-06-10 22:42:30 -05:00
}
}
}
select() {
const it = this.$$index.values();
return {
[Symbol.iterator]() {
return this;
},
next: () => {
const result = it.next();
if (result.done) {
return {done: true, value: undefined};
}
2024-06-26 07:41:07 -05:00
return {done: false, value: this.$$ecs.get(result.value)};
2024-06-10 22:42:30 -05:00
},
};
}
}