import { Entity } from './entity.ts'; import { Observable } from './observable.ts'; import { Component, ComponentCtor } from './component.ts'; export type ComponentInstance = T extends ComponentCtor ? R : never; /** * Represents query for entities that match a list of types that is cached and observable * * Queries can be strongly typed by supplying a type union in the optional type parameter * ```typescript * const queryAB = new ex.Query(['A', 'B']); * ``` */ export class Query = never> { public readonly id: string; public components: Set = new Set(); public entities: Entity>[] = []; /** * This fires right after the component is added */ public entityAdded$: Observable>> = new Observable>>(); /** * This fires right before the component is actually removed from the entity, it will still be available for cleanup purposes */ public entityRemoved$: Observable>> = new Observable>>(); constructor(public readonly requiredComponents: TKnownComponentCtors[]) { if (requiredComponents.length === 0) { throw new Error('Cannot create query without components'); } for (const type of requiredComponents) { this.components.add(type); } this.id = Query.createId(requiredComponents); } static createId(requiredComponents: Function[]): string { // TODO what happens if a user defines the same type name as a built in type // ! TODO this could be dangerous depending on the bundler's settings for names // Maybe some kind of hash function is better here? return requiredComponents .slice() .map((c) => c.name) .sort() .join('-'); } /** * Potentially adds an entity to a query index, returns true if added, false if not * @param entity */ checkAndAdd(entity: Entity): boolean { if (!this.entities.includes(entity) && entity.hasAll(Array.from(this.components))) { this.entities.push(entity); this.entityAdded$.notifyAll(entity); return true; } return false; } removeEntity(entity: Entity): void { const index = this.entities.indexOf(entity); if (index > -1) { this.entities.splice(index, 1); this.entityRemoved$.notifyAll(entity); } } /** * Returns a list of entities that match the query * @param sort Optional sorting function to sort entities returned from the query */ public getEntities(sort?: (a: Entity, b: Entity) => number): Entity>[] { if (sort) { this.entities.sort(sort); } return this.entities; } }