style(core): ESLint自动修复代码格式问题 (#210)

This commit is contained in:
YHH
2025-11-01 17:41:50 +08:00
committed by GitHub
parent 4355538d8d
commit 620f3eecc7
80 changed files with 634 additions and 640 deletions

View File

@@ -329,8 +329,8 @@ export class Core {
*/ */
public static setScene<T extends IScene>(scene: T): T { public static setScene<T extends IScene>(scene: T): T {
if (!this._instance) { if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()"); Core._logger.warn('Core实例未创建请先调用Core.create()');
throw new Error("Core实例未创建"); throw new Error('Core实例未创建');
} }
return this._instance._sceneManager.setScene(scene); return this._instance._sceneManager.setScene(scene);
@@ -387,7 +387,7 @@ export class Core {
*/ */
public static loadScene<T extends IScene>(scene: T): void { public static loadScene<T extends IScene>(scene: T): void {
if (!this._instance) { if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()"); Core._logger.warn('Core实例未创建请先调用Core.create()');
return; return;
} }
@@ -422,7 +422,7 @@ export class Core {
*/ */
public static update(deltaTime: number): void { public static update(deltaTime: number): void {
if (!this._instance) { if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()"); Core._logger.warn('Core实例未创建请先调用Core.create()');
return; return;
} }
@@ -472,7 +472,7 @@ export class Core {
*/ */
public static enableDebug(config: IECSDebugConfig): void { public static enableDebug(config: IECSDebugConfig): void {
if (!this._instance) { if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()"); Core._logger.warn('Core实例未创建请先调用Core.create()');
return; return;
} }

View File

@@ -123,7 +123,7 @@ export function Updatable(priority: number = 0): ClassDecorator {
if (!prototype || typeof prototype.update !== 'function') { if (!prototype || typeof prototype.update !== 'function') {
throw new Error( throw new Error(
`@Updatable() decorator requires class ${target.name} to implement IUpdatable interface with update() method. ` + `@Updatable() decorator requires class ${target.name} to implement IUpdatable interface with update() method. ` +
`Please add 'implements IUpdatable' and define update(deltaTime?: number): void method.` 'Please add \'implements IUpdatable\' and define update(deltaTime?: number): void method.'
); );
} }
@@ -249,7 +249,7 @@ export function createInstance<T>(
if (typeof serviceType === 'string' || typeof serviceType === 'symbol') { if (typeof serviceType === 'string' || typeof serviceType === 'symbol') {
// 字符串或Symbol类型的服务标识 // 字符串或Symbol类型的服务标识
throw new Error( throw new Error(
`String and Symbol service identifiers are not yet supported in constructor injection. ` + 'String and Symbol service identifiers are not yet supported in constructor injection. ' +
`Please use class types for ${constructor.name} parameter ${i}` `Please use class types for ${constructor.name} parameter ${i}`
); );
} else { } else {
@@ -338,7 +338,7 @@ export function registerInjectable<T extends IService>(
if (!isInjectable(serviceType)) { if (!isInjectable(serviceType)) {
throw new Error( throw new Error(
`${serviceType.name} is not marked as @Injectable(). ` + `${serviceType.name} is not marked as @Injectable(). ` +
`Please add @Injectable() decorator to the class.` 'Please add @Injectable() decorator to the class.'
); );
} }

View File

@@ -240,7 +240,7 @@ export class ServiceContainer {
// 检测循环依赖 // 检测循环依赖
if (this._resolving.has(type as ServiceType<IService>)) { if (this._resolving.has(type as ServiceType<IService>)) {
const chain = Array.from(this._resolving).map(t => t.name).join(' -> '); const chain = Array.from(this._resolving).map((t) => t.name).join(' -> ');
throw new Error(`Circular dependency detected: ${chain} -> ${type.name}`); throw new Error(`Circular dependency detected: ${chain} -> ${type.name}`);
} }
@@ -337,7 +337,7 @@ export class ServiceContainer {
// 如果有单例实例,调用 dispose // 如果有单例实例,调用 dispose
if (registration.instance) { if (registration.instance) {
// 从可更新列表中移除 // 从可更新列表中移除
const index = this._updatableServices.findIndex(item => item.instance === registration.instance); const index = this._updatableServices.findIndex((item) => item.instance === registration.instance);
if (index !== -1) { if (index !== -1) {
this._updatableServices.splice(index, 1); this._updatableServices.splice(index, 1);
} }

View File

@@ -1,7 +1,7 @@
import { Entity } from '../Entity'; import { Entity } from '../Entity';
import { ComponentType, ComponentRegistry } from './ComponentStorage'; import { ComponentType, ComponentRegistry } from './ComponentStorage';
import { BitMask64Data, BitMask64Utils } from "../Utils"; import { BitMask64Data, BitMask64Utils } from '../Utils';
import { BitMaskHashMap } from "../Utils/BitMaskHashMap"; import { BitMaskHashMap } from '../Utils/BitMaskHashMap';
/** /**
* 原型标识符 * 原型标识符
@@ -247,7 +247,7 @@ export class ArchetypeSystem {
*/ */
private updateAllArchetypeArrays(): void { private updateAllArchetypeArrays(): void {
this._allArchetypes = []; this._allArchetypes = [];
for (let archetype of this._archetypes.values()) { for (const archetype of this._archetypes.values()) {
this._allArchetypes.push(archetype); this._allArchetypes.push(archetype);
} }
} }
@@ -258,7 +258,7 @@ export class ArchetypeSystem {
private getEntityComponentTypes(entity: Entity): ComponentType[] { private getEntityComponentTypes(entity: Entity): ComponentType[] {
let componentTypes = this._entityComponentTypesCache.get(entity); let componentTypes = this._entityComponentTypesCache.get(entity);
if (!componentTypes) { if (!componentTypes) {
componentTypes = entity.components.map(component => component.constructor as ComponentType); componentTypes = entity.components.map((component) => component.constructor as ComponentType);
this._entityComponentTypesCache.set(entity, componentTypes); this._entityComponentTypesCache.set(entity, componentTypes);
} }
return componentTypes; return componentTypes;
@@ -269,7 +269,7 @@ export class ArchetypeSystem {
* 使用ComponentRegistry确保与Entity.componentMask使用相同的bitIndex * 使用ComponentRegistry确保与Entity.componentMask使用相同的bitIndex
*/ */
private generateArchetypeId(componentTypes: ComponentType[]): ArchetypeId { private generateArchetypeId(componentTypes: ComponentType[]): ArchetypeId {
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO); const mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const type of componentTypes) { for (const type of componentTypes) {
if (!ComponentRegistry.isRegistered(type)) { if (!ComponentRegistry.isRegistered(type)) {
ComponentRegistry.register(type); ComponentRegistry.register(type);

View File

@@ -9,7 +9,6 @@ import { ComponentRegistry, ComponentType } from './ComponentStorage/ComponentRe
export { ComponentRegistry, ComponentType }; export { ComponentRegistry, ComponentType };
/** /**
* 高性能组件存储器 * 高性能组件存储器
*/ */
@@ -152,7 +151,7 @@ export class ComponentStorage<T extends Component> {
usedSlots: number; usedSlots: number;
freeSlots: number; freeSlots: number;
fragmentation: number; fragmentation: number;
} { } {
const totalSlots = this.dense.length; const totalSlots = this.dense.length;
const usedSlots = this.dense.length; const usedSlots = this.dense.length;
const freeSlots = 0; // 永远无空洞 const freeSlots = 0; // 永远无空洞
@@ -342,7 +341,7 @@ export class ComponentStorageManager {
* @returns 组件位掩码 * @returns 组件位掩码
*/ */
public getComponentMask(entityId: number): BitMask64Data { public getComponentMask(entityId: number): BitMask64Data {
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO); const mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const [componentType, storage] of this.storages.entries()) { for (const [componentType, storage] of this.storages.entries()) {
if (storage.hasComponent(entityId)) { if (storage.hasComponent(entityId)) {

View File

@@ -181,7 +181,7 @@ export class ComponentRegistry {
return this.maskCache.get(cacheKey)!; return this.maskCache.get(cacheKey)!;
} }
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO); const mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const name of componentNames) { for (const name of componentNames) {
const componentId = this.getComponentId(name); const componentId = this.getComponentId(name);
if (componentId !== undefined) { if (componentId !== undefined) {

View File

@@ -164,7 +164,7 @@ export class ECSFluentAPI {
componentStats: Map<string, unknown>; componentStats: Map<string, unknown>;
queryStats: unknown; queryStats: unknown;
eventStats: Map<string, unknown>; eventStats: Map<string, unknown>;
} { } {
return { return {
entityCount: this.scene.entities.count, entityCount: this.scene.entities.count,
systemCount: this.scene.systems.length, systemCount: this.scene.systems.length,

View File

@@ -15,7 +15,7 @@ export class EntityBuilder {
this.scene = scene; this.scene = scene;
this.storageManager = storageManager; this.storageManager = storageManager;
const id = scene.identifierPool.checkOut(); const id = scene.identifierPool.checkOut();
this.entity = new Entity("", id); this.entity = new Entity('', id);
this.entity.scene = this.scene as any; this.entity.scene = this.scene as any;
} }

View File

@@ -1,3 +1,2 @@
export { QuerySystem } from '../QuerySystem'; export { QuerySystem } from '../QuerySystem';
export { ECSFluentAPI, createECSAPI } from '../FluentAPI'; export { ECSFluentAPI, createECSAPI } from '../FluentAPI';

View File

@@ -882,7 +882,7 @@ export class QuerySystem {
size: number; size: number;
hitRate: string; hitRate: string;
}; };
} { } {
return { return {
entityCount: this._entities.length, entityCount: this._entities.length,
indexStats: { indexStats: {

View File

@@ -136,7 +136,7 @@ export class ReactiveQuery {
private generateQueryId(): string { private generateQueryId(): string {
const typeStr = this._condition.type; const typeStr = this._condition.type;
const componentsStr = this._condition.componentTypes const componentsStr = this._condition.componentTypes
.map(t => t.name) .map((t) => t.name)
.sort() .sort()
.join(','); .join(',');
return `${typeStr}:${componentsStr}`; return `${typeStr}:${componentsStr}`;

View File

@@ -578,7 +578,7 @@ export class SoAStorage<T extends Component> {
} }
if (obj instanceof Array) { if (obj instanceof Array) {
return obj.map(item => this.deepClone(item)); return obj.map((item) => this.deepClone(item));
} }
if (obj instanceof Map) { if (obj instanceof Map) {

View File

@@ -1,6 +1,6 @@
import type {Component} from '../Component'; import type { Component } from '../Component';
import type {EntitySystem} from '../Systems'; import type { EntitySystem } from '../Systems';
import {ComponentType} from "../../Types"; import { ComponentType } from '../../Types';
/** /**
* 存储组件类型名称的Symbol键 * 存储组件类型名称的Symbol键

View File

@@ -212,7 +212,7 @@ export class ComponentSerializer {
// 数组 // 数组
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map(item => this.serializeValue(item)); return value.map((item) => this.serializeValue(item));
} }
// Map (如果没有使用@SerializeMap装饰器) // Map (如果没有使用@SerializeMap装饰器)
@@ -276,7 +276,7 @@ export class ComponentSerializer {
// 数组 // 数组
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map(item => this.deserializeValue(item)); return value.map((item) => this.deserializeValue(item));
} }
// 普通对象 // 普通对象
@@ -340,10 +340,10 @@ export class ComponentSerializer {
return { return {
type: metadata.options.typeId || getComponentTypeName(componentType), type: metadata.options.typeId || getComponentTypeName(componentType),
version: metadata.options.version, version: metadata.options.version,
fields: Array.from(metadata.fields.keys()).map(k => fields: Array.from(metadata.fields.keys()).map((k) =>
typeof k === 'symbol' ? k.toString() : k typeof k === 'symbol' ? k.toString() : k
), ),
ignoredFields: Array.from(metadata.ignoredFields).map(k => ignoredFields: Array.from(metadata.ignoredFields).map((k) =>
typeof k === 'symbol' ? k.toString() : k typeof k === 'symbol' ? k.toString() : k
), ),
isSerializable: true isSerializable: true

View File

@@ -696,22 +696,22 @@ export class IncrementalSerializer {
componentChanges: incremental.componentChanges.length, componentChanges: incremental.componentChanges.length,
sceneDataChanges: incremental.sceneDataChanges.length, sceneDataChanges: incremental.sceneDataChanges.length,
addedEntities: incremental.entityChanges.filter( addedEntities: incremental.entityChanges.filter(
c => c.operation === ChangeOperation.EntityAdded (c) => c.operation === ChangeOperation.EntityAdded
).length, ).length,
removedEntities: incremental.entityChanges.filter( removedEntities: incremental.entityChanges.filter(
c => c.operation === ChangeOperation.EntityRemoved (c) => c.operation === ChangeOperation.EntityRemoved
).length, ).length,
updatedEntities: incremental.entityChanges.filter( updatedEntities: incremental.entityChanges.filter(
c => c.operation === ChangeOperation.EntityUpdated (c) => c.operation === ChangeOperation.EntityUpdated
).length, ).length,
addedComponents: incremental.componentChanges.filter( addedComponents: incremental.componentChanges.filter(
c => c.operation === ChangeOperation.ComponentAdded (c) => c.operation === ChangeOperation.ComponentAdded
).length, ).length,
removedComponents: incremental.componentChanges.filter( removedComponents: incremental.componentChanges.filter(
c => c.operation === ChangeOperation.ComponentRemoved (c) => c.operation === ChangeOperation.ComponentRemoved
).length, ).length,
updatedComponents: incremental.componentChanges.filter( updatedComponents: incremental.componentChanges.filter(
c => c.operation === ChangeOperation.ComponentUpdated (c) => c.operation === ChangeOperation.ComponentUpdated
).length ).length
}; };
} }

View File

@@ -363,7 +363,7 @@ export class SceneSerializer {
// 数组 // 数组
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map(item => this.serializeValue(item)); return value.map((item) => this.serializeValue(item));
} }
// 普通对象 // 普通对象
@@ -409,7 +409,7 @@ export class SceneSerializer {
// 数组 // 数组
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map(item => this.deserializeValue(item)); return value.map((item) => this.deserializeValue(item));
} }
// 普通对象 // 普通对象
@@ -437,8 +437,8 @@ export class SceneSerializer {
const componentTypeSet = new Set(options.components); const componentTypeSet = new Set(options.components);
// 只返回拥有指定组件的实体 // 只返回拥有指定组件的实体
return entities.filter(entity => { return entities.filter((entity) => {
return Array.from(entity.components).some(component => return Array.from(entity.components).some((component) =>
componentTypeSet.has(component.constructor as ComponentType) componentTypeSet.has(component.constructor as ComponentType)
); );
}); });

View File

@@ -127,7 +127,7 @@ export class VersionMigrationManager {
return component; return component;
} }
let migratedData = { ...component }; const migratedData = { ...component };
let version = currentVersion; let version = currentVersion;
// 执行迁移链 // 执行迁移链
@@ -193,12 +193,12 @@ export class VersionMigrationManager {
private static migrateSceneComponents(scene: SerializedScene): SerializedScene { private static migrateSceneComponents(scene: SerializedScene): SerializedScene {
const migratedScene = { ...scene }; const migratedScene = { ...scene };
migratedScene.entities = scene.entities.map(entity => ({ migratedScene.entities = scene.entities.map((entity) => ({
...entity, ...entity,
components: entity.components.map(component => { components: entity.components.map((component) => {
// 查找组件的目标版本 // 查找组件的目标版本
const typeInfo = scene.componentTypeRegistry.find( const typeInfo = scene.componentTypeRegistry.find(
t => t.typeName === component.type (t) => t.typeName === component.type
); );
if (typeInfo && typeInfo.version !== component.version) { if (typeInfo && typeInfo.version !== component.version) {
@@ -220,10 +220,10 @@ export class VersionMigrationManager {
entities: any[], entities: any[],
typeRegistry: Array<{ typeName: string; version: number }> typeRegistry: Array<{ typeName: string; version: number }>
): any[] { ): any[] {
return entities.map(entity => ({ return entities.map((entity) => ({
...entity, ...entity,
components: entity.components.map((component: SerializedComponent) => { components: entity.components.map((component: SerializedComponent) => {
const typeInfo = typeRegistry.find(t => t.typeName === component.type); const typeInfo = typeRegistry.find((t) => t.typeName === component.type);
if (typeInfo && typeInfo.version !== component.version) { if (typeInfo && typeInfo.version !== component.version) {
return this.migrateComponent(component, typeInfo.version); return this.migrateComponent(component, typeInfo.version);

View File

@@ -154,7 +154,7 @@ export class EntityCache {
trackedCount: number; trackedCount: number;
frameEntityCount: number; frameEntityCount: number;
persistentEntityCount: number; persistentEntityCount: number;
} { } {
return { return {
hasFrame: this._frameCache !== null, hasFrame: this._frameCache !== null,
hasPersistent: this._persistentCache !== null, hasPersistent: this._persistentCache !== null,

View File

@@ -414,7 +414,7 @@ export abstract class WorkerEntitySystem<TEntityData = any> extends EntitySystem
${sharedProcessFunctionBody} ${sharedProcessFunctionBody}
}; };
userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig); userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig);
` : ``} ` : ''}
} }
`; `;
} }
@@ -494,7 +494,7 @@ export abstract class WorkerEntitySystem<TEntityData = any> extends EntitySystem
const deltaTime = Time.deltaTime; const deltaTime = Time.deltaTime;
// 3. Worker执行阶段 // 3. Worker执行阶段
const promises = batches.map(batch => const promises = batches.map((batch) =>
this.workerPool!.execute({ this.workerPool!.execute({
entities: batch, entities: batch,
deltaTime, deltaTime,
@@ -525,7 +525,7 @@ export abstract class WorkerEntitySystem<TEntityData = any> extends EntitySystem
*/ */
private processSynchronously(entities: readonly Entity[]): void { private processSynchronously(entities: readonly Entity[]): void {
// 1. 数据提取阶段 // 1. 数据提取阶段
const entityData = entities.map(entity => this.extractEntityData(entity)); const entityData = entities.map((entity) => this.extractEntityData(entity));
// 2. 主线程处理阶段 // 2. 主线程处理阶段
const deltaTime = Time.deltaTime; const deltaTime = Time.deltaTime;
@@ -534,7 +534,7 @@ export abstract class WorkerEntitySystem<TEntityData = any> extends EntitySystem
// 3. 结果应用阶段 // 3. 结果应用阶段
// 处理Promise返回值 // 处理Promise返回值
if (results && typeof (results as any).then === 'function') { if (results && typeof (results as any).then === 'function') {
(results as Promise<TEntityData[]>).then(finalResults => { (results as Promise<TEntityData[]>).then((finalResults) => {
entities.forEach((entity, index) => { entities.forEach((entity, index) => {
this.applyResult(entity, finalResults[index]!); this.applyResult(entity, finalResults[index]!);
}); });
@@ -813,7 +813,7 @@ export abstract class WorkerEntitySystem<TEntityData = any> extends EntitySystem
sharedArrayBufferSupported: boolean; sharedArrayBufferSupported: boolean;
sharedArrayBufferEnabled: boolean; sharedArrayBufferEnabled: boolean;
currentMode: 'shared-buffer' | 'worker' | 'sync'; currentMode: 'shared-buffer' | 'worker' | 'sync';
} { } {
let currentMode: 'shared-buffer' | 'worker' | 'sync' = 'sync'; let currentMode: 'shared-buffer' | 'worker' | 'sync' = 'sync';
if (this.config.enableWorker && this.workerPool) { if (this.config.enableWorker && this.workerPool) {

View File

@@ -69,7 +69,7 @@ export class BitMask64Utils {
return maskSegments.some((seg, index) => { return maskSegments.some((seg, index) => {
const bitsSeg = bitsSegments[index]; const bitsSeg = bitsSegments[index];
return bitsSeg && ((seg[SegmentPart.LOW] & bitsSeg[SegmentPart.LOW]) !== 0 || (seg[SegmentPart.HIGH] & bitsSeg[SegmentPart.HIGH]) !== 0); return bitsSeg && ((seg[SegmentPart.LOW] & bitsSeg[SegmentPart.LOW]) !== 0 || (seg[SegmentPart.HIGH] & bitsSeg[SegmentPart.HIGH]) !== 0);
}) });
} }
/** /**
@@ -145,7 +145,7 @@ export class BitMask64Utils {
return baseIsZero; return baseIsZero;
} }
// 额外检查扩展区域是否都为0 // 额外检查扩展区域是否都为0
return mask.segments.every(seg => seg[SegmentPart.LOW] === 0 && seg[SegmentPart.HIGH] === 0); return mask.segments.every((seg) => seg[SegmentPart.LOW] === 0 && seg[SegmentPart.HIGH] === 0);
} }
/** /**
@@ -155,7 +155,7 @@ export class BitMask64Utils {
* @returns 如果两个掩码完全相等则返回true * @returns 如果两个掩码完全相等则返回true
*/ */
public static equals(a: BitMask64Data, b: BitMask64Data): boolean { public static equals(a: BitMask64Data, b: BitMask64Data): boolean {
let baseEquals = a.base[SegmentPart.LOW] === b.base[SegmentPart.LOW] && a.base[SegmentPart.HIGH] === b.base[SegmentPart.HIGH]; const baseEquals = a.base[SegmentPart.LOW] === b.base[SegmentPart.LOW] && a.base[SegmentPart.HIGH] === b.base[SegmentPart.HIGH];
// base不相等或ab都没有扩展区域位直接返回base比较结果 // base不相等或ab都没有扩展区域位直接返回base比较结果
if(!baseEquals || (!a.segments && !b.segments)) return baseEquals; if(!baseEquals || (!a.segments && !b.segments)) return baseEquals;
// 不能假设ab的segments都存在或长度相同. // 不能假设ab的segments都存在或长度相同.
@@ -355,7 +355,7 @@ export class BitMask64Utils {
if(!source.segments || source.segments.length == 0) return; if(!source.segments || source.segments.length == 0) return;
// 没有拓展段,则直接复制数组 // 没有拓展段,则直接复制数组
if(!target.segments){ if(!target.segments){
target.segments = source.segments.map(seg => [...seg]); target.segments = source.segments.map((seg) => [...seg]);
return; return;
} }
// source有扩展段target扩展段不足则补充长度 // source有扩展段target扩展段不足则补充长度
@@ -382,7 +382,7 @@ export class BitMask64Utils {
public static clone(mask: BitMask64Data): BitMask64Data { public static clone(mask: BitMask64Data): BitMask64Data {
return { return {
base: mask.base.slice() as BitMask64Segment, base: mask.base.slice() as BitMask64Segment,
...(mask.segments && { segments: mask.segments.map(seg => [...seg] as BitMask64Segment) }) ...(mask.segments && { segments: mask.segments.map((seg) => [...seg] as BitMask64Segment) })
}; };
} }
@@ -414,8 +414,8 @@ export class BitMask64Utils {
for (let i = -1; i < totalLength; i++) { for (let i = -1; i < totalLength; i++) {
let segResult = ''; let segResult = '';
const bitMaskData = i == -1 ? mask.base : mask.segments![i]!; const bitMaskData = i == -1 ? mask.base : mask.segments![i]!;
let hi = bitMaskData[SegmentPart.HIGH]; const hi = bitMaskData[SegmentPart.HIGH];
let lo = bitMaskData[SegmentPart.LOW]; const lo = bitMaskData[SegmentPart.LOW];
if(radix == 2){ if(radix == 2){
const hiBits = hi.toString(2).padStart(32, '0'); const hiBits = hi.toString(2).padStart(32, '0');
const loBits = lo.toString(2).padStart(32, '0'); const loBits = lo.toString(2).padStart(32, '0');

View File

@@ -1,4 +1,4 @@
import { BitMask64Data } from "./BigIntCompatibility"; import { BitMask64Data } from './BigIntCompatibility';
// FlatHashMapFast.ts // FlatHashMapFast.ts

View File

@@ -77,7 +77,7 @@ export class ComponentSparseSet {
this.removeEntity(entity); this.removeEntity(entity);
} }
let componentMask = BitMask64Utils.clone(BitMask64Utils.ZERO); const componentMask = BitMask64Utils.clone(BitMask64Utils.ZERO);
const entityComponents = new Set<ComponentType>(); const entityComponents = new Set<ComponentType>();
// 分析实体组件并构建位掩码 // 分析实体组件并构建位掩码
@@ -169,7 +169,7 @@ export class ComponentSparseSet {
} }
// 构建目标位掩码 // 构建目标位掩码
let targetMask = BitMask64Utils.clone(BitMask64Utils.ZERO); const targetMask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const componentType of componentTypes) { for (const componentType of componentTypes) {
if (!ComponentRegistry.isRegistered(componentType)) { if (!ComponentRegistry.isRegistered(componentType)) {
return new Set<Entity>(); // 未注册的组件类型,结果为空 return new Set<Entity>(); // 未注册的组件类型,结果为空
@@ -209,7 +209,7 @@ export class ComponentSparseSet {
} }
// 构建目标位掩码 // 构建目标位掩码
let targetMask = BitMask64Utils.clone(BitMask64Utils.ZERO); const targetMask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const componentType of componentTypes) { for (const componentType of componentTypes) {
if (ComponentRegistry.isRegistered(componentType)) { if (ComponentRegistry.isRegistered(componentType)) {
const bitMask = ComponentRegistry.getBitMask(componentType); const bitMask = ComponentRegistry.getBitMask(componentType);
@@ -327,7 +327,7 @@ export class ComponentSparseSet {
masksMemory: number; masksMemory: number;
mappingsMemory: number; mappingsMemory: number;
totalMemory: number; totalMemory: number;
} { } {
const entitiesStats = this._entities.getMemoryStats(); const entitiesStats = this._entities.getMemoryStats();
const masksMemory = this._componentMasks.length * 16; // 估计每个BigInt 16字节 const masksMemory = this._componentMasks.length * 16; // 估计每个BigInt 16字节

View File

@@ -263,7 +263,7 @@ export class EntityList {
pendingAdd: number; pendingAdd: number;
pendingRemove: number; pendingRemove: number;
nameIndexSize: number; nameIndexSize: number;
} { } {
let activeCount = 0; let activeCount = 0;
for (const entity of this.buffer) { for (const entity of this.buffer) {
if (entity.enabled && !entity.isDestroyed) { if (entity.enabled && !entity.isDestroyed) {

View File

@@ -117,8 +117,8 @@ export class IdentifierPool {
if (this._nextAvailableIndex > IdentifierPool.MAX_INDEX) { if (this._nextAvailableIndex > IdentifierPool.MAX_INDEX) {
throw new Error( throw new Error(
`实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。` + `实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。` +
`这意味着您已经分配了超过65535个不同的实体索引。` + '这意味着您已经分配了超过65535个不同的实体索引。' +
`这是16位索引设计的限制考虑优化实体回收策略或升级到64位ID设计。` '这是16位索引设计的限制考虑优化实体回收策略或升级到64位ID设计。'
); );
} }
@@ -155,7 +155,7 @@ export class IdentifierPool {
// 检查是否已经在待回收队列中 // 检查是否已经在待回收队列中
const alreadyPending = this._pendingRecycle.some( const alreadyPending = this._pendingRecycle.some(
item => item.index === index && item.generation === generation (item) => item.index === index && item.generation === generation
); );
if (alreadyPending) { if (alreadyPending) {
@@ -217,7 +217,7 @@ export class IdentifierPool {
averageGeneration: number; averageGeneration: number;
/** 世代存储大小 */ /** 世代存储大小 */
generationStorageSize: number; generationStorageSize: number;
} { } {
// 计算平均世代版本 // 计算平均世代版本
let totalGeneration = 0; let totalGeneration = 0;
let generationCount = 0; let generationCount = 0;

View File

@@ -267,15 +267,15 @@ export class Matcher {
const parts: string[] = []; const parts: string[] = [];
if (this.condition.all.length > 0) { if (this.condition.all.length > 0) {
parts.push(`all(${this.condition.all.map(t => getComponentTypeName(t)).join(', ')})`); parts.push(`all(${this.condition.all.map((t) => getComponentTypeName(t)).join(', ')})`);
} }
if (this.condition.any.length > 0) { if (this.condition.any.length > 0) {
parts.push(`any(${this.condition.any.map(t => getComponentTypeName(t)).join(', ')})`); parts.push(`any(${this.condition.any.map((t) => getComponentTypeName(t)).join(', ')})`);
} }
if (this.condition.none.length > 0) { if (this.condition.none.length > 0) {
parts.push(`none(${this.condition.none.map(t => getComponentTypeName(t)).join(', ')})`); parts.push(`none(${this.condition.none.map((t) => getComponentTypeName(t)).join(', ')})`);
} }
if (this.condition.tag !== undefined) { if (this.condition.tag !== undefined) {

View File

@@ -267,7 +267,7 @@ export class SparseSet<T> {
denseArraySize: number; denseArraySize: number;
sparseMapSize: number; sparseMapSize: number;
totalMemory: number; totalMemory: number;
} { } {
const denseArraySize = this._dense.length * 8; // 估计每个引用8字节 const denseArraySize = this._dense.length * 8; // 估计每个引用8字节
const sparseMapSize = this._sparse.size * 16; // 估计每个Map条目16字节 const sparseMapSize = this._sparse.size * 16; // 估计每个Map条目16字节

View File

@@ -408,7 +408,7 @@ export class World {
globalSystemCount: this._globalSystems.length, globalSystemCount: this._globalSystems.length,
createdAt: this._createdAt, createdAt: this._createdAt,
config: { ...this._config }, config: { ...this._config },
scenes: Array.from(this._scenes.keys()).map(sceneId => ({ scenes: Array.from(this._scenes.keys()).map((sceneId) => ({
id: sceneId, id: sceneId,
isActive: this._activeScenes.has(sceneId), isActive: this._activeScenes.has(sceneId),
name: this._scenes.get(sceneId)?.name || sceneId name: this._scenes.get(sceneId)?.name || sceneId

View File

@@ -444,7 +444,7 @@ export class WorldManager implements IService {
// 检查是否所有Scene都是空的 // 检查是否所有Scene都是空的
const allScenes = world.getAllScenes(); const allScenes = world.getAllScenes();
const hasEntities = allScenes.some(scene => const hasEntities = allScenes.some((scene) =>
scene.entities && scene.entities.count > 0 scene.entities && scene.entities.count > 0
); );

View File

@@ -98,7 +98,7 @@ export class PlatformManager {
platformSupportsSharedArrayBuffer: boolean; platformSupportsSharedArrayBuffer: boolean;
platformMaxWorkerCount: number; platformMaxWorkerCount: number;
platformLimitations: any; platformLimitations: any;
} { } {
if (!this.adapter) { if (!this.adapter) {
return { return {
platformSupportsWorker: false, platformSupportsWorker: false,

View File

@@ -208,8 +208,8 @@ export class DebugPlugin implements IPlugin, IService {
return { return {
name: scene.name, name: scene.name,
entityCount: entities.length, entityCount: entities.length,
systems: systems.map(sys => this.getSystemInfo(sys)), systems: systems.map((sys) => this.getSystemInfo(sys)),
entities: entities.map(entity => this.getEntityInfo(entity)) entities: entities.map((entity) => this.getEntityInfo(entity))
}; };
} }
@@ -246,7 +246,7 @@ export class DebugPlugin implements IPlugin, IService {
enabled: entity.enabled, enabled: entity.enabled,
tag: entity.tag, tag: entity.tag,
componentCount: components.length, componentCount: components.length,
components: components.map(comp => this.getComponentInfo(comp)) components: components.map((comp) => this.getComponentInfo(comp))
}; };
} }
@@ -304,7 +304,7 @@ export class DebugPlugin implements IPlugin, IService {
if (filter.hasComponent) { if (filter.hasComponent) {
const hasComp = entity.components.some( const hasComp = entity.components.some(
c => c.constructor.name === filter.hasComponent (c) => c.constructor.name === filter.hasComponent
); );
if (!hasComp) { if (!hasComp) {
continue; continue;

View File

@@ -47,8 +47,8 @@ export class ComponentDataCollector {
}); });
// 获取池利用率信息 // 获取池利用率信息
let poolUtilizations = new Map<string, number>(); const poolUtilizations = new Map<string, number>();
let poolSizes = new Map<string, number>(); const poolSizes = new Map<string, number>();
try { try {
const poolManager = ComponentPoolManager.getInstance(); const poolManager = ComponentPoolManager.getInstance();

View File

@@ -135,7 +135,7 @@ export class DebugManager implements IService, IUpdatable {
* 格式化日志消息 * 格式化日志消息
*/ */
private formatLogMessage(args: unknown[]): string { private formatLogMessage(args: unknown[]): string {
return args.map(arg => { return args.map((arg) => {
if (typeof arg === 'string') return arg; if (typeof arg === 'string') return arg;
if (arg instanceof Error) return `${arg.name}: ${arg.message}`; if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
if (arg === null) return 'null'; if (arg === null) return 'null';
@@ -173,7 +173,7 @@ export class DebugManager implements IService, IUpdatable {
seen.add(value); seen.add(value);
if (Array.isArray(value)) { if (Array.isArray(value)) {
const result = value.map(item => stringify(item, depth + 1)); const result = value.map((item) => stringify(item, depth + 1));
seen.delete(value); seen.delete(value);
return result; return result;
} }
@@ -436,9 +436,6 @@ export class DebugManager implements IService, IUpdatable {
} }
/** /**
* 处理内存快照请求 * 处理内存快照请求
*/ */
@@ -519,7 +516,7 @@ export class DebugManager implements IService, IUpdatable {
jsHeapSizeLimit: number; jsHeapSizeLimit: number;
} | null; } | null;
detailedMemory?: unknown; detailedMemory?: unknown;
} { } {
const memoryInfo = { const memoryInfo = {
totalMemory: 0, totalMemory: 0,
usedMemory: 0, usedMemory: 0,
@@ -575,7 +572,6 @@ export class DebugManager implements IService, IUpdatable {
} }
/** /**
* 收集组件内存统计(仅用于内存快照) * 收集组件内存统计(仅用于内存快照)
*/ */
@@ -672,7 +668,7 @@ export class DebugManager implements IService, IUpdatable {
enabled: boolean; enabled: boolean;
updateOrder: number; updateOrder: number;
}>; }>;
} { } {
const scene = this.sceneManager.currentScene; const scene = this.sceneManager.currentScene;
let totalSystemMemory = 0; let totalSystemMemory = 0;
const systemBreakdown: Array<{ const systemBreakdown: Array<{
@@ -766,7 +762,7 @@ export class DebugManager implements IService, IUpdatable {
utilization: number; utilization: number;
hitRate?: number; hitRate?: number;
}>; }>;
} { } {
let totalPoolMemory = 0; let totalPoolMemory = 0;
const poolBreakdown: Array<{ const poolBreakdown: Array<{
typeName: string; typeName: string;
@@ -845,7 +841,7 @@ export class DebugManager implements IService, IUpdatable {
samples: number; samples: number;
}>; }>;
error?: string; error?: string;
} { } {
try { try {
if (!this.performanceMonitor) { if (!this.performanceMonitor) {
return { enabled: false }; return { enabled: false };

View File

@@ -641,10 +641,10 @@ export class EntityDataCollector {
componentTypes: baseDebugInfo.componentTypes || componentDetails.map((comp) => comp.typeName), componentTypes: baseDebugInfo.componentTypes || componentDetails.map((comp) => comp.typeName),
cachePerformance: componentCacheStats cachePerformance: componentCacheStats
? { ? {
hitRate: componentCacheStats.cacheStats.hitRate, hitRate: componentCacheStats.cacheStats.hitRate,
size: componentCacheStats.cacheStats.size, size: componentCacheStats.cacheStats.size,
maxSize: componentCacheStats.cacheStats.maxSize maxSize: componentCacheStats.cacheStats.maxSize
} }
: null : null
}; };
}); });

View File

@@ -34,7 +34,7 @@ export class PerformanceDataCollector {
} }
// 计算ECS执行时间统计 // 计算ECS执行时间统计
const history = this.frameTimeHistory.filter(t => t >= 0); const history = this.frameTimeHistory.filter((t) => t >= 0);
const averageECSTime = history.length > 0 ? history.reduce((a, b) => a + b, 0) / history.length : ecsExecutionTimeMs; const averageECSTime = history.length > 0 ? history.reduce((a, b) => a + b, 0) / history.length : ecsExecutionTimeMs;
const minECSTime = history.length > 0 ? Math.min(...history) : ecsExecutionTimeMs; const minECSTime = history.length > 0 ? Math.min(...history) : ecsExecutionTimeMs;
const maxECSTime = history.length > 0 ? Math.max(...history) : ecsExecutionTimeMs; const maxECSTime = history.length > 0 ? Math.max(...history) : ecsExecutionTimeMs;
@@ -100,7 +100,7 @@ export class PerformanceDataCollector {
} }
// 计算各系统占ECS总时间的百分比 // 计算各系统占ECS总时间的百分比
systemBreakdown.forEach(system => { systemBreakdown.forEach((system) => {
system.percentage = totalTime > 0 ? (system.executionTime / totalTime * 100) : 0; system.percentage = totalTime > 0 ? (system.executionTime / totalTime * 100) : 0;
}); });

View File

@@ -112,7 +112,7 @@ export class WebSocketManager {
this.reconnectAttempts++; this.reconnectAttempts++;
this.reconnectTimer = setTimeout(() => { this.reconnectTimer = setTimeout(() => {
this.connect().catch(_error => { this.connect().catch((_error) => {
if (this.reconnectAttempts < this.maxReconnectAttempts) { if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.scheduleReconnect(); this.scheduleReconnect();
} }

View File

@@ -47,9 +47,9 @@ export class Emitter<T, TContext = unknown> {
* @param handler 事件函数 * @param handler 事件函数
*/ */
public removeObserver(eventType: T, handler: Function) { public removeObserver(eventType: T, handler: Function) {
let messageData = this._messageTable.get(eventType); const messageData = this._messageTable.get(eventType);
if (messageData) { if (messageData) {
let index = messageData.findIndex(data => data.func == handler); const index = messageData.findIndex((data) => data.func == handler);
if (index != -1) if (index != -1)
messageData.splice(index, 1); messageData.splice(index, 1);
} }
@@ -61,9 +61,9 @@ export class Emitter<T, TContext = unknown> {
* @param data 事件数据 * @param data 事件数据
*/ */
public emit<TData = unknown>(eventType: T, ...data: TData[]) { public emit<TData = unknown>(eventType: T, ...data: TData[]) {
let list = this._messageTable.get(eventType); const list = this._messageTable.get(eventType);
if (list) { if (list) {
for (let observer of list) { for (const observer of list) {
observer.func.call(observer.context, ...data); observer.func.call(observer.context, ...data);
} }
} }
@@ -75,8 +75,8 @@ export class Emitter<T, TContext = unknown> {
* @param handler 事件函数 * @param handler 事件函数
*/ */
public hasObserver(eventType: T, handler: Function): boolean { public hasObserver(eventType: T, handler: Function): boolean {
let list = this._messageTable.get(eventType); const list = this._messageTable.get(eventType);
return list ? list.some(observer => observer.func === handler) : false; return list ? list.some((observer) => observer.func === handler) : false;
} }
/** /**

View File

@@ -1,5 +1,5 @@
import { Colors, LogLevel } from "./Constants"; import { Colors, LogLevel } from './Constants';
import { ILogger, LoggerColorConfig, LoggerConfig } from "./Types"; import { ILogger, LoggerColorConfig, LoggerConfig } from './Types';
/** /**

View File

@@ -1,6 +1,6 @@
import { ConsoleLogger } from "./ConsoleLogger"; import { ConsoleLogger } from './ConsoleLogger';
import { LogLevel } from "./Constants"; import { LogLevel } from './Constants';
import { ILogger, LoggerColorConfig } from "./Types"; import { ILogger, LoggerColorConfig } from './Types';
/** /**
* 日志管理器 * 日志管理器

View File

@@ -1,4 +1,4 @@
import type { LogLevel } from "./Constants"; import type { LogLevel } from './Constants';
/** /**
* 日志接口 * 日志接口

View File

@@ -276,12 +276,12 @@ export class PerformanceMonitor implements IService {
*/ */
public getPerformanceReport(): string { public getPerformanceReport(): string {
if (!this._isEnabled) { if (!this._isEnabled) {
return "Performance monitoring is disabled."; return 'Performance monitoring is disabled.';
} }
const lines: string[] = []; const lines: string[] = [];
lines.push("=== ECS Performance Report ==="); lines.push('=== ECS Performance Report ===');
lines.push(""); lines.push('');
// 按平均执行时间排序 // 按平均执行时间排序
const sortedSystems = Array.from(this._systemStats.entries()) const sortedSystems = Array.from(this._systemStats.entries())
@@ -300,7 +300,7 @@ export class PerformanceMonitor implements IService {
lines.push(` Per Entity: ${data.averageTimePerEntity.toFixed(4)}ms`); lines.push(` Per Entity: ${data.averageTimePerEntity.toFixed(4)}ms`);
} }
lines.push(""); lines.push('');
} }
// 总体统计 // 总体统计

View File

@@ -30,7 +30,7 @@ export class TimerManager implements IService, IUpdatable {
* @param onTime * @param onTime
*/ */
public schedule<TContext = unknown>(timeInSeconds: number, repeats: boolean, context: TContext, onTime: (timer: ITimer<TContext>)=>void): Timer<TContext> { public schedule<TContext = unknown>(timeInSeconds: number, repeats: boolean, context: TContext, onTime: (timer: ITimer<TContext>)=>void): Timer<TContext> {
let timer = new Timer<TContext>(); const timer = new Timer<TContext>();
timer.initialize(timeInSeconds, repeats, context, onTime); timer.initialize(timeInSeconds, repeats, context, onTime);
this._timers.push(timer as Timer<unknown>); this._timers.push(timer as Timer<unknown>);