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:
YHH
2025-12-01 22:28:51 +08:00
committed by GitHub
parent 189714c727
commit b42a7b4e43
468 changed files with 18301 additions and 9075 deletions

View File

@@ -1,465 +0,0 @@
import { Core } from '../src/Core';
import { Scene } from '../src/ECS/Scene';
import { SceneManager } from '../src/ECS/SceneManager';
import { Entity } from '../src/ECS/Entity';
import { Component } from '../src/ECS/Component';
import { ITimer } from '../src/Utils/Timers/ITimer';
import { Updatable } from '../src/Core/DI';
import type { IService } from '../src/Core/ServiceContainer';
import type { IUpdatable } from '../src/Types/IUpdatable';
// 测试组件
class TestComponent extends Component {
public value: number;
constructor(...args: unknown[]) {
super();
const [value = 0] = args as [number?];
this.value = value;
}
}
// 测试场景
class TestScene extends Scene {
public initializeCalled = false;
public beginCalled = false;
public endCalled = false;
public updateCallCount = 0;
public override initialize(): void {
this.initializeCalled = true;
}
public override begin(): void {
this.beginCalled = true;
}
public override end(): void {
this.endCalled = true;
}
public override update(): void {
this.updateCallCount++;
}
}
// 测试可更新服务
@Updatable()
class TestUpdatableService implements IService, IUpdatable {
public updateCallCount = 0;
public update(): void {
this.updateCallCount++;
}
public dispose(): void {
// 清理资源
}
}
describe('Core - 核心管理系统测试', () => {
let originalConsoleWarn: typeof console.warn;
beforeEach(() => {
// 清除之前的实例
(Core as any)._instance = null;
// 注意WorldManager不再是单例无需reset
// 模拟console.warn以避免测试输出
originalConsoleWarn = console.warn;
console.warn = jest.fn();
});
afterEach(() => {
// 恢复console.warn
console.warn = originalConsoleWarn;
// 清理Core实例
if (Core.Instance) {
Core.destroy();
}
});
describe('实例创建和管理', () => {
test('应该能够创建Core实例', () => {
const core = Core.create(true);
expect(core).toBeDefined();
expect(core).toBeInstanceOf(Core);
expect(core.debug).toBe(true);
expect(Core.entitySystemsEnabled).toBe(true);
});
test('应该能够通过配置对象创建Core实例', () => {
const config = {
debug: false,
enableEntitySystems: false
};
const core = Core.create(config);
expect(core.debug).toBe(false);
expect(Core.entitySystemsEnabled).toBe(false);
});
test('重复调用create应该返回同一个实例', () => {
const core1 = Core.create(true);
const core2 = Core.create(false); // 不同参数
expect(core1).toBe(core2);
});
test('应该能够获取Core实例', () => {
const core = Core.create(true);
const instance = Core.Instance;
expect(instance).toBe(core);
});
test('在未创建实例时调用update应该显示警告', () => {
Core.update(0.016);
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("Core实例未创建请先调用Core.create()"));
});
});
// 注意场景管理功能已移至SceneManager
// 相关测试请查看 SceneManager.test.ts
describe('更新循环 - 可更新服务', () => {
let core: Core;
let updatableService: TestUpdatableService;
beforeEach(() => {
core = Core.create(true);
updatableService = new TestUpdatableService();
Core.services.registerInstance(TestUpdatableService, updatableService);
});
test('应该能够更新可更新服务', () => {
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(1);
});
test('暂停状态下不应该执行更新', () => {
Core.paused = true;
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(0);
// 恢复状态
Core.paused = false;
});
test('多次更新应该累积调用', () => {
Core.update(0.016);
Core.update(0.016);
Core.update(0.016);
expect(updatableService.updateCallCount).toBe(3);
});
});
describe('服务容器集成', () => {
let core: Core;
let service1: TestUpdatableService;
beforeEach(() => {
core = Core.create(true);
service1 = new TestUpdatableService();
});
test('应该能够通过ServiceContainer注册可更新服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
// 测试更新是否被调用
Core.update(0.016);
expect(service1.updateCallCount).toBe(1);
});
test('应该能够注销服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
Core.services.unregister(TestUpdatableService);
// 测试更新不应该被调用
Core.update(0.016);
expect(service1.updateCallCount).toBe(0);
});
test('应该能够通过ServiceContainer解析服务', () => {
Core.services.registerInstance(TestUpdatableService, service1);
const retrieved = Core.services.resolve(TestUpdatableService);
expect(retrieved).toBe(service1);
});
test('解析不存在的服务应该抛出错误', () => {
expect(() => {
Core.services.resolve(TestUpdatableService);
}).toThrow();
});
});
describe('定时器系统', () => {
let core: Core;
beforeEach(() => {
core = Core.create(true);
});
test('应该能够调度定时器', () => {
let callbackExecuted = false;
let timerInstance: ITimer | null = null;
const timer = Core.schedule(0.1, false, null, (timer) => {
callbackExecuted = true;
timerInstance = timer;
});
expect(timer).toBeDefined();
// 模拟时间推进
for (let i = 0; i < 10; i++) {
Core.update(0.016); // 约160ms总计
}
expect(callbackExecuted).toBe(true);
expect(timerInstance).toBe(timer);
});
test('应该能够调度重复定时器', () => {
let callbackCount = 0;
Core.schedule(0.05, true, null, () => {
callbackCount++;
});
// 模拟足够长的时间以触发多次回调
for (let i = 0; i < 15; i++) {
Core.update(0.016); // 约240ms总计应该触发4-5次
}
expect(callbackCount).toBeGreaterThan(1);
});
test('应该支持带上下文的定时器', () => {
const context = { value: 42 };
let receivedContext: any = null;
Core.schedule(0.05, false, context, function(this: any, timer) {
receivedContext = this;
});
// 模拟时间推进
for (let i = 0; i < 5; i++) {
Core.update(0.016);
}
expect(receivedContext).toBe(context);
});
});
describe('调试功能', () => {
test('应该能够启用调试功能', () => {
const core = Core.create(true);
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(Core.isDebugEnabled).toBe(true);
});
test('应该能够禁用调试功能', () => {
const core = Core.create(true);
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
Core.disableDebug();
expect(Core.isDebugEnabled).toBe(false);
});
test('在未创建实例时启用调试应该显示警告', () => {
const debugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
autoReconnect: true,
updateInterval: 1000,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("Core实例未创建请先调用Core.create()"));
});
});
// ECS API 现在由 SceneManager 管理
// 相关测试请查看 SceneManager.test.ts
describe('性能监控集成', () => {
let core: Core;
beforeEach(() => {
core = Core.create(true);
});
test('调试模式下应该启用性能监控', () => {
const performanceMonitor = (core as any)._performanceMonitor;
expect(performanceMonitor).toBeDefined();
// 性能监控器应该在调试模式下被启用
expect(performanceMonitor.isEnabled).toBe(true);
});
test('更新循环应该包含性能监控', () => {
const performanceMonitor = (core as any)._performanceMonitor;
const startMonitoringSpy = jest.spyOn(performanceMonitor, 'startMonitoring');
const endMonitoringSpy = jest.spyOn(performanceMonitor, 'endMonitoring');
Core.update(0.016);
expect(startMonitoringSpy).toHaveBeenCalled();
expect(endMonitoringSpy).toHaveBeenCalled();
});
});
describe('Core.destroy() 生命周期', () => {
// 测试服务类
class TestGameService implements IService {
public disposed = false;
public value = 'test-value';
dispose(): void {
this.disposed = true;
}
}
test('destroy 后应该清理所有服务', () => {
// 创建 Core 并注册服务
Core.create({ debug: true });
const service = new TestGameService();
Core.services.registerInstance(TestGameService, service);
// 验证服务已注册
expect(Core.services.isRegistered(TestGameService)).toBe(true);
// 销毁 Core
Core.destroy();
// 验证服务的 dispose 被调用
expect(service.disposed).toBe(true);
// 验证 Core 实例已清空
expect(Core.Instance).toBeNull();
});
test('destroy 后重新 create 应该能够成功注册服务', () => {
// 第一次:创建 Core 并注册服务
Core.create({ debug: true });
Core.services.registerSingleton(TestGameService);
// 验证服务已注册
expect(Core.services.isRegistered(TestGameService)).toBe(true);
const firstService = Core.services.resolve(TestGameService);
expect(firstService).toBeDefined();
expect(firstService.value).toBe('test-value');
// 销毁 Core
Core.destroy();
// 第二次:重新创建 Core
Core.create({ debug: true });
// 应该能够重新注册相同的服务(不应该报错或 warn
expect(() => {
Core.services.registerSingleton(TestGameService);
}).not.toThrow();
// 验证服务重新注册成功
expect(Core.services.isRegistered(TestGameService)).toBe(true);
const secondService = Core.services.resolve(TestGameService);
expect(secondService).toBeDefined();
expect(secondService.value).toBe('test-value');
// 两次获取的应该是不同的实例
expect(secondService).not.toBe(firstService);
// 第一个实例应该已经被 dispose
expect(firstService.disposed).toBe(true);
});
test('destroy 后旧的服务引用不应该影响新的 Core 实例', () => {
// 第一次:创建 Core 并注册服务
Core.create({ debug: true });
const firstService = new TestGameService();
Core.services.registerInstance(TestGameService, firstService);
// 销毁 Core
Core.destroy();
// 验证旧服务被 dispose
expect(firstService.disposed).toBe(true);
// 第二次:重新创建 Core 并注册新的服务实例
Core.create({ debug: true });
const secondService = new TestGameService();
Core.services.registerInstance(TestGameService, secondService);
// 验证新服务注册成功
const resolved = Core.services.resolve(TestGameService);
expect(resolved).toBe(secondService);
expect(resolved).not.toBe(firstService);
// 新服务应该未被 dispose
expect(secondService.disposed).toBe(false);
});
test('多次调用 destroy 应该安全', () => {
Core.create({ debug: true });
const service = new TestGameService();
Core.services.registerInstance(TestGameService, service);
// 第一次 destroy
Core.destroy();
expect(service.disposed).toBe(true);
expect(Core.Instance).toBeNull();
// 第二次 destroy应该安全不抛出错误
expect(() => {
Core.destroy();
}).not.toThrow();
expect(Core.Instance).toBeNull();
});
});
});

View File

@@ -1,691 +0,0 @@
import {
EntityBuilder,
SceneBuilder,
ComponentBuilder,
ECSFluentAPI,
EntityBatchOperator,
createECSAPI,
initializeECS,
ECS
} from '../../../src/ECS/Core/FluentAPI';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { QuerySystem } from '../../../src/ECS/Core/QuerySystem';
import { TypeSafeEventSystem } from '../../../src/ECS/Core/EventSystem';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
// 测试组件
class TestComponent extends Component {
public value: number;
constructor(...args: unknown[]) {
super();
const [value = 0] = args as [number?];
this.value = value;
}
}
class PositionComponent extends Component {
public x: number;
public y: number;
constructor(...args: unknown[]) {
super();
const [x = 0, y = 0] = args as [number?, number?];
this.x = x;
this.y = y;
}
}
class VelocityComponent extends Component {
public vx: number;
public vy: number;
constructor(...args: unknown[]) {
super();
const [vx = 0, vy = 0] = args as [number?, number?];
this.vx = vx;
this.vy = vy;
}
}
// 测试系统
class TestSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TestComponent));
}
protected override process(entities: Entity[]): void {
// 测试系统
}
}
describe('FluentAPI - 流式API测试', () => {
let scene: Scene;
let querySystem: QuerySystem;
let eventSystem: TypeSafeEventSystem;
beforeEach(() => {
scene = new Scene();
querySystem = new QuerySystem();
eventSystem = new TypeSafeEventSystem();
});
describe('EntityBuilder - 实体构建器', () => {
let builder: EntityBuilder;
beforeEach(() => {
builder = new EntityBuilder(scene, scene.componentStorageManager);
});
test('应该能够创建实体构建器', () => {
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('应该能够设置实体名称', () => {
const entity = builder.named('TestEntity').build();
expect(entity.name).toBe('TestEntity');
});
test('应该能够设置实体标签', () => {
const entity = builder.tagged(42).build();
expect(entity.tag).toBe(42);
});
test('应该能够添加组件', () => {
const component = new TestComponent(100);
const entity = builder.with(component).build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.getComponent(TestComponent)).toBe(component);
});
test('应该能够添加多个组件', () => {
const comp1 = new TestComponent(100);
const comp2 = new PositionComponent(10, 20);
const comp3 = new VelocityComponent(1, 2);
const entity = builder.withComponents(comp1, comp2, comp3).build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
});
test('应该能够条件性添加组件', () => {
const comp1 = new TestComponent(100);
const comp2 = new PositionComponent(10, 20);
const entity = builder
.withIf(true, comp1)
.withIf(false, comp2)
.build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(false);
});
test('应该能够使用工厂函数创建组件', () => {
const entity = builder
.withFactory(() => new TestComponent(200))
.build();
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.getComponent(TestComponent)!.value).toBe(200);
});
test('应该能够配置组件属性', () => {
const entity = builder
.with(new TestComponent(100))
.configure(TestComponent, (comp) => {
comp.value = 300;
})
.build();
expect(entity.getComponent(TestComponent)!.value).toBe(300);
});
test('配置不存在的组件应该安全处理', () => {
expect(() => {
builder.configure(TestComponent, (comp) => {
comp.value = 300;
}).build();
}).not.toThrow();
});
test('应该能够设置实体启用状态', () => {
const entity1 = builder.enabled(true).build();
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).enabled(false).build();
expect(entity1.enabled).toBe(true);
expect(entity2.enabled).toBe(false);
});
test('应该能够设置实体活跃状态', () => {
const entity1 = builder.active(true).build();
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).active(false).build();
expect(entity1.active).toBe(true);
expect(entity2.active).toBe(false);
});
test('应该能够添加子实体', () => {
const childBuilder = new EntityBuilder(scene, scene.componentStorageManager)
.named('Child')
.with(new TestComponent(50));
const parent = builder
.named('Parent')
.withChild(childBuilder)
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child');
});
test('应该能够添加多个子实体', () => {
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
const child3 = new EntityBuilder(scene, scene.componentStorageManager).named('Child3');
const parent = builder
.named('Parent')
.withChildren(child1, child2, child3)
.build();
expect(parent.children.length).toBe(3);
expect(parent.children[0].name).toBe('Child1');
expect(parent.children[1].name).toBe('Child2');
expect(parent.children[2].name).toBe('Child3');
});
test('应该能够使用工厂函数创建子实体', () => {
const parent = builder
.named('Parent')
.withChildFactory((parentEntity) => {
return new EntityBuilder(scene, scene.componentStorageManager)
.named(`Child_of_${parentEntity.name}`)
.with(new TestComponent(100));
})
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child_of_Parent');
});
test('应该能够条件性添加子实体', () => {
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
const parent = builder
.named('Parent')
.withChildIf(true, child1)
.withChildIf(false, child2)
.build();
expect(parent.children.length).toBe(1);
expect(parent.children[0].name).toBe('Child1');
});
test('应该能够构建实体并添加到场景', () => {
const entity = builder
.named('SpawnedEntity')
.with(new TestComponent(100))
.spawn();
expect(entity.name).toBe('SpawnedEntity');
expect(entity.scene).toBe(scene);
});
test('应该能够克隆构建器', () => {
const originalBuilder = builder.named('Original').with(new TestComponent(100));
const clonedBuilder = originalBuilder.clone();
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
expect(clonedBuilder).not.toBe(originalBuilder);
});
test('流式调用应该工作正常', () => {
const entity = builder
.named('ComplexEntity')
.tagged(42)
.with(new TestComponent(100))
.with(new PositionComponent(10, 20))
.enabled(true)
.active(true)
.configure(TestComponent, (comp) => {
comp.value = 200;
})
.build();
expect(entity.name).toBe('ComplexEntity');
expect(entity.tag).toBe(42);
expect(entity.enabled).toBe(true);
expect(entity.active).toBe(true);
expect(entity.hasComponent(TestComponent)).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.getComponent(TestComponent)!.value).toBe(200);
});
});
describe('SceneBuilder - 场景构建器', () => {
let builder: SceneBuilder;
beforeEach(() => {
builder = new SceneBuilder();
});
test('应该能够创建场景构建器', () => {
expect(builder).toBeInstanceOf(SceneBuilder);
});
test('应该能够设置场景名称', () => {
const scene = builder.named('TestScene').build();
expect(scene.name).toBe('TestScene');
});
test('应该能够添加实体', () => {
const entity = new Entity('TestEntity', 1);
const scene = builder.withEntity(entity).build();
expect(scene.entities.count).toBe(1);
expect(scene.findEntity('TestEntity')).toBe(entity);
});
test('应该能够使用实体构建器添加实体', () => {
const scene = builder
.withEntityBuilder((builder) => {
return builder
.named('BuilderEntity')
.with(new TestComponent(100));
})
.build();
expect(scene.entities.count).toBe(1);
expect(scene.findEntity('BuilderEntity')).not.toBeNull();
});
test('应该能够批量添加实体', () => {
const entity1 = new Entity('Entity1', 1);
const entity2 = new Entity('Entity2', 2);
const entity3 = new Entity('Entity3', 3);
const scene = builder
.withEntities(entity1, entity2, entity3)
.build();
expect(scene.entities.count).toBe(3);
});
test('应该能够添加系统', () => {
const system = new TestSystem();
const scene = builder.withSystem(system).build();
expect(scene.systems.length).toBe(1);
expect(scene.systems[0]).toBe(system);
});
test('应该能够批量添加系统', () => {
const system1 = new TestSystem();
const system2 = new TestSystem();
const scene = builder
.withSystems(system1, system2)
.build();
expect(scene.systems.length).toBe(1);
});
test('流式调用应该工作正常', () => {
const entity = new Entity('TestEntity', 1);
const system = new TestSystem();
const scene = builder
.named('ComplexScene')
.withEntity(entity)
.withSystem(system)
.withEntityBuilder((builder) => {
return builder.named('BuilderEntity');
})
.build();
expect(scene.name).toBe('ComplexScene');
expect(scene.entities.count).toBe(2);
expect(scene.systems.length).toBe(1);
});
});
describe('ComponentBuilder - 组件构建器', () => {
test('应该能够创建组件构建器', () => {
const builder = new ComponentBuilder(TestComponent, 100);
expect(builder).toBeInstanceOf(ComponentBuilder);
});
test('应该能够设置组件属性', () => {
const component = new ComponentBuilder(TestComponent, 100)
.set('value', 200)
.build();
expect(component.value).toBe(200);
});
test('应该能够使用配置函数', () => {
const component = new ComponentBuilder(PositionComponent, 10, 20)
.configure((comp) => {
comp.x = 30;
comp.y = 40;
})
.build();
expect(component.x).toBe(30);
expect(component.y).toBe(40);
});
test('应该能够条件性设置属性', () => {
const component = new ComponentBuilder(TestComponent, 100)
.setIf(true, 'value', 200)
.setIf(false, 'value', 300)
.build();
expect(component.value).toBe(200);
});
test('流式调用应该工作正常', () => {
const component = new ComponentBuilder(PositionComponent, 0, 0)
.set('x', 10)
.set('y', 20)
.setIf(true, 'x', 30)
.configure((comp) => {
comp.y = 40;
})
.build();
expect(component.x).toBe(30);
expect(component.y).toBe(40);
});
});
describe('ECSFluentAPI - 主API', () => {
let api: ECSFluentAPI;
beforeEach(() => {
api = new ECSFluentAPI(scene, querySystem, eventSystem);
});
test('应该能够创建ECS API', () => {
expect(api).toBeInstanceOf(ECSFluentAPI);
});
test('应该能够创建实体构建器', () => {
const builder = api.createEntity();
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('应该能够创建场景构建器', () => {
const builder = api.createScene();
expect(builder).toBeInstanceOf(SceneBuilder);
});
test('应该能够创建组件构建器', () => {
const builder = api.createComponent(TestComponent, 100);
expect(builder).toBeInstanceOf(ComponentBuilder);
});
test('应该能够创建查询构建器', () => {
const builder = api.query();
expect(builder).toBeDefined();
});
test('应该能够查找实体', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new TestComponent(100));
querySystem.setEntities([entity]);
const results = api.find(TestComponent);
expect(results.length).toBe(1);
expect(results[0]).toBe(entity);
});
test('应该能够查找第一个匹配的实体', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
entity1.addComponent(new TestComponent(100));
entity2.addComponent(new TestComponent(200));
querySystem.setEntities([entity1, entity2]);
const result = api.findFirst(TestComponent);
expect(result).not.toBeNull();
expect([entity1, entity2]).toContain(result);
});
test('查找不存在的实体应该返回null', () => {
const result = api.findFirst(TestComponent);
expect(result).toBeNull();
});
test('应该能够按名称查找实体', () => {
const entity = scene.createEntity('TestEntity');
const result = api.findByName('TestEntity');
expect(result).toBe(entity);
});
test('应该能够按标签查找实体', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
entity1.tag = 42;
entity2.tag = 42;
const results = api.findByTag(42);
expect(results.length).toBe(2);
expect(results).toContain(entity1);
expect(results).toContain(entity2);
});
test('应该能够触发同步事件', () => {
let eventReceived = false;
let eventData: any = null;
api.on('test:event', (data) => {
eventReceived = true;
eventData = data;
});
api.emit('test:event', { message: 'hello' });
expect(eventReceived).toBe(true);
expect(eventData.message).toBe('hello');
});
test('应该能够触发异步事件', async () => {
let eventReceived = false;
let eventData: any = null;
api.on('test:event', (data) => {
eventReceived = true;
eventData = data;
});
await api.emitAsync('test:event', { message: 'hello' });
expect(eventReceived).toBe(true);
expect(eventData.message).toBe('hello');
});
test('应该能够一次性监听事件', () => {
let callCount = 0;
api.once('test:event', () => {
callCount++;
});
api.emit('test:event', {});
api.emit('test:event', {});
expect(callCount).toBe(1);
});
test('应该能够移除事件监听器', () => {
let callCount = 0;
const listenerId = api.on('test:event', () => {
callCount++;
});
api.emit('test:event', {});
api.off('test:event', listenerId);
api.emit('test:event', {});
expect(callCount).toBe(1);
});
test('应该能够创建批量操作器', () => {
const entity1 = new Entity('Entity1', 1);
const entity2 = new Entity('Entity2', 2);
const batch = api.batch([entity1, entity2]);
expect(batch).toBeInstanceOf(EntityBatchOperator);
});
test('应该能够获取统计信息', () => {
const stats = api.getStats();
expect(stats).toBeDefined();
expect(stats.entityCount).toBeDefined();
expect(stats.systemCount).toBeDefined();
expect(stats.componentStats).toBeDefined();
expect(stats.queryStats).toBeDefined();
expect(stats.eventStats).toBeDefined();
});
});
describe('EntityBatchOperator - 批量操作器', () => {
let entity1: Entity;
let entity2: Entity;
let entity3: Entity;
let batchOp: EntityBatchOperator;
beforeEach(() => {
entity1 = scene.createEntity('Entity1');
entity2 = scene.createEntity('Entity2');
entity3 = scene.createEntity('Entity3');
batchOp = new EntityBatchOperator([entity1, entity2, entity3]);
});
test('应该能够创建批量操作器', () => {
expect(batchOp).toBeInstanceOf(EntityBatchOperator);
});
test('应该能够批量添加组件', () => {
const component = new TestComponent(100);
batchOp.addComponent(component);
expect(entity1.hasComponent(TestComponent)).toBe(true);
expect(entity2.hasComponent(TestComponent)).toBe(true);
expect(entity3.hasComponent(TestComponent)).toBe(true);
});
test('应该能够批量移除组件', () => {
entity1.addComponent(new TestComponent(100));
entity2.addComponent(new TestComponent(200));
entity3.addComponent(new TestComponent(300));
batchOp.removeComponent(TestComponent);
expect(entity1.hasComponent(TestComponent)).toBe(false);
expect(entity2.hasComponent(TestComponent)).toBe(false);
expect(entity3.hasComponent(TestComponent)).toBe(false);
});
test('应该能够批量设置活跃状态', () => {
batchOp.setActive(false);
expect(entity1.active).toBe(false);
expect(entity2.active).toBe(false);
expect(entity3.active).toBe(false);
});
test('应该能够批量设置标签', () => {
batchOp.setTag(42);
expect(entity1.tag).toBe(42);
expect(entity2.tag).toBe(42);
expect(entity3.tag).toBe(42);
});
test('应该能够批量执行操作', () => {
const names: string[] = [];
const indices: number[] = [];
batchOp.forEach((entity, index) => {
names.push(entity.name);
indices.push(index);
});
expect(names).toEqual(['Entity1', 'Entity2', 'Entity3']);
expect(indices).toEqual([0, 1, 2]);
});
test('应该能够过滤实体', () => {
entity1.tag = 1;
entity2.tag = 2;
entity3.tag = 1;
const filtered = batchOp.filter(entity => entity.tag === 1);
expect(filtered.count()).toBe(2);
expect(filtered.toArray()).toContain(entity1);
expect(filtered.toArray()).toContain(entity3);
});
test('应该能够获取实体数组', () => {
const entities = batchOp.toArray();
expect(entities.length).toBe(3);
expect(entities).toContain(entity1);
expect(entities).toContain(entity2);
expect(entities).toContain(entity3);
});
test('应该能够获取实体数量', () => {
expect(batchOp.count()).toBe(3);
});
test('流式调用应该工作正常', () => {
const result = batchOp
.addComponent(new TestComponent(100))
.setActive(false)
.setTag(42)
.forEach((entity) => {
entity.name = entity.name + '_Modified';
});
expect(result).toBe(batchOp);
expect(entity1.hasComponent(TestComponent)).toBe(true);
expect(entity1.active).toBe(false);
expect(entity1.tag).toBe(42);
expect(entity1.name).toBe('Entity1_Modified');
});
});
describe('工厂函数和全局API', () => {
test('createECSAPI应该创建API实例', () => {
const api = createECSAPI(scene, querySystem, eventSystem);
expect(api).toBeInstanceOf(ECSFluentAPI);
});
test('initializeECS应该初始化全局ECS', () => {
initializeECS(scene, querySystem, eventSystem);
expect(ECS).toBeInstanceOf(ECSFluentAPI);
});
test('全局ECS应该可用', () => {
initializeECS(scene, querySystem, eventSystem);
const builder = ECS.createEntity();
expect(builder).toBeInstanceOf(EntityBuilder);
});
});
});

View File

@@ -0,0 +1,321 @@
import { EntityBuilder } from '../../../../src/ECS/Core/FluentAPI/EntityBuilder';
import { Scene } from '../../../../src/ECS/Scene';
import { Component } from '../../../../src/ECS/Component';
import { HierarchySystem } from '../../../../src/ECS/Systems/HierarchySystem';
import { ECSComponent } from '../../../../src/ECS/Decorators';
@ECSComponent('BuilderTestPosition')
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('BuilderTestVelocity')
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
@ECSComponent('BuilderTestHealth')
class HealthComponent extends Component {
public current: number = 100;
public max: number = 100;
}
// Helper function to create EntityBuilder
function createBuilder(scene: Scene): EntityBuilder {
return new EntityBuilder(scene, scene.componentStorageManager);
}
describe('EntityBuilder', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene({ name: 'BuilderTestScene' });
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('basic building', () => {
test('should create entity with name', () => {
const builder = createBuilder(scene);
const entity = builder.named('TestEntity').build();
expect(entity.name).toBe('TestEntity');
});
test('should create entity with tag', () => {
const builder = createBuilder(scene);
const entity = builder.tagged(0x100).build();
expect(entity.tag).toBe(0x100);
});
test('should support chaining name and tag', () => {
const entity = createBuilder(scene)
.named('ChainedEntity')
.tagged(0x200)
.build();
expect(entity.name).toBe('ChainedEntity');
expect(entity.tag).toBe(0x200);
});
});
describe('component management', () => {
test('should add single component with .with()', () => {
const entity = createBuilder(scene)
.with(new PositionComponent(10, 20))
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos).not.toBeNull();
expect(pos!.x).toBe(10);
expect(pos!.y).toBe(20);
});
test('should add multiple components with .withComponents()', () => {
const entity = createBuilder(scene)
.withComponents(
new PositionComponent(5, 10),
new VelocityComponent(),
new HealthComponent()
)
.build();
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
expect(entity.hasComponent(HealthComponent)).toBe(true);
});
test('should conditionally add component with .withIf()', () => {
const shouldAdd = true;
const shouldNotAdd = false;
const entity = createBuilder(scene)
.withIf(shouldAdd, new PositionComponent())
.withIf(shouldNotAdd, new VelocityComponent())
.build();
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(false);
});
test('should add component using factory with .withFactory()', () => {
const entity = createBuilder(scene)
.withFactory(() => new PositionComponent(100, 200))
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos).not.toBeNull();
expect(pos!.x).toBe(100);
expect(pos!.y).toBe(200);
});
test('should configure existing component with .configure()', () => {
const entity = createBuilder(scene)
.with(new PositionComponent(0, 0))
.configure(PositionComponent, (pos: PositionComponent) => {
pos.x = 999;
pos.y = 888;
})
.build();
const pos = entity.getComponent(PositionComponent);
expect(pos!.x).toBe(999);
expect(pos!.y).toBe(888);
});
test('.configure() should do nothing if component does not exist', () => {
const entity = createBuilder(scene)
.configure(PositionComponent, (pos: PositionComponent) => {
pos.x = 100;
})
.build();
expect(entity.hasComponent(PositionComponent)).toBe(false);
});
});
describe('entity state', () => {
test('should set enabled state', () => {
const disabledEntity = createBuilder(scene)
.enabled(false)
.build();
const enabledEntity = createBuilder(scene)
.enabled(true)
.build();
expect(disabledEntity.enabled).toBe(false);
expect(enabledEntity.enabled).toBe(true);
});
test('should set active state', () => {
const inactiveEntity = createBuilder(scene)
.active(false)
.build();
const activeEntity = createBuilder(scene)
.active(true)
.build();
expect(inactiveEntity.active).toBe(false);
expect(activeEntity.active).toBe(true);
});
});
describe('hierarchy building', () => {
test('should call withChild method', () => {
const childBuilder = createBuilder(scene).named('Child');
const builder = createBuilder(scene)
.named('Parent')
.withChild(childBuilder);
// withChild returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildren method', () => {
const child1Builder = createBuilder(scene).named('Child1');
const child2Builder = createBuilder(scene).named('Child2');
const builder = createBuilder(scene)
.named('Parent')
.withChildren(child1Builder, child2Builder);
// withChildren returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildFactory method', () => {
const builder = createBuilder(scene)
.named('Parent')
.with(new PositionComponent(100, 100))
.withChildFactory((parentEntity) => {
return createBuilder(scene)
.named('ChildFromFactory')
.with(new PositionComponent(10, 20));
});
// withChildFactory returns the builder for chaining
expect(builder).toBeInstanceOf(EntityBuilder);
});
test('should call withChildIf method', () => {
const shouldAdd = true;
const shouldNotAdd = false;
const child1Builder = createBuilder(scene).named('Child1');
const builder1 = createBuilder(scene)
.named('Parent')
.withChildIf(shouldAdd, child1Builder);
expect(builder1).toBeInstanceOf(EntityBuilder);
const child2Builder = createBuilder(scene).named('Child2');
const builder2 = createBuilder(scene)
.named('Parent2')
.withChildIf(shouldNotAdd, child2Builder);
expect(builder2).toBeInstanceOf(EntityBuilder);
});
});
describe('spawning and cloning', () => {
test('should spawn entity to scene with .spawn()', () => {
const initialCount = scene.entities.count;
const entity = createBuilder(scene)
.named('SpawnedEntity')
.with(new PositionComponent())
.spawn();
expect(scene.entities.count).toBe(initialCount + 1);
expect(scene.findEntityById(entity.id)).toBe(entity);
});
test('.build() should not add to scene automatically', () => {
const initialCount = scene.entities.count;
createBuilder(scene)
.named('BuiltEntity')
.build();
expect(scene.entities.count).toBe(initialCount);
});
test('should clone builder', () => {
const builder = createBuilder(scene)
.named('OriginalEntity')
.tagged(0x50);
const clonedBuilder = builder.clone();
expect(clonedBuilder).not.toBe(builder);
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
});
});
describe('complex building scenarios', () => {
test('should build complete entity with all options', () => {
const entity = createBuilder(scene)
.named('CompleteEntity')
.tagged(0x100)
.with(new PositionComponent(50, 75))
.with(new VelocityComponent())
.withFactory(() => new HealthComponent())
.configure(HealthComponent, (h: HealthComponent) => {
h.current = 80;
h.max = 100;
})
.enabled(true)
.active(true)
.build();
expect(entity.name).toBe('CompleteEntity');
expect(entity.tag).toBe(0x100);
expect(entity.enabled).toBe(true);
expect(entity.active).toBe(true);
expect(entity.hasComponent(PositionComponent)).toBe(true);
expect(entity.hasComponent(VelocityComponent)).toBe(true);
expect(entity.hasComponent(HealthComponent)).toBe(true);
const health = entity.getComponent(HealthComponent);
expect(health!.current).toBe(80);
expect(health!.max).toBe(100);
});
test('should support complex chaining', () => {
const builder = createBuilder(scene)
.named('Root')
.with(new PositionComponent(1, 1));
// Add child builder chain
const childBuilder = createBuilder(scene)
.named('Child')
.with(new PositionComponent(2, 2));
// Chain withChild
builder.withChild(childBuilder);
// Build and spawn
const root = builder.spawn();
expect(root.name).toBe('Root');
expect(root.hasComponent(PositionComponent)).toBe(true);
});
});
});

View File

@@ -1,274 +0,0 @@
import { describe, test, expect, beforeEach } from '@jest/globals';
import { Scene } from '../../src/ECS/Scene';
import { Component } from '../../src/ECS/Component';
import { Entity } from '../../src/ECS/Entity';
import { EntityRef, ECSComponent } from '../../src/ECS/Decorators';
@ECSComponent('ParentRef')
class ParentComponent extends Component {
@EntityRef() parent: Entity | null = null;
}
@ECSComponent('TargetRef')
class TargetComponent extends Component {
@EntityRef() target: Entity | null = null;
@EntityRef() ally: Entity | null = null;
}
describe('EntityRef Integration Tests', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
describe('基础功能', () => {
test('应该支持EntityRef装饰器', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(comp.parent).toBe(entity2);
});
test('Entity销毁时应该自动清理所有引用', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const comp1 = child1.addComponent(new ParentComponent());
const comp2 = child2.addComponent(new ParentComponent());
comp1.parent = parent;
comp2.parent = parent;
expect(comp1.parent).toBe(parent);
expect(comp2.parent).toBe(parent);
parent.destroy();
expect(comp1.parent).toBeNull();
expect(comp2.parent).toBeNull();
});
test('修改引用应该更新ReferenceTracker', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const entity3 = scene.createEntity('Entity3');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
comp.parent = entity3;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
expect(scene.referenceTracker.getReferencesTo(entity3.id)).toHaveLength(1);
});
test('设置为null应该注销引用', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
comp.parent = null;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
});
});
describe('Component生命周期', () => {
test('移除Component应该清理其所有引用注册', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
entity1.removeComponent(comp);
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
});
test('移除Component应该清除entityId引用', () => {
const entity1 = scene.createEntity('Entity1');
const comp = entity1.addComponent(new ParentComponent());
expect(comp.entityId).toBe(entity1.id);
entity1.removeComponent(comp);
expect(comp.entityId).toBeNull();
});
});
describe('多属性引用', () => {
test('应该支持同一Component的多个EntityRef属性', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const entity3 = scene.createEntity('Entity3');
const comp = entity1.addComponent(new TargetComponent());
comp.target = entity2;
comp.ally = entity3;
expect(comp.target).toBe(entity2);
expect(comp.ally).toBe(entity3);
entity2.destroy();
expect(comp.target).toBeNull();
expect(comp.ally).toBe(entity3);
entity3.destroy();
expect(comp.ally).toBeNull();
});
});
describe('边界情况', () => {
test('跨Scene引用应该失败', () => {
const scene2 = new Scene({ name: 'TestScene2' });
const entity1 = scene.createEntity('Entity1');
const entity2 = scene2.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
expect(comp.parent).toBeNull();
});
test('引用已销毁的Entity应该失败', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
entity2.destroy();
comp.parent = entity2;
expect(comp.parent).toBeNull();
});
test('重复设置相同值不应重复注册', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
comp.parent = entity2;
comp.parent = entity2;
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
});
test('循环引用应该正常工作', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp1 = entity1.addComponent(new ParentComponent());
const comp2 = entity2.addComponent(new ParentComponent());
comp1.parent = entity2;
comp2.parent = entity1;
expect(comp1.parent).toBe(entity2);
expect(comp2.parent).toBe(entity1);
entity1.destroy();
expect(comp2.parent).toBeNull();
expect(entity2.isDestroyed).toBe(false);
});
});
describe('复杂场景', () => {
test('父子实体销毁应该正确清理引用', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const observer = scene.createEntity('Observer');
parent.addChild(child1);
parent.addChild(child2);
const observerComp = observer.addComponent(new TargetComponent());
observerComp.target = parent;
observerComp.ally = child1;
expect(observerComp.target).toBe(parent);
expect(observerComp.ally).toBe(child1);
parent.destroy();
expect(observerComp.target).toBeNull();
expect(observerComp.ally).toBeNull();
expect(child1.isDestroyed).toBe(true);
expect(child2.isDestroyed).toBe(true);
});
test('大量引用场景', () => {
const target = scene.createEntity('Target');
const entities: Entity[] = [];
const components: ParentComponent[] = [];
for (let i = 0; i < 100; i++) {
const entity = scene.createEntity(`Entity${i}`);
const comp = entity.addComponent(new ParentComponent());
comp.parent = target;
entities.push(entity);
components.push(comp);
}
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(100);
target.destroy();
for (const comp of components) {
expect(comp.parent).toBeNull();
}
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(0);
});
test('批量销毁后引用应全部清理', () => {
const entities: Entity[] = [];
const components: TargetComponent[] = [];
for (let i = 0; i < 50; i++) {
entities.push(scene.createEntity(`Entity${i}`));
}
for (let i = 0; i < 50; i++) {
const comp = entities[i].addComponent(new TargetComponent());
if (i > 0) {
comp.target = entities[i - 1];
}
if (i < 49) {
comp.ally = entities[i + 1];
}
components.push(comp);
}
scene.destroyAllEntities();
for (const comp of components) {
expect(comp.target).toBeNull();
expect(comp.ally).toBeNull();
}
});
});
describe('调试功能', () => {
test('getDebugInfo应该返回引用信息', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const comp = entity1.addComponent(new ParentComponent());
comp.parent = entity2;
const debugInfo = scene.referenceTracker.getDebugInfo();
expect(debugInfo).toHaveProperty(`entity_${entity2.id}`);
});
});
});

View File

@@ -0,0 +1,237 @@
import {
EntityTags,
hasEntityTag,
addEntityTag,
removeEntityTag,
isFolder,
isHidden,
isLocked
} from '../../src/ECS/EntityTags';
describe('EntityTags', () => {
describe('tag constants', () => {
test('should have correct NONE value', () => {
expect(EntityTags.NONE).toBe(0x0000);
});
test('should have correct FOLDER value', () => {
expect(EntityTags.FOLDER).toBe(0x1000);
});
test('should have correct HIDDEN value', () => {
expect(EntityTags.HIDDEN).toBe(0x2000);
});
test('should have correct LOCKED value', () => {
expect(EntityTags.LOCKED).toBe(0x4000);
});
test('should have correct EDITOR_ONLY value', () => {
expect(EntityTags.EDITOR_ONLY).toBe(0x8000);
});
test('should have correct PREFAB_INSTANCE value', () => {
expect(EntityTags.PREFAB_INSTANCE).toBe(0x0100);
});
test('should have correct PREFAB_ROOT value', () => {
expect(EntityTags.PREFAB_ROOT).toBe(0x0200);
});
test('all tags should have unique values', () => {
const values = Object.values(EntityTags).filter((v) => typeof v === 'number');
const uniqueValues = new Set(values);
expect(uniqueValues.size).toBe(values.length);
});
});
describe('hasEntityTag', () => {
test('should return true when tag is present', () => {
const tag = EntityTags.FOLDER;
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
});
test('should return false when tag is not present', () => {
const tag = EntityTags.FOLDER;
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(false);
});
test('should work with combined tags', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
expect(hasEntityTag(combined, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(combined, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(combined, EntityTags.LOCKED)).toBe(true);
expect(hasEntityTag(combined, EntityTags.EDITOR_ONLY)).toBe(false);
});
test('should return false for NONE tag', () => {
const tag = EntityTags.NONE;
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
});
});
describe('addEntityTag', () => {
test('should add tag to empty tags', () => {
const result = addEntityTag(EntityTags.NONE, EntityTags.FOLDER);
expect(result).toBe(EntityTags.FOLDER);
});
test('should add tag to existing tags', () => {
const existing = EntityTags.FOLDER as number;
const result = addEntityTag(existing, EntityTags.HIDDEN);
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(true);
});
test('should not change value when adding same tag', () => {
const existing = EntityTags.FOLDER as number;
const result = addEntityTag(existing, EntityTags.FOLDER);
expect(result).toBe(EntityTags.FOLDER);
});
test('should handle multiple tag additions', () => {
let tag: number = EntityTags.NONE;
tag = addEntityTag(tag, EntityTags.FOLDER);
tag = addEntityTag(tag, EntityTags.HIDDEN);
tag = addEntityTag(tag, EntityTags.LOCKED);
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(true);
});
});
describe('removeEntityTag', () => {
test('should remove tag from combined tags', () => {
const combined = (EntityTags.FOLDER | EntityTags.HIDDEN) as number;
const result = removeEntityTag(combined, EntityTags.HIDDEN);
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(false);
});
test('should return same value when removing non-existent tag', () => {
const existing = EntityTags.FOLDER as number;
const result = removeEntityTag(existing, EntityTags.HIDDEN);
expect(result).toBe(EntityTags.FOLDER);
});
test('should return NONE when removing last tag', () => {
const result = removeEntityTag(EntityTags.FOLDER, EntityTags.FOLDER);
expect(result).toBe(EntityTags.NONE);
});
test('should handle multiple tag removals', () => {
let tag: number = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
tag = removeEntityTag(tag, EntityTags.FOLDER);
tag = removeEntityTag(tag, EntityTags.LOCKED);
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(false);
});
});
describe('isFolder', () => {
test('should return true for folder tag', () => {
expect(isFolder(EntityTags.FOLDER)).toBe(true);
});
test('should return true for combined tags including folder', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
expect(isFolder(combined)).toBe(true);
});
test('should return false for non-folder tag', () => {
expect(isFolder(EntityTags.HIDDEN)).toBe(false);
expect(isFolder(EntityTags.NONE)).toBe(false);
});
});
describe('isHidden', () => {
test('should return true for hidden tag', () => {
expect(isHidden(EntityTags.HIDDEN)).toBe(true);
});
test('should return true for combined tags including hidden', () => {
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
expect(isHidden(combined)).toBe(true);
});
test('should return false for non-hidden tag', () => {
expect(isHidden(EntityTags.FOLDER)).toBe(false);
expect(isHidden(EntityTags.NONE)).toBe(false);
});
});
describe('isLocked', () => {
test('should return true for locked tag', () => {
expect(isLocked(EntityTags.LOCKED)).toBe(true);
});
test('should return true for combined tags including locked', () => {
const combined = EntityTags.FOLDER | EntityTags.LOCKED;
expect(isLocked(combined)).toBe(true);
});
test('should return false for non-locked tag', () => {
expect(isLocked(EntityTags.FOLDER)).toBe(false);
expect(isLocked(EntityTags.NONE)).toBe(false);
});
});
describe('tag combinations', () => {
test('should correctly combine and identify multiple tags', () => {
const tag = (EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.PREFAB_ROOT) as number;
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(true);
expect(hasEntityTag(tag, EntityTags.PREFAB_ROOT)).toBe(true);
expect(isLocked(tag)).toBe(false);
});
test('should support complex add/remove operations', () => {
let tag: number = EntityTags.NONE;
// Add tags
tag = addEntityTag(tag, EntityTags.FOLDER);
tag = addEntityTag(tag, EntityTags.HIDDEN);
tag = addEntityTag(tag, EntityTags.LOCKED);
tag = addEntityTag(tag, EntityTags.EDITOR_ONLY);
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(true);
expect(isLocked(tag)).toBe(true);
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
// Remove some tags
tag = removeEntityTag(tag, EntityTags.HIDDEN);
tag = removeEntityTag(tag, EntityTags.LOCKED);
expect(isFolder(tag)).toBe(true);
expect(isHidden(tag)).toBe(false);
expect(isLocked(tag)).toBe(false);
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
});
test('should work correctly with prefab tags', () => {
const prefabInstanceTag = EntityTags.PREFAB_INSTANCE as number;
const prefabRootTag = EntityTags.PREFAB_ROOT as number;
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_INSTANCE)).toBe(true);
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_ROOT)).toBe(false);
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_ROOT)).toBe(true);
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_INSTANCE)).toBe(false);
// Combine both
const combined = (prefabInstanceTag | prefabRootTag) as number;
expect(hasEntityTag(combined, EntityTags.PREFAB_INSTANCE)).toBe(true);
expect(hasEntityTag(combined, EntityTags.PREFAB_ROOT)).toBe(true);
});
});
});

View File

@@ -0,0 +1,648 @@
import { Scene, Entity, HierarchyComponent, HierarchySystem } from '../../src';
describe('HierarchySystem', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene();
scene.initialize();
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('setParent', () => {
it('should set parent-child relationship', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getParent(child)).toBe(parent);
expect(hierarchySystem.getChildren(parent)).toContain(child);
expect(hierarchySystem.getChildCount(parent)).toBe(1);
});
it('should auto-add HierarchyComponent if not present', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
expect(parent.getComponent(HierarchyComponent)).toBeNull();
expect(child.getComponent(HierarchyComponent)).toBeNull();
hierarchySystem.setParent(child, parent);
expect(parent.getComponent(HierarchyComponent)).not.toBeNull();
expect(child.getComponent(HierarchyComponent)).not.toBeNull();
});
it('should move child to root when parent is null', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getParent(child)).toBe(parent);
hierarchySystem.setParent(child, null);
expect(hierarchySystem.getParent(child)).toBeNull();
expect(hierarchySystem.getChildren(parent)).not.toContain(child);
});
it('should transfer child to new parent', () => {
const parent1 = scene.createEntity('Parent1');
const parent2 = scene.createEntity('Parent2');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent1);
expect(hierarchySystem.getParent(child)).toBe(parent1);
expect(hierarchySystem.getChildCount(parent1)).toBe(1);
hierarchySystem.setParent(child, parent2);
expect(hierarchySystem.getParent(child)).toBe(parent2);
expect(hierarchySystem.getChildCount(parent1)).toBe(0);
expect(hierarchySystem.getChildCount(parent2)).toBe(1);
});
it('should throw error on circular reference', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, parent);
hierarchySystem.setParent(grandchild, child);
expect(() => {
hierarchySystem.setParent(parent, grandchild);
}).toThrow('Cannot set parent: would create circular reference');
});
it('should not change if setting same parent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const hierarchy = child.getComponent(HierarchyComponent)!;
hierarchy.bCacheDirty = false;
hierarchySystem.setParent(child, parent);
// Should not mark dirty since parent didn't change
expect(hierarchy.bCacheDirty).toBe(false);
});
});
describe('insertChildAt', () => {
it('should insert child at specific position', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child3, parent);
hierarchySystem.insertChildAt(parent, child2, 1);
const children = hierarchySystem.getChildren(parent);
expect(children[0]).toBe(child1);
expect(children[1]).toBe(child2);
expect(children[2]).toBe(child3);
});
it('should append child when index is -1', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.insertChildAt(parent, child2, -1);
const children = hierarchySystem.getChildren(parent);
expect(children[children.length - 1]).toBe(child2);
});
});
describe('removeChild', () => {
it('should remove child from parent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.getChildCount(parent)).toBe(1);
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(true);
expect(hierarchySystem.getChildCount(parent)).toBe(0);
expect(hierarchySystem.getParent(child)).toBeNull();
});
it('should return false if child is not a child of parent', () => {
const parent1 = scene.createEntity('Parent1');
const parent2 = scene.createEntity('Parent2');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent1);
const result = hierarchySystem.removeChild(parent2, child);
expect(result).toBe(false);
});
});
describe('removeAllChildren', () => {
it('should remove all children from parent', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
expect(hierarchySystem.getChildCount(parent)).toBe(3);
hierarchySystem.removeAllChildren(parent);
expect(hierarchySystem.getChildCount(parent)).toBe(0);
expect(hierarchySystem.getParent(child1)).toBeNull();
expect(hierarchySystem.getParent(child2)).toBeNull();
expect(hierarchySystem.getParent(child3)).toBeNull();
});
});
describe('hierarchy queries', () => {
it('should check if entity has children', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
expect(hierarchySystem.hasChildren(parent)).toBe(false);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.hasChildren(parent)).toBe(true);
});
it('should check isAncestorOf', () => {
const grandparent = scene.createEntity('Grandparent');
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(parent, grandparent);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isAncestorOf(grandparent, child)).toBe(true);
expect(hierarchySystem.isAncestorOf(parent, child)).toBe(true);
expect(hierarchySystem.isAncestorOf(child, grandparent)).toBe(false);
});
it('should check isDescendantOf', () => {
const grandparent = scene.createEntity('Grandparent');
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(parent, grandparent);
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isDescendantOf(child, grandparent)).toBe(true);
expect(hierarchySystem.isDescendantOf(child, parent)).toBe(true);
expect(hierarchySystem.isDescendantOf(grandparent, child)).toBe(false);
});
it('should get root entity', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
expect(hierarchySystem.getRoot(grandchild)).toBe(root);
expect(hierarchySystem.getRoot(child)).toBe(root);
expect(hierarchySystem.getRoot(root)).toBe(root);
});
it('should get depth correctly', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
expect(hierarchySystem.getDepth(root)).toBe(0);
expect(hierarchySystem.getDepth(child)).toBe(1);
expect(hierarchySystem.getDepth(grandchild)).toBe(2);
});
});
describe('findChild', () => {
it('should find child by name', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Target');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const found = hierarchySystem.findChild(parent, 'Target');
expect(found).toBe(child2);
});
it('should find child recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Target');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const found = hierarchySystem.findChild(root, 'Target', true);
expect(found).toBe(grandchild);
const notFound = hierarchySystem.findChild(root, 'Target', false);
expect(notFound).toBeNull();
});
});
describe('forEachChild', () => {
it('should iterate over children', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const visited: Entity[] = [];
hierarchySystem.forEachChild(parent, (child) => {
visited.push(child);
});
expect(visited).toContain(child1);
expect(visited).toContain(child2);
expect(visited.length).toBe(2);
});
it('should iterate recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const visited: Entity[] = [];
hierarchySystem.forEachChild(root, (entity) => {
visited.push(entity);
}, true);
expect(visited).toContain(child);
expect(visited).toContain(grandchild);
expect(visited.length).toBe(2);
});
});
describe('getRootEntities', () => {
it('should return all root entities', () => {
const root1 = scene.createEntity('Root1');
const root2 = scene.createEntity('Root2');
const child = scene.createEntity('Child');
root1.addComponent(new HierarchyComponent());
root2.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root1);
const roots = hierarchySystem.getRootEntities();
expect(roots).toContain(root1);
expect(roots).toContain(root2);
expect(roots).not.toContain(child);
});
});
describe('activeInHierarchy', () => {
it('should be inactive if parent is inactive', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(true);
parent.active = false;
// Mark cache dirty to recalculate
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = true;
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
});
it('should be inactive if self is inactive', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
child.active = false;
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
});
});
});
describe('HierarchyComponent', () => {
it('should have correct default values', () => {
const component = new HierarchyComponent();
expect(component.parentId).toBeNull();
expect(component.childIds).toEqual([]);
expect(component.depth).toBe(0);
expect(component.bActiveInHierarchy).toBe(true);
expect(component.bCacheDirty).toBe(true);
});
});
describe('HierarchySystem - Extended Tests', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
beforeEach(() => {
scene = new Scene();
scene.initialize();
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
});
afterEach(() => {
scene.end();
});
describe('findChildrenByTag', () => {
it('should find children by tag', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
child1.tag = 0x01;
child2.tag = 0x02;
child3.tag = 0x01;
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
const found = hierarchySystem.findChildrenByTag(parent, 0x01);
expect(found.length).toBe(2);
expect(found).toContain(child1);
expect(found).toContain(child3);
});
it('should find children by tag recursively', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
child.tag = 0x01;
grandchild.tag = 0x01;
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const foundNonRecursive = hierarchySystem.findChildrenByTag(root, 0x01, false);
expect(foundNonRecursive.length).toBe(1);
expect(foundNonRecursive[0]).toBe(child);
const foundRecursive = hierarchySystem.findChildrenByTag(root, 0x01, true);
expect(foundRecursive.length).toBe(2);
expect(foundRecursive).toContain(child);
expect(foundRecursive).toContain(grandchild);
});
it('should return empty array when no children match tag', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
child.tag = 0x01;
hierarchySystem.setParent(child, parent);
const found = hierarchySystem.findChildrenByTag(parent, 0x02);
expect(found).toEqual([]);
});
});
describe('flattenHierarchy', () => {
it('should flatten hierarchy with expanded nodes', () => {
const root = scene.createEntity('Root');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child1, root);
hierarchySystem.setParent(child2, root);
hierarchySystem.setParent(grandchild, child1);
const expandedIds = new Set([root.id, child1.id]);
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
expect(flattened.length).toBe(4);
expect(flattened[0].entity).toBe(root);
expect(flattened[0].depth).toBe(0);
expect(flattened[0].bHasChildren).toBe(true);
expect(flattened[0].bIsExpanded).toBe(true);
});
it('should not include children of collapsed nodes', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
root.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
// Root is expanded, but child is collapsed
const expandedIds = new Set([root.id]);
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
expect(flattened.length).toBe(2);
expect(flattened[0].entity).toBe(root);
expect(flattened[1].entity).toBe(child);
expect(flattened[1].bHasChildren).toBe(true);
expect(flattened[1].bIsExpanded).toBe(false);
});
it('should return empty array when no root entities', () => {
const flattened = hierarchySystem.flattenHierarchy(new Set());
expect(flattened).toEqual([]);
});
});
describe('updateOrder', () => {
it('should have negative update order for early processing', () => {
expect(hierarchySystem.updateOrder).toBe(-1000);
});
});
describe('process - cache update', () => {
it('should update dirty caches during process', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// Cache should be dirty after setParent
const childHierarchy = child.getComponent(HierarchyComponent)!;
expect(childHierarchy.bCacheDirty).toBe(true);
// Update scene to process
scene.update();
// Cache should be clean after process
expect(childHierarchy.bCacheDirty).toBe(false);
});
});
describe('insertChildAt edge cases', () => {
it('should handle circular reference prevention', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, parent);
hierarchySystem.setParent(grandchild, child);
expect(() => {
hierarchySystem.insertChildAt(grandchild, parent, 0);
}).toThrow('Cannot set parent: would create circular reference');
});
it('should move child within same parent to different position', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
const child3 = scene.createEntity('Child3');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
hierarchySystem.setParent(child3, parent);
// Move child3 to position 0
hierarchySystem.insertChildAt(parent, child3, 0);
const children = hierarchySystem.getChildren(parent);
expect(children[0]).toBe(child3);
expect(children[1]).toBe(child1);
expect(children[2]).toBe(child2);
});
});
describe('removeChild edge cases', () => {
it('should return false when parent has no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(false);
});
it('should return false when child has no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new HierarchyComponent());
const result = hierarchySystem.removeChild(parent, child);
expect(result).toBe(false);
});
});
describe('removeAllChildren edge cases', () => {
it('should handle entity with no HierarchyComponent', () => {
const parent = scene.createEntity('Parent');
expect(() => {
hierarchySystem.removeAllChildren(parent);
}).not.toThrow();
});
});
describe('getChildren edge cases', () => {
it('should return empty array when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
const children = hierarchySystem.getChildren(entity);
expect(children).toEqual([]);
});
});
describe('getChildCount edge cases', () => {
it('should return 0 when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
expect(hierarchySystem.getChildCount(entity)).toBe(0);
});
});
describe('getDepth edge cases', () => {
it('should return 0 when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
expect(hierarchySystem.getDepth(entity)).toBe(0);
});
it('should use cached depth when cache is valid', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new HierarchyComponent());
hierarchySystem.setParent(child, parent);
// First call computes depth
const depth1 = hierarchySystem.getDepth(child);
expect(depth1).toBe(1);
// Mark cache as valid
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = false;
// Second call should use cache
const depth2 = hierarchySystem.getDepth(child);
expect(depth2).toBe(1);
});
});
describe('isActiveInHierarchy edge cases', () => {
it('should return entity.active when entity has no HierarchyComponent', () => {
const entity = scene.createEntity('Entity');
entity.active = true;
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(true);
entity.active = false;
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(false);
});
it('should use cached value when cache is valid', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// First call computes activeInHierarchy
const active1 = hierarchySystem.isActiveInHierarchy(child);
expect(active1).toBe(true);
// Mark cache as valid
const childHierarchy = child.getComponent(HierarchyComponent)!;
childHierarchy.bCacheDirty = false;
// Second call should use cache
const active2 = hierarchySystem.isActiveInHierarchy(child);
expect(active2).toBe(true);
});
});
describe('dispose', () => {
it('should not throw when disposing', () => {
expect(() => {
hierarchySystem.dispose();
}).not.toThrow();
});
});
});

View File

@@ -629,4 +629,201 @@ describe('Scene - 场景管理系统测试', () => {
scene2.end();
});
});
describe('扩展测试 - 补齐覆盖率', () => {
describe('实体标签查找', () => {
test('findEntitiesByTag 应该返回具有指定标签的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.tag = 0x01;
const entity2 = scene.createEntity('Entity2');
entity2.tag = 0x02;
const entity3 = scene.createEntity('Entity3');
entity3.tag = 0x01;
const found = scene.findEntitiesByTag(0x01);
expect(found.length).toBe(2);
expect(found).toContain(entity1);
expect(found).toContain(entity3);
});
test('findEntitiesByTag 应该在没有匹配时返回空数组', () => {
scene.createEntity('Entity1');
const found = scene.findEntitiesByTag(0xFF);
expect(found).toEqual([]);
});
});
describe('批量实体操作', () => {
test('destroyEntities 应该批量销毁实体', () => {
const entities = scene.createEntities(5, 'Entity');
expect(scene.entities.count).toBe(5);
const toDestroy = entities.slice(0, 3);
scene.destroyEntities(toDestroy);
expect(scene.entities.count).toBe(2);
});
test('destroyEntities 应该处理空数组', () => {
scene.createEntities(3, 'Entity');
expect(() => {
scene.destroyEntities([]);
}).not.toThrow();
expect(scene.entities.count).toBe(3);
});
});
describe('查询方法', () => {
test('queryAny 应该返回具有任意一个组件的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const entity3 = scene.createEntity('Entity3');
entity3.addComponent(new HealthComponent());
const result = scene.queryAny(PositionComponent, VelocityComponent);
expect(result.entities.length).toBe(2);
});
test('queryNone 应该返回不包含指定组件的实体', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const entity3 = scene.createEntity('Entity3');
const result = scene.queryNone(PositionComponent);
expect(result.entities.length).toBe(2);
expect(result.entities).toContain(entity2);
expect(result.entities).toContain(entity3);
});
test('query 应该创建类型安全的查询构建器', () => {
const builder = scene.query();
expect(builder).toBeDefined();
const matcher = builder.withAll(PositionComponent).buildMatcher();
expect(matcher).toBeDefined();
});
});
describe('服务容器', () => {
test('scene.services 应该返回服务容器', () => {
expect(scene.services).toBeDefined();
});
});
describe('系统错误处理', () => {
test('频繁出错的系统应该被自动禁用', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
class ErrorProneSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(PositionComponent));
}
protected override process(): void {
throw new Error('Intentional error');
}
}
const system = new ErrorProneSystem();
scene.addEntityProcessor(system);
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent(0, 0));
// 多次更新以触发错误阈值
for (let i = 0; i < 15; i++) {
scene.update();
}
// 系统应该被禁用
expect(system.enabled).toBe(false);
consoleSpy.mockRestore();
});
});
describe('已废弃方法', () => {
test('getEntityByName 应该作为 findEntity 的别名工作', () => {
const entity = scene.createEntity('TestEntity');
const found = scene.getEntityByName('TestEntity');
expect(found).toBe(entity);
});
test('getEntitiesByTag 应该作为 findEntitiesByTag 的别名工作', () => {
const entity = scene.createEntity('Entity');
entity.tag = 0x10;
const found = scene.getEntitiesByTag(0x10);
expect(found.length).toBe(1);
expect(found[0]).toBe(entity);
});
});
describe('系统管理扩展', () => {
test('getSystem 应该返回指定类型的系统', () => {
const movementSystem = new MovementSystem();
scene.addEntityProcessor(movementSystem);
const found = scene.getSystem(MovementSystem);
expect(found).toBe(movementSystem);
});
test('getSystem 应该在系统不存在时返回 null', () => {
const found = scene.getSystem(MovementSystem);
expect(found).toBeNull();
});
test('markSystemsOrderDirty 应该标记系统顺序为脏', () => {
const system1 = new MovementSystem();
const system2 = new RenderSystem();
scene.addEntityProcessor(system1);
scene.addEntityProcessor(system2);
// 访问 systems 以清除脏标记
const _ = scene.systems;
// 标记为脏
scene.markSystemsOrderDirty();
// 再次访问应该重新构建缓存
const systems = scene.systems;
expect(systems).toBeDefined();
});
});
describe('延迟缓存清理', () => {
test('addEntity 应该支持延迟缓存清理', () => {
scene.createEntity('Entity1');
const entity2 = new Entity('Entity2', scene.identifierPool.checkOut());
// 延迟缓存清理
scene.addEntity(entity2, true);
expect(scene.entities.count).toBe(2);
});
});
});
});

View File

@@ -0,0 +1,495 @@
import { EntitySerializer, SerializedEntity } from '../../../src/ECS/Serialization/EntitySerializer';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { HierarchyComponent } from '../../../src/ECS/Components/HierarchyComponent';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
@ECSComponent('EntitySerTest_Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('EntitySerTest_Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public vx: number = 0;
@Serialize()
public vy: number = 0;
}
describe('EntitySerializer', () => {
let scene: Scene;
let hierarchySystem: HierarchySystem;
let componentRegistry: Map<string, ComponentType>;
beforeEach(() => {
ComponentRegistry.reset();
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
ComponentRegistry.register(HierarchyComponent);
scene = new Scene({ name: 'EntitySerializerTestScene' });
hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
});
afterEach(() => {
scene.end();
});
describe('serialize', () => {
test('should serialize basic entity properties', () => {
const entity = scene.createEntity('TestEntity');
entity.tag = 42;
entity.active = false;
entity.enabled = false;
entity.updateOrder = 10;
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.id).toBe(entity.id);
expect(serialized.name).toBe('TestEntity');
expect(serialized.tag).toBe(42);
expect(serialized.active).toBe(false);
expect(serialized.enabled).toBe(false);
expect(serialized.updateOrder).toBe(10);
});
test('should serialize entity with components', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(100, 200));
entity.addComponent(new VelocityComponent());
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.components.length).toBe(2);
});
test('should serialize entity without children when includeChildren is false', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const serialized = EntitySerializer.serialize(parent, false, hierarchySystem);
expect(serialized.children).toEqual([]);
});
test('should serialize entity with children when includeChildren is true', () => {
const parent = scene.createEntity('Parent');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, parent);
hierarchySystem.setParent(child2, parent);
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
expect(serialized.children.length).toBe(2);
expect(serialized.children.some(c => c.name === 'Child1')).toBe(true);
expect(serialized.children.some(c => c.name === 'Child2')).toBe(true);
});
test('should serialize nested hierarchy', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
const grandchild = scene.createEntity('Grandchild');
hierarchySystem.setParent(child, root);
hierarchySystem.setParent(grandchild, child);
const serialized = EntitySerializer.serialize(root, true, hierarchySystem);
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].name).toBe('Child');
expect(serialized.children[0].children.length).toBe(1);
expect(serialized.children[0].children[0].name).toBe('Grandchild');
});
test('should include parentId in serialized data', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const serializedChild = EntitySerializer.serialize(child, false, hierarchySystem);
expect(serializedChild.parentId).toBe(parent.id);
});
});
describe('deserialize', () => {
test('should deserialize basic entity properties', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'DeserializedEntity',
tag: 77,
active: false,
enabled: false,
updateOrder: 5,
components: [],
children: []
};
let nextId = 1;
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false
);
expect(entity.name).toBe('DeserializedEntity');
expect(entity.tag).toBe(77);
expect(entity.active).toBe(false);
expect(entity.enabled).toBe(false);
expect(entity.updateOrder).toBe(5);
});
test('should preserve IDs when preserveIds is true', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
};
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => 1,
true
);
expect(entity.id).toBe(999);
});
test('should generate new IDs when preserveIds is false', () => {
const serialized: SerializedEntity = {
id: 999,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
};
let nextId = 100;
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false
);
expect(entity.id).toBe(100);
});
test('should deserialize components', () => {
const serialized: SerializedEntity = {
id: 1,
name: 'Entity',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [
{ type: 'EntitySerTest_Position', version: 1, data: { x: 100, y: 200 } }
],
children: []
};
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => 1,
true,
scene
);
expect(entity.hasComponent(PositionComponent)).toBe(true);
const pos = entity.getComponent(PositionComponent)!;
expect(pos.x).toBe(100);
expect(pos.y).toBe(200);
});
test('should deserialize children with hierarchy relationships', () => {
const serialized: SerializedEntity = {
id: 1,
name: 'Parent',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 2,
name: 'Child',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
]
};
let nextId = 10;
const allEntities = new Map<number, Entity>();
const entity = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false,
scene,
hierarchySystem,
allEntities
);
expect(allEntities.size).toBe(2);
// Add deserialized entities to scene so hierarchySystem can find them
for (const [, e] of allEntities) {
scene.addEntity(e);
}
const children = hierarchySystem.getChildren(entity);
expect(children.length).toBe(1);
expect(children[0].name).toBe('Child');
});
});
describe('serializeEntities', () => {
test('should serialize multiple entities', () => {
const entity1 = scene.createEntity('Entity1');
const entity2 = scene.createEntity('Entity2');
const serialized = EntitySerializer.serializeEntities([entity1, entity2], false);
expect(serialized.length).toBe(2);
});
test('should only serialize root entities when includeChildren is true', () => {
const root = scene.createEntity('Root');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, root);
const serialized = EntitySerializer.serializeEntities(
[root, child],
true,
hierarchySystem
);
// Should only have root (child is serialized inside root)
expect(serialized.length).toBe(1);
expect(serialized[0].name).toBe('Root');
expect(serialized[0].children.length).toBe(1);
});
});
describe('deserializeEntities', () => {
test('should deserialize multiple entities', () => {
const serializedEntities: SerializedEntity[] = [
{
id: 1,
name: 'Entity1',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
},
{
id: 2,
name: 'Entity2',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
];
let nextId = 100;
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedEntities,
componentRegistry,
() => nextId++,
false,
scene
);
expect(rootEntities.length).toBe(2);
expect(allEntities.size).toBe(2);
});
test('should deserialize entities with nested hierarchy', () => {
const serializedEntities: SerializedEntity[] = [
{
id: 1,
name: 'Root',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 2,
name: 'Child',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: [
{
id: 3,
name: 'Grandchild',
tag: 0,
active: true,
enabled: true,
updateOrder: 0,
components: [],
children: []
}
]
}
]
}
];
let nextId = 10;
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedEntities,
componentRegistry,
() => nextId++,
false,
scene,
hierarchySystem
);
expect(rootEntities.length).toBe(1);
expect(allEntities.size).toBe(3);
});
});
describe('clone', () => {
test('should clone entity with new ID', () => {
const original = scene.createEntity('Original');
original.tag = 99;
original.addComponent(new PositionComponent(50, 100));
// Use serialize + deserialize with scene for proper cloning
const serialized = EntitySerializer.serialize(original, false);
let nextId = 1000;
const cloned = EntitySerializer.deserialize(
serialized,
componentRegistry,
() => nextId++,
false,
scene // Pass scene so components can be added
);
expect(cloned.id).not.toBe(original.id);
expect(cloned.name).toBe('Original');
expect(cloned.tag).toBe(99);
expect(cloned.hasComponent(PositionComponent)).toBe(true);
const clonedPos = cloned.getComponent(PositionComponent)!;
expect(clonedPos.x).toBe(50);
expect(clonedPos.y).toBe(100);
});
test('should clone entity basic properties without components', () => {
// Test the clone method directly with entity that has no components
const original = scene.createEntity('Original');
original.tag = 99;
original.active = false;
original.enabled = false;
original.updateOrder = 5;
let nextId = 1000;
const cloned = EntitySerializer.clone(
original,
componentRegistry,
() => nextId++
);
expect(cloned.id).not.toBe(original.id);
expect(cloned.name).toBe('Original');
expect(cloned.tag).toBe(99);
expect(cloned.active).toBe(false);
expect(cloned.enabled).toBe(false);
expect(cloned.updateOrder).toBe(5);
});
test('should clone entity with children hierarchy data', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
// Serialize with children
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
// Verify the serialized data contains children
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].name).toBe('Child');
});
});
describe('edge cases', () => {
test('should handle entity with no components', () => {
const entity = scene.createEntity('Empty');
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.components).toEqual([]);
});
test('should handle entity with no hierarchy component', () => {
const entity = new Entity('Standalone', 999);
const serialized = EntitySerializer.serialize(entity, true);
expect(serialized.children).toEqual([]);
expect(serialized.parentId).toBeUndefined();
});
test('should handle default values in serialization', () => {
const entity = scene.createEntity('Default');
const serialized = EntitySerializer.serialize(entity, false);
expect(serialized.active).toBe(true);
expect(serialized.enabled).toBe(true);
expect(serialized.updateOrder).toBe(0);
});
});
});

View File

@@ -1,117 +0,0 @@
/**
* 父子实体序列化和反序列化测试
*
* 测试场景序列化和反序列化时父子实体关系的正确性
*/
import { Scene } from '../../../src';
describe('父子实体序列化测试', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
test('应该正确反序列化父子实体层次结构', () => {
// 创建父实体
const parent = scene.createEntity('parent');
parent.tag = 100;
// 创建2个子实体
const child1 = scene.createEntity('child1');
child1.tag = 200;
parent.addChild(child1);
const child2 = scene.createEntity('child2');
child2.tag = 200;
parent.addChild(child2);
// 创建1个顶层实体对照组
const topLevel = scene.createEntity('topLevel');
topLevel.tag = 200;
// 验证序列化前的状态
expect(scene.querySystem.queryAll().entities.length).toBe(4);
expect(scene.findEntitiesByTag(100).length).toBe(1);
expect(scene.findEntitiesByTag(200).length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证所有实体都被正确恢复
const allEntities = scene2.querySystem.queryAll().entities;
expect(allEntities.length).toBe(4);
expect(scene2.findEntitiesByTag(100).length).toBe(1);
expect(scene2.findEntitiesByTag(200).length).toBe(3);
// 验证父子关系正确恢复
const restoredParent = scene2.findEntity('parent');
expect(restoredParent).not.toBeNull();
expect(restoredParent!.children.length).toBe(2);
const restoredChild1 = scene2.findEntity('child1');
const restoredChild2 = scene2.findEntity('child2');
expect(restoredChild1).not.toBeNull();
expect(restoredChild2).not.toBeNull();
expect(restoredChild1!.parent).toBe(restoredParent);
expect(restoredChild2!.parent).toBe(restoredParent);
scene2.end();
});
test('应该正确反序列化多层级实体层次结构', () => {
// 创建多层级实体结构grandparent -> parent -> child
const grandparent = scene.createEntity('grandparent');
grandparent.tag = 1;
const parent = scene.createEntity('parent');
parent.tag = 2;
grandparent.addChild(parent);
const child = scene.createEntity('child');
child.tag = 3;
parent.addChild(child);
expect(scene.querySystem.queryAll().entities.length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证多层级结构正确恢复
expect(scene2.querySystem.queryAll().entities.length).toBe(3);
const restoredGrandparent = scene2.findEntity('grandparent');
const restoredParent = scene2.findEntity('parent');
const restoredChild = scene2.findEntity('child');
expect(restoredGrandparent).not.toBeNull();
expect(restoredParent).not.toBeNull();
expect(restoredChild).not.toBeNull();
expect(restoredParent!.parent).toBe(restoredGrandparent);
expect(restoredChild!.parent).toBe(restoredParent);
expect(restoredGrandparent!.children.length).toBe(1);
expect(restoredParent!.children.length).toBe(1);
scene2.end();
});
});

View File

@@ -0,0 +1,439 @@
import { SceneSerializer } from '../../../src/ECS/Serialization/SceneSerializer';
import { Scene } from '../../../src/ECS/Scene';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
@ECSComponent('SceneSerTest_Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('SceneSerTest_Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public vx: number = 0;
@Serialize()
public vy: number = 0;
}
describe('SceneSerializer', () => {
let scene: Scene;
let componentRegistry: Map<string, ComponentType>;
beforeEach(() => {
ComponentRegistry.reset();
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
scene = new Scene({ name: 'SceneSerializerTestScene' });
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
});
afterEach(() => {
scene.end();
});
describe('serialize', () => {
test('should serialize scene to JSON string', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent(10, 20));
scene.createEntity('Entity2').addComponent(new VelocityComponent());
const result = SceneSerializer.serialize(scene);
expect(typeof result).toBe('string');
const parsed = JSON.parse(result as string);
expect(parsed.name).toBe('SceneSerializerTestScene');
expect(parsed.entities.length).toBe(2);
});
test('should serialize scene to binary format', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { format: 'binary' });
expect(result).toBeInstanceOf(Uint8Array);
});
test('should include metadata when requested', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { includeMetadata: true });
const parsed = JSON.parse(result as string);
expect(parsed.metadata).toBeDefined();
expect(parsed.metadata.entityCount).toBe(1);
expect(parsed.timestamp).toBeDefined();
});
test('should pretty print JSON when requested', () => {
scene.createEntity('Entity');
const result = SceneSerializer.serialize(scene, { pretty: true });
expect(typeof result).toBe('string');
expect((result as string).includes('\n')).toBe(true);
expect((result as string).includes(' ')).toBe(true);
});
test('should serialize scene data', () => {
scene.sceneData.set('level', 5);
scene.sceneData.set('config', { difficulty: 'hard' });
const result = SceneSerializer.serialize(scene);
const parsed = JSON.parse(result as string);
expect(parsed.sceneData).toBeDefined();
expect(parsed.sceneData.level).toBe(5);
expect(parsed.sceneData.config.difficulty).toBe('hard');
});
test('should serialize with component filter', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent());
scene.createEntity('Entity2').addComponent(new VelocityComponent());
const result = SceneSerializer.serialize(scene, {
components: [PositionComponent]
});
const parsed = JSON.parse(result as string);
// Only entities with PositionComponent should be included
expect(parsed.entities.length).toBe(1);
});
});
describe('deserialize', () => {
test('should deserialize scene from JSON string', () => {
scene.createEntity('Entity1').addComponent(new PositionComponent(100, 200));
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.entities.count).toBe(1);
const entity = newScene.findEntity('Entity1');
expect(entity).not.toBeNull();
expect(entity!.hasComponent(PositionComponent)).toBe(true);
const pos = entity!.getComponent(PositionComponent)!;
expect(pos.x).toBe(100);
expect(pos.y).toBe(200);
newScene.end();
});
test('should deserialize scene from binary format', () => {
scene.createEntity('BinaryEntity').addComponent(new PositionComponent(50, 75));
const serialized = SceneSerializer.serialize(scene, { format: 'binary' });
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.entities.count).toBe(1);
const entity = newScene.findEntity('BinaryEntity');
expect(entity).not.toBeNull();
newScene.end();
});
test('should replace existing entities with strategy replace', () => {
scene.createEntity('Original');
const serialized = SceneSerializer.serialize(scene);
const targetScene = new Scene({ name: 'Target' });
targetScene.createEntity('Existing1');
targetScene.createEntity('Existing2');
expect(targetScene.entities.count).toBe(2);
SceneSerializer.deserialize(targetScene, serialized, {
strategy: 'replace',
componentRegistry
});
expect(targetScene.entities.count).toBe(1);
expect(targetScene.findEntity('Original')).not.toBeNull();
expect(targetScene.findEntity('Existing1')).toBeNull();
targetScene.end();
});
test('should merge with existing entities with strategy merge', () => {
scene.createEntity('FromSave');
const serialized = SceneSerializer.serialize(scene);
const targetScene = new Scene({ name: 'Target' });
targetScene.createEntity('Existing');
expect(targetScene.entities.count).toBe(1);
SceneSerializer.deserialize(targetScene, serialized, {
strategy: 'merge',
componentRegistry
});
expect(targetScene.entities.count).toBe(2);
expect(targetScene.findEntity('Existing')).not.toBeNull();
expect(targetScene.findEntity('FromSave')).not.toBeNull();
targetScene.end();
});
test('should restore scene data', () => {
scene.sceneData.set('weather', 'sunny');
scene.sceneData.set('time', 12.5);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
expect(newScene.sceneData.get('weather')).toBe('sunny');
expect(newScene.sceneData.get('time')).toBe(12.5);
newScene.end();
});
test('should call migration function when versions differ', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene);
// Manually modify version
const parsed = JSON.parse(serialized as string);
parsed.version = 0;
const modifiedSerialized = JSON.stringify(parsed);
const migrationFn = jest.fn((oldVersion, newVersion, data) => {
expect(oldVersion).toBe(0);
return data;
});
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, modifiedSerialized, {
componentRegistry,
migration: migrationFn
});
expect(migrationFn).toHaveBeenCalled();
newScene.end();
});
test('should throw on invalid JSON', () => {
const newScene = new Scene({ name: 'NewScene' });
expect(() => {
SceneSerializer.deserialize(newScene, 'invalid json{{{', { componentRegistry });
}).toThrow();
newScene.end();
});
});
describe('validate', () => {
test('should validate correct save data', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene);
const result = SceneSerializer.validate(serialized as string);
expect(result.valid).toBe(true);
expect(result.version).toBe(1);
});
test('should return errors for missing version', () => {
const invalid = JSON.stringify({ entities: [], componentTypeRegistry: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing version field');
});
test('should return errors for missing entities', () => {
const invalid = JSON.stringify({ version: 1, componentTypeRegistry: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing or invalid entities field');
});
test('should return errors for missing componentTypeRegistry', () => {
const invalid = JSON.stringify({ version: 1, entities: [] });
const result = SceneSerializer.validate(invalid);
expect(result.valid).toBe(false);
expect(result.errors).toContain('Missing or invalid componentTypeRegistry field');
});
test('should handle JSON parse errors', () => {
const result = SceneSerializer.validate('not valid json');
expect(result.valid).toBe(false);
expect(result.errors).toBeDefined();
expect(result.errors![0]).toContain('JSON parse error');
});
});
describe('getInfo', () => {
test('should return info from save data', () => {
scene.name = 'InfoTestScene';
scene.createEntity('Entity1');
scene.createEntity('Entity2');
scene.createEntity('Entity3');
const serialized = SceneSerializer.serialize(scene);
const info = SceneSerializer.getInfo(serialized as string);
expect(info).not.toBeNull();
expect(info!.name).toBe('InfoTestScene');
expect(info!.entityCount).toBe(3);
expect(info!.version).toBe(1);
});
test('should return null for invalid data', () => {
const info = SceneSerializer.getInfo('invalid');
expect(info).toBeNull();
});
test('should include timestamp when present', () => {
scene.createEntity('Entity');
const serialized = SceneSerializer.serialize(scene, { includeMetadata: true });
const info = SceneSerializer.getInfo(serialized as string);
expect(info!.timestamp).toBeDefined();
});
});
describe('scene data serialization', () => {
test('should serialize Date objects', () => {
const date = new Date('2024-01-01T00:00:00Z');
scene.sceneData.set('createdAt', date);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.createdAt.__type).toBe('Date');
});
test('should deserialize Date objects', () => {
const date = new Date('2024-01-01T00:00:00Z');
scene.sceneData.set('createdAt', date);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredDate = newScene.sceneData.get('createdAt');
expect(restoredDate).toBeInstanceOf(Date);
expect(restoredDate.getTime()).toBe(date.getTime());
newScene.end();
});
test('should serialize Map objects', () => {
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
scene.sceneData.set('mapping', map);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.mapping.__type).toBe('Map');
});
test('should deserialize Map objects', () => {
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
scene.sceneData.set('mapping', map);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredMap = newScene.sceneData.get('mapping');
expect(restoredMap).toBeInstanceOf(Map);
expect(restoredMap.get('key1')).toBe('value1');
expect(restoredMap.get('key2')).toBe('value2');
newScene.end();
});
test('should serialize Set objects', () => {
const set = new Set([1, 2, 3]);
scene.sceneData.set('numbers', set);
const serialized = SceneSerializer.serialize(scene);
const parsed = JSON.parse(serialized as string);
expect(parsed.sceneData.numbers.__type).toBe('Set');
});
test('should deserialize Set objects', () => {
const set = new Set([1, 2, 3]);
scene.sceneData.set('numbers', set);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const restoredSet = newScene.sceneData.get('numbers');
expect(restoredSet).toBeInstanceOf(Set);
expect(restoredSet.has(1)).toBe(true);
expect(restoredSet.has(2)).toBe(true);
expect(restoredSet.has(3)).toBe(true);
newScene.end();
});
});
describe('hierarchy serialization', () => {
test('should serialize and deserialize entity hierarchy', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const root = scene.createEntity('Root');
const child1 = scene.createEntity('Child1');
const child2 = scene.createEntity('Child2');
hierarchySystem.setParent(child1, root);
hierarchySystem.setParent(child2, root);
const serialized = SceneSerializer.serialize(scene);
const newScene = new Scene({ name: 'NewScene' });
const newHierarchySystem = new HierarchySystem();
newScene.addSystem(newHierarchySystem);
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
const newRoot = newScene.findEntity('Root');
expect(newRoot).not.toBeNull();
const children = newHierarchySystem.getChildren(newRoot!);
expect(children.length).toBe(2);
newScene.end();
});
});
});

View File

@@ -1,629 +0,0 @@
/**
* 序列化系统测试
*/
import { Component } from '../../../src/ECS/Component';
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import {
Serializable,
Serialize,
SerializeAsMap,
SerializeAsSet,
IgnoreSerialization,
ComponentSerializer,
EntitySerializer,
SceneSerializer,
VersionMigrationManager,
MigrationBuilder
} from '../../../src/ECS/Serialization';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 测试组件定义
@ECSComponent('Position')
@Serializable({ version: 1 })
class PositionComponent extends Component {
@Serialize()
public x: number = 0;
@Serialize()
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('Velocity')
@Serializable({ version: 1 })
class VelocityComponent extends Component {
@Serialize()
public dx: number = 0;
@Serialize()
public dy: number = 0;
}
@ECSComponent('Player')
@Serializable({ version: 1 })
class PlayerComponent extends Component {
@Serialize()
public name: string = '';
@Serialize()
public level: number = 1;
@SerializeAsMap()
public inventory: Map<string, number> = new Map();
@SerializeAsSet()
public tags: Set<string> = new Set();
@IgnoreSerialization()
public tempCache: any = null;
}
@ECSComponent('Health')
@Serializable({ version: 1 })
class HealthComponent extends Component {
@Serialize()
public current: number = 100;
@Serialize()
public max: number = 100;
}
// 非可序列化组件
class NonSerializableComponent extends Component {
public data: any = null;
}
describe('ECS Serialization System', () => {
let scene: Scene;
beforeEach(() => {
// 清空测试环境
ComponentRegistry.reset();
// 重新注册测试组件因为reset会清空所有注册
ComponentRegistry.register(PositionComponent);
ComponentRegistry.register(VelocityComponent);
ComponentRegistry.register(PlayerComponent);
ComponentRegistry.register(HealthComponent);
// 创建测试场景
scene = new Scene();
});
describe('Component Serialization', () => {
it('should serialize a simple component', () => {
const position = new PositionComponent(100, 200);
const serialized = ComponentSerializer.serialize(position);
expect(serialized).not.toBeNull();
expect(serialized!.type).toBe('Position');
expect(serialized!.version).toBe(1);
expect(serialized!.data.x).toBe(100);
expect(serialized!.data.y).toBe(200);
});
it('should deserialize a simple component', () => {
const serializedData = {
type: 'Position',
version: 1,
data: { x: 150, y: 250 }
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
const component = ComponentSerializer.deserialize(serializedData, registry);
expect(component).not.toBeNull();
expect(component).toBeInstanceOf(PositionComponent);
expect((component as PositionComponent).x).toBe(150);
expect((component as PositionComponent).y).toBe(250);
});
it('should serialize Map fields', () => {
const player = new PlayerComponent();
player.name = 'Hero';
player.level = 5;
player.inventory.set('sword', 1);
player.inventory.set('potion', 10);
const serialized = ComponentSerializer.serialize(player);
expect(serialized).not.toBeNull();
expect(serialized!.data.inventory).toEqual([
['sword', 1],
['potion', 10]
]);
});
it('should deserialize Map fields', () => {
const serializedData = {
type: 'Player',
version: 1,
data: {
name: 'Hero',
level: 5,
inventory: [
['sword', 1],
['potion', 10]
],
tags: ['warrior', 'hero']
}
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
const component = ComponentSerializer.deserialize(
serializedData,
registry
) as PlayerComponent;
expect(component).not.toBeNull();
expect(component.inventory.get('sword')).toBe(1);
expect(component.inventory.get('potion')).toBe(10);
expect(component.tags.has('warrior')).toBe(true);
expect(component.tags.has('hero')).toBe(true);
});
it('should ignore fields marked with @IgnoreSerialization', () => {
const player = new PlayerComponent();
player.tempCache = { foo: 'bar' };
const serialized = ComponentSerializer.serialize(player);
expect(serialized).not.toBeNull();
expect(serialized!.data.tempCache).toBeUndefined();
});
it('should return null for non-serializable components', () => {
const nonSerializable = new NonSerializableComponent();
const serialized = ComponentSerializer.serialize(nonSerializable);
expect(serialized).toBeNull();
});
});
describe('Entity Serialization', () => {
it('should serialize an entity with components', () => {
const entity = scene.createEntity('Player');
entity.addComponent(new PositionComponent(50, 100));
entity.addComponent(new VelocityComponent());
entity.tag = 10;
const serialized = EntitySerializer.serialize(entity);
expect(serialized.id).toBe(entity.id);
expect(serialized.name).toBe('Player');
expect(serialized.tag).toBe(10);
expect(serialized.components.length).toBe(2);
});
it('should serialize entity hierarchy', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addComponent(new PositionComponent(0, 0));
child.addComponent(new PositionComponent(10, 10));
parent.addChild(child);
const serialized = EntitySerializer.serialize(parent);
expect(serialized.children.length).toBe(1);
expect(serialized.children[0].id).toBe(child.id);
expect(serialized.children[0].name).toBe('Child');
});
it('should deserialize an entity', () => {
const serializedEntity = {
id: 1,
name: 'TestEntity',
tag: 5,
active: true,
enabled: true,
updateOrder: 0,
components: [
{
type: 'Position',
version: 1,
data: { x: 100, y: 200 }
}
],
children: []
};
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
let idCounter = 10;
const entity = EntitySerializer.deserialize(
serializedEntity,
registry,
() => idCounter++,
false,
scene
);
expect(entity.name).toBe('TestEntity');
expect(entity.tag).toBe(5);
expect(entity.components.length).toBe(1);
});
});
describe('Scene Serialization', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
it('should serialize a scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new PlayerComponent());
const saveData = scene.serialize({ format: 'json', pretty: true });
expect(saveData).toBeTruthy();
expect(typeof saveData).toBe('string');
const parsed = JSON.parse(saveData as string);
expect(parsed.name).toBe('TestScene');
expect(parsed.version).toBe(1);
expect(parsed.entities.length).toBe(2);
});
it('should deserialize a scene with replace strategy', () => {
// 创建初始实体
const entity1 = scene.createEntity('Initial');
entity1.addComponent(new PositionComponent(0, 0));
// 序列化
const entity2 = scene.createEntity('ToSave');
entity2.addComponent(new PositionComponent(100, 100));
const saveData = scene.serialize();
// 清空并重新加载
scene.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
expect(scene.entities.count).toBeGreaterThan(0);
});
it('should filter components during serialization', () => {
const entity = scene.createEntity('Mixed');
entity.addComponent(new PositionComponent(1, 2));
entity.addComponent(new PlayerComponent());
entity.addComponent(new HealthComponent());
const saveData = scene.serialize({
components: [PositionComponent, PlayerComponent],
format: 'json'
});
const parsed = JSON.parse(saveData as string);
expect(parsed.entities.length).toBeGreaterThan(0);
});
it('should preserve entity hierarchy', () => {
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
parent.addChild(child);
parent.addComponent(new PositionComponent(0, 0));
child.addComponent(new PositionComponent(10, 10));
const saveData = scene.serialize({ format: 'json' });
const parsed = JSON.parse(saveData as string);
// 只有父实体在顶层
expect(parsed.entities.length).toBe(1);
expect(parsed.entities[0].children.length).toBe(1);
});
it('should validate save data', () => {
const entity = scene.createEntity('Test');
entity.addComponent(new PositionComponent(5, 5));
const saveData = scene.serialize({ format: 'json' });
const validation = SceneSerializer.validate(saveData as string);
expect(validation.valid).toBe(true);
expect(validation.version).toBe(1);
});
it('should get save data info', () => {
const entity = scene.createEntity('InfoTest');
entity.addComponent(new PositionComponent(1, 1));
const saveData = scene.serialize({ format: 'json' });
const info = SceneSerializer.getInfo(saveData as string);
expect(info).not.toBeNull();
expect(info!.name).toBe('TestScene');
expect(info!.version).toBe(1);
});
});
describe('Version Migration', () => {
@ECSComponent('OldPlayer')
@Serializable({ version: 1 })
class OldPlayerV1 extends Component {
@Serialize()
public name: string = '';
@Serialize()
public hp: number = 100;
}
@ECSComponent('OldPlayer')
@Serializable({ version: 2 })
class OldPlayerV2 extends Component {
@Serialize()
public name: string = '';
@Serialize()
public health: number = 100; // 重命名了字段
@Serialize()
public maxHealth: number = 100; // 新增字段
}
beforeEach(() => {
VersionMigrationManager.clearMigrations();
});
it('should migrate component from v1 to v2', () => {
// 注册迁移
VersionMigrationManager.registerComponentMigration(
'OldPlayer',
1,
2,
(data) => {
return {
name: data.name,
health: data.hp,
maxHealth: data.hp
};
}
);
const v1Data = {
type: 'OldPlayer',
version: 1,
data: { name: 'Hero', hp: 80 }
};
const migrated = VersionMigrationManager.migrateComponent(v1Data, 2);
expect(migrated.version).toBe(2);
expect(migrated.data.health).toBe(80);
expect(migrated.data.maxHealth).toBe(80);
expect(migrated.data.hp).toBeUndefined();
});
it('should use MigrationBuilder for component migration', () => {
new MigrationBuilder()
.forComponent('Player')
.fromVersionToVersion(1, 2)
.migrate((data: any) => {
data.experience = 0;
return data;
});
expect(VersionMigrationManager.canMigrateComponent('Player', 1, 2)).toBe(true);
});
it('should check migration path availability', () => {
VersionMigrationManager.registerComponentMigration('Test', 1, 2, (d) => d);
VersionMigrationManager.registerComponentMigration('Test', 2, 3, (d) => d);
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 3)).toBe(true);
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 4)).toBe(false);
});
it('should get migration path', () => {
VersionMigrationManager.registerComponentMigration('PathTest', 1, 2, (d) => d);
VersionMigrationManager.registerComponentMigration('PathTest', 2, 3, (d) => d);
const path = VersionMigrationManager.getComponentMigrationPath('PathTest');
expect(path).toEqual([1, 2]);
});
});
// ComponentTypeRegistry已被移除现在使用ComponentRegistry自动管理组件类型
describe('Integration Tests', () => {
it('should perform full save/load cycle', () => {
const scene1 = new Scene({ name: 'SaveTest' });
// 创建复杂实体
const player = scene1.createEntity('Player');
const playerComp = new PlayerComponent();
playerComp.name = 'TestHero';
playerComp.level = 10;
playerComp.inventory.set('sword', 1);
playerComp.inventory.set('shield', 1);
playerComp.tags.add('warrior');
player.addComponent(playerComp);
player.addComponent(new PositionComponent(100, 200));
player.addComponent(new HealthComponent());
// 创建子实体
const weapon = scene1.createEntity('Weapon');
weapon.addComponent(new PositionComponent(5, 0));
player.addChild(weapon);
// 序列化
const saveData = scene1.serialize();
// 新场景
const scene2 = new Scene({ name: 'LoadTest' });
// 反序列化
scene2.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证
const loadedPlayer = scene2.findEntity('Player');
expect(loadedPlayer).not.toBeNull();
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
expect(loadedPlayerComp).not.toBeNull();
expect(loadedPlayerComp.name).toBe('TestHero');
expect(loadedPlayerComp.level).toBe(10);
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
expect(loadedPlayerComp.tags.has('warrior')).toBe(true);
// 验证层级结构
expect(loadedPlayer!.childCount).toBe(1);
scene1.end();
scene2.end();
});
it('should serialize and deserialize scene custom data', () => {
const scene1 = new Scene({ name: 'SceneDataTest' });
// 设置场景自定义数据
scene1.sceneData.set('weather', 'rainy');
scene1.sceneData.set('timeOfDay', 14.5);
scene1.sceneData.set('difficulty', 'hard');
scene1.sceneData.set('checkpoint', { x: 100, y: 200 });
scene1.sceneData.set('tags', new Set(['action', 'adventure']));
scene1.sceneData.set('metadata', new Map([['author', 'test'], ['version', '1.0']]));
// 序列化
const saveData = scene1.serialize();
// 新场景
const scene2 = new Scene({ name: 'LoadTest' });
// 反序列化
scene2.deserialize(saveData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证场景数据
expect(scene2.sceneData.get('weather')).toBe('rainy');
expect(scene2.sceneData.get('timeOfDay')).toBe(14.5);
expect(scene2.sceneData.get('difficulty')).toBe('hard');
expect(scene2.sceneData.get('checkpoint')).toEqual({ x: 100, y: 200 });
const tags = scene2.sceneData.get('tags');
expect(tags).toBeInstanceOf(Set);
expect(tags.has('action')).toBe(true);
expect(tags.has('adventure')).toBe(true);
const metadata = scene2.sceneData.get('metadata');
expect(metadata).toBeInstanceOf(Map);
expect(metadata.get('author')).toBe('test');
expect(metadata.get('version')).toBe('1.0');
scene1.end();
scene2.end();
});
it('should serialize and deserialize using binary format', () => {
const scene1 = new Scene({ name: 'BinaryTest' });
// 创建测试数据
const player = scene1.createEntity('Player');
const playerComp = new PlayerComponent();
playerComp.name = 'BinaryHero';
playerComp.level = 5;
playerComp.inventory.set('sword', 1);
player.addComponent(playerComp);
player.addComponent(new PositionComponent(100, 200));
scene1.sceneData.set('weather', 'sunny');
scene1.sceneData.set('score', 9999);
// 二进制序列化
const binaryData = scene1.serialize({ format: 'binary' });
// 验证是Uint8Array类型
expect(binaryData instanceof Uint8Array).toBe(true);
expect((binaryData as Uint8Array).length).toBeGreaterThan(0);
// 新场景反序列化二进制数据
const scene2 = new Scene({ name: 'LoadTest' });
scene2.deserialize(binaryData, {
strategy: 'replace',
// componentRegistry会自动从ComponentRegistry获取
});
// 验证数据完整性
const loadedPlayer = scene2.findEntity('Player');
expect(loadedPlayer).not.toBeNull();
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
expect(loadedPlayerComp.name).toBe('BinaryHero');
expect(loadedPlayerComp.level).toBe(5);
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
const loadedPos = loadedPlayer!.getComponent(PositionComponent as any) as PositionComponent;
expect(loadedPos.x).toBe(100);
expect(loadedPos.y).toBe(200);
expect(scene2.sceneData.get('weather')).toBe('sunny');
expect(scene2.sceneData.get('score')).toBe(9999);
scene1.end();
scene2.end();
});
it('should handle complex nested data in binary format', () => {
const scene1 = new Scene({ name: 'NestedBinaryTest' });
// 复杂嵌套数据
scene1.sceneData.set('config', {
graphics: {
quality: 'high',
resolution: { width: 1920, height: 1080 }
},
audio: {
masterVolume: 0.8,
effects: new Map([['music', 0.7], ['sfx', 0.9]])
},
tags: new Set(['multiplayer', 'ranked']),
timestamp: new Date('2024-01-01')
});
// 二进制序列化
const binaryData = scene1.serialize({ format: 'binary' });
// 反序列化
const scene2 = new Scene({ name: 'LoadTest' });
scene2.deserialize(binaryData, {
// componentRegistry会自动从ComponentRegistry获取
});
const config = scene2.sceneData.get('config');
expect(config.graphics.quality).toBe('high');
expect(config.graphics.resolution.width).toBe(1920);
expect(config.audio.masterVolume).toBe(0.8);
expect(config.audio.effects.get('music')).toBe(0.7);
expect(config.tags.has('multiplayer')).toBe(true);
expect(config.timestamp).toBeInstanceOf(Date);
scene1.end();
scene2.end();
});
});
});

View File

@@ -1,145 +0,0 @@
/**
* Scene查询方法测试
*/
import { Component } from '../src/ECS/Component';
import { Entity } from '../src/ECS/Entity';
import { Scene } from '../src/ECS/Scene';
import { Core } from '../src/Core';
import { ECSComponent } from '../src/ECS/Decorators';
import { EntitySystem } from '../src/ECS/Systems/EntitySystem';
@ECSComponent('Position')
class Position extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('Velocity')
class Velocity extends Component {
constructor(public dx: number = 0, public dy: number = 0) {
super();
}
}
@ECSComponent('Disabled')
class Disabled extends Component {}
describe('Scene查询方法', () => {
let scene: Scene;
beforeEach(() => {
Core.create({ debug: false, enableEntitySystems: true });
scene = new Scene();
scene.initialize();
});
afterEach(() => {
scene.end();
});
describe('基础查询方法', () => {
test('queryAll 查询拥有所有组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.addComponent(new Velocity(1, 2));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
const result = scene.queryAll(Position, Velocity);
expect(result.entities).toHaveLength(1);
expect(result.entities[0]).toBe(e1);
});
test('queryAny 查询拥有任意组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
const e2 = scene.createEntity('E2');
e2.addComponent(new Velocity(1, 2));
const e3 = scene.createEntity('E3');
e3.addComponent(new Disabled());
const result = scene.queryAny(Position, Velocity);
expect(result.entities).toHaveLength(2);
});
test('queryNone 查询不包含指定组件的实体', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.addComponent(new Disabled());
const result = scene.queryNone(Disabled);
expect(result.entities).toHaveLength(1);
expect(result.entities[0]).toBe(e1);
});
});
describe('TypedQueryBuilder', () => {
test('scene.query() 创建类型安全的查询构建器', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.addComponent(new Velocity(1, 2));
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.addComponent(new Velocity(3, 4));
e2.addComponent(new Disabled());
// 构建查询
const query = scene.query()
.withAll(Position, Velocity)
.withNone(Disabled);
const matcher = query.buildMatcher();
// 创建System使用这个matcher
class TestSystem extends EntitySystem {
public processedCount = 0;
constructor() {
super(matcher);
}
protected override process(entities: readonly Entity[]): void {
this.processedCount = entities.length;
}
}
const system = new TestSystem();
scene.addSystem(system);
scene.update();
// 应该只处理e1e2被Disabled排除
expect(system.processedCount).toBe(1);
});
test('TypedQueryBuilder 支持复杂查询', () => {
const e1 = scene.createEntity('E1');
e1.addComponent(new Position(10, 20));
e1.tag = 100;
const e2 = scene.createEntity('E2');
e2.addComponent(new Position(30, 40));
e2.tag = 200;
const query = scene.query()
.withAll(Position)
.withTag(100);
const condition = query.getCondition();
expect(condition.all).toContain(Position as any);
expect(condition.tag).toBe(100);
});
});
});

View File

@@ -1,205 +0,0 @@
/**
* TypeScript类型推断测试
*
* 验证组件类型自动推断功能
*/
import { Component } from '../src/ECS/Component';
import { Entity } from '../src/ECS/Entity';
import { Scene } from '../src/ECS/Scene';
import { Core } from '../src/Core';
import { ECSComponent } from '../src/ECS/Decorators';
import { requireComponent, tryGetComponent, getComponents } from '../src/ECS/TypedEntity';
// 测试组件
@ECSComponent('Position')
class Position extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('Velocity')
class Velocity extends Component {
constructor(public dx: number = 0, public dy: number = 0) {
super();
}
}
@ECSComponent('Health')
class Health extends Component {
constructor(public value: number = 100, public maxValue: number = 100) {
super();
}
}
describe('TypeScript类型推断', () => {
let scene: Scene;
let entity: Entity;
beforeEach(() => {
Core.create({ debug: false, enableEntitySystems: true });
scene = new Scene();
scene.initialize();
entity = scene.createEntity('TestEntity');
});
afterEach(() => {
scene.end();
});
describe('Entity.getComponent 类型推断', () => {
test('getComponent 应该自动推断正确的返回类型', () => {
entity.addComponent(new Position(100, 200));
// 类型推断为 Position | null
const position = entity.getComponent(Position);
// TypeScript应该知道position可能为null
expect(position).not.toBeNull();
// 在null检查后TypeScript应该知道position是Position类型
if (position) {
expect(position.x).toBe(100);
expect(position.y).toBe(200);
// 这些操作应该有完整的类型提示
position.x += 10;
position.y += 20;
expect(position.x).toBe(110);
expect(position.y).toBe(220);
}
});
test('getComponent 返回null时类型安全', () => {
// 实体没有Velocity组件
const velocity = entity.getComponent(Velocity);
// 应该返回null
expect(velocity).toBeNull();
});
test('多个不同类型组件的类型推断', () => {
entity.addComponent(new Position(10, 20));
entity.addComponent(new Velocity(1, 2));
entity.addComponent(new Health(100));
const pos = entity.getComponent(Position);
const vel = entity.getComponent(Velocity);
const health = entity.getComponent(Health);
// 所有组件都应该被正确推断
if (pos && vel && health) {
// Position类型的字段
pos.x = 50;
pos.y = 60;
// Velocity类型的字段
vel.dx = 5;
vel.dy = 10;
// Health类型的字段
health.value = 80;
health.maxValue = 150;
expect(pos.x).toBe(50);
expect(vel.dx).toBe(5);
expect(health.value).toBe(80);
}
});
});
describe('Entity.createComponent 类型推断', () => {
test('createComponent 应该自动推断返回类型', () => {
// 应该推断为Position类型非null
const position = entity.createComponent(Position, 100, 200);
expect(position).toBeInstanceOf(Position);
expect(position.x).toBe(100);
expect(position.y).toBe(200);
// 应该有完整的类型提示
position.x = 300;
expect(position.x).toBe(300);
});
});
describe('Entity.hasComponent 类型守卫', () => {
test('hasComponent 可以用作类型守卫', () => {
entity.addComponent(new Position(10, 20));
if (entity.hasComponent(Position)) {
// 在这个作用域内,我们知道组件存在
const pos = entity.getComponent(Position)!;
pos.x = 100;
expect(pos.x).toBe(100);
}
});
});
describe('Entity.getOrCreateComponent 类型推断', () => {
test('getOrCreateComponent 应该自动推断返回类型', () => {
// 第一次调用:创建新组件
const position1 = entity.getOrCreateComponent(Position, 50, 60);
expect(position1.x).toBe(50);
expect(position1.y).toBe(60);
// 第二次调用:返回已存在的组件
const position2 = entity.getOrCreateComponent(Position, 100, 200);
// 应该是同一个组件
expect(position2).toBe(position1);
expect(position2.x).toBe(50); // 值未改变
});
});
describe('TypedEntity工具函数类型推断', () => {
test('requireComponent 返回非空类型', () => {
entity.addComponent(new Position(100, 200));
// requireComponent 返回非null类型
const position = requireComponent(entity, Position);
// 不需要null检查
expect(position.x).toBe(100);
position.x = 300;
expect(position.x).toBe(300);
});
test('tryGetComponent 返回可选类型', () => {
entity.addComponent(new Position(50, 50));
const position = tryGetComponent(entity, Position);
// 应该返回组件
expect(position).toBeDefined();
if (position) {
expect(position.x).toBe(50);
}
// 不存在的组件返回undefined
const velocity = tryGetComponent(entity, Velocity);
expect(velocity).toBeUndefined();
});
test('getComponents 批量获取组件', () => {
entity.addComponent(new Position(10, 20));
entity.addComponent(new Velocity(1, 2));
entity.addComponent(new Health(100));
const [pos, vel, health] = getComponents(entity, Position, Velocity, Health);
// 应该推断为数组类型
expect(pos).not.toBeNull();
expect(vel).not.toBeNull();
expect(health).not.toBeNull();
if (pos && vel && health) {
expect(pos.x).toBe(10);
expect(vel.dx).toBe(1);
expect(health.value).toBe(100);
}
});
});
});

View File

@@ -0,0 +1,410 @@
import { EntityDataCollector } from '../../../src/Utils/Debug/EntityDataCollector';
import { Scene } from '../../../src/ECS/Scene';
import { Component } from '../../../src/ECS/Component';
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
import { HierarchyComponent } from '../../../src/ECS/Components/HierarchyComponent';
import { ECSComponent } from '../../../src/ECS/Decorators';
@ECSComponent('TestPosition')
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
constructor(x: number = 0, y: number = 0) {
super();
this.x = x;
this.y = y;
}
}
@ECSComponent('TestVelocity')
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
describe('EntityDataCollector', () => {
let collector: EntityDataCollector;
let scene: Scene;
beforeEach(() => {
collector = new EntityDataCollector();
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
describe('collectEntityData', () => {
test('should return empty data when scene is null', () => {
const data = collector.collectEntityData(null);
expect(data.totalEntities).toBe(0);
expect(data.activeEntities).toBe(0);
expect(data.pendingAdd).toBe(0);
expect(data.pendingRemove).toBe(0);
expect(data.entitiesPerArchetype).toEqual([]);
expect(data.topEntitiesByComponents).toEqual([]);
});
test('should return empty data when scene is undefined', () => {
const data = collector.collectEntityData(undefined);
expect(data.totalEntities).toBe(0);
expect(data.activeEntities).toBe(0);
});
test('should collect entity data from scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const data = collector.collectEntityData(scene);
expect(data.totalEntities).toBe(2);
expect(data.activeEntities).toBeGreaterThanOrEqual(0);
});
test('should collect archetype distribution', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new PositionComponent());
const entity3 = scene.createEntity('Entity3');
entity3.addComponent(new VelocityComponent());
const data = collector.collectEntityData(scene);
expect(data.entitiesPerArchetype.length).toBeGreaterThan(0);
});
});
describe('getRawEntityList', () => {
test('should return empty array when scene is null', () => {
const list = collector.getRawEntityList(null);
expect(list).toEqual([]);
});
test('should return raw entity list from scene', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent(10, 20));
entity1.tag = 0x01;
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new VelocityComponent());
const list = collector.getRawEntityList(scene);
expect(list.length).toBe(2);
expect(list[0].name).toBe('Entity1');
expect(list[0].componentCount).toBe(1);
expect(list[0].tag).toBe(0x01);
});
test('should include hierarchy information', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const parent = scene.createEntity('Parent');
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, parent);
const list = collector.getRawEntityList(scene);
const childInfo = list.find(e => e.name === 'Child');
expect(childInfo).toBeDefined();
expect(childInfo!.parentId).toBe(parent.id);
expect(childInfo!.depth).toBe(1);
});
});
describe('getEntityDetails', () => {
test('should return null when scene is null', () => {
const details = collector.getEntityDetails(1, null);
expect(details).toBeNull();
});
test('should return null when entity not found', () => {
const details = collector.getEntityDetails(9999, scene);
expect(details).toBeNull();
});
test('should return entity details', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent(100, 200));
entity.tag = 42;
const details = collector.getEntityDetails(entity.id, scene);
expect(details).not.toBeNull();
expect(details.componentCount).toBe(1);
expect(details.scene).toBeDefined();
});
test('should handle errors gracefully', () => {
const details = collector.getEntityDetails(-1, scene);
expect(details).toBeNull();
});
});
describe('collectEntityDataWithMemory', () => {
test('should return empty data when scene is null', () => {
const data = collector.collectEntityDataWithMemory(null);
expect(data.totalEntities).toBe(0);
expect(data.entityHierarchy).toEqual([]);
expect(data.entityDetailsMap).toEqual({});
});
test('should collect entity data with memory information', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(10, 20));
const data = collector.collectEntityDataWithMemory(scene);
expect(data.totalEntities).toBe(1);
expect(data.topEntitiesByComponents.length).toBeGreaterThan(0);
});
test('should include entity details map', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const data = collector.collectEntityDataWithMemory(scene);
expect(data.entityDetailsMap).toBeDefined();
expect(data.entityDetailsMap![entity.id]).toBeDefined();
});
test('should build entity hierarchy tree', () => {
const hierarchySystem = new HierarchySystem();
scene.addSystem(hierarchySystem);
const root = scene.createEntity('Root');
root.addComponent(new HierarchyComponent());
const child = scene.createEntity('Child');
hierarchySystem.setParent(child, root);
const data = collector.collectEntityDataWithMemory(scene);
expect(data.entityHierarchy).toBeDefined();
expect(data.entityHierarchy!.length).toBe(1);
expect(data.entityHierarchy![0].name).toBe('Root');
});
});
describe('estimateEntityMemoryUsage', () => {
test('should estimate memory for entity', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(10, 20));
const memory = collector.estimateEntityMemoryUsage(entity);
expect(memory).toBeGreaterThanOrEqual(0);
expect(typeof memory).toBe('number');
});
test('should return 0 for invalid entity', () => {
const memory = collector.estimateEntityMemoryUsage(null);
expect(memory).toBe(0);
});
test('should handle errors and return 0', () => {
const badEntity = { components: null };
const memory = collector.estimateEntityMemoryUsage(badEntity);
expect(memory).toBeGreaterThanOrEqual(0);
});
});
describe('calculateObjectSize', () => {
test('should return 0 for null/undefined', () => {
expect(collector.calculateObjectSize(null)).toBe(0);
expect(collector.calculateObjectSize(undefined)).toBe(0);
});
test('should calculate size for simple object', () => {
const obj = { x: 10, y: 20, name: 'test' };
const size = collector.calculateObjectSize(obj);
expect(size).toBeGreaterThan(0);
});
test('should respect exclude keys', () => {
const obj = { x: 10, excluded: 'large string'.repeat(100) };
const sizeWithExclude = collector.calculateObjectSize(obj, ['excluded']);
const sizeWithoutExclude = collector.calculateObjectSize(obj);
expect(sizeWithExclude).toBeLessThan(sizeWithoutExclude);
});
test('should handle nested objects with limited depth', () => {
const obj = {
level1: {
level2: {
level3: {
value: 42
}
}
}
};
const size = collector.calculateObjectSize(obj);
expect(size).toBeGreaterThan(0);
});
});
describe('extractComponentDetails', () => {
test('should extract component details', () => {
const component = new PositionComponent(100, 200);
const details = collector.extractComponentDetails([component]);
expect(details.length).toBe(1);
expect(details[0].typeName).toBe('TestPosition');
expect(details[0].properties.x).toBe(100);
expect(details[0].properties.y).toBe(200);
});
test('should handle empty components array', () => {
const details = collector.extractComponentDetails([]);
expect(details).toEqual([]);
});
test('should skip private properties', () => {
class ComponentWithPrivate extends Component {
public publicValue: number = 1;
private _privateValue: number = 2;
}
const component = new ComponentWithPrivate();
const details = collector.extractComponentDetails([component]);
expect(details[0].properties.publicValue).toBe(1);
expect(details[0].properties._privateValue).toBeUndefined();
});
});
describe('getComponentProperties', () => {
test('should return empty object when scene is null', () => {
const props = collector.getComponentProperties(1, 0, null);
expect(props).toEqual({});
});
test('should return empty object when entity not found', () => {
const props = collector.getComponentProperties(9999, 0, scene);
expect(props).toEqual({});
});
test('should return empty object when component index is out of bounds', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const props = collector.getComponentProperties(entity.id, 99, scene);
expect(props).toEqual({});
});
test('should return component properties', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(50, 75));
const props = collector.getComponentProperties(entity.id, 0, scene);
expect(props.x).toBe(50);
expect(props.y).toBe(75);
});
});
describe('expandLazyObject', () => {
test('should return null when scene is null', () => {
const result = collector.expandLazyObject(1, 0, 'path', null);
expect(result).toBeNull();
});
test('should return null when entity not found', () => {
const result = collector.expandLazyObject(9999, 0, 'path', scene);
expect(result).toBeNull();
});
test('should return null when component index is out of bounds', () => {
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent());
const result = collector.expandLazyObject(entity.id, 99, '', scene);
expect(result).toBeNull();
});
test('should expand object at path', () => {
class ComponentWithNested extends Component {
public nested = { value: 42 };
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithNested());
const result = collector.expandLazyObject(entity.id, 0, 'nested', scene);
expect(result).toBeDefined();
expect(result.value).toBe(42);
});
test('should handle array index in path', () => {
class ComponentWithArray extends Component {
public items = [{ id: 1 }, { id: 2 }];
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithArray());
const result = collector.expandLazyObject(entity.id, 0, 'items[1]', scene);
expect(result).toBeDefined();
expect(result.id).toBe(2);
});
});
describe('edge cases', () => {
test('should handle scene without entities buffer', () => {
const mockScene = {
entities: null,
getSystem: () => null
};
const data = collector.collectEntityData(mockScene as any);
expect(data.totalEntities).toBe(0);
});
test('should handle entity with long string properties', () => {
class ComponentWithLongString extends Component {
public longText = 'x'.repeat(300);
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithLongString());
const details = collector.extractComponentDetails(entity.components);
expect(details[0].properties.longText).toContain('[长字符串:');
});
test('should handle entity with large arrays', () => {
class ComponentWithLargeArray extends Component {
public items = Array.from({ length: 20 }, (_, i) => i);
}
const entity = scene.createEntity('Entity');
entity.addComponent(new ComponentWithLargeArray());
const details = collector.extractComponentDetails(entity.components);
expect(details[0].properties.items).toBeDefined();
expect(details[0].properties.items._isLazyArray).toBe(true);
expect(details[0].properties.items._arrayLength).toBe(20);
});
});
});

View File

@@ -0,0 +1,417 @@
import { AutoProfiler, Profile, ProfileClass } from '../../../src/Utils/Profiler/AutoProfiler';
import { ProfilerSDK } from '../../../src/Utils/Profiler/ProfilerSDK';
import { ProfileCategory } from '../../../src/Utils/Profiler/ProfilerTypes';
describe('AutoProfiler', () => {
beforeEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
});
describe('getInstance', () => {
test('should return singleton instance', () => {
const instance1 = AutoProfiler.getInstance();
const instance2 = AutoProfiler.getInstance();
expect(instance1).toBe(instance2);
});
test('should accept custom config', () => {
const instance = AutoProfiler.getInstance({ minDuration: 1.0 });
expect(instance).toBeDefined();
});
});
describe('resetInstance', () => {
test('should reset the singleton instance', () => {
const instance1 = AutoProfiler.getInstance();
AutoProfiler.resetInstance();
const instance2 = AutoProfiler.getInstance();
expect(instance1).not.toBe(instance2);
});
});
describe('setEnabled', () => {
test('should enable/disable auto profiling', () => {
AutoProfiler.setEnabled(false);
const instance = AutoProfiler.getInstance();
expect(instance).toBeDefined();
AutoProfiler.setEnabled(true);
expect(instance).toBeDefined();
});
});
describe('wrapFunction', () => {
test('should wrap a synchronous function', () => {
ProfilerSDK.beginFrame();
const originalFn = (a: number, b: number) => a + b;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'add', ProfileCategory.Custom);
const result = wrappedFn(2, 3);
expect(result).toBe(5);
ProfilerSDK.endFrame();
});
test('should preserve function behavior', () => {
const originalFn = (x: number) => x * 2;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'double', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(wrappedFn(5)).toBe(10);
expect(wrappedFn(0)).toBe(0);
expect(wrappedFn(-3)).toBe(-6);
ProfilerSDK.endFrame();
});
test('should handle async functions', async () => {
const asyncFn = async (x: number) => {
await new Promise((resolve) => setTimeout(resolve, 1));
return x * 2;
};
const wrappedFn = AutoProfiler.wrapFunction(asyncFn, 'asyncDouble', ProfileCategory.Script);
ProfilerSDK.beginFrame();
const result = await wrappedFn(5);
expect(result).toBe(10);
ProfilerSDK.endFrame();
});
test('should handle function that throws error', () => {
const errorFn = () => {
throw new Error('Test error');
};
const wrappedFn = AutoProfiler.wrapFunction(errorFn, 'errorFn', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(() => wrappedFn()).toThrow('Test error');
ProfilerSDK.endFrame();
});
test('should return original function when disabled', () => {
AutoProfiler.setEnabled(false);
const originalFn = (x: number) => x + 1;
const wrappedFn = AutoProfiler.wrapFunction(originalFn, 'increment', ProfileCategory.Script);
expect(wrappedFn(5)).toBe(6);
});
});
describe('wrapInstance', () => {
test('should wrap all methods of an object', () => {
class Calculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
}
const calc = new Calculator();
AutoProfiler.wrapInstance(calc, 'Calculator', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(calc.add(5, 3)).toBe(8);
expect(calc.subtract(5, 3)).toBe(2);
ProfilerSDK.endFrame();
});
test('should not wrap already wrapped objects', () => {
class MyClass {
getValue(): number {
return 42;
}
}
const obj = new MyClass();
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
ProfilerSDK.beginFrame();
expect(obj.getValue()).toBe(42);
ProfilerSDK.endFrame();
});
test('should return object unchanged when disabled', () => {
AutoProfiler.setEnabled(false);
class MyClass {
getValue(): number {
return 42;
}
}
const obj = new MyClass();
const wrapped = AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
expect(wrapped).toBe(obj);
});
test('should exclude methods matching exclude patterns', () => {
class MyClass {
getValue(): number {
return 42;
}
_privateMethod(): number {
return 1;
}
getName(): string {
return 'test';
}
isValid(): boolean {
return true;
}
hasData(): boolean {
return true;
}
}
const obj = new MyClass();
AutoProfiler.wrapInstance(obj, 'MyClass', ProfileCategory.Custom);
ProfilerSDK.beginFrame();
expect(obj.getValue()).toBe(42);
expect(obj._privateMethod()).toBe(1);
expect(obj.getName()).toBe('test');
expect(obj.isValid()).toBe(true);
expect(obj.hasData()).toBe(true);
ProfilerSDK.endFrame();
});
});
describe('registerClass', () => {
test('should register a class for auto profiling', () => {
class MySystem {
update(): void {
// Do something
}
}
const RegisteredClass = AutoProfiler.registerClass(MySystem, ProfileCategory.ECS);
ProfilerSDK.beginFrame();
const instance = new RegisteredClass();
instance.update();
ProfilerSDK.endFrame();
expect(instance).toBeInstanceOf(MySystem);
});
test('should accept custom class name', () => {
class MySystem {
process(): number {
return 1;
}
}
const RegisteredClass = AutoProfiler.registerClass(MySystem, ProfileCategory.ECS, 'CustomSystem');
ProfilerSDK.beginFrame();
const instance = new RegisteredClass();
expect(instance.process()).toBe(1);
ProfilerSDK.endFrame();
});
});
describe('sampling profiler', () => {
test('should start and stop sampling', () => {
AutoProfiler.startSampling();
const samples = AutoProfiler.stopSampling();
expect(Array.isArray(samples)).toBe(true);
});
test('should return empty array when sampling was never started', () => {
const samples = AutoProfiler.stopSampling();
expect(samples).toEqual([]);
});
test('should collect samples during execution', async () => {
AutoProfiler.startSampling();
// Do some work
for (let i = 0; i < 100; i++) {
Math.sqrt(i);
}
// Wait a bit for samples to accumulate
await new Promise((resolve) => setTimeout(resolve, 50));
const samples = AutoProfiler.stopSampling();
expect(Array.isArray(samples)).toBe(true);
});
});
describe('dispose', () => {
test('should clean up resources', () => {
const instance = AutoProfiler.getInstance();
instance.startSampling();
instance.dispose();
// After dispose, stopping sampling should return empty array
const samples = instance.stopSampling();
expect(samples).toEqual([]);
});
});
describe('minDuration filtering', () => {
test('should respect minDuration setting', () => {
AutoProfiler.resetInstance();
const instance = AutoProfiler.getInstance({ minDuration: 1000 });
const quickFn = () => 1;
const wrappedFn = instance.wrapFunction(quickFn, 'quickFn', ProfileCategory.Script);
ProfilerSDK.beginFrame();
expect(wrappedFn()).toBe(1);
ProfilerSDK.endFrame();
});
});
});
describe('@Profile decorator', () => {
beforeEach(() => {
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
ProfilerSDK.reset();
});
test('should profile decorated methods', () => {
class TestClass {
@Profile()
calculate(): number {
return 42;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
const result = instance.calculate();
ProfilerSDK.endFrame();
expect(result).toBe(42);
});
test('should use custom name when provided', () => {
class TestClass {
@Profile('CustomMethodName', ProfileCategory.Physics)
compute(): number {
return 100;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
expect(instance.compute()).toBe(100);
ProfilerSDK.endFrame();
});
test('should handle async methods', async () => {
class TestClass {
@Profile()
async asyncMethod(): Promise<number> {
await new Promise((resolve) => setTimeout(resolve, 1));
return 99;
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
const result = await instance.asyncMethod();
ProfilerSDK.endFrame();
expect(result).toBe(99);
});
test('should handle method that throws error', () => {
class TestClass {
@Profile()
throwingMethod(): void {
throw new Error('Decorated error');
}
}
const instance = new TestClass();
ProfilerSDK.beginFrame();
expect(() => instance.throwingMethod()).toThrow('Decorated error');
ProfilerSDK.endFrame();
});
test('should skip profiling when ProfilerSDK is disabled', () => {
ProfilerSDK.setEnabled(false);
class TestClass {
@Profile()
simpleMethod(): number {
return 1;
}
}
const instance = new TestClass();
expect(instance.simpleMethod()).toBe(1);
});
});
describe('@ProfileClass decorator', () => {
beforeEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
ProfilerSDK.setEnabled(true);
});
afterEach(() => {
AutoProfiler.resetInstance();
ProfilerSDK.reset();
});
test('should profile all methods of decorated class', () => {
@ProfileClass(ProfileCategory.ECS)
class GameSystem {
update(): void {
// Update logic
}
render(): number {
return 1;
}
}
ProfilerSDK.beginFrame();
const system = new GameSystem();
system.update();
expect(system.render()).toBe(1);
ProfilerSDK.endFrame();
});
test('should use default category when not specified', () => {
@ProfileClass()
class DefaultSystem {
process(): boolean {
return true;
}
}
ProfilerSDK.beginFrame();
const system = new DefaultSystem();
expect(system.process()).toBe(true);
ProfilerSDK.endFrame();
});
});