Files
esengine/packages/core/src/ECS/Entity.ts

920 lines
24 KiB
TypeScript
Raw Normal View History

import { Component } from './Component';
import { ComponentRegistry, ComponentType } from './Core/ComponentStorage';
import { EventBus } from './Core/EventBus';
import { BitMask64Utils, BitMask64Data } from './Utils/BigIntCompatibility';
import { createLogger } from '../Utils/Logger';
import { getComponentInstanceTypeName, getComponentTypeName } from './Decorators';
import type { IScene } from './IScene';
/**
*
*
* ID比较
*/
export class EntityComparer {
/**
*
*
* @param self -
* @param other -
* @returns self优先级更高other优先级更高0
*/
public compare(self: Entity, other: Entity): number {
let compare = self.updateOrder - other.updateOrder;
if (compare == 0)
compare = self.id - other.id;
return compare;
}
}
/**
*
*
* ECS架构中的实体Entity
*
*
*
* @example
* ```typescript
* // 创建实体
* const entity = new Entity("Player", 1);
*
* // 添加组件
* const healthComponent = entity.addComponent(new HealthComponent(100));
*
* // 获取组件
* const health = entity.getComponent(HealthComponent);
*
2025-06-10 13:12:14 +08:00
* // 添加位置组件
* entity.addComponent(new PositionComponent(100, 200));
*
* // 添加子实体
* const weapon = new Entity("Weapon", 2);
* entity.addChild(weapon);
* ```
*/
export class Entity {
/**
* Entity专用日志器
*/
private static _logger = createLogger('Entity');
/**
*
*/
public static entityComparer: EntityComparer = new EntityComparer();
/**
* 线
*
*/
public static eventBus: EventBus | null = null;
/**
* Scene中的QuerySystem实体组件发生变动
*
* @param entity
*/
private static notifyQuerySystems(entity: Entity): void {
// 只通知Scene中的QuerySystem
if (entity.scene && entity.scene.querySystem) {
entity.scene.querySystem.updateEntity(entity);
entity.scene.clearSystemEntityCaches();
}
}
/**
*
*/
public name: string;
/**
*
*/
public readonly id: number;
/**
*
*/
public readonly components: Component[] = [];
/**
*
*/
public scene: IScene | null = null;
/**
*
*/
public _isDestroyed: boolean = false;
/**
*
*/
private _parent: Entity | null = null;
/**
*
*/
private _children: Entity[] = [];
/**
*
*/
private _active: boolean = true;
/**
*
*/
private _tag: number = 0;
/**
*
*/
private _enabled: boolean = true;
/**
*
*/
private _updateOrder: number = 0;
/**
*
*/
private _componentMask: BitMask64Data = BitMask64Utils.clone(BitMask64Utils.ZERO);
/**
* ID直址的稀疏数组
*/
private _componentsByTypeId: (Component | undefined)[] = [];
/**
* typeId到components数组中密集索引的映射表
*/
private _componentDenseIndexByTypeId: number[] = [];
/**
*
*
* @param name -
* @param id -
*/
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
/**
*
* @returns true
*/
public get isDestroyed(): boolean {
return this._isDestroyed;
}
/**
*
* @returns null
*/
public get parent(): Entity | null {
return this._parent;
}
/**
*
*
* @returns
*/
public get children(): readonly Entity[] {
return [...this._children];
}
/**
*
*
* @returns
*/
public get childCount(): number {
return this._children.length;
}
/**
*
*
* @returns true
*/
public get active(): boolean {
return this._active;
}
/**
*
*
*
*
* @param value -
*/
public set active(value: boolean) {
if (this._active !== value) {
this._active = value;
this.onActiveChanged();
}
}
/**
*
*
* true
*
* @returns
*/
public get activeInHierarchy(): boolean {
if (!this._active) return false;
if (this._parent) return this._parent.activeInHierarchy;
return true;
}
/**
*
*
* @returns
*/
public get tag(): number {
return this._tag;
}
/**
*
*
* @param value -
*/
public set tag(value: number) {
this._tag = value;
}
/**
*
*
* @returns true
*/
public get enabled(): boolean {
return this._enabled;
}
/**
*
*
* @param value -
*/
public set enabled(value: boolean) {
this._enabled = value;
}
/**
*
*
* @returns
*/
public get updateOrder(): number {
return this._updateOrder;
}
/**
*
*
* @param value -
*/
public set updateOrder(value: number) {
this._updateOrder = value;
}
/**
*
*
* @returns
*/
public get componentMask(): BitMask64Data {
return this._componentMask;
}
/**
*
*
* @param componentType -
* @param args -
* @returns
*/
public createComponent<T extends Component>(
componentType: ComponentType<T>,
2025-08-12 11:47:18 +08:00
...args: any[]
): T {
const component = new componentType(...args);
return this.addComponent(component);
}
/**
*
*
* @param component -
* @returns
*/
private addComponentInternal<T extends Component>(component: T): T {
const componentType = component.constructor as ComponentType<T>;
if (!ComponentRegistry.isRegistered(componentType)) {
ComponentRegistry.register(componentType);
}
const typeId = ComponentRegistry.getBitIndex(componentType);
this._componentsByTypeId[typeId] = component;
const denseIndex = this.components.length;
this._componentDenseIndexByTypeId[typeId] = denseIndex;
this.components.push(component);
const componentMask = ComponentRegistry.getBitMask(componentType);
BitMask64Utils.orInPlace(this._componentMask, componentMask);
return component;
}
/**
*
*
* @param component -
* @returns
* @throws {Error}
*/
public addComponent<T extends Component>(component: T): T {
const componentType = component.constructor as ComponentType<T>;
if (this.hasComponent(componentType)) {
throw new Error(`Entity ${this.name} already has component ${getComponentTypeName(componentType)}`);
}
this.addComponentInternal(component);
if (this.scene && this.scene.componentStorageManager) {
this.scene.componentStorageManager.addComponent(this.id, component);
}
component.onAddedToEntity();
if (Entity.eventBus) {
Entity.eventBus.emitComponentAdded({
timestamp: Date.now(),
source: 'Entity',
entityId: this.id,
entityName: this.name,
entityTag: this.tag?.toString(),
componentType: getComponentTypeName(componentType),
component: component
});
}
// 通知所有相关的QuerySystem组件已变动
Entity.notifyQuerySystems(this);
return component;
}
/**
*
*
* @param type -
* @returns null
*/
public getComponent<T extends Component>(type: ComponentType<T>): T | null {
if (!ComponentRegistry.isRegistered(type)) {
return null;
}
const mask = ComponentRegistry.getBitMask(type);
if (BitMask64Utils.hasNone(this._componentMask, mask)) {
return null;
}
const typeId = ComponentRegistry.getBitIndex(type);
const component = this._componentsByTypeId[typeId];
if (component && component.constructor === type) {
return component as T;
}
if (this.scene && this.scene.componentStorageManager) {
const storageComponent = this.scene.componentStorageManager.getComponent(this.id, type);
if (storageComponent) {
this._componentsByTypeId[typeId] = storageComponent;
if (!this.components.includes(storageComponent)) {
const denseIndex = this.components.length;
this._componentDenseIndexByTypeId[typeId] = denseIndex;
this.components.push(storageComponent);
}
return storageComponent;
}
}
for (let i = 0; i < this.components.length; i++) {
const component = this.components[i];
if (component instanceof type) {
this._componentsByTypeId[typeId] = component;
this._componentDenseIndexByTypeId[typeId] = i;
return component as T;
}
}
return null;
}
/**
*
*
* @param type -
* @returns true
*/
public hasComponent<T extends Component>(type: ComponentType<T>): boolean {
if (!ComponentRegistry.isRegistered(type)) {
return false;
}
const mask = ComponentRegistry.getBitMask(type);
return BitMask64Utils.hasAny(this._componentMask, mask);
}
/**
*
*
* @param type -
* @param args - 使
* @returns
*/
public getOrCreateComponent<T extends Component>(
type: ComponentType<T>,
2025-08-12 11:47:18 +08:00
...args: any[]
): T {
let component = this.getComponent(type);
if (!component) {
component = this.createComponent(type, ...args);
}
return component;
}
/**
*
*
* @param component -
*/
public removeComponent(component: Component): void {
const componentType = component.constructor as ComponentType;
if (!ComponentRegistry.isRegistered(componentType)) {
return;
}
const typeId = ComponentRegistry.getBitIndex(componentType);
this._componentsByTypeId[typeId] = undefined;
BitMask64Utils.clearBit(this._componentMask, typeId);
const denseIndex = this._componentDenseIndexByTypeId[typeId];
if (denseIndex !== undefined && denseIndex < this.components.length) {
const lastIndex = this.components.length - 1;
if (denseIndex !== lastIndex) {
const lastComponent = this.components[lastIndex];
this.components[denseIndex] = lastComponent;
const lastComponentType = lastComponent.constructor as ComponentType;
const lastTypeId = ComponentRegistry.getBitIndex(lastComponentType);
this._componentDenseIndexByTypeId[lastTypeId] = denseIndex;
}
this.components.pop();
}
this._componentDenseIndexByTypeId[typeId] = -1;
if (this.scene && this.scene.componentStorageManager) {
this.scene.componentStorageManager.removeComponent(this.id, componentType);
}
if (component.onRemovedFromEntity) {
component.onRemovedFromEntity();
}
if (Entity.eventBus) {
Entity.eventBus.emitComponentRemoved({
timestamp: Date.now(),
source: 'Entity',
entityId: this.id,
entityName: this.name,
entityTag: this.tag?.toString(),
componentType: getComponentTypeName(componentType),
component: component
});
}
// 通知所有相关的QuerySystem组件已变动
Entity.notifyQuerySystems(this);
}
/**
*
*
* @param type -
* @returns null
*/
public removeComponentByType<T extends Component>(type: ComponentType<T>): T | null {
const component = this.getComponent(type);
if (component) {
this.removeComponent(component);
return component;
}
return null;
}
/**
*
*/
public removeAllComponents(): void {
const componentsToRemove = [...this.components];
this._componentsByTypeId.length = 0;
this._componentDenseIndexByTypeId.length = 0;
BitMask64Utils.clear(this._componentMask);
for (const component of componentsToRemove) {
const componentType = component.constructor as ComponentType;
if (this.scene && this.scene.componentStorageManager) {
this.scene.componentStorageManager.removeComponent(this.id, componentType);
}
component.onRemovedFromEntity();
}
this.components.length = 0;
// 通知所有相关的QuerySystem组件已全部移除
Entity.notifyQuerySystems(this);
}
/**
*
*
* @param components -
* @returns
*/
public addComponents<T extends Component>(components: T[]): T[] {
const addedComponents: T[] = [];
for (const component of components) {
try {
addedComponents.push(this.addComponent(component));
} catch (error) {
Entity._logger.warn(`添加组件失败 ${getComponentInstanceTypeName(component)}:`, error);
}
}
return addedComponents;
}
/**
*
*
* @param componentTypes -
* @returns
*/
public removeComponentsByTypes<T extends Component>(componentTypes: ComponentType<T>[]): (T | null)[] {
const removedComponents: (T | null)[] = [];
for (const componentType of componentTypes) {
removedComponents.push(this.removeComponentByType(componentType));
}
return removedComponents;
}
/**
*
*
* @param type -
* @returns
*/
public getComponents<T extends Component>(type: ComponentType<T>): T[] {
const result: T[] = [];
for (const component of this.components) {
if (component instanceof type) {
result.push(component as T);
}
}
return result;
}
/**
*
*
* @param child -
* @returns
*/
public addChild(child: Entity): Entity {
if (child === this) {
throw new Error("Entity cannot be its own child");
}
if (child._parent === this) {
return child; // 已经是子实体
}
if (child._parent) {
child._parent.removeChild(child);
}
child._parent = this;
this._children.push(child);
if (!child.scene && this.scene) {
child.scene = this.scene;
this.scene.addEntity(child);
}
return child;
}
/**
*
*
* @param child -
* @returns
*/
public removeChild(child: Entity): boolean {
const index = this._children.indexOf(child);
if (index === -1) {
return false;
}
this._children.splice(index, 1);
child._parent = null;
return true;
}
/**
*
*/
public removeAllChildren(): void {
const childrenToRemove = [...this._children];
for (const child of childrenToRemove) {
this.removeChild(child);
}
}
/**
*
*
* @param name -
* @param recursive -
* @returns null
*/
public findChild(name: string, recursive: boolean = false): Entity | null {
for (const child of this._children) {
if (child.name === name) {
return child;
}
}
if (recursive) {
for (const child of this._children) {
const found = child.findChild(name, true);
if (found) {
return found;
}
}
}
return null;
}
/**
*
*
* @param tag -
* @param recursive -
* @returns
*/
public findChildrenByTag(tag: number, recursive: boolean = false): Entity[] {
const result: Entity[] = [];
for (const child of this._children) {
if (child.tag === tag) {
result.push(child);
}
}
if (recursive) {
for (const child of this._children) {
result.push(...child.findChildrenByTag(tag, true));
}
}
return result;
}
/**
*
*
* @returns
*/
public getRoot(): Entity {
let root: Entity = this;
while (root._parent) {
root = root._parent;
}
return root;
}
/**
*
*
* @param entity -
* @returns true
*/
public isAncestorOf(entity: Entity): boolean {
let current = entity._parent;
while (current) {
if (current === this) {
return true;
}
current = current._parent;
}
return false;
}
/**
*
*
* @param entity -
* @returns true
*/
public isDescendantOf(entity: Entity): boolean {
return entity.isAncestorOf(this);
}
/**
*
*
* @returns 0
*/
public getDepth(): number {
let depth = 0;
let current = this._parent;
while (current) {
depth++;
current = current._parent;
}
return depth;
}
/**
*
*
* @param callback -
* @param recursive -
*/
public forEachChild(callback: (child: Entity, index: number) => void, recursive: boolean = false): void {
this._children.forEach((child, index) => {
callback(child, index);
if (recursive) {
child.forEachChild(callback, true);
}
});
}
/**
*
*/
private onActiveChanged(): void {
for (const component of this.components) {
if ('onActiveChanged' in component && typeof component.onActiveChanged === 'function') {
(component as any).onActiveChanged();
}
}
if (this.scene && this.scene.eventSystem) {
this.scene.eventSystem.emitSync('entity:activeChanged', {
entity: this,
active: this._active,
activeInHierarchy: this.activeInHierarchy
});
}
}
/**
*
*
*
*/
public destroy(): void {
if (this._isDestroyed) {
return;
}
this._isDestroyed = true;
const childrenToDestroy = [...this._children];
for (const child of childrenToDestroy) {
child.destroy();
}
if (this._parent) {
this._parent.removeChild(this);
}
this.removeAllComponents();
if (this.scene) {
if (this.scene.querySystem) {
this.scene.querySystem.removeEntity(this);
}
if (this.scene.entities) {
this.scene.entities.remove(this);
}
}
}
/**
*
*
* @param other -
* @returns
*/
public compareTo(other: Entity): number {
return EntityComparer.prototype.compare(this, other);
}
/**
*
*
* @returns
*/
public toString(): string {
return `Entity[${this.name}:${this.id}]`;
}
/**
*
*
* @returns
*/
public getDebugInfo(): {
name: string;
id: number;
enabled: boolean;
active: boolean;
activeInHierarchy: boolean;
destroyed: boolean;
componentCount: number;
componentTypes: string[];
componentMask: string;
parentId: number | null;
childCount: number;
childIds: number[];
depth: number;
indexMappingSize: number;
denseIndexMappingSize: number;
} {
return {
name: this.name,
id: this.id,
enabled: this._enabled,
active: this._active,
activeInHierarchy: this.activeInHierarchy,
destroyed: this._isDestroyed,
componentCount: this.components.length,
componentTypes: this.components.map(c => getComponentInstanceTypeName(c)),
componentMask: BitMask64Utils.toString(this._componentMask, 2), // 二进制表示
parentId: this._parent?.id || null,
childCount: this._children.length,
childIds: this._children.map(c => c.id),
depth: this.getDepth(),
indexMappingSize: this._componentsByTypeId.filter(c => c !== undefined).length,
denseIndexMappingSize: this._componentDenseIndexByTypeId.filter(idx => idx !== -1 && idx !== undefined).length
};
}
}