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:
495
packages/core/tests/ECS/Serialization/EntitySerializer.test.ts
Normal file
495
packages/core/tests/ECS/Serialization/EntitySerializer.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
439
packages/core/tests/ECS/Serialization/SceneSerializer.test.ts
Normal file
439
packages/core/tests/ECS/Serialization/SceneSerializer.test.ts
Normal 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user