Feature/editor optimization (#251)
* refactor: 编辑器/运行时架构拆分与构建系统升级 * feat(core): 层级系统重构与UI变换矩阵修复 * refactor: 移除 ecs-components 聚合包并修复跨包组件查找问题 * fix(physics): 修复跨包组件类引用问题 * feat: 统一运行时架构与浏览器运行支持 * feat(asset): 实现浏览器运行时资产加载系统 * fix: 修复文档、CodeQL安全问题和CI类型检查错误 * fix: 修复文档、CodeQL安全问题和CI类型检查错误 * fix: 修复文档、CodeQL安全问题、CI类型检查和测试错误 * test: 补齐核心模块测试用例,修复CI构建配置 * fix: 修复测试用例中的类型错误和断言问题 * fix: 修复 turbo build:npm 任务的依赖顺序问题 * fix: 修复 CI 构建错误并优化构建性能
This commit is contained in:
56
packages/core/src/ECS/Components/HierarchyComponent.ts
Normal file
56
packages/core/src/ECS/Components/HierarchyComponent.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { Component } from '../Component';
|
||||
import { ECSComponent } from '../Decorators';
|
||||
import { Serializable, Serialize } from '../Serialization/SerializationDecorators';
|
||||
|
||||
/**
|
||||
* 层级关系组件 - 用于建立实体间的父子关系
|
||||
*
|
||||
* 只有需要层级关系的实体才添加此组件,遵循 ECS 组合原则。
|
||||
* 层级操作应通过 HierarchySystem 进行,而非直接修改此组件。
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 通过 HierarchySystem 设置父子关系
|
||||
* const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
* hierarchySystem.setParent(childEntity, parentEntity);
|
||||
*
|
||||
* // 查询层级信息
|
||||
* const parent = hierarchySystem.getParent(entity);
|
||||
* const children = hierarchySystem.getChildren(entity);
|
||||
* ```
|
||||
*/
|
||||
@ECSComponent('Hierarchy')
|
||||
@Serializable({ version: 1, typeId: 'Hierarchy' })
|
||||
export class HierarchyComponent extends Component {
|
||||
/**
|
||||
* 父实体 ID
|
||||
* null 表示根实体(无父级)
|
||||
*/
|
||||
@Serialize()
|
||||
public parentId: number | null = null;
|
||||
|
||||
/**
|
||||
* 子实体 ID 列表
|
||||
* 顺序即为子级的排列顺序
|
||||
*/
|
||||
@Serialize()
|
||||
public childIds: number[] = [];
|
||||
|
||||
/**
|
||||
* 在层级中的深度
|
||||
* 根实体深度为 0,由 HierarchySystem 维护
|
||||
*/
|
||||
public depth: number = 0;
|
||||
|
||||
/**
|
||||
* 层级中是否激活
|
||||
* 考虑所有祖先的激活状态,由 HierarchySystem 维护
|
||||
*/
|
||||
public bActiveInHierarchy: boolean = true;
|
||||
|
||||
/**
|
||||
* 层级缓存是否脏
|
||||
* 用于优化缓存更新
|
||||
*/
|
||||
public bCacheDirty: boolean = true;
|
||||
}
|
||||
1
packages/core/src/ECS/Components/index.ts
Normal file
1
packages/core/src/ECS/Components/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { HierarchyComponent } from './HierarchyComponent';
|
||||
@@ -2,6 +2,7 @@ import { Entity } from '../../Entity';
|
||||
import { Component } from '../../Component';
|
||||
import { IScene } from '../../IScene';
|
||||
import { ComponentType, ComponentStorageManager } from '../ComponentStorage';
|
||||
import { HierarchySystem } from '../../Systems/HierarchySystem';
|
||||
|
||||
/**
|
||||
* 实体构建器 - 提供流式API创建和配置实体
|
||||
@@ -129,7 +130,8 @@ export class EntityBuilder {
|
||||
*/
|
||||
public withChild(childBuilder: EntityBuilder): EntityBuilder {
|
||||
const child = childBuilder.build();
|
||||
this.entity.addChild(child);
|
||||
const hierarchySystem = this.scene.getSystem(HierarchySystem);
|
||||
hierarchySystem?.setParent(child, this.entity);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -139,9 +141,10 @@ export class EntityBuilder {
|
||||
* @returns 实体构建器
|
||||
*/
|
||||
public withChildren(...childBuilders: EntityBuilder[]): EntityBuilder {
|
||||
const hierarchySystem = this.scene.getSystem(HierarchySystem);
|
||||
for (const childBuilder of childBuilders) {
|
||||
const child = childBuilder.build();
|
||||
this.entity.addChild(child);
|
||||
hierarchySystem?.setParent(child, this.entity);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
@@ -154,7 +157,8 @@ export class EntityBuilder {
|
||||
public withChildFactory(childFactory: (parent: Entity) => EntityBuilder): EntityBuilder {
|
||||
const childBuilder = childFactory(this.entity);
|
||||
const child = childBuilder.build();
|
||||
this.entity.addChild(child);
|
||||
const hierarchySystem = this.scene.getSystem(HierarchySystem);
|
||||
hierarchySystem?.setParent(child, this.entity);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -167,7 +171,8 @@ export class EntityBuilder {
|
||||
public withChildIf(condition: boolean, childBuilder: EntityBuilder): EntityBuilder {
|
||||
if (condition) {
|
||||
const child = childBuilder.build();
|
||||
this.entity.addChild(child);
|
||||
const hierarchySystem = this.scene.getSystem(HierarchySystem);
|
||||
hierarchySystem?.setParent(child, this.entity);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -37,12 +37,14 @@ export class EntityComparer {
|
||||
*
|
||||
* ECS架构中的实体(Entity),作为组件的容器。
|
||||
* 实体本身不包含游戏逻辑,所有功能都通过组件来实现。
|
||||
* 支持父子关系,可以构建实体层次结构。
|
||||
*
|
||||
* 层级关系通过 HierarchyComponent 和 HierarchySystem 管理,
|
||||
* 而非 Entity 内置属性,符合 ECS 组合原则。
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 创建实体
|
||||
* const entity = new Entity("Player", 1);
|
||||
* const entity = scene.createEntity("Player");
|
||||
*
|
||||
* // 添加组件
|
||||
* const healthComponent = entity.addComponent(new HealthComponent(100));
|
||||
@@ -50,12 +52,9 @@ export class EntityComparer {
|
||||
* // 获取组件
|
||||
* const health = entity.getComponent(HealthComponent);
|
||||
*
|
||||
* // 添加位置组件
|
||||
* entity.addComponent(new PositionComponent(100, 200));
|
||||
*
|
||||
* // 添加子实体
|
||||
* const weapon = new Entity("Weapon", 2);
|
||||
* entity.addChild(weapon);
|
||||
* // 层级关系使用 HierarchySystem
|
||||
* const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
* hierarchySystem.setParent(childEntity, parentEntity);
|
||||
* ```
|
||||
*/
|
||||
export class Entity {
|
||||
@@ -89,16 +88,6 @@ export class Entity {
|
||||
*/
|
||||
private _isDestroyed: boolean = false;
|
||||
|
||||
/**
|
||||
* 父实体引用
|
||||
*/
|
||||
private _parent: Entity | null = null;
|
||||
|
||||
/**
|
||||
* 子实体集合
|
||||
*/
|
||||
private _children: Entity[] = [];
|
||||
|
||||
/**
|
||||
* 激活状态
|
||||
*/
|
||||
@@ -201,32 +190,6 @@ export class Entity {
|
||||
this._componentCache = components;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取父实体
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取活跃状态
|
||||
*
|
||||
@@ -239,8 +202,6 @@ export class Entity {
|
||||
/**
|
||||
* 设置活跃状态
|
||||
*
|
||||
* 设置实体的活跃状态,会影响子实体的有效活跃状态。
|
||||
*
|
||||
* @param value - 新的活跃状态
|
||||
*/
|
||||
public set active(value: boolean) {
|
||||
@@ -250,19 +211,6 @@ export class Entity {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实体的有效活跃状态
|
||||
*
|
||||
* 考虑父实体的活跃状态,只有当实体本身和所有父实体都处于活跃状态时才返回true。
|
||||
*
|
||||
* @returns 有效的活跃状态
|
||||
*/
|
||||
public get activeInHierarchy(): boolean {
|
||||
if (!this._active) return false;
|
||||
if (this._parent) return this._parent.activeInHierarchy;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实体标签
|
||||
*
|
||||
@@ -690,185 +638,6 @@ export class Entity {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加子实体
|
||||
*
|
||||
* @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 {
|
||||
if (!this._parent) {
|
||||
return this;
|
||||
}
|
||||
return this._parent.getRoot();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否是指定实体的祖先
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 活跃状态改变时的回调
|
||||
*/
|
||||
@@ -882,8 +651,7 @@ export class Entity {
|
||||
if (this.scene && this.scene.eventSystem) {
|
||||
this.scene.eventSystem.emitSync('entity:activeChanged', {
|
||||
entity: this,
|
||||
active: this._active,
|
||||
activeInHierarchy: this.activeInHierarchy
|
||||
active: this._active
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -891,7 +659,8 @@ export class Entity {
|
||||
/**
|
||||
* 销毁实体
|
||||
*
|
||||
* 移除所有组件、子实体并标记为已销毁
|
||||
* 移除所有组件并标记为已销毁。
|
||||
* 层级关系的清理由 HierarchySystem 处理。
|
||||
*/
|
||||
public destroy(): void {
|
||||
if (this._isDestroyed) {
|
||||
@@ -905,15 +674,6 @@ export class Entity {
|
||||
this.scene.referenceTracker.unregisterEntityScene(this.id);
|
||||
}
|
||||
|
||||
const childrenToDestroy = [...this._children];
|
||||
for (const child of childrenToDestroy) {
|
||||
child.destroy();
|
||||
}
|
||||
|
||||
if (this._parent) {
|
||||
this._parent.removeChild(this);
|
||||
}
|
||||
|
||||
this.removeAllComponents();
|
||||
|
||||
if (this.scene) {
|
||||
@@ -927,43 +687,6 @@ export class Entity {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量销毁所有子实体
|
||||
*/
|
||||
public destroyAllChildren(): void {
|
||||
if (this._children.length === 0) return;
|
||||
|
||||
const scene = this.scene;
|
||||
const toDestroy: Entity[] = [];
|
||||
|
||||
const collectChildren = (entity: Entity) => {
|
||||
for (const child of entity._children) {
|
||||
toDestroy.push(child);
|
||||
collectChildren(child);
|
||||
}
|
||||
};
|
||||
collectChildren(this);
|
||||
|
||||
for (const entity of toDestroy) {
|
||||
entity.setDestroyedState(true);
|
||||
}
|
||||
|
||||
for (const entity of toDestroy) {
|
||||
entity.removeAllComponents();
|
||||
}
|
||||
|
||||
if (scene) {
|
||||
for (const entity of toDestroy) {
|
||||
scene.entities.remove(entity);
|
||||
scene.querySystem.removeEntity(entity);
|
||||
}
|
||||
|
||||
scene.clearSystemEntityCaches();
|
||||
}
|
||||
|
||||
this._children.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较实体
|
||||
*
|
||||
@@ -993,31 +716,21 @@ export class Entity {
|
||||
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;
|
||||
cacheBuilt: boolean;
|
||||
} {
|
||||
} {
|
||||
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(),
|
||||
componentMask: BitMask64Utils.toString(this._componentMask, 2),
|
||||
cacheBuilt: this._componentCache !== null
|
||||
};
|
||||
}
|
||||
|
||||
95
packages/core/src/ECS/EntityTags.ts
Normal file
95
packages/core/src/ECS/EntityTags.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 实体标签常量
|
||||
*
|
||||
* 用于标识特殊类型的实体,如文件夹、摄像机等。
|
||||
* 使用位掩码实现,支持多标签组合。
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 创建文件夹实体
|
||||
* entity.tag = EntityTags.FOLDER;
|
||||
*
|
||||
* // 检查是否是文件夹
|
||||
* if ((entity.tag & EntityTags.FOLDER) !== 0) {
|
||||
* // 是文件夹
|
||||
* }
|
||||
*
|
||||
* // 组合多个标签
|
||||
* entity.tag = EntityTags.FOLDER | EntityTags.HIDDEN;
|
||||
* ```
|
||||
*/
|
||||
export const EntityTags = {
|
||||
/** 无标签 */
|
||||
NONE: 0x0000,
|
||||
|
||||
/** 文件夹实体 - 用于场景层级中的组织分类 */
|
||||
FOLDER: 0x1000,
|
||||
|
||||
/** 隐藏实体 - 在编辑器层级中不显示 */
|
||||
HIDDEN: 0x2000,
|
||||
|
||||
/** 锁定实体 - 在编辑器中不可选择/编辑 */
|
||||
LOCKED: 0x4000,
|
||||
|
||||
/** 编辑器专用实体 - 仅在编辑器中存在,不导出到运行时 */
|
||||
EDITOR_ONLY: 0x8000,
|
||||
|
||||
/** 预制件实例 */
|
||||
PREFAB_INSTANCE: 0x0100,
|
||||
|
||||
/** 预制件根节点 */
|
||||
PREFAB_ROOT: 0x0200
|
||||
} as const;
|
||||
|
||||
export type EntityTagValue = (typeof EntityTags)[keyof typeof EntityTags];
|
||||
|
||||
/**
|
||||
* 检查实体是否具有指定标签
|
||||
*
|
||||
* @param entityTag - 实体的 tag 值
|
||||
* @param tag - 要检查的标签
|
||||
*/
|
||||
export function hasEntityTag(entityTag: number, tag: EntityTagValue): boolean {
|
||||
return (entityTag & tag) !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加标签到实体
|
||||
*
|
||||
* @param entityTag - 当前 tag 值
|
||||
* @param tag - 要添加的标签
|
||||
*/
|
||||
export function addEntityTag(entityTag: number, tag: EntityTagValue): number {
|
||||
return entityTag | tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从实体移除标签
|
||||
*
|
||||
* @param entityTag - 当前 tag 值
|
||||
* @param tag - 要移除的标签
|
||||
*/
|
||||
export function removeEntityTag(entityTag: number, tag: EntityTagValue): number {
|
||||
return entityTag & ~tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查实体是否是文件夹
|
||||
*/
|
||||
export function isFolder(entityTag: number): boolean {
|
||||
return hasEntityTag(entityTag, EntityTags.FOLDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查实体是否隐藏
|
||||
*/
|
||||
export function isHidden(entityTag: number): boolean {
|
||||
return hasEntityTag(entityTag, EntityTags.HIDDEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查实体是否锁定
|
||||
*/
|
||||
export function isLocked(entityTag: number): boolean {
|
||||
return hasEntityTag(entityTag, EntityTags.LOCKED);
|
||||
}
|
||||
@@ -21,6 +21,9 @@ import {
|
||||
} from './Serialization/IncrementalSerializer';
|
||||
import { ComponentPoolManager } from './Core/ComponentPool';
|
||||
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
|
||||
import { ProfilerSDK } from '../Utils/Profiler/ProfilerSDK';
|
||||
import { ProfileCategory } from '../Utils/Profiler/ProfilerTypes';
|
||||
import { AutoProfiler } from '../Utils/Profiler/AutoProfiler';
|
||||
import { ServiceContainer, type ServiceType, type IService } from '../Core/ServiceContainer';
|
||||
import { createInstance, isInjectable, injectProperties } from '../Core/DI';
|
||||
import { createLogger } from '../Utils/Logger';
|
||||
@@ -334,30 +337,58 @@ export class Scene implements IScene {
|
||||
* 更新场景
|
||||
*/
|
||||
public update() {
|
||||
ComponentPoolManager.getInstance().update();
|
||||
// 开始性能采样帧
|
||||
ProfilerSDK.beginFrame();
|
||||
const frameHandle = ProfilerSDK.beginSample('Scene.update', ProfileCategory.ECS);
|
||||
|
||||
this.entities.updateLists();
|
||||
try {
|
||||
ComponentPoolManager.getInstance().update();
|
||||
|
||||
const systems = this.systems;
|
||||
this.entities.updateLists();
|
||||
|
||||
for (const system of systems) {
|
||||
if (system.enabled) {
|
||||
try {
|
||||
system.update();
|
||||
} catch (error) {
|
||||
this._handleSystemError(system, 'update', error);
|
||||
const systems = this.systems;
|
||||
|
||||
// Update 阶段
|
||||
const updateHandle = ProfilerSDK.beginSample('Systems.update', ProfileCategory.ECS);
|
||||
try {
|
||||
for (const system of systems) {
|
||||
if (system.enabled) {
|
||||
const systemHandle = ProfilerSDK.beginSample(system.systemName, ProfileCategory.ECS);
|
||||
try {
|
||||
system.update();
|
||||
} catch (error) {
|
||||
this._handleSystemError(system, 'update', error);
|
||||
} finally {
|
||||
ProfilerSDK.endSample(systemHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
ProfilerSDK.endSample(updateHandle);
|
||||
}
|
||||
}
|
||||
|
||||
for (const system of systems) {
|
||||
if (system.enabled) {
|
||||
try {
|
||||
system.lateUpdate();
|
||||
} catch (error) {
|
||||
this._handleSystemError(system, 'lateUpdate', error);
|
||||
// LateUpdate 阶段
|
||||
const lateUpdateHandle = ProfilerSDK.beginSample('Systems.lateUpdate', ProfileCategory.ECS);
|
||||
try {
|
||||
for (const system of systems) {
|
||||
if (system.enabled) {
|
||||
const systemHandle = ProfilerSDK.beginSample(`${system.systemName}.late`, ProfileCategory.ECS);
|
||||
try {
|
||||
system.lateUpdate();
|
||||
} catch (error) {
|
||||
this._handleSystemError(system, 'lateUpdate', error);
|
||||
} finally {
|
||||
ProfilerSDK.endSample(systemHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
ProfilerSDK.endSample(lateUpdateHandle);
|
||||
}
|
||||
} finally {
|
||||
ProfilerSDK.endSample(frameHandle);
|
||||
// 结束性能采样帧
|
||||
ProfilerSDK.endFrame();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,6 +724,11 @@ export class Scene implements IScene {
|
||||
|
||||
injectProperties(system, this._services);
|
||||
|
||||
// 调试模式下自动包装系统方法以收集性能数据(ProfilerSDK 启用时表示调试模式)
|
||||
if (ProfilerSDK.isEnabled()) {
|
||||
AutoProfiler.wrapInstance(system, system.systemName, ProfileCategory.ECS);
|
||||
}
|
||||
|
||||
system.initialize();
|
||||
|
||||
this.logger.debug(`System ${constructor.name} registered and initialized`);
|
||||
|
||||
@@ -8,6 +8,8 @@ import { Entity } from '../Entity';
|
||||
import { ComponentType } from '../Core/ComponentStorage';
|
||||
import { ComponentSerializer, SerializedComponent } from './ComponentSerializer';
|
||||
import { IScene } from '../IScene';
|
||||
import { HierarchyComponent } from '../Components/HierarchyComponent';
|
||||
import { HierarchySystem } from '../Systems/HierarchySystem';
|
||||
|
||||
/**
|
||||
* 序列化后的实体数据
|
||||
@@ -68,9 +70,14 @@ export class EntitySerializer {
|
||||
*
|
||||
* @param entity 要序列化的实体
|
||||
* @param includeChildren 是否包含子实体(默认true)
|
||||
* @param hierarchySystem 层级系统(可选,用于获取层级信息)
|
||||
* @returns 序列化后的实体数据
|
||||
*/
|
||||
public static serialize(entity: Entity, includeChildren: boolean = true): SerializedEntity {
|
||||
public static serialize(
|
||||
entity: Entity,
|
||||
includeChildren: boolean = true,
|
||||
hierarchySystem?: HierarchySystem
|
||||
): SerializedEntity {
|
||||
const serializedComponents = ComponentSerializer.serializeComponents(
|
||||
Array.from(entity.components)
|
||||
);
|
||||
@@ -86,15 +93,24 @@ export class EntitySerializer {
|
||||
children: []
|
||||
};
|
||||
|
||||
// 序列化父实体引用
|
||||
if (entity.parent) {
|
||||
serializedEntity.parentId = entity.parent.id;
|
||||
// 通过 HierarchyComponent 获取层级信息
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (hierarchy?.parentId !== null && hierarchy?.parentId !== undefined) {
|
||||
serializedEntity.parentId = hierarchy.parentId;
|
||||
}
|
||||
|
||||
// 序列化子实体
|
||||
if (includeChildren) {
|
||||
for (const child of entity.children) {
|
||||
serializedEntity.children.push(this.serialize(child, true));
|
||||
// 直接使用 HierarchyComponent.childIds 获取子实体
|
||||
if (includeChildren && hierarchy && hierarchy.childIds.length > 0) {
|
||||
// 获取场景引用:优先从 hierarchySystem,否则从 entity.scene
|
||||
const scene = hierarchySystem?.scene ?? entity.scene;
|
||||
if (scene) {
|
||||
for (const childId of hierarchy.childIds) {
|
||||
const child = scene.findEntityById(childId);
|
||||
if (child) {
|
||||
serializedEntity.children.push(this.serialize(child, true, hierarchySystem));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +125,7 @@ export class EntitySerializer {
|
||||
* @param idGenerator 实体ID生成器(用于生成新ID或保持原ID)
|
||||
* @param preserveIds 是否保持原始ID(默认false)
|
||||
* @param scene 目标场景(可选,用于设置entity.scene以支持添加组件)
|
||||
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
|
||||
* @returns 反序列化后的实体
|
||||
*/
|
||||
public static deserialize(
|
||||
@@ -116,12 +133,17 @@ export class EntitySerializer {
|
||||
componentRegistry: Map<string, ComponentType>,
|
||||
idGenerator: () => number,
|
||||
preserveIds: boolean = false,
|
||||
scene?: IScene
|
||||
scene?: IScene,
|
||||
hierarchySystem?: HierarchySystem | null,
|
||||
allEntities?: Map<number, Entity>
|
||||
): Entity {
|
||||
// 创建实体(使用原始ID或新生成的ID)
|
||||
const entityId = preserveIds ? serializedEntity.id : idGenerator();
|
||||
const entity = new Entity(serializedEntity.name, entityId);
|
||||
|
||||
// 将实体添加到收集 Map 中(用于后续添加到场景)
|
||||
allEntities?.set(entity.id, entity);
|
||||
|
||||
// 如果提供了scene,先设置entity.scene以支持添加组件
|
||||
if (scene) {
|
||||
entity.scene = scene;
|
||||
@@ -143,16 +165,28 @@ export class EntitySerializer {
|
||||
entity.addComponent(component);
|
||||
}
|
||||
|
||||
// 反序列化子实体
|
||||
// 重要:清除 HierarchyComponent 中的旧 ID
|
||||
// 当 preserveIds=false 时,序列化的 parentId 和 childIds 是旧 ID,需要重新建立
|
||||
// 通过 hierarchySystem.setParent 会正确设置新的 ID
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (hierarchy) {
|
||||
hierarchy.parentId = null;
|
||||
hierarchy.childIds = [];
|
||||
}
|
||||
|
||||
// 反序列化子实体并建立层级关系
|
||||
for (const childData of serializedEntity.children) {
|
||||
const childEntity = this.deserialize(
|
||||
childData,
|
||||
componentRegistry,
|
||||
idGenerator,
|
||||
preserveIds,
|
||||
scene
|
||||
scene,
|
||||
hierarchySystem,
|
||||
allEntities
|
||||
);
|
||||
entity.addChild(childEntity);
|
||||
// 使用 HierarchySystem 建立层级关系
|
||||
hierarchySystem?.setParent(childEntity, entity);
|
||||
}
|
||||
|
||||
return entity;
|
||||
@@ -163,19 +197,23 @@ export class EntitySerializer {
|
||||
*
|
||||
* @param entities 实体数组
|
||||
* @param includeChildren 是否包含子实体
|
||||
* @param hierarchySystem 层级系统(可选,用于获取层级信息)
|
||||
* @returns 序列化后的实体数据数组
|
||||
*/
|
||||
public static serializeEntities(
|
||||
entities: Entity[],
|
||||
includeChildren: boolean = true
|
||||
includeChildren: boolean = true,
|
||||
hierarchySystem?: HierarchySystem
|
||||
): SerializedEntity[] {
|
||||
const result: SerializedEntity[] = [];
|
||||
|
||||
for (const entity of entities) {
|
||||
// 只序列化顶层实体(没有父实体的实体)
|
||||
// 子实体会在父实体序列化时一并处理
|
||||
if (!entity.parent || !includeChildren) {
|
||||
result.push(this.serialize(entity, includeChildren));
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
const bHasParent = hierarchy?.parentId !== null && hierarchy?.parentId !== undefined;
|
||||
if (!bHasParent || !includeChildren) {
|
||||
result.push(this.serialize(entity, includeChildren, hierarchySystem));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,6 +228,7 @@ export class EntitySerializer {
|
||||
* @param idGenerator 实体ID生成器
|
||||
* @param preserveIds 是否保持原始ID
|
||||
* @param scene 目标场景(可选,用于设置entity.scene以支持添加组件)
|
||||
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
|
||||
* @returns 反序列化后的实体数组
|
||||
*/
|
||||
public static deserializeEntities(
|
||||
@@ -197,9 +236,11 @@ export class EntitySerializer {
|
||||
componentRegistry: Map<string, ComponentType>,
|
||||
idGenerator: () => number,
|
||||
preserveIds: boolean = false,
|
||||
scene?: IScene
|
||||
): Entity[] {
|
||||
const result: Entity[] = [];
|
||||
scene?: IScene,
|
||||
hierarchySystem?: HierarchySystem | null
|
||||
): { rootEntities: Entity[]; allEntities: Map<number, Entity> } {
|
||||
const rootEntities: Entity[] = [];
|
||||
const allEntities = new Map<number, Entity>();
|
||||
|
||||
for (const serialized of serializedEntities) {
|
||||
const entity = this.deserialize(
|
||||
@@ -207,12 +248,14 @@ export class EntitySerializer {
|
||||
componentRegistry,
|
||||
idGenerator,
|
||||
preserveIds,
|
||||
scene
|
||||
scene,
|
||||
hierarchySystem,
|
||||
allEntities
|
||||
);
|
||||
result.push(entity);
|
||||
rootEntities.push(entity);
|
||||
}
|
||||
|
||||
return result;
|
||||
return { rootEntities, allEntities };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,8 @@ import { ComponentSerializer, SerializedComponent } from './ComponentSerializer'
|
||||
import { SerializedEntity } from './EntitySerializer';
|
||||
import { ComponentType } from '../Core/ComponentStorage';
|
||||
import { BinarySerializer } from '../../Utils/BinarySerializer';
|
||||
import { HierarchyComponent } from '../Components/HierarchyComponent';
|
||||
import { HierarchySystem } from '../Systems/HierarchySystem';
|
||||
|
||||
/**
|
||||
* 变更操作类型
|
||||
@@ -196,6 +198,10 @@ export class IncrementalSerializer {
|
||||
for (const entity of scene.entities.buffer) {
|
||||
snapshot.entityIds.add(entity.id);
|
||||
|
||||
// 获取层级信息
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
const parentId = hierarchy?.parentId;
|
||||
|
||||
// 存储实体基本信息
|
||||
snapshot.entities.set(entity.id, {
|
||||
name: entity.name,
|
||||
@@ -203,7 +209,7 @@ export class IncrementalSerializer {
|
||||
active: entity.active,
|
||||
enabled: entity.enabled,
|
||||
updateOrder: entity.updateOrder,
|
||||
...(entity.parent && { parentId: entity.parent.id })
|
||||
...(parentId !== null && parentId !== undefined && { parentId })
|
||||
});
|
||||
|
||||
// 快照组件
|
||||
@@ -272,6 +278,10 @@ export class IncrementalSerializer {
|
||||
for (const entity of scene.entities.buffer) {
|
||||
currentEntityIds.add(entity.id);
|
||||
|
||||
// 获取层级信息
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
const parentId = hierarchy?.parentId;
|
||||
|
||||
if (!baseSnapshot.entityIds.has(entity.id)) {
|
||||
// 新增实体
|
||||
incremental.entityChanges.push({
|
||||
@@ -285,7 +295,7 @@ export class IncrementalSerializer {
|
||||
active: entity.active,
|
||||
enabled: entity.enabled,
|
||||
updateOrder: entity.updateOrder,
|
||||
...(entity.parent && { parentId: entity.parent.id }),
|
||||
...(parentId !== null && parentId !== undefined && { parentId }),
|
||||
components: [],
|
||||
children: []
|
||||
}
|
||||
@@ -312,7 +322,7 @@ export class IncrementalSerializer {
|
||||
oldData.active !== entity.active ||
|
||||
oldData.enabled !== entity.enabled ||
|
||||
oldData.updateOrder !== entity.updateOrder ||
|
||||
oldData.parentId !== entity.parent?.id;
|
||||
oldData.parentId !== parentId;
|
||||
|
||||
if (entityChanged) {
|
||||
incremental.entityChanges.push({
|
||||
@@ -324,7 +334,7 @@ export class IncrementalSerializer {
|
||||
active: entity.active,
|
||||
enabled: entity.enabled,
|
||||
updateOrder: entity.updateOrder,
|
||||
...(entity.parent && { parentId: entity.parent.id })
|
||||
...(parentId !== null && parentId !== undefined && { parentId })
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -539,16 +549,20 @@ export class IncrementalSerializer {
|
||||
if (change.entityData.enabled !== undefined) entity.enabled = change.entityData.enabled;
|
||||
if (change.entityData.updateOrder !== undefined) entity.updateOrder = change.entityData.updateOrder;
|
||||
|
||||
if (change.entityData.parentId !== undefined) {
|
||||
const newParent = scene.entities.findEntityById(change.entityData.parentId);
|
||||
if (newParent && entity.parent !== newParent) {
|
||||
if (entity.parent) {
|
||||
entity.parent.removeChild(entity);
|
||||
// 使用 HierarchySystem 更新层级关系
|
||||
const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
if (hierarchySystem) {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
const currentParentId = hierarchy?.parentId;
|
||||
|
||||
if (change.entityData.parentId !== undefined) {
|
||||
const newParent = scene.entities.findEntityById(change.entityData.parentId);
|
||||
if (newParent && currentParentId !== change.entityData.parentId) {
|
||||
hierarchySystem.setParent(entity, newParent);
|
||||
}
|
||||
newParent.addChild(entity);
|
||||
} else if (currentParentId !== null && currentParentId !== undefined) {
|
||||
hierarchySystem.setParent(entity, null);
|
||||
}
|
||||
} else if (entity.parent) {
|
||||
entity.parent.removeChild(entity);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ import { EntitySerializer, SerializedEntity } from './EntitySerializer';
|
||||
import { getComponentTypeName } from '../Decorators';
|
||||
import { getSerializationMetadata } from './SerializationDecorators';
|
||||
import { BinarySerializer } from '../../Utils/BinarySerializer';
|
||||
import { HierarchySystem } from '../Systems/HierarchySystem';
|
||||
import { HierarchyComponent } from '../Components/HierarchyComponent';
|
||||
|
||||
/**
|
||||
* 场景序列化格式
|
||||
@@ -167,8 +169,11 @@ export class SceneSerializer {
|
||||
// 过滤实体和组件
|
||||
const entities = this.filterEntities(scene, opts);
|
||||
|
||||
// 序列化实体
|
||||
const serializedEntities = EntitySerializer.serializeEntities(entities, true);
|
||||
// 获取层级系统用于序列化子实体
|
||||
const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
|
||||
// 序列化实体(传入 hierarchySystem 以正确序列化子实体)
|
||||
const serializedEntities = EntitySerializer.serializeEntities(entities, true, hierarchySystem ?? undefined);
|
||||
|
||||
// 收集组件类型信息
|
||||
const componentTypeRegistry = this.buildComponentTypeRegistry(entities);
|
||||
@@ -258,19 +263,24 @@ export class SceneSerializer {
|
||||
// ID生成器
|
||||
const idGenerator = () => scene.identifierPool.checkOut();
|
||||
|
||||
// 获取层级系统
|
||||
const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
|
||||
// 反序列化实体
|
||||
const entities = EntitySerializer.deserializeEntities(
|
||||
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
|
||||
serializedScene.entities,
|
||||
componentRegistry,
|
||||
idGenerator,
|
||||
opts.preserveIds || false,
|
||||
scene
|
||||
scene,
|
||||
hierarchySystem
|
||||
);
|
||||
|
||||
// 将实体添加到场景
|
||||
for (const entity of entities) {
|
||||
// 将所有实体添加到场景(包括子实体)
|
||||
// 先添加根实体,再递归添加子实体
|
||||
for (const entity of rootEntities) {
|
||||
scene.addEntity(entity, true);
|
||||
this.addChildrenRecursively(entity, scene);
|
||||
this.addChildrenRecursively(entity, scene, hierarchySystem, allEntities);
|
||||
}
|
||||
|
||||
// 统一清理缓存(批量操作完成后)
|
||||
@@ -285,8 +295,8 @@ export class SceneSerializer {
|
||||
// 调用所有组件的 onDeserialized 生命周期方法
|
||||
// Call onDeserialized lifecycle method on all components
|
||||
const deserializedPromises: Promise<void>[] = [];
|
||||
for (const entity of entities) {
|
||||
this.callOnDeserializedRecursively(entity, deserializedPromises);
|
||||
for (const entity of allEntities.values()) {
|
||||
this.callOnDeserializedForEntity(entity, deserializedPromises);
|
||||
}
|
||||
|
||||
// 如果有异步的 onDeserialized,在后台执行
|
||||
@@ -298,9 +308,12 @@ export class SceneSerializer {
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归调用实体及其子实体所有组件的 onDeserialized 方法
|
||||
* 调用实体所有组件的 onDeserialized 方法(不递归)
|
||||
*/
|
||||
private static callOnDeserializedRecursively(entity: Entity, promises: Promise<void>[]): void {
|
||||
private static callOnDeserializedForEntity(
|
||||
entity: Entity,
|
||||
promises: Promise<void>[]
|
||||
): void {
|
||||
for (const component of entity.components) {
|
||||
try {
|
||||
const result = component.onDeserialized();
|
||||
@@ -311,10 +324,6 @@ export class SceneSerializer {
|
||||
console.error(`Error calling onDeserialized on component ${component.constructor.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
for (const child of entity.children) {
|
||||
this.callOnDeserializedRecursively(child, promises);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -327,11 +336,27 @@ export class SceneSerializer {
|
||||
*
|
||||
* @param entity 父实体
|
||||
* @param scene 目标场景
|
||||
* @param hierarchySystem 层级系统
|
||||
*/
|
||||
private static addChildrenRecursively(entity: Entity, scene: IScene): void {
|
||||
for (const child of entity.children) {
|
||||
scene.addEntity(child, true); // 延迟缓存清理
|
||||
this.addChildrenRecursively(child, scene); // 递归处理子实体的子实体
|
||||
private static addChildrenRecursively(
|
||||
entity: Entity,
|
||||
scene: IScene,
|
||||
hierarchySystem?: HierarchySystem | null,
|
||||
childEntitiesMap?: Map<number, Entity>
|
||||
): void {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy || hierarchy.childIds.length === 0) return;
|
||||
|
||||
// 获取子实体
|
||||
// 注意:此时子实体还没有被添加到场景,所以不能用 scene.findEntityById
|
||||
// 需要从 childEntitiesMap 中查找(如果提供了的话)
|
||||
for (const childId of hierarchy.childIds) {
|
||||
// 尝试从 map 中获取,否则从场景获取(用于已添加的情况)
|
||||
const child = childEntitiesMap?.get(childId) ?? scene.findEntityById(childId);
|
||||
if (child) {
|
||||
scene.addEntity(child, true); // 延迟缓存清理
|
||||
this.addChildrenRecursively(child, scene, hierarchySystem, childEntitiesMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
549
packages/core/src/ECS/Systems/HierarchySystem.ts
Normal file
549
packages/core/src/ECS/Systems/HierarchySystem.ts
Normal file
@@ -0,0 +1,549 @@
|
||||
import { Entity } from '../Entity';
|
||||
import { EntitySystem } from './EntitySystem';
|
||||
import { Matcher } from '../Utils/Matcher';
|
||||
import { HierarchyComponent } from '../Components/HierarchyComponent';
|
||||
|
||||
/**
|
||||
* 层级关系系统 - 管理实体间的父子关系
|
||||
*
|
||||
* 提供层级操作的统一 API,维护层级缓存(depth、activeInHierarchy)。
|
||||
* 所有层级操作应通过此系统进行,而非直接修改 HierarchyComponent。
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const hierarchySystem = scene.getSystem(HierarchySystem);
|
||||
*
|
||||
* // 设置父子关系
|
||||
* hierarchySystem.setParent(child, parent);
|
||||
*
|
||||
* // 查询层级
|
||||
* const parent = hierarchySystem.getParent(entity);
|
||||
* const children = hierarchySystem.getChildren(entity);
|
||||
* const depth = hierarchySystem.getDepth(entity);
|
||||
* ```
|
||||
*/
|
||||
export class HierarchySystem extends EntitySystem {
|
||||
private static readonly MAX_DEPTH = 32;
|
||||
|
||||
constructor() {
|
||||
super(Matcher.empty().all(HierarchyComponent));
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统优先级,确保在其他系统之前更新层级缓存
|
||||
*/
|
||||
public override get updateOrder(): number {
|
||||
return -1000;
|
||||
}
|
||||
|
||||
protected override process(): void {
|
||||
// 更新所有脏缓存
|
||||
for (const entity of this.entities) {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (hierarchy?.bCacheDirty) {
|
||||
this.updateHierarchyCache(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置实体的父级
|
||||
*
|
||||
* @param child - 子实体
|
||||
* @param parent - 父实体,null 表示移动到根级
|
||||
*/
|
||||
public setParent(child: Entity, parent: Entity | null): void {
|
||||
let childHierarchy = child.getComponent(HierarchyComponent);
|
||||
|
||||
// 如果子实体没有 HierarchyComponent,自动添加
|
||||
if (!childHierarchy) {
|
||||
childHierarchy = new HierarchyComponent();
|
||||
child.addComponent(childHierarchy);
|
||||
}
|
||||
|
||||
// 检查是否需要变更
|
||||
const currentParentId = childHierarchy.parentId;
|
||||
const newParentId = parent?.id ?? null;
|
||||
if (currentParentId === newParentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 防止循环引用
|
||||
if (parent && this.isAncestorOf(child, parent)) {
|
||||
throw new Error('Cannot set parent: would create circular reference');
|
||||
}
|
||||
|
||||
// 从旧父级移除
|
||||
if (currentParentId !== null) {
|
||||
const oldParent = this.scene?.findEntityById(currentParentId);
|
||||
if (oldParent) {
|
||||
const oldParentHierarchy = oldParent.getComponent(HierarchyComponent);
|
||||
if (oldParentHierarchy) {
|
||||
const idx = oldParentHierarchy.childIds.indexOf(child.id);
|
||||
if (idx !== -1) {
|
||||
oldParentHierarchy.childIds.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加到新父级
|
||||
if (parent) {
|
||||
let parentHierarchy = parent.getComponent(HierarchyComponent);
|
||||
if (!parentHierarchy) {
|
||||
parentHierarchy = new HierarchyComponent();
|
||||
parent.addComponent(parentHierarchy);
|
||||
}
|
||||
childHierarchy.parentId = parent.id;
|
||||
parentHierarchy.childIds.push(child.id);
|
||||
} else {
|
||||
childHierarchy.parentId = null;
|
||||
}
|
||||
|
||||
// 标记缓存脏
|
||||
this.markCacheDirty(child);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在指定位置插入子实体
|
||||
*
|
||||
* @param parent - 父实体
|
||||
* @param child - 子实体
|
||||
* @param index - 插入位置索引,-1 表示追加到末尾
|
||||
*/
|
||||
public insertChildAt(parent: Entity, child: Entity, index: number): void {
|
||||
let childHierarchy = child.getComponent(HierarchyComponent);
|
||||
let parentHierarchy = parent.getComponent(HierarchyComponent);
|
||||
|
||||
// 自动添加 HierarchyComponent
|
||||
if (!childHierarchy) {
|
||||
childHierarchy = new HierarchyComponent();
|
||||
child.addComponent(childHierarchy);
|
||||
}
|
||||
if (!parentHierarchy) {
|
||||
parentHierarchy = new HierarchyComponent();
|
||||
parent.addComponent(parentHierarchy);
|
||||
}
|
||||
|
||||
// 防止循环引用
|
||||
if (this.isAncestorOf(child, parent)) {
|
||||
throw new Error('Cannot set parent: would create circular reference');
|
||||
}
|
||||
|
||||
// 从旧父级移除
|
||||
if (childHierarchy.parentId !== null && childHierarchy.parentId !== parent.id) {
|
||||
const oldParent = this.scene?.findEntityById(childHierarchy.parentId);
|
||||
if (oldParent) {
|
||||
const oldParentHierarchy = oldParent.getComponent(HierarchyComponent);
|
||||
if (oldParentHierarchy) {
|
||||
const idx = oldParentHierarchy.childIds.indexOf(child.id);
|
||||
if (idx !== -1) {
|
||||
oldParentHierarchy.childIds.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新父级
|
||||
childHierarchy.parentId = parent.id;
|
||||
|
||||
// 从当前父级的子列表中移除(如果已存在)
|
||||
const existingIdx = parentHierarchy.childIds.indexOf(child.id);
|
||||
if (existingIdx !== -1) {
|
||||
parentHierarchy.childIds.splice(existingIdx, 1);
|
||||
}
|
||||
|
||||
// 插入到指定位置
|
||||
if (index < 0 || index >= parentHierarchy.childIds.length) {
|
||||
parentHierarchy.childIds.push(child.id);
|
||||
} else {
|
||||
parentHierarchy.childIds.splice(index, 0, child.id);
|
||||
}
|
||||
|
||||
// 标记缓存脏
|
||||
this.markCacheDirty(child);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除子实体(将其移动到根级)
|
||||
*/
|
||||
public removeChild(parent: Entity, child: Entity): boolean {
|
||||
const parentHierarchy = parent.getComponent(HierarchyComponent);
|
||||
const childHierarchy = child.getComponent(HierarchyComponent);
|
||||
|
||||
if (!parentHierarchy || !childHierarchy) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (childHierarchy.parentId !== parent.id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const idx = parentHierarchy.childIds.indexOf(child.id);
|
||||
if (idx !== -1) {
|
||||
parentHierarchy.childIds.splice(idx, 1);
|
||||
}
|
||||
|
||||
childHierarchy.parentId = null;
|
||||
this.markCacheDirty(child);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除所有子实体
|
||||
*/
|
||||
public removeAllChildren(parent: Entity): void {
|
||||
const parentHierarchy = parent.getComponent(HierarchyComponent);
|
||||
if (!parentHierarchy) return;
|
||||
|
||||
const childIds = [...parentHierarchy.childIds];
|
||||
for (const childId of childIds) {
|
||||
const child = this.scene?.findEntityById(childId);
|
||||
if (child) {
|
||||
this.removeChild(parent, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实体的父级
|
||||
*/
|
||||
public getParent(entity: Entity): Entity | null {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy || hierarchy.parentId === null) {
|
||||
return null;
|
||||
}
|
||||
return this.scene?.findEntityById(hierarchy.parentId) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实体的子级列表
|
||||
*/
|
||||
public getChildren(entity: Entity): Entity[] {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return [];
|
||||
|
||||
const children: Entity[] = [];
|
||||
for (const childId of hierarchy.childIds) {
|
||||
const child = this.scene?.findEntityById(childId);
|
||||
if (child) {
|
||||
children.push(child);
|
||||
}
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取子级数量
|
||||
*/
|
||||
public getChildCount(entity: Entity): number {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
return hierarchy?.childIds.length ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查实体是否有子级
|
||||
*/
|
||||
public hasChildren(entity: Entity): boolean {
|
||||
return this.getChildCount(entity) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 ancestor 是否是 entity 的祖先
|
||||
*/
|
||||
public isAncestorOf(ancestor: Entity, entity: Entity): boolean {
|
||||
let current = this.getParent(entity);
|
||||
let depth = 0;
|
||||
|
||||
while (current && depth < HierarchySystem.MAX_DEPTH) {
|
||||
if (current.id === ancestor.id) {
|
||||
return true;
|
||||
}
|
||||
current = this.getParent(current);
|
||||
depth++;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 descendant 是否是 entity 的后代
|
||||
*/
|
||||
public isDescendantOf(descendant: Entity, entity: Entity): boolean {
|
||||
return this.isAncestorOf(entity, descendant);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取根实体
|
||||
*/
|
||||
public getRoot(entity: Entity): Entity {
|
||||
let current = entity;
|
||||
let parent = this.getParent(current);
|
||||
let depth = 0;
|
||||
|
||||
while (parent && depth < HierarchySystem.MAX_DEPTH) {
|
||||
current = parent;
|
||||
parent = this.getParent(current);
|
||||
depth++;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取实体在层级中的深度
|
||||
*/
|
||||
public getDepth(entity: Entity): number {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return 0;
|
||||
|
||||
// 如果缓存有效,直接返回
|
||||
if (!hierarchy.bCacheDirty) {
|
||||
return hierarchy.depth;
|
||||
}
|
||||
|
||||
// 重新计算
|
||||
let depth = 0;
|
||||
let current = this.getParent(entity);
|
||||
while (current && depth < HierarchySystem.MAX_DEPTH) {
|
||||
depth++;
|
||||
current = this.getParent(current);
|
||||
}
|
||||
|
||||
hierarchy.depth = depth;
|
||||
return depth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查实体在层级中是否激活
|
||||
*/
|
||||
public isActiveInHierarchy(entity: Entity): boolean {
|
||||
if (!entity.active) return false;
|
||||
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return entity.active;
|
||||
|
||||
// 如果缓存有效,直接返回
|
||||
if (!hierarchy.bCacheDirty) {
|
||||
return hierarchy.bActiveInHierarchy;
|
||||
}
|
||||
|
||||
// 重新计算
|
||||
const parent = this.getParent(entity);
|
||||
if (!parent) {
|
||||
hierarchy.bActiveInHierarchy = entity.active;
|
||||
} else {
|
||||
hierarchy.bActiveInHierarchy = entity.active && this.isActiveInHierarchy(parent);
|
||||
}
|
||||
|
||||
return hierarchy.bActiveInHierarchy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有根实体(没有父级的实体)
|
||||
*/
|
||||
public getRootEntities(): Entity[] {
|
||||
const roots: Entity[] = [];
|
||||
for (const entity of this.entities) {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (hierarchy && hierarchy.parentId === null) {
|
||||
roots.push(entity);
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称查找子实体
|
||||
*
|
||||
* @param entity - 父实体
|
||||
* @param name - 子实体名称
|
||||
* @param bRecursive - 是否递归查找
|
||||
*/
|
||||
public findChild(entity: Entity, name: string, bRecursive: boolean = false): Entity | null {
|
||||
const children = this.getChildren(entity);
|
||||
|
||||
for (const child of children) {
|
||||
if (child.name === name) {
|
||||
return child;
|
||||
}
|
||||
}
|
||||
|
||||
if (bRecursive) {
|
||||
for (const child of children) {
|
||||
const found = this.findChild(child, name, true);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据标签查找子实体
|
||||
*
|
||||
* @param entity - 父实体
|
||||
* @param tag - 标签值
|
||||
* @param bRecursive - 是否递归查找
|
||||
*/
|
||||
public findChildrenByTag(entity: Entity, tag: number, bRecursive: boolean = false): Entity[] {
|
||||
const result: Entity[] = [];
|
||||
const children = this.getChildren(entity);
|
||||
|
||||
for (const child of children) {
|
||||
if ((child.tag & tag) !== 0) {
|
||||
result.push(child);
|
||||
}
|
||||
|
||||
if (bRecursive) {
|
||||
result.push(...this.findChildrenByTag(child, tag, true));
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历所有子级
|
||||
*
|
||||
* @param entity - 父实体
|
||||
* @param callback - 回调函数
|
||||
* @param bRecursive - 是否递归遍历
|
||||
*/
|
||||
public forEachChild(
|
||||
entity: Entity,
|
||||
callback: (child: Entity) => void,
|
||||
bRecursive: boolean = false
|
||||
): void {
|
||||
const children = this.getChildren(entity);
|
||||
|
||||
for (const child of children) {
|
||||
callback(child);
|
||||
|
||||
if (bRecursive) {
|
||||
this.forEachChild(child, callback, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 扁平化层级树(用于虚拟化渲染)
|
||||
*
|
||||
* @param expandedIds - 展开的实体 ID 集合
|
||||
* @returns 扁平化的节点列表
|
||||
*/
|
||||
public flattenHierarchy(expandedIds: Set<number>): Array<{
|
||||
entity: Entity;
|
||||
depth: number;
|
||||
bHasChildren: boolean;
|
||||
bIsExpanded: boolean;
|
||||
}> {
|
||||
const result: Array<{
|
||||
entity: Entity;
|
||||
depth: number;
|
||||
bHasChildren: boolean;
|
||||
bIsExpanded: boolean;
|
||||
}> = [];
|
||||
|
||||
const traverse = (entity: Entity, depth: number): void => {
|
||||
const bHasChildren = this.hasChildren(entity);
|
||||
const bIsExpanded = expandedIds.has(entity.id);
|
||||
|
||||
result.push({
|
||||
entity,
|
||||
depth,
|
||||
bHasChildren,
|
||||
bIsExpanded
|
||||
});
|
||||
|
||||
if (bHasChildren && bIsExpanded) {
|
||||
for (const child of this.getChildren(entity)) {
|
||||
traverse(child, depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const root of this.getRootEntities()) {
|
||||
traverse(root, 0);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记缓存为脏
|
||||
*/
|
||||
private markCacheDirty(entity: Entity): void {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return;
|
||||
|
||||
hierarchy.bCacheDirty = true;
|
||||
|
||||
// 递归标记所有子级
|
||||
for (const childId of hierarchy.childIds) {
|
||||
const child = this.scene?.findEntityById(childId);
|
||||
if (child) {
|
||||
this.markCacheDirty(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新层级缓存
|
||||
*/
|
||||
private updateHierarchyCache(entity: Entity): void {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return;
|
||||
|
||||
// 计算深度
|
||||
hierarchy.depth = this.getDepth(entity);
|
||||
|
||||
// 计算激活状态
|
||||
hierarchy.bActiveInHierarchy = this.isActiveInHierarchy(entity);
|
||||
|
||||
// 标记缓存有效
|
||||
hierarchy.bCacheDirty = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当实体被移除时清理层级关系
|
||||
*/
|
||||
protected onEntityRemoved(entity: Entity): void {
|
||||
const hierarchy = entity.getComponent(HierarchyComponent);
|
||||
if (!hierarchy) return;
|
||||
|
||||
// 从父级移除
|
||||
if (hierarchy.parentId !== null) {
|
||||
const parent = this.scene?.findEntityById(hierarchy.parentId);
|
||||
if (parent) {
|
||||
const parentHierarchy = parent.getComponent(HierarchyComponent);
|
||||
if (parentHierarchy) {
|
||||
const idx = parentHierarchy.childIds.indexOf(entity.id);
|
||||
if (idx !== -1) {
|
||||
parentHierarchy.childIds.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理子级:可选择销毁或移动到根级
|
||||
// 默认将子级移动到根级
|
||||
for (const childId of hierarchy.childIds) {
|
||||
const child = this.scene?.findEntityById(childId);
|
||||
if (child) {
|
||||
const childHierarchy = child.getComponent(HierarchyComponent);
|
||||
if (childHierarchy) {
|
||||
childHierarchy.parentId = null;
|
||||
this.markCacheDirty(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override dispose(): void {
|
||||
// 清理资源
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ export { ProcessingSystem } from './ProcessingSystem';
|
||||
export { PassiveSystem } from './PassiveSystem';
|
||||
export { IntervalSystem } from './IntervalSystem';
|
||||
export { WorkerEntitySystem } from './WorkerEntitySystem';
|
||||
export { HierarchySystem } from './HierarchySystem';
|
||||
|
||||
// Worker系统相关类型导出
|
||||
export type {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Entity } from './Entity';
|
||||
import type { Component } from './Component';
|
||||
import type { ComponentType } from './Core/ComponentStorage';
|
||||
import type { ComponentConstructor, ComponentInstance } from '../Types/TypeHelpers';
|
||||
import { HierarchySystem } from './Systems/HierarchySystem';
|
||||
|
||||
/**
|
||||
* 获取组件,如果不存在则抛出错误
|
||||
@@ -277,7 +278,8 @@ export class TypedEntityBuilder {
|
||||
* 添加子实体
|
||||
*/
|
||||
withChild(child: Entity): this {
|
||||
this._entity.addChild(child);
|
||||
const hierarchySystem = this._entity.scene?.getSystem(HierarchySystem);
|
||||
hierarchySystem?.setParent(child, this._entity);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ export { ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator } from './
|
||||
export * from './Systems';
|
||||
export * from './Utils';
|
||||
export * from './Decorators';
|
||||
export * from './Components';
|
||||
export { Scene } from './Scene';
|
||||
export { IScene, ISceneFactory, ISceneConfig } from './IScene';
|
||||
export { SceneManager } from './SceneManager';
|
||||
@@ -18,3 +19,4 @@ export { ReferenceTracker, getSceneByEntityId } from './Core/ReferenceTracker';
|
||||
export type { EntityRefRecord } from './Core/ReferenceTracker';
|
||||
export { ReactiveQuery, ReactiveQueryChangeType } from './Core/ReactiveQuery';
|
||||
export type { ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig } from './Core/ReactiveQuery';
|
||||
export * from './EntityTags';
|
||||
|
||||
Reference in New Issue
Block a user