diff --git a/packages/core/src/Core.ts b/packages/core/src/Core.ts index 0af10582..858547ca 100644 --- a/packages/core/src/Core.ts +++ b/packages/core/src/Core.ts @@ -1,20 +1,20 @@ -import {TimerManager} from "./Utils/Timers/TimerManager"; -import {ITimer} from "./Utils/Timers/ITimer"; -import {Timer} from "./Utils/Timers/Timer"; -import {Time} from "./Utils/Time"; -import {PerformanceMonitor} from "./Utils/PerformanceMonitor"; -import {PoolManager} from "./Utils/Pool/PoolManager"; -import {DebugManager} from "./Utils/Debug"; -import {ICoreConfig, IECSDebugConfig} from "./Types"; -import {createLogger} from "./Utils/Logger"; -import {SceneManager} from "./ECS/SceneManager"; -import {IScene} from "./ECS/IScene"; -import {ServiceContainer} from "./Core/ServiceContainer"; -import {PluginManager} from "./Core/PluginManager"; -import {IPlugin} from "./Core/Plugin"; -import {WorldManager} from "./ECS/WorldManager"; -import {DebugConfigService} from "./Utils/Debug/DebugConfigService"; -import {createInstance} from "./Core/DI/Decorators"; +import { TimerManager } from './Utils/Timers/TimerManager'; +import { ITimer } from './Utils/Timers/ITimer'; +import { Timer } from './Utils/Timers/Timer'; +import { Time } from './Utils/Time'; +import { PerformanceMonitor } from './Utils/PerformanceMonitor'; +import { PoolManager } from './Utils/Pool/PoolManager'; +import { DebugManager } from './Utils/Debug'; +import { ICoreConfig, IECSDebugConfig } from './Types'; +import { createLogger } from './Utils/Logger'; +import { SceneManager } from './ECS/SceneManager'; +import { IScene } from './ECS/IScene'; +import { ServiceContainer } from './Core/ServiceContainer'; +import { PluginManager } from './Core/PluginManager'; +import { IPlugin } from './Core/Plugin'; +import { WorldManager } from './ECS/WorldManager'; +import { DebugConfigService } from './Utils/Debug/DebugConfigService'; +import { createInstance } from './Core/DI/Decorators'; /** * 游戏引擎核心类 @@ -67,7 +67,7 @@ export class Core { /** * Core专用日志器 */ - private static _logger = createLogger("Core"); + private static _logger = createLogger('Core'); /** * 实体系统启用状态 @@ -246,7 +246,7 @@ export class Core { */ public static get services(): ServiceContainer { if (!this._instance) { - throw new Error("Core实例未创建,请先调用Core.create()"); + throw new Error('Core实例未创建,请先调用Core.create()'); } return this._instance._serviceContainer; } @@ -270,7 +270,7 @@ export class Core { */ public static get worldManager(): WorldManager { if (!this._instance) { - throw new Error("Core实例未创建,请先调用Core.create()"); + throw new Error('Core实例未创建,请先调用Core.create()'); } return this._instance._worldManager; } @@ -302,12 +302,12 @@ export class Core { public static create(config: ICoreConfig | boolean = true): Core { if (this._instance == null) { // 向后兼容:如果传入boolean,转换为配置对象 - const coreConfig: ICoreConfig = typeof config === "boolean" - ? {debug: config, enableEntitySystems: true} + const coreConfig: ICoreConfig = typeof config === 'boolean' + ? { debug: config, enableEntitySystems: true } : config; this._instance = new Core(coreConfig); } else { - this._logger.warn("Core实例已创建,返回现有实例"); + this._logger.warn('Core实例已创建,返回现有实例'); } return this._instance; } @@ -329,8 +329,8 @@ export class Core { */ public static setScene(scene: T): T { if (!this._instance) { - Core._logger.warn("Core实例未创建,请先调用Core.create()"); - throw new Error("Core实例未创建"); + Core._logger.warn('Core实例未创建,请先调用Core.create()'); + throw new Error('Core实例未创建'); } return this._instance._sceneManager.setScene(scene); @@ -387,7 +387,7 @@ export class Core { */ public static loadScene(scene: T): void { if (!this._instance) { - Core._logger.warn("Core实例未创建,请先调用Core.create()"); + Core._logger.warn('Core实例未创建,请先调用Core.create()'); return; } @@ -422,7 +422,7 @@ export class Core { */ public static update(deltaTime: number): void { if (!this._instance) { - Core._logger.warn("Core实例未创建,请先调用Core.create()"); + Core._logger.warn('Core实例未创建,请先调用Core.create()'); return; } @@ -457,10 +457,10 @@ export class Core { */ public static schedule(timeInSeconds: number, repeats: boolean = false, context?: TContext, onTime?: (timer: ITimer) => void): Timer { if (!this._instance) { - throw new Error("Core实例未创建,请先调用Core.create()"); + throw new Error('Core实例未创建,请先调用Core.create()'); } if (!onTime) { - throw new Error("onTime callback is required"); + throw new Error('onTime callback is required'); } return this._instance._timerManager.schedule(timeInSeconds, repeats, context as TContext, onTime); } @@ -472,7 +472,7 @@ export class Core { */ public static enableDebug(config: IECSDebugConfig): void { if (!this._instance) { - Core._logger.warn("Core实例未创建,请先调用Core.create()"); + Core._logger.warn('Core实例未创建,请先调用Core.create()'); return; } @@ -549,7 +549,7 @@ export class Core { */ public static async installPlugin(plugin: IPlugin): Promise { if (!this._instance) { - throw new Error("Core实例未创建,请先调用Core.create()"); + throw new Error('Core实例未创建,请先调用Core.create()'); } await this._instance._pluginManager.install(plugin); @@ -568,7 +568,7 @@ export class Core { */ public static async uninstallPlugin(name: string): Promise { if (!this._instance) { - throw new Error("Core实例未创建,请先调用Core.create()"); + throw new Error('Core实例未创建,请先调用Core.create()'); } await this._instance._pluginManager.uninstall(name); @@ -624,7 +624,7 @@ export class Core { */ protected initialize() { // 核心系统初始化 - Core._logger.info("Core initialized", { + Core._logger.info('Core initialized', { debug: this.debug, entitySystemsEnabled: Core.entitySystemsEnabled, debugEnabled: this._config.debugConfig?.enabled || false @@ -640,20 +640,20 @@ export class Core { if (Core.paused) return; // 开始性能监控 - const frameStartTime = this._performanceMonitor.startMonitoring("Core.update"); + const frameStartTime = this._performanceMonitor.startMonitoring('Core.update'); // 更新时间系统 Time.update(deltaTime); // 更新FPS监控(如果性能监控器支持) - if ("updateFPS" in this._performanceMonitor && typeof this._performanceMonitor.updateFPS === "function") { + if ('updateFPS' in this._performanceMonitor && typeof this._performanceMonitor.updateFPS === 'function') { this._performanceMonitor.updateFPS(Time.deltaTime); } // 更新所有可更新的服务 - const servicesStartTime = this._performanceMonitor.startMonitoring("Services.update"); + const servicesStartTime = this._performanceMonitor.startMonitoring('Services.update'); this._serviceContainer.updateAll(deltaTime); - this._performanceMonitor.endMonitoring("Services.update", servicesStartTime, this._serviceContainer.getUpdatableCount()); + this._performanceMonitor.endMonitoring('Services.update', servicesStartTime, this._serviceContainer.getUpdatableCount()); // 更新对象池管理器 this._poolManager.update(); @@ -665,7 +665,7 @@ export class Core { this._worldManager.updateAll(); // 结束性能监控 - this._performanceMonitor.endMonitoring("Core.update", frameStartTime); + this._performanceMonitor.endMonitoring('Core.update', frameStartTime); } /** @@ -684,7 +684,7 @@ export class Core { // 清理所有服务 this._instance._serviceContainer.clear(); - Core._logger.info("Core destroyed"); + Core._logger.info('Core destroyed'); // 清空实例引用,允许重新创建Core实例 this._instance = null; diff --git a/packages/core/src/Core/DI/Decorators.ts b/packages/core/src/Core/DI/Decorators.ts index 3b7d701d..4701eccb 100644 --- a/packages/core/src/Core/DI/Decorators.ts +++ b/packages/core/src/Core/DI/Decorators.ts @@ -4,8 +4,8 @@ * 提供 @Injectable、@Inject 和 @Updatable 装饰器,用于标记可注入的类和依赖注入点 */ -import type {ServiceContainer} from "../ServiceContainer"; -import type {IService, ServiceType} from "../ServiceContainer"; +import type { ServiceContainer } from '../ServiceContainer'; +import type { IService, ServiceType } from '../ServiceContainer'; /** * 依赖注入元数据存储 @@ -82,7 +82,7 @@ export function Injectable(): ClassDecorator { injectableMetadata.set(target as Constructor, { injectable: true, dependencies: [], - ...(existing?.properties && {properties: existing.properties}) + ...(existing?.properties && { properties: existing.properties }) }); } as ClassDecorator; } @@ -120,7 +120,7 @@ export function Updatable(priority: number = 0): ClassDecorator { return function (target: Constructor): void { // 验证类原型上是否有update方法 const prototype = (target as Constructor & { prototype: { update?: unknown } }).prototype; - if (!prototype || typeof prototype.update !== "function") { + if (!prototype || typeof prototype.update !== 'function') { throw new Error( `@Updatable() decorator requires class ${target.name} to implement IUpdatable interface with update() method. ` + "Please add 'implements IUpdatable' and define update(deltaTime?: number): void method." @@ -228,6 +228,7 @@ export function getInjectMetadata(target: Constructor): Map( constructor: new (...args: any[]) => T, container: ServiceContainer @@ -246,10 +247,10 @@ export function createInstance( if (serviceType) { // 如果有显式的@Inject标记,使用标记的类型 - if (typeof serviceType === "string" || typeof serviceType === "symbol") { + if (typeof serviceType === 'string' || typeof serviceType === 'symbol') { // 字符串或Symbol类型的服务标识 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}` ); } else { @@ -338,7 +339,7 @@ export function registerInjectable( if (!isInjectable(serviceType)) { throw new Error( `${serviceType.name} is not marked as @Injectable(). ` + - "Please add @Injectable() decorator to the class." + 'Please add @Injectable() decorator to the class.' ); } diff --git a/packages/core/src/Core/DI/index.ts b/packages/core/src/Core/DI/index.ts index 02564cd2..43803bd9 100644 --- a/packages/core/src/Core/DI/index.ts +++ b/packages/core/src/Core/DI/index.ts @@ -17,6 +17,6 @@ export { createInstance, injectProperties, registerInjectable -} from "./Decorators"; +} from './Decorators'; -export type {InjectableMetadata, UpdatableMetadata} from "./Decorators"; +export type { InjectableMetadata, UpdatableMetadata } from './Decorators'; diff --git a/packages/core/src/Core/Plugin.ts b/packages/core/src/Core/Plugin.ts index fd0c5b3c..e00c1d55 100644 --- a/packages/core/src/Core/Plugin.ts +++ b/packages/core/src/Core/Plugin.ts @@ -1,5 +1,5 @@ -import type {Core} from "../Core"; -import type {ServiceContainer} from "./ServiceContainer"; +import type { Core } from '../Core'; +import type { ServiceContainer } from './ServiceContainer'; /** * 插件状态 @@ -8,17 +8,17 @@ export enum PluginState { /** * 未安装 */ - NotInstalled = "not_installed", + NotInstalled = 'not_installed', /** * 已安装 */ - Installed = "installed", + Installed = 'installed', /** * 安装失败 */ - Failed = "failed" + Failed = 'failed' } /** diff --git a/packages/core/src/Core/PluginManager.ts b/packages/core/src/Core/PluginManager.ts index 01fee992..a25607c4 100644 --- a/packages/core/src/Core/PluginManager.ts +++ b/packages/core/src/Core/PluginManager.ts @@ -1,10 +1,10 @@ -import {IPlugin, IPluginMetadata, PluginState} from "./Plugin"; -import type {IService} from "./ServiceContainer"; -import type {Core} from "../Core"; -import type {ServiceContainer} from "./ServiceContainer"; -import {createLogger} from "../Utils/Logger"; +import { IPlugin, IPluginMetadata, PluginState } from './Plugin'; +import type { IService } from './ServiceContainer'; +import type { Core } from '../Core'; +import type { ServiceContainer } from './ServiceContainer'; +import { createLogger } from '../Utils/Logger'; -const logger = createLogger("PluginManager"); +const logger = createLogger('PluginManager'); /** * 插件管理器 @@ -57,7 +57,7 @@ export class PluginManager implements IService { public initialize(core: Core, services: ServiceContainer): void { this._core = core; this._services = services; - logger.info("PluginManager initialized"); + logger.info('PluginManager initialized'); } /** @@ -70,7 +70,7 @@ export class PluginManager implements IService { */ public async install(plugin: IPlugin): Promise { if (!this._core || !this._services) { - throw new Error("PluginManager not initialized. Call initialize() first."); + throw new Error('PluginManager not initialized. Call initialize() first.'); } // 检查是否已安装 @@ -213,7 +213,7 @@ export class PluginManager implements IService { if (missingDeps.length > 0) { throw new Error( - `Plugin ${plugin.name} has unmet dependencies: ${missingDeps.join(", ")}` + `Plugin ${plugin.name} has unmet dependencies: ${missingDeps.join(', ')}` ); } } @@ -235,7 +235,7 @@ export class PluginManager implements IService { if (dependents.length > 0) { throw new Error( - `Cannot uninstall plugin ${name}: it is required by ${dependents.join(", ")}` + `Cannot uninstall plugin ${name}: it is required by ${dependents.join(', ')}` ); } } @@ -261,6 +261,6 @@ export class PluginManager implements IService { this._core = null; this._services = null; - logger.info("PluginManager disposed"); + logger.info('PluginManager disposed'); } } diff --git a/packages/core/src/Core/ServiceContainer.ts b/packages/core/src/Core/ServiceContainer.ts index 04e2ce3e..d7288ecc 100644 --- a/packages/core/src/Core/ServiceContainer.ts +++ b/packages/core/src/Core/ServiceContainer.ts @@ -1,7 +1,7 @@ -import {createLogger} from "../Utils/Logger"; -import {isUpdatable as checkUpdatable, getUpdatableMetadata} from "./DI"; +import { createLogger } from '../Utils/Logger'; +import { isUpdatable as checkUpdatable, getUpdatableMetadata } from './DI'; -const logger = createLogger("ServiceContainer"); +const logger = createLogger('ServiceContainer'); /** * 服务基础接口 @@ -19,8 +19,9 @@ export interface IService { * 服务类型 * * 支持任意构造函数签名,以便与依赖注入装饰器配合使用 - * 使用 any[] 以允许任意参数类型的构造函数 + * 使用 any[] 以允许任意参数类型的构造函数,这是类型系统的必要妥协 */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type ServiceType = new (...args: any[]) => T; /** @@ -30,12 +31,12 @@ export enum ServiceLifetime { /** * 单例模式 - 整个应用生命周期内只有一个实例 */ - Singleton = "singleton", + Singleton = 'singleton', /** * 瞬时模式 - 每次请求都创建新实例 */ - Transient = "transient" + Transient = 'transient' } /** @@ -139,7 +140,7 @@ export class ServiceContainer { this._services.set(type as ServiceType, { type: type as ServiceType, - ...(factory && {factory: factory as (container: ServiceContainer) => IService}), + ...(factory && { factory: factory as (container: ServiceContainer) => IService }), lifetime: ServiceLifetime.Singleton }); @@ -171,7 +172,7 @@ export class ServiceContainer { this._services.set(type as ServiceType, { type: type as ServiceType, - ...(factory && {factory: factory as (container: ServiceContainer) => IService}), + ...(factory && { factory: factory as (container: ServiceContainer) => IService }), lifetime: ServiceLifetime.Transient }); @@ -208,7 +209,7 @@ export class ServiceContainer { if (checkUpdatable(type)) { const metadata = getUpdatableMetadata(type); const priority = metadata?.priority ?? 0; - this._updatableServices.push({instance, priority}); + this._updatableServices.push({ instance, priority }); // 按优先级排序(数值越小越先执行) this._updatableServices.sort((a, b) => a.priority - b.priority); @@ -240,7 +241,7 @@ export class ServiceContainer { // 检测循环依赖 if (this._resolving.has(type as ServiceType)) { - 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}`); } @@ -272,7 +273,7 @@ export class ServiceContainer { if (checkUpdatable(registration.type)) { const metadata = getUpdatableMetadata(registration.type); const priority = metadata?.priority ?? 0; - this._updatableServices.push({instance, priority}); + this._updatableServices.push({ instance, priority }); // 按优先级排序(数值越小越先执行) this._updatableServices.sort((a, b) => a.priority - b.priority); @@ -363,7 +364,7 @@ export class ServiceContainer { this._services.clear(); this._updatableServices = []; - logger.debug("Cleared all services"); + logger.debug('Cleared all services'); } /** @@ -391,7 +392,7 @@ export class ServiceContainer { * ``` */ public updateAll(deltaTime?: number): void { - for (const {instance} of this._updatableServices) { + for (const { instance } of this._updatableServices) { (instance as IService & { update: (deltaTime?: number) => void }).update(deltaTime); } } diff --git a/packages/core/src/ECS/Component.ts b/packages/core/src/ECS/Component.ts index 2e057d00..b9455da4 100644 --- a/packages/core/src/ECS/Component.ts +++ b/packages/core/src/ECS/Component.ts @@ -1,4 +1,4 @@ -import type {IComponent} from "../Types"; +import type { IComponent } from '../Types'; /** * 游戏组件基类 diff --git a/packages/core/src/ECS/Core/ArchetypeSystem.ts b/packages/core/src/ECS/Core/ArchetypeSystem.ts index 0687a0b0..c1ea5727 100644 --- a/packages/core/src/ECS/Core/ArchetypeSystem.ts +++ b/packages/core/src/ECS/Core/ArchetypeSystem.ts @@ -1,7 +1,7 @@ -import {Entity} from "../Entity"; -import {ComponentType, ComponentRegistry} from "./ComponentStorage"; -import {BitMask64Data, BitMask64Utils} from "../Utils"; -import {BitMaskHashMap} from "../Utils/BitMaskHashMap"; +import { Entity } from '../Entity'; +import { ComponentType, ComponentRegistry } from './ComponentStorage'; +import { BitMask64Data, BitMask64Utils } from '../Utils'; +import { BitMaskHashMap } from '../Utils/BitMaskHashMap'; /** * 原型标识符 @@ -126,18 +126,18 @@ export class ArchetypeSystem { * @param operation 查询操作类型:'AND'(包含所有)或 'OR'(包含任意) * @returns 匹配的原型列表及实体总数 */ - public queryArchetypes(componentTypes: ComponentType[], operation: "AND" | "OR" = "AND"): ArchetypeQueryResult { + public queryArchetypes(componentTypes: ComponentType[], operation: 'AND' | 'OR' = 'AND'): ArchetypeQueryResult { const matchingArchetypes: Archetype[] = []; let totalEntities = 0; - if (operation === "AND") { + if (operation === 'AND') { if (componentTypes.length === 0) { for (const archetype of this._allArchetypes) { matchingArchetypes.push(archetype); totalEntities += archetype.entities.size; } - return {archetypes: matchingArchetypes, totalEntities}; + return { archetypes: matchingArchetypes, totalEntities }; } if (componentTypes.length === 1) { @@ -148,7 +148,7 @@ export class ArchetypeSystem { totalEntities += archetype.entities.size; } } - return {archetypes: matchingArchetypes, totalEntities}; + return { archetypes: matchingArchetypes, totalEntities }; } let smallestSet: Set | undefined; @@ -157,7 +157,7 @@ export class ArchetypeSystem { for (const componentType of componentTypes) { const archetypes = this._componentToArchetypes.get(componentType); if (!archetypes || archetypes.size === 0) { - return {archetypes: [], totalEntities: 0}; + return { archetypes: [], totalEntities: 0 }; } if (archetypes.size < smallestSize) { smallestSize = archetypes.size; diff --git a/packages/core/src/ECS/Core/ComponentPool.ts b/packages/core/src/ECS/Core/ComponentPool.ts index 68a4eadf..c8e07763 100644 --- a/packages/core/src/ECS/Core/ComponentPool.ts +++ b/packages/core/src/ECS/Core/ComponentPool.ts @@ -1,4 +1,4 @@ -import {Component} from "../Component"; +import { Component } from '../Component'; /** * 组件对象池,用于复用组件实例以减少内存分配 @@ -183,7 +183,7 @@ export class ComponentPoolManager { acquireComponent(componentName: string): T | null { const pool = this.pools.get(componentName); - this.trackUsage(componentName, "create"); + this.trackUsage(componentName, 'create'); return pool ? (pool.acquire() as T) : null; } @@ -194,7 +194,7 @@ export class ComponentPoolManager { releaseComponent(componentName: string, component: T): void { const pool = this.pools.get(componentName); - this.trackUsage(componentName, "release"); + this.trackUsage(componentName, 'release'); if (pool) { pool.release(component); @@ -204,7 +204,7 @@ export class ComponentPoolManager { /** * 追踪使用情况 */ - private trackUsage(componentName: string, action: "create" | "release"): void { + private trackUsage(componentName: string, action: 'create' | 'release'): void { let tracker = this.usageTracker.get(componentName); if (!tracker) { @@ -216,7 +216,7 @@ export class ComponentPoolManager { this.usageTracker.set(componentName, tracker); } - if (action === "create") { + if (action === 'create') { tracker.createCount++; } else { tracker.releaseCount++; @@ -289,12 +289,12 @@ export class ComponentPoolManager { */ getGlobalStats(): Array<{ componentName: string; - poolStats: ReturnType["getStats"]>; + poolStats: ReturnType['getStats']>; usage: ComponentUsageTracker | undefined; }> { const stats: Array<{ componentName: string; - poolStats: ReturnType["getStats"]>; + poolStats: ReturnType['getStats']>; usage: ComponentUsageTracker | undefined; }> = []; diff --git a/packages/core/src/ECS/Core/ComponentStorage.ts b/packages/core/src/ECS/Core/ComponentStorage.ts index c528136a..c35c138f 100644 --- a/packages/core/src/ECS/Core/ComponentStorage.ts +++ b/packages/core/src/ECS/Core/ComponentStorage.ts @@ -1,12 +1,12 @@ -import {Component} from "../Component"; -import {BitMask64Utils, BitMask64Data} from "../Utils/BigIntCompatibility"; -import {SoAStorage, SupportedTypedArray} from "./SoAStorage"; -import {createLogger} from "../../Utils/Logger"; -import {getComponentTypeName} from "../Decorators"; -import {ComponentRegistry, ComponentType} from "./ComponentStorage/ComponentRegistry"; +import { Component } from '../Component'; +import { BitMask64Utils, BitMask64Data } from '../Utils/BigIntCompatibility'; +import { SoAStorage, SupportedTypedArray } from './SoAStorage'; +import { createLogger } from '../../Utils/Logger'; +import { getComponentTypeName } from '../Decorators'; +import { ComponentRegistry, ComponentType } from './ComponentStorage/ComponentRegistry'; // 导出核心类型 -export {ComponentRegistry, ComponentType}; +export { ComponentRegistry, ComponentType }; /** @@ -171,7 +171,7 @@ export class ComponentStorage { * 管理所有组件类型的存储器 */ export class ComponentStorageManager { - private static readonly _logger = createLogger("ComponentStorage"); + private static readonly _logger = createLogger('ComponentStorage'); private storages = new Map | SoAStorage>(); /** diff --git a/packages/core/src/ECS/Core/ComponentStorage/ComponentRegistry.ts b/packages/core/src/ECS/Core/ComponentStorage/ComponentRegistry.ts index 3bc51610..948aa2c5 100644 --- a/packages/core/src/ECS/Core/ComponentStorage/ComponentRegistry.ts +++ b/packages/core/src/ECS/Core/ComponentStorage/ComponentRegistry.ts @@ -1,11 +1,12 @@ -import {Component} from "../../Component"; -import {BitMask64Utils, BitMask64Data} from "../../Utils/BigIntCompatibility"; -import {createLogger} from "../../../Utils/Logger"; -import {getComponentTypeName} from "../../Decorators"; +import { Component } from '../../Component'; +import { BitMask64Utils, BitMask64Data } from '../../Utils/BigIntCompatibility'; +import { createLogger } from '../../../Utils/Logger'; +import { getComponentTypeName } from '../../Decorators'; /** * 组件类型定义 */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type ComponentType = new (...args: any[]) => T; /** @@ -13,7 +14,7 @@ export type ComponentType = new (...args: any[] * 管理组件类型的位掩码分配 */ export class ComponentRegistry { - protected static readonly _logger = createLogger("ComponentStorage"); + protected static readonly _logger = createLogger('ComponentStorage'); private static componentTypes = new Map(); private static bitIndexToType = new Map(); private static componentNameToType = new Map(); @@ -175,7 +176,7 @@ export class ComponentRegistry { */ public static createComponentMask(componentNames: string[]): BitMask64Data { const sortedNames = [...componentNames].sort(); - const cacheKey = `multi:${sortedNames.join(",")}`; + const cacheKey = `multi:${sortedNames.join(',')}`; if (this.maskCache.has(cacheKey)) { return this.maskCache.get(cacheKey)!; diff --git a/packages/core/src/ECS/Core/EventBus.ts b/packages/core/src/ECS/Core/EventBus.ts index 00c01348..3cad9d58 100644 --- a/packages/core/src/ECS/Core/EventBus.ts +++ b/packages/core/src/ECS/Core/EventBus.ts @@ -8,25 +8,25 @@ import { ISystemEventData, ISceneEventData, IPerformanceEventData -} from "../../Types"; -import {createLogger} from "../../Utils/Logger"; +} from '../../Types'; +import { createLogger } from '../../Utils/Logger'; import { TypeSafeEventSystem, EventListenerConfig, EventStats -} from "./EventSystem"; +} from './EventSystem'; import { ECSEventType, EventPriority, EventTypeValidator -} from "../CoreEvents"; +} from '../CoreEvents'; /** * 增强的事件总线实现 * 基于TypeSafeEventSystem,提供类型安全的事件发布订阅机制 */ export class EventBus implements IEventBus { - private static readonly _logger = createLogger("EventBus"); + private static readonly _logger = createLogger('EventBus'); private eventSystem: TypeSafeEventSystem; private eventIdCounter = 0; private isDebugMode = false; @@ -112,7 +112,7 @@ export class EventBus implements IEventBus { handler: (data: T) => void, config: IEventListenerConfig = {} ): string { - return this.on(eventType, handler, {...config, once: true}); + return this.on(eventType, handler, { ...config, once: true }); } /** @@ -127,7 +127,7 @@ export class EventBus implements IEventBus { handler: (data: T) => Promise, config: IEventListenerConfig = {} ): string { - return this.on(eventType, handler as any, {...config, async: true}); + return this.on(eventType, handler as (data: T) => void, { ...config, async: true }); } /** @@ -187,7 +187,7 @@ export class EventBus implements IEventBus { */ public clear(): void { if (this.isDebugMode) { - EventBus._logger.info("清空所有监听器"); + EventBus._logger.info('清空所有监听器'); } this.eventSystem.clear(); @@ -399,7 +399,7 @@ export class EventBus implements IEventBus { return { timestamp: Date.now(), eventId: `${eventType}_${++this.eventIdCounter}`, - source: "EventBus" + source: 'EventBus' } as T & IEventData; } @@ -413,7 +413,7 @@ export class EventBus implements IEventBus { enhanced.eventId = `${eventType}_${++this.eventIdCounter}`; } if (!enhanced.source) { - enhanced.source = "EventBus"; + enhanced.source = 'EventBus'; } return enhanced; diff --git a/packages/core/src/ECS/Core/EventSystem.ts b/packages/core/src/ECS/Core/EventSystem.ts index f252d796..ffc5d630 100644 --- a/packages/core/src/ECS/Core/EventSystem.ts +++ b/packages/core/src/ECS/Core/EventSystem.ts @@ -1,14 +1,14 @@ -import {createLogger} from "../../Utils/Logger"; +import { createLogger } from '../../Utils/Logger'; /** * 事件处理器函数类型 */ -export type EventHandler = (event: T) => void; +export type EventHandler = (event: T) => void; /** * 异步事件处理器函数类型 */ -export type AsyncEventHandler = (event: T) => Promise; +export type AsyncEventHandler = (event: T) => Promise; /** * 事件监听器配置 @@ -21,13 +21,13 @@ export interface EventListenerConfig { /** 是否异步执行 */ async?: boolean; /** 执行上下文 */ - context?: any; + context?: unknown; } /** * 内部事件监听器 */ -interface InternalEventListener { +interface InternalEventListener { handler: EventHandler | AsyncEventHandler; config: EventListenerConfig; id: string; @@ -68,11 +68,11 @@ export interface EventBatchConfig { * 支持同步/异步事件、优先级、批处理等功能 */ export class TypeSafeEventSystem { - private static readonly _logger = createLogger("EventSystem"); + private static readonly _logger = createLogger('EventSystem'); private listeners = new Map(); private stats = new Map(); - private batchQueue = new Map(); - private batchTimers = new Map(); + private batchQueue = new Map(); + private batchTimers = new Map>(); private batchConfigs = new Map(); private nextListenerId = 0; private isEnabled = true; @@ -105,7 +105,7 @@ export class TypeSafeEventSystem { handler: EventHandler, config: EventListenerConfig = {} ): string { - return this.addListener(eventType, handler, {...config, once: true}); + return this.addListener(eventType, handler, { ...config, once: true }); } /** @@ -120,7 +120,7 @@ export class TypeSafeEventSystem { handler: AsyncEventHandler, config: EventListenerConfig = {} ): string { - return this.addListener(eventType, handler, {...config, async: true}); + return this.addListener(eventType, handler, { ...config, async: true }); } /** @@ -340,7 +340,7 @@ export class TypeSafeEventSystem { // 检查监听器数量限制 if (listeners.length >= this.maxListeners) { TypeSafeEventSystem._logger.warn(`事件类型 ${eventType} 的监听器数量超过最大限制 (${this.maxListeners})`); - return ""; + return ''; } const listenerId = `listener_${this.nextListenerId++}`; @@ -353,7 +353,7 @@ export class TypeSafeEventSystem { id: listenerId }; - listeners.push(listener); + listeners.push(listener as InternalEventListener); // 初始化统计信息 if (!this.stats.has(eventType)) { @@ -488,7 +488,7 @@ export class TypeSafeEventSystem { this.flushBatch(eventType); }, config.delay); - this.batchTimers.set(eventType, timer as any); + this.batchTimers.set(eventType, timer); } } diff --git a/packages/core/src/ECS/Core/Events/index.ts b/packages/core/src/ECS/Core/Events/index.ts index 575d57b7..a8de6f02 100644 --- a/packages/core/src/ECS/Core/Events/index.ts +++ b/packages/core/src/ECS/Core/Events/index.ts @@ -1,2 +1,2 @@ -export {EventBus, GlobalEventBus} from "../EventBus"; -export {TypeSafeEventSystem, EventListenerConfig, EventStats} from "../EventSystem"; +export { EventBus, GlobalEventBus } from '../EventBus'; +export { TypeSafeEventSystem, EventListenerConfig, EventStats } from '../EventSystem'; diff --git a/packages/core/src/ECS/Core/FluentAPI.ts b/packages/core/src/ECS/Core/FluentAPI.ts index c2c71d29..9a7033f2 100644 --- a/packages/core/src/ECS/Core/FluentAPI.ts +++ b/packages/core/src/ECS/Core/FluentAPI.ts @@ -8,4 +8,4 @@ export { createECSAPI, initializeECS, ECS -} from "./FluentAPI/index"; +} from './FluentAPI/index'; diff --git a/packages/core/src/ECS/Core/FluentAPI/ComponentBuilder.ts b/packages/core/src/ECS/Core/FluentAPI/ComponentBuilder.ts index d0014064..ac21d5ac 100644 --- a/packages/core/src/ECS/Core/FluentAPI/ComponentBuilder.ts +++ b/packages/core/src/ECS/Core/FluentAPI/ComponentBuilder.ts @@ -1,4 +1,4 @@ -import {Component} from "../../Component"; +import { Component } from '../../Component'; /** * 组件构建器 - 提供流式API创建组件 diff --git a/packages/core/src/ECS/Core/FluentAPI/ECSFluentAPI.ts b/packages/core/src/ECS/Core/FluentAPI/ECSFluentAPI.ts index e4defd60..9ab2fc7b 100644 --- a/packages/core/src/ECS/Core/FluentAPI/ECSFluentAPI.ts +++ b/packages/core/src/ECS/Core/FluentAPI/ECSFluentAPI.ts @@ -1,13 +1,13 @@ -import {Entity} from "../../Entity"; -import {Component} from "../../Component"; -import {IScene} from "../../IScene"; -import {ComponentType} from "../ComponentStorage"; -import {QuerySystem, QueryBuilder} from "../QuerySystem"; -import {TypeSafeEventSystem} from "../EventSystem"; -import {EntityBuilder} from "./EntityBuilder"; -import {SceneBuilder} from "./SceneBuilder"; -import {ComponentBuilder} from "./ComponentBuilder"; -import {EntityBatchOperator} from "./EntityBatchOperator"; +import { Entity } from '../../Entity'; +import { Component } from '../../Component'; +import { IScene } from '../../IScene'; +import { ComponentType } from '../ComponentStorage'; +import { QuerySystem, QueryBuilder } from '../QuerySystem'; +import { TypeSafeEventSystem } from '../EventSystem'; +import { EntityBuilder } from './EntityBuilder'; +import { SceneBuilder } from './SceneBuilder'; +import { ComponentBuilder } from './ComponentBuilder'; +import { EntityBatchOperator } from './EntityBatchOperator'; /** * ECS流式API主入口 diff --git a/packages/core/src/ECS/Core/FluentAPI/EntityBatchOperator.ts b/packages/core/src/ECS/Core/FluentAPI/EntityBatchOperator.ts index 30a2c368..8eb8b04f 100644 --- a/packages/core/src/ECS/Core/FluentAPI/EntityBatchOperator.ts +++ b/packages/core/src/ECS/Core/FluentAPI/EntityBatchOperator.ts @@ -1,6 +1,6 @@ -import {Entity} from "../../Entity"; -import {Component} from "../../Component"; -import {ComponentType} from "../ComponentStorage"; +import { Entity } from '../../Entity'; +import { Component } from '../../Component'; +import { ComponentType } from '../ComponentStorage'; /** * 实体批量操作器 diff --git a/packages/core/src/ECS/Core/FluentAPI/EntityBuilder.ts b/packages/core/src/ECS/Core/FluentAPI/EntityBuilder.ts index 5943344f..a49881db 100644 --- a/packages/core/src/ECS/Core/FluentAPI/EntityBuilder.ts +++ b/packages/core/src/ECS/Core/FluentAPI/EntityBuilder.ts @@ -1,7 +1,7 @@ -import {Entity} from "../../Entity"; -import {Component} from "../../Component"; -import {IScene} from "../../IScene"; -import {ComponentType, ComponentStorageManager} from "../ComponentStorage"; +import { Entity } from '../../Entity'; +import { Component } from '../../Component'; +import { IScene } from '../../IScene'; +import { ComponentType, ComponentStorageManager } from '../ComponentStorage'; /** * 实体构建器 - 提供流式API创建和配置实体 @@ -15,8 +15,8 @@ export class EntityBuilder { this.scene = scene; this.storageManager = storageManager; const id = scene.identifierPool.checkOut(); - this.entity = new Entity("", id); - this.entity.scene = this.scene as any; + this.entity = new Entity('', id); + this.entity.scene = this.scene; } /** diff --git a/packages/core/src/ECS/Core/FluentAPI/SceneBuilder.ts b/packages/core/src/ECS/Core/FluentAPI/SceneBuilder.ts index 95443690..33b1c830 100644 --- a/packages/core/src/ECS/Core/FluentAPI/SceneBuilder.ts +++ b/packages/core/src/ECS/Core/FluentAPI/SceneBuilder.ts @@ -1,7 +1,7 @@ -import {Entity} from "../../Entity"; -import {Scene} from "../../Scene"; -import {EntitySystem} from "../../Systems/EntitySystem"; -import {EntityBuilder} from "./EntityBuilder"; +import { Entity } from '../../Entity'; +import { Scene } from '../../Scene'; +import { EntitySystem } from '../../Systems/EntitySystem'; +import { EntityBuilder } from './EntityBuilder'; /** * 场景构建器 - 提供流式API创建和配置场景 diff --git a/packages/core/src/ECS/Core/FluentAPI/index.ts b/packages/core/src/ECS/Core/FluentAPI/index.ts index 9a4ba644..f141b41d 100644 --- a/packages/core/src/ECS/Core/FluentAPI/index.ts +++ b/packages/core/src/ECS/Core/FluentAPI/index.ts @@ -1,5 +1,5 @@ -export {EntityBuilder} from "./EntityBuilder"; -export {SceneBuilder} from "./SceneBuilder"; -export {ComponentBuilder} from "./ComponentBuilder"; -export {EntityBatchOperator} from "./EntityBatchOperator"; -export {ECSFluentAPI, createECSAPI, initializeECS, ECS} from "./ECSFluentAPI"; +export { EntityBuilder } from './EntityBuilder'; +export { SceneBuilder } from './SceneBuilder'; +export { ComponentBuilder } from './ComponentBuilder'; +export { EntityBatchOperator } from './EntityBatchOperator'; +export { ECSFluentAPI, createECSAPI, initializeECS, ECS } from './ECSFluentAPI'; diff --git a/packages/core/src/ECS/Core/Query/TypedQuery.ts b/packages/core/src/ECS/Core/Query/TypedQuery.ts index baf9e086..2c7169d4 100644 --- a/packages/core/src/ECS/Core/Query/TypedQuery.ts +++ b/packages/core/src/ECS/Core/Query/TypedQuery.ts @@ -4,9 +4,9 @@ * 提供完整的TypeScript类型推断,在编译时确保类型安全 */ -import type {Entity} from "../../Entity"; -import type {ComponentConstructor} from "../../../Types/TypeHelpers"; -import {Matcher, type QueryCondition} from "../../Utils/Matcher"; +import type { Entity } from '../../Entity'; +import type { ComponentConstructor } from '../../../Types/TypeHelpers'; +import { Matcher, type QueryCondition } from '../../Utils/Matcher'; /** * 类型安全的查询结果 @@ -326,8 +326,8 @@ export class TypedQueryBuilder< all: [...this._all] as ComponentConstructor[], any: [...this._any] as ComponentConstructor[], none: [...this._none] as ComponentConstructor[], - ...(this._tag !== undefined && {tag: this._tag}), - ...(this._name !== undefined && {name: this._name}) + ...(this._tag !== undefined && { tag: this._tag }), + ...(this._name !== undefined && { name: this._name }) }; } diff --git a/packages/core/src/ECS/Core/Query/index.ts b/packages/core/src/ECS/Core/Query/index.ts index 67f73eca..89efc042 100644 --- a/packages/core/src/ECS/Core/Query/index.ts +++ b/packages/core/src/ECS/Core/Query/index.ts @@ -1,2 +1,2 @@ -export {QuerySystem} from "../QuerySystem"; -export {ECSFluentAPI, createECSAPI} from "../FluentAPI"; +export { QuerySystem } from '../QuerySystem'; +export { ECSFluentAPI, createECSAPI } from '../FluentAPI'; diff --git a/packages/core/src/ECS/Core/QuerySystem.ts b/packages/core/src/ECS/Core/QuerySystem.ts index 0f6756cc..0b96b330 100644 --- a/packages/core/src/ECS/Core/QuerySystem.ts +++ b/packages/core/src/ECS/Core/QuerySystem.ts @@ -1,14 +1,14 @@ -import {Entity} from "../Entity"; -import {Component} from "../Component"; -import {ComponentRegistry, ComponentType} from "./ComponentStorage"; -import {BitMask64Utils, BitMask64Data} from "../Utils/BigIntCompatibility"; -import {createLogger} from "../../Utils/Logger"; -import {getComponentTypeName} from "../Decorators"; -import {Archetype, ArchetypeSystem} from "./ArchetypeSystem"; -import {ReactiveQuery, ReactiveQueryConfig} from "./ReactiveQuery"; -import {QueryCondition, QueryConditionType, QueryResult} from "./QueryTypes"; +import { Entity } from '../Entity'; +import { Component } from '../Component'; +import { ComponentRegistry, ComponentType } from './ComponentStorage'; +import { BitMask64Utils, BitMask64Data } from '../Utils/BigIntCompatibility'; +import { createLogger } from '../../Utils/Logger'; +import { getComponentTypeName } from '../Decorators'; +import { Archetype, ArchetypeSystem } from './ArchetypeSystem'; +import { ReactiveQuery, ReactiveQueryConfig } from './ReactiveQuery'; +import { QueryCondition, QueryConditionType, QueryResult } from './QueryTypes'; -export {QueryCondition, QueryConditionType, QueryResult}; +export { QueryCondition, QueryConditionType, QueryResult }; /** * 实体索引结构 @@ -43,7 +43,7 @@ interface QueryCacheEntry { * ``` */ export class QuerySystem { - private _logger = createLogger("QuerySystem"); + private _logger = createLogger('QuerySystem'); private entities: Entity[] = []; private entityIndex: EntityIndex; @@ -550,7 +550,7 @@ export class QuerySystem { const startTime = performance.now(); this.queryStats.totalQueries++; - const cacheKey = this.generateCacheKey("component", [componentType]); + const cacheKey = this.generateCacheKey('component', [componentType]); // 检查缓存 const cached = this.getFromCache(cacheKey); @@ -627,7 +627,7 @@ export class QuerySystem { // 如果还是太满,移除最少使用的条目 if (this.queryCache.size >= this.cacheMaxSize) { let minHitCount = Infinity; - let oldestKey = ""; + let oldestKey = ''; let oldestTimestamp = Infinity; // 单次遍历找到最少使用或最旧的条目 @@ -682,7 +682,7 @@ export class QuerySystem { const sortKey = componentTypes.map((t) => { const name = getComponentTypeName(t); return name; - }).sort().join(","); + }).sort().join(','); const fullKey = `${prefix}:${sortKey}`; @@ -729,7 +729,7 @@ export class QuerySystem { config?: ReactiveQueryConfig ): ReactiveQuery { if (!componentTypes || componentTypes.length === 0) { - throw new Error("组件类型列表不能为空"); + throw new Error('组件类型列表不能为空'); } const mask = this.createComponentMask(componentTypes); @@ -747,7 +747,7 @@ export class QuerySystem { ); query.initializeWith(initialEntities); - const cacheKey = this.generateCacheKey("all", componentTypes); + const cacheKey = this.generateCacheKey('all', componentTypes); this._reactiveQueries.set(cacheKey, query); for (const type of componentTypes) { @@ -812,7 +812,7 @@ export class QuerySystem { // 生成缓存键 const cacheKey = componentTypes.map((t) => { return getComponentTypeName(t); - }).sort().join(","); + }).sort().join(','); // 检查缓存 const cached = this.componentMaskCache.get(cacheKey); @@ -895,7 +895,11 @@ export class QuerySystem { cacheHitRate: string; }; optimizationStats: { - archetypeSystem: any; + archetypeSystem: Array<{ + id: BitMask64Data; + componentTypes: string[]; + entityCount: number; + }>; }; cacheStats: { size: number; @@ -912,7 +916,7 @@ export class QuerySystem { queryStats: { ...this.queryStats, cacheHitRate: this.queryStats.totalQueries > 0 ? - (this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + "%" : "0%" + (this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + '%' : '0%' }, optimizationStats: { archetypeSystem: this.archetypeSystem.getAllArchetypes().map((a) => ({ @@ -924,7 +928,7 @@ export class QuerySystem { cacheStats: { size: this._reactiveQueries.size, hitRate: this.queryStats.totalQueries > 0 ? - (this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + "%" : "0%" + (this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + '%' : '0%' } }; } @@ -1022,7 +1026,7 @@ export class QuerySystem { ): Entity[] { switch (queryType) { case QueryConditionType.ALL: { - const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, "AND"); + const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'AND'); const entities: Entity[] = []; for (const archetype of archetypeResult.archetypes) { for (const entity of archetype.entities) { @@ -1032,7 +1036,7 @@ export class QuerySystem { return entities; } case QueryConditionType.ANY: { - const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, "OR"); + const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'OR'); const entities: Entity[] = []; for (const archetype of archetypeResult.archetypes) { for (const entity of archetype.entities) { @@ -1172,7 +1176,7 @@ export class QuerySystem { * ``` */ export class QueryBuilder { - private _logger = createLogger("QueryBuilder"); + private _logger = createLogger('QueryBuilder'); private conditions: QueryCondition[] = []; private querySystem: QuerySystem; diff --git a/packages/core/src/ECS/Core/QueryTypes.ts b/packages/core/src/ECS/Core/QueryTypes.ts index c934f2bc..64a5acd5 100644 --- a/packages/core/src/ECS/Core/QueryTypes.ts +++ b/packages/core/src/ECS/Core/QueryTypes.ts @@ -1,17 +1,17 @@ -import {ComponentType} from "./ComponentStorage"; -import {BitMask64Data} from "../Utils/BigIntCompatibility"; -import {Entity} from "../Entity"; +import { ComponentType } from './ComponentStorage'; +import { BitMask64Data } from '../Utils/BigIntCompatibility'; +import { Entity } from '../Entity'; /** * 查询条件类型 */ export enum QueryConditionType { /** 必须包含所有指定组件 */ - ALL = "all", + ALL = 'all', /** 必须包含任意一个指定组件 */ - ANY = "any", + ANY = 'any', /** 不能包含任何指定组件 */ - NONE = "none" + NONE = 'none' } /** diff --git a/packages/core/src/ECS/Core/ReactiveQuery.ts b/packages/core/src/ECS/Core/ReactiveQuery.ts index ee244b1e..5c2194ab 100644 --- a/packages/core/src/ECS/Core/ReactiveQuery.ts +++ b/packages/core/src/ECS/Core/ReactiveQuery.ts @@ -1,20 +1,20 @@ -import {Entity} from "../Entity"; -import {QueryCondition, QueryConditionType} from "./QueryTypes"; -import {BitMask64Utils} from "../Utils/BigIntCompatibility"; -import {createLogger} from "../../Utils/Logger"; +import { Entity } from '../Entity'; +import { QueryCondition, QueryConditionType } from './QueryTypes'; +import { BitMask64Utils } from '../Utils/BigIntCompatibility'; +import { createLogger } from '../../Utils/Logger'; -const logger = createLogger("ReactiveQuery"); +const logger = createLogger('ReactiveQuery'); /** * 响应式查询变化类型 */ export enum ReactiveQueryChangeType { /** 实体添加到查询结果 */ - ADDED = "added", + ADDED = 'added', /** 实体从查询结果移除 */ - REMOVED = "removed", + REMOVED = 'removed', /** 查询结果批量更新 */ - BATCH_UPDATE = "batch_update" + BATCH_UPDATE = 'batch_update' } /** @@ -138,7 +138,7 @@ export class ReactiveQuery { const componentsStr = this._condition.componentTypes .map((t) => t.name) .sort() - .join(","); + .join(','); return `${typeStr}:${componentsStr}`; } @@ -153,8 +153,8 @@ export class ReactiveQuery { throw new Error(`Cannot subscribe to disposed ReactiveQuery ${this._id}`); } - if (typeof listener !== "function") { - throw new TypeError("Listener must be a function"); + if (typeof listener !== 'function') { + throw new TypeError('Listener must be a function'); } this._listeners.push(listener); @@ -239,7 +239,7 @@ export class ReactiveQuery { // 通知监听器 if (this._config.enableBatchMode) { - this.addToBatch("added", entity); + this.addToBatch('added', entity); } else { this.notifyListeners({ type: ReactiveQueryChangeType.ADDED, @@ -276,7 +276,7 @@ export class ReactiveQuery { // 通知监听器 if (this._config.enableBatchMode) { - this.addToBatch("removed", entity); + this.addToBatch('removed', entity); } else { this.notifyListeners({ type: ReactiveQueryChangeType.REMOVED, @@ -337,8 +337,8 @@ export class ReactiveQuery { /** * 添加到批量变化缓存 */ - private addToBatch(type: "added" | "removed", entity: Entity): void { - if (type === "added") { + private addToBatch(type: 'added' | 'removed', entity: Entity): void { + if (type === 'added') { this._batchChanges.added.push(entity); } else { this._batchChanges.removed.push(entity); diff --git a/packages/core/src/ECS/Core/ReferenceTracker.ts b/packages/core/src/ECS/Core/ReferenceTracker.ts index 128ef2ca..5dde1911 100644 --- a/packages/core/src/ECS/Core/ReferenceTracker.ts +++ b/packages/core/src/ECS/Core/ReferenceTracker.ts @@ -1,6 +1,6 @@ -import {Component} from "../Component"; -import type {Entity} from "../Entity"; -import type {IScene} from "../IScene"; +import { Component } from '../Component'; +import type { Entity } from '../Entity'; +import type { IScene } from '../IScene'; /** * WeakRef 接口定义 @@ -39,15 +39,22 @@ interface IWeakRefConstructor { new (target: T): IWeakRef; } +/** + * 包含 WeakRef 的全局对象类型 + */ +interface GlobalWithWeakRef { + WeakRef?: IWeakRefConstructor; +} + /** * WeakRef 实现 * * 优先使用原生 WeakRef,不支持时降级到 Polyfill */ const WeakRefImpl: IWeakRefConstructor = ( - (typeof globalThis !== "undefined" && (globalThis as any).WeakRef) || - (typeof global !== "undefined" && (global as any).WeakRef) || - (typeof window !== "undefined" && (window as any).WeakRef) || + (typeof globalThis !== 'undefined' && (globalThis as GlobalWithWeakRef).WeakRef) || + (typeof global !== 'undefined' && (global as unknown as GlobalWithWeakRef).WeakRef) || + (typeof window !== 'undefined' && (window as unknown as GlobalWithWeakRef).WeakRef) || WeakRefPolyfill ) as IWeakRefConstructor; @@ -174,6 +181,8 @@ export class ReferenceTracker { for (const record of validRecords) { const component = record.component.deref(); if (component) { + // 使用 any 进行动态属性访问,因为无法静态验证所有可能的组件属性 + // eslint-disable-next-line @typescript-eslint/no-explicit-any (component as any)[record.propertyKey] = null; } } @@ -287,7 +296,7 @@ export class ReferenceTracker { * 获取调试信息 */ public getDebugInfo(): object { - const info: Record = {}; + const info: Record = {}; for (const [entityId, records] of this._references.entries()) { const validRecords = []; diff --git a/packages/core/src/ECS/Core/SoAStorage.ts b/packages/core/src/ECS/Core/SoAStorage.ts index 797f5160..6d7ac76c 100644 --- a/packages/core/src/ECS/Core/SoAStorage.ts +++ b/packages/core/src/ECS/Core/SoAStorage.ts @@ -1,13 +1,43 @@ -import {Component} from "../Component"; -import {ComponentType} from "./ComponentStorage"; -import {createLogger} from "../../Utils/Logger"; +import { Component } from '../Component'; +import { ComponentType } from './ComponentStorage'; +import { createLogger } from '../../Utils/Logger'; + +/** + * 装饰器目标类型,用于存储元数据 + */ +interface DecoratorTarget { + constructor: ComponentTypeWithMetadata; +} + +/** + * 带有元数据的组件类型 + */ +interface ComponentTypeWithMetadata { + __enableSoA?: boolean; + __highPrecisionFields?: Set; + __float64Fields?: Set; + __float32Fields?: Set; + __int32Fields?: Set; + __uint32Fields?: Set; + __int16Fields?: Set; + __uint16Fields?: Set; + __int8Fields?: Set; + __uint8Fields?: Set; + __uint8ClampedFields?: Set; + __serializeMapFields?: Set; + __serializeSetFields?: Set; + __serializeArrayFields?: Set; + __deepCopyFields?: Set; + __autoTypedFields?: Map>; + __bigIntFields?: Set; +} /** * 启用SoA优化装饰器 * 默认关闭SoA,只有在大规模批量操作场景下才建议开启 */ export function EnableSoA(target: T): T { - (target as any).__enableSoA = true; + (target as unknown as { __enableSoA: boolean }).__enableSoA = true; return target; } @@ -16,7 +46,7 @@ export function EnableSoA(target: T): T { * 高精度数值装饰器 * 标记字段需要保持完整精度,存储为复杂对象而非TypedArray */ -export function HighPrecision(target: any, propertyKey: string | symbol): void { +export function HighPrecision(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__highPrecisionFields) { target.constructor.__highPrecisionFields = new Set(); @@ -28,7 +58,7 @@ export function HighPrecision(target: any, propertyKey: string | symbol): void { * 64位浮点数装饰器 * 标记字段使用Float64Array存储(更高精度但更多内存) */ -export function Float64(target: any, propertyKey: string | symbol): void { +export function Float64(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__float64Fields) { target.constructor.__float64Fields = new Set(); @@ -40,7 +70,7 @@ export function Float64(target: any, propertyKey: string | symbol): void { * 32位浮点数装饰器 * 标记字段使用Float32Array存储(默认类型,平衡性能和精度) */ -export function Float32(target: any, propertyKey: string | symbol): void { +export function Float32(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__float32Fields) { target.constructor.__float32Fields = new Set(); @@ -52,7 +82,7 @@ export function Float32(target: any, propertyKey: string | symbol): void { * 32位整数装饰器 * 标记字段使用Int32Array存储(适用于整数值) */ -export function Int32(target: any, propertyKey: string | symbol): void { +export function Int32(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__int32Fields) { target.constructor.__int32Fields = new Set(); @@ -64,7 +94,7 @@ export function Int32(target: any, propertyKey: string | symbol): void { * 32位无符号整数装饰器 * 标记字段使用Uint32Array存储(适用于无符号整数,如ID、标志位等) */ -export function Uint32(target: any, propertyKey: string | symbol): void { +export function Uint32(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__uint32Fields) { target.constructor.__uint32Fields = new Set(); @@ -76,7 +106,7 @@ export function Uint32(target: any, propertyKey: string | symbol): void { * 16位整数装饰器 * 标记字段使用Int16Array存储(适用于小范围整数) */ -export function Int16(target: any, propertyKey: string | symbol): void { +export function Int16(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__int16Fields) { target.constructor.__int16Fields = new Set(); @@ -88,7 +118,7 @@ export function Int16(target: any, propertyKey: string | symbol): void { * 16位无符号整数装饰器 * 标记字段使用Uint16Array存储(适用于小范围无符号整数) */ -export function Uint16(target: any, propertyKey: string | symbol): void { +export function Uint16(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__uint16Fields) { target.constructor.__uint16Fields = new Set(); @@ -100,7 +130,7 @@ export function Uint16(target: any, propertyKey: string | symbol): void { * 8位整数装饰器 * 标记字段使用Int8Array存储(适用于很小的整数值) */ -export function Int8(target: any, propertyKey: string | symbol): void { +export function Int8(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__int8Fields) { target.constructor.__int8Fields = new Set(); @@ -112,7 +142,7 @@ export function Int8(target: any, propertyKey: string | symbol): void { * 8位无符号整数装饰器 * 标记字段使用Uint8Array存储(适用于字节值、布尔标志等) */ -export function Uint8(target: any, propertyKey: string | symbol): void { +export function Uint8(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__uint8Fields) { target.constructor.__uint8Fields = new Set(); @@ -124,7 +154,7 @@ export function Uint8(target: any, propertyKey: string | symbol): void { * 8位夹紧整数装饰器 * 标记字段使用Uint8ClampedArray存储(适用于颜色值等需要夹紧的数据) */ -export function Uint8Clamped(target: any, propertyKey: string | symbol): void { +export function Uint8Clamped(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__uint8ClampedFields) { target.constructor.__uint8ClampedFields = new Set(); @@ -137,7 +167,7 @@ export function Uint8Clamped(target: any, propertyKey: string | symbol): void { * 序列化Map装饰器 * 标记Map字段需要序列化/反序列化存储 */ -export function SerializeMap(target: any, propertyKey: string | symbol): void { +export function SerializeMap(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__serializeMapFields) { target.constructor.__serializeMapFields = new Set(); @@ -149,7 +179,7 @@ export function SerializeMap(target: any, propertyKey: string | symbol): void { * 序列化Set装饰器 * 标记Set字段需要序列化/反序列化存储 */ -export function SerializeSet(target: any, propertyKey: string | symbol): void { +export function SerializeSet(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__serializeSetFields) { target.constructor.__serializeSetFields = new Set(); @@ -161,7 +191,7 @@ export function SerializeSet(target: any, propertyKey: string | symbol): void { * 序列化Array装饰器 * 标记Array字段需要序列化/反序列化存储 */ -export function SerializeArray(target: any, propertyKey: string | symbol): void { +export function SerializeArray(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__serializeArrayFields) { target.constructor.__serializeArrayFields = new Set(); @@ -173,7 +203,7 @@ export function SerializeArray(target: any, propertyKey: string | symbol): void * 深拷贝装饰器 * 标记字段需要深拷贝处理(适用于嵌套对象) */ -export function DeepCopy(target: any, propertyKey: string | symbol): void { +export function DeepCopy(target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__deepCopyFields) { target.constructor.__deepCopyFields = new Set(); @@ -197,7 +227,7 @@ export function AutoTyped(options?: { precision?: boolean; signed?: boolean; }) { - return function (target: any, propertyKey: string | symbol): void { + return function (target: DecoratorTarget, propertyKey: string | symbol): void { const key = String(propertyKey); if (!target.constructor.__autoTypedFields) { target.constructor.__autoTypedFields = new Map(); @@ -214,6 +244,7 @@ export class TypeInference { /** * 根据数值范围推断最优的TypedArray类型 */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any public static inferOptimalType(value: any, options: { minValue?: number; maxValue?: number; @@ -222,23 +253,23 @@ export class TypeInference { } = {}): string { const type = typeof value; - if (type === "boolean") { - return "uint8"; // 布尔值使用最小的无符号整数 + if (type === 'boolean') { + return 'uint8'; // 布尔值使用最小的无符号整数 } - if (type !== "number") { - return "float32"; // 非数值类型默认使用Float32 + if (type !== 'number') { + return 'float32'; // 非数值类型默认使用Float32 } - const {minValue, maxValue, precision, signed} = options; + const { minValue, maxValue, precision, signed } = options; // 如果显式要求精度,使用浮点数 if (precision === true) { // 检查是否需要双精度 if (Math.abs(value) > 3.4028235e+38 || (minValue !== undefined && Math.abs(minValue) > 3.4028235e+38) || (maxValue !== undefined && Math.abs(maxValue) > 3.4028235e+38)) { - return "float64"; + return 'float64'; } - return "float32"; + return 'float32'; } // 如果显式禁用精度,或者是整数值,尝试使用整数数组 @@ -251,48 +282,48 @@ export class TypeInference { if (needsSigned) { // 有符号整数 if (actualMin >= -128 && actualMax <= 127) { - return "int8"; + return 'int8'; } else if (actualMin >= -32768 && actualMax <= 32767) { - return "int16"; + return 'int16'; } else if (actualMin >= -2147483648 && actualMax <= 2147483647) { - return "int32"; + return 'int32'; } else { - return "float64"; // 超出int32范围,使用双精度浮点 + return 'float64'; // 超出int32范围,使用双精度浮点 } } else { // 无符号整数 if (actualMax <= 255) { - return "uint8"; + return 'uint8'; } else if (actualMax <= 65535) { - return "uint16"; + return 'uint16'; } else if (actualMax <= 4294967295) { - return "uint32"; + return 'uint32'; } else { - return "float64"; // 超出uint32范围,使用双精度浮点 + return 'float64'; // 超出uint32范围,使用双精度浮点 } } } // 默认情况:检查是否为小数 if (!Number.isInteger(value)) { - return "float32"; + return 'float32'; } // 整数值,但没有指定范围,根据值的大小选择 if (value >= 0 && value <= 255) { - return "uint8"; + return 'uint8'; } else if (value >= -128 && value <= 127) { - return "int8"; + return 'int8'; } else if (value >= 0 && value <= 65535) { - return "uint16"; + return 'uint16'; } else if (value >= -32768 && value <= 32767) { - return "int16"; + return 'int16'; } else if (value >= 0 && value <= 4294967295) { - return "uint32"; + return 'uint32'; } else if (value >= -2147483648 && value <= 2147483647) { - return "int32"; + return 'int32'; } else { - return "float64"; + return 'float64'; } } @@ -301,15 +332,15 @@ export class TypeInference { */ public static getTypedArrayConstructor(typeName: string): typeof Float32Array | typeof Float64Array | typeof Int32Array | typeof Uint32Array | typeof Int16Array | typeof Uint16Array | typeof Int8Array | typeof Uint8Array | typeof Uint8ClampedArray { switch (typeName) { - case "float32": return Float32Array; - case "float64": return Float64Array; - case "int32": return Int32Array; - case "uint32": return Uint32Array; - case "int16": return Int16Array; - case "uint16": return Uint16Array; - case "int8": return Int8Array; - case "uint8": return Uint8Array; - case "uint8clamped": return Uint8ClampedArray; + case 'float32': return Float32Array; + case 'float64': return Float64Array; + case 'int32': return Int32Array; + case 'uint32': return Uint32Array; + case 'int16': return Int16Array; + case 'uint16': return Uint16Array; + case 'int8': return Int8Array; + case 'uint8': return Uint8Array; + case 'uint8clamped': return Uint8ClampedArray; default: return Float32Array; } } @@ -334,11 +365,11 @@ export type SupportedTypedArray = * 使用Structure of Arrays存储模式,在大规模批量操作时提供优异性能 */ export class SoAStorage { - private static readonly _logger = createLogger("SoAStorage"); + private static readonly _logger = createLogger('SoAStorage'); private fields = new Map(); private stringFields = new Map(); // 专门存储字符串 private serializedFields = new Map(); // 序列化存储Map/Set/Array - private complexFields = new Map>(); // 存储复杂对象 + private complexFields = new Map>(); // 存储复杂对象 private entityToIndex = new Map(); private indexToEntity: number[] = []; private freeIndices: number[] = []; @@ -353,28 +384,28 @@ export class SoAStorage { private initializeFields(componentType: ComponentType): void { const instance = new componentType(); - const highPrecisionFields = (componentType as any).__highPrecisionFields || new Set(); - const float64Fields = (componentType as any).__float64Fields || new Set(); - const float32Fields = (componentType as any).__float32Fields || new Set(); - const int32Fields = (componentType as any).__int32Fields || new Set(); - const uint32Fields = (componentType as any).__uint32Fields || new Set(); - const int16Fields = (componentType as any).__int16Fields || new Set(); - const uint16Fields = (componentType as any).__uint16Fields || new Set(); - const int8Fields = (componentType as any).__int8Fields || new Set(); - const uint8Fields = (componentType as any).__uint8Fields || new Set(); - const uint8ClampedFields = (componentType as any).__uint8ClampedFields || new Set(); - const autoTypedFields = (componentType as any).__autoTypedFields || new Map(); - const serializeMapFields = (componentType as any).__serializeMapFields || new Set(); - const serializeSetFields = (componentType as any).__serializeSetFields || new Set(); - const serializeArrayFields = (componentType as any).__serializeArrayFields || new Set(); - // const deepCopyFields = (componentType as any).__deepCopyFields || new Set(); // 未使用,但保留供future使用 + const highPrecisionFields = (componentType as unknown as ComponentTypeWithMetadata).__highPrecisionFields || new Set(); + const float64Fields = (componentType as unknown as ComponentTypeWithMetadata).__float64Fields || new Set(); + const float32Fields = (componentType as unknown as ComponentTypeWithMetadata).__float32Fields || new Set(); + const int32Fields = (componentType as unknown as ComponentTypeWithMetadata).__int32Fields || new Set(); + const uint32Fields = (componentType as unknown as ComponentTypeWithMetadata).__uint32Fields || new Set(); + const int16Fields = (componentType as unknown as ComponentTypeWithMetadata).__int16Fields || new Set(); + const uint16Fields = (componentType as unknown as ComponentTypeWithMetadata).__uint16Fields || new Set(); + const int8Fields = (componentType as unknown as ComponentTypeWithMetadata).__int8Fields || new Set(); + const uint8Fields = (componentType as unknown as ComponentTypeWithMetadata).__uint8Fields || new Set(); + const uint8ClampedFields = (componentType as unknown as ComponentTypeWithMetadata).__uint8ClampedFields || new Set(); + const autoTypedFields = (componentType as unknown as ComponentTypeWithMetadata).__autoTypedFields || new Map(); + const serializeMapFields = (componentType as unknown as ComponentTypeWithMetadata).__serializeMapFields || new Set(); + const serializeSetFields = (componentType as unknown as ComponentTypeWithMetadata).__serializeSetFields || new Set(); + const serializeArrayFields = (componentType as unknown as ComponentTypeWithMetadata).__serializeArrayFields || new Set(); + // const deepCopyFields = (componentType as unknown as ComponentTypeWithMetadata).__deepCopyFields || new Set(); // 未使用,但保留供future使用 for (const key in instance) { - if (Object.prototype.hasOwnProperty.call(instance, key) && key !== "id") { + if (Object.prototype.hasOwnProperty.call(instance, key) && key !== 'id') { const value = (instance as any)[key]; const type = typeof value; - if (type === "number") { + if (type === 'number') { if (highPrecisionFields.has(key)) { // 标记为高精度,作为复杂对象处理 // 不添加到fields,会在updateComponentAtIndex中自动添加到complexFields @@ -416,7 +447,7 @@ export class SoAStorage { // 默认使用Float32Array this.fields.set(key, new Float32Array(this._capacity)); } - } else if (type === "boolean") { + } else if (type === 'boolean') { // 布尔值默认使用Uint8Array存储为0/1(更节省内存) if (uint8Fields.has(key) || (!float32Fields.has(key) && !float64Fields.has(key))) { this.fields.set(key, new Uint8Array(this._capacity)); @@ -424,10 +455,10 @@ export class SoAStorage { // 兼容性:如果显式指定浮点类型则使用原有方式 this.fields.set(key, new Float32Array(this._capacity)); } - } else if (type === "string") { + } else if (type === 'string') { // 字符串专门处理 this.stringFields.set(key, new Array(this._capacity)); - } else if (type === "object" && value !== null) { + } else if (type === 'object' && value !== null) { // 处理集合类型 if (serializeMapFields.has(key) || serializeSetFields.has(key) || serializeArrayFields.has(key)) { // 序列化存储 @@ -473,11 +504,11 @@ export class SoAStorage { // 处理所有字段 for (const key in component) { - if (Object.prototype.hasOwnProperty.call(component, key) && key !== "id") { + if (Object.prototype.hasOwnProperty.call(component, key) && key !== 'id') { const value = (component as any)[key]; const type = typeof value; - if (type === "number") { + if (type === 'number') { if (highPrecisionFields.has(key) || !this.fields.has(key)) { // 标记为高精度或未在TypedArray中的数值作为复杂对象存储 complexFieldMap.set(key, value); @@ -486,7 +517,7 @@ export class SoAStorage { const array = this.fields.get(key)!; array[index] = value; } - } else if (type === "boolean" && this.fields.has(key)) { + } else if (type === 'boolean' && this.fields.has(key)) { // 布尔值存储到TypedArray const array = this.fields.get(key)!; array[index] = value ? 1 : 0; @@ -536,7 +567,7 @@ export class SoAStorage { } } catch (error) { SoAStorage._logger.warn(`SoA序列化字段 ${key} 失败:`, error); - return "{}"; + return '{}'; } } @@ -569,7 +600,7 @@ export class SoAStorage { * 深拷贝对象 */ private deepClone(obj: any): any { - if (obj === null || typeof obj !== "object") { + if (obj === null || typeof obj !== 'object') { return obj; } @@ -624,7 +655,7 @@ export class SoAStorage { const value = array[index]; const fieldType = this.getFieldType(fieldName); - if (fieldType === "boolean") { + if (fieldType === 'boolean') { component[fieldName] = value === 1; } else { component[fieldName] = value; @@ -854,35 +885,35 @@ export class SoAStorage { if (array instanceof Float32Array) { bytesPerElement = 4; - typeName = "float32"; + typeName = 'float32'; } else if (array instanceof Float64Array) { bytesPerElement = 8; - typeName = "float64"; + typeName = 'float64'; } else if (array instanceof Int32Array) { bytesPerElement = 4; - typeName = "int32"; + typeName = 'int32'; } else if (array instanceof Uint32Array) { bytesPerElement = 4; - typeName = "uint32"; + typeName = 'uint32'; } else if (array instanceof Int16Array) { bytesPerElement = 2; - typeName = "int16"; + typeName = 'int16'; } else if (array instanceof Uint16Array) { bytesPerElement = 2; - typeName = "uint16"; + typeName = 'uint16'; } else if (array instanceof Int8Array) { bytesPerElement = 1; - typeName = "int8"; + typeName = 'int8'; } else if (array instanceof Uint8Array) { bytesPerElement = 1; - typeName = "uint8"; + typeName = 'uint8'; } else if (array instanceof Uint8ClampedArray) { bytesPerElement = 1; - typeName = "uint8clamped"; + typeName = 'uint8clamped'; } else { // 默认回退 bytesPerElement = 4; - typeName = "unknown"; + typeName = 'unknown'; } const memory = array.length * bytesPerElement; diff --git a/packages/core/src/ECS/Core/Storage/index.ts b/packages/core/src/ECS/Core/Storage/index.ts index f4395c91..37edc40e 100644 --- a/packages/core/src/ECS/Core/Storage/index.ts +++ b/packages/core/src/ECS/Core/Storage/index.ts @@ -1,3 +1,3 @@ -export {ComponentPool, ComponentPoolManager} from "../ComponentPool"; -export {ComponentStorage, ComponentRegistry} from "../ComponentStorage"; -export {EnableSoA, HighPrecision, Float64, Float32, Int32, SerializeMap, SoAStorage} from "../SoAStorage"; +export { ComponentPool, ComponentPoolManager } from '../ComponentPool'; +export { ComponentStorage, ComponentRegistry } from '../ComponentStorage'; +export { EnableSoA, HighPrecision, Float64, Float32, Int32, SerializeMap, SoAStorage } from '../SoAStorage'; diff --git a/packages/core/src/ECS/Core/StorageDecorators.ts b/packages/core/src/ECS/Core/StorageDecorators.ts index 078595e7..31ebbe55 100644 --- a/packages/core/src/ECS/Core/StorageDecorators.ts +++ b/packages/core/src/ECS/Core/StorageDecorators.ts @@ -46,4 +46,4 @@ export { // 类型定义 SupportedTypedArray -} from "./SoAStorage"; +} from './SoAStorage'; diff --git a/packages/core/src/ECS/CoreEvents.ts b/packages/core/src/ECS/CoreEvents.ts index a642c4ba..94aa4c4d 100644 --- a/packages/core/src/ECS/CoreEvents.ts +++ b/packages/core/src/ECS/CoreEvents.ts @@ -6,75 +6,75 @@ */ export enum ECSEventType { // 实体相关事件 - ENTITY_CREATED = "entity:created", - ENTITY_DESTROYED = "entity:destroyed", - ENTITY_ENABLED = "entity:enabled", - ENTITY_DISABLED = "entity:disabled", - ENTITY_TAG_ADDED = "entity:tag:added", - ENTITY_TAG_REMOVED = "entity:tag:removed", - ENTITY_NAME_CHANGED = "entity:name:changed", + ENTITY_CREATED = 'entity:created', + ENTITY_DESTROYED = 'entity:destroyed', + ENTITY_ENABLED = 'entity:enabled', + ENTITY_DISABLED = 'entity:disabled', + ENTITY_TAG_ADDED = 'entity:tag:added', + ENTITY_TAG_REMOVED = 'entity:tag:removed', + ENTITY_NAME_CHANGED = 'entity:name:changed', // 组件相关事件 - COMPONENT_ADDED = "component:added", - COMPONENT_REMOVED = "component:removed", - COMPONENT_MODIFIED = "component:modified", - COMPONENT_ENABLED = "component:enabled", - COMPONENT_DISABLED = "component:disabled", + COMPONENT_ADDED = 'component:added', + COMPONENT_REMOVED = 'component:removed', + COMPONENT_MODIFIED = 'component:modified', + COMPONENT_ENABLED = 'component:enabled', + COMPONENT_DISABLED = 'component:disabled', // 系统相关事件 - SYSTEM_ADDED = "system:added", - SYSTEM_REMOVED = "system:removed", - SYSTEM_ENABLED = "system:enabled", - SYSTEM_DISABLED = "system:disabled", - SYSTEM_PROCESSING_START = "system:processing:start", - SYSTEM_PROCESSING_END = "system:processing:end", - SYSTEM_ERROR = "system:error", + SYSTEM_ADDED = 'system:added', + SYSTEM_REMOVED = 'system:removed', + SYSTEM_ENABLED = 'system:enabled', + SYSTEM_DISABLED = 'system:disabled', + SYSTEM_PROCESSING_START = 'system:processing:start', + SYSTEM_PROCESSING_END = 'system:processing:end', + SYSTEM_ERROR = 'system:error', // 场景相关事件 - SCENE_CREATED = "scene:created", - SCENE_DESTROYED = "scene:destroyed", - SCENE_ACTIVATED = "scene:activated", - SCENE_DEACTIVATED = "scene:deactivated", - SCENE_PAUSED = "scene:paused", - SCENE_RESUMED = "scene:resumed", + SCENE_CREATED = 'scene:created', + SCENE_DESTROYED = 'scene:destroyed', + SCENE_ACTIVATED = 'scene:activated', + SCENE_DEACTIVATED = 'scene:deactivated', + SCENE_PAUSED = 'scene:paused', + SCENE_RESUMED = 'scene:resumed', // 查询相关事件 - QUERY_EXECUTED = "query:executed", - QUERY_CACHE_HIT = "query:cache:hit", - QUERY_CACHE_MISS = "query:cache:miss", - QUERY_OPTIMIZED = "query:optimized", + QUERY_EXECUTED = 'query:executed', + QUERY_CACHE_HIT = 'query:cache:hit', + QUERY_CACHE_MISS = 'query:cache:miss', + QUERY_OPTIMIZED = 'query:optimized', // 性能相关事件 - PERFORMANCE_WARNING = "performance:warning", - PERFORMANCE_CRITICAL = "performance:critical", - MEMORY_USAGE_HIGH = "memory:usage:high", - FRAME_RATE_DROP = "frame:rate:drop", + PERFORMANCE_WARNING = 'performance:warning', + PERFORMANCE_CRITICAL = 'performance:critical', + MEMORY_USAGE_HIGH = 'memory:usage:high', + FRAME_RATE_DROP = 'frame:rate:drop', // 索引相关事件 - INDEX_CREATED = "index:created", - INDEX_UPDATED = "index:updated", - INDEX_OPTIMIZED = "index:optimized", + INDEX_CREATED = 'index:created', + INDEX_UPDATED = 'index:updated', + INDEX_OPTIMIZED = 'index:optimized', // Archetype相关事件 - ARCHETYPE_CREATED = "archetype:created", - ARCHETYPE_ENTITY_ADDED = "archetype:entity:added", - ARCHETYPE_ENTITY_REMOVED = "archetype:entity:removed", + ARCHETYPE_CREATED = 'archetype:created', + ARCHETYPE_ENTITY_ADDED = 'archetype:entity:added', + ARCHETYPE_ENTITY_REMOVED = 'archetype:entity:removed', // 脏标记相关事件 - DIRTY_MARK_ADDED = "dirty:mark:added", - DIRTY_BATCH_PROCESSED = "dirty:batch:processed", + DIRTY_MARK_ADDED = 'dirty:mark:added', + DIRTY_BATCH_PROCESSED = 'dirty:batch:processed', // 错误和警告事件 - ERROR_OCCURRED = "error:occurred", - WARNING_ISSUED = "warning:issued", + ERROR_OCCURRED = 'error:occurred', + WARNING_ISSUED = 'warning:issued', // 生命周期事件 - FRAMEWORK_INITIALIZED = "framework:initialized", - FRAMEWORK_SHUTDOWN = "framework:shutdown", + FRAMEWORK_INITIALIZED = 'framework:initialized', + FRAMEWORK_SHUTDOWN = 'framework:shutdown', // 调试相关事件 - DEBUG_INFO = "debug:info", - DEBUG_STATS_UPDATED = "debug:stats:updated" + DEBUG_INFO = 'debug:info', + DEBUG_STATS_UPDATED = 'debug:stats:updated' } /** diff --git a/packages/core/src/ECS/Decorators/EntityRefDecorator.ts b/packages/core/src/ECS/Decorators/EntityRefDecorator.ts index 52c4751b..33bde380 100644 --- a/packages/core/src/ECS/Decorators/EntityRefDecorator.ts +++ b/packages/core/src/ECS/Decorators/EntityRefDecorator.ts @@ -1,19 +1,19 @@ -import type {Entity} from "../Entity"; -import type {Component} from "../Component"; -import {getSceneByEntityId} from "../Core/ReferenceTracker"; -import {createLogger} from "../../Utils/Logger"; +import type { Entity } from '../Entity'; +import type { Component } from '../Component'; +import { getSceneByEntityId } from '../Core/ReferenceTracker'; +import { createLogger } from '../../Utils/Logger'; -const logger = createLogger("EntityRefDecorator"); +const logger = createLogger('EntityRefDecorator'); /** * EntityRef元数据的Symbol键 */ -export const ENTITY_REF_METADATA = Symbol("EntityRefMetadata"); +export const ENTITY_REF_METADATA = Symbol('EntityRefMetadata'); /** * EntityRef值存储的Symbol键 */ -const ENTITY_REF_VALUES = Symbol("EntityRefValues"); +const ENTITY_REF_VALUES = Symbol('EntityRefValues'); /** * EntityRef元数据 @@ -66,7 +66,7 @@ export function EntityRef(): PropertyDecorator { constructor[ENTITY_REF_METADATA] = metadata; } - const propKeyString = typeof propertyKey === "symbol" ? propertyKey.toString() : propertyKey; + const propKeyString = typeof propertyKey === 'symbol' ? propertyKey.toString() : propertyKey; metadata.properties.add(propKeyString); Object.defineProperty(target, propertyKey, { @@ -97,7 +97,7 @@ export function EntityRef(): PropertyDecorator { if (newValue) { if (newValue.scene !== scene) { - logger.error(`Cannot reference Entity from different Scene. Entity: ${newValue.name}, Scene: ${newValue.scene?.name || "null"}`); + logger.error(`Cannot reference Entity from different Scene. Entity: ${newValue.name}, Scene: ${newValue.scene?.name || 'null'}`); return; } @@ -129,7 +129,7 @@ export function getEntityRefMetadata(component: any): EntityRefMetadata | null { return null; } - const constructor = typeof component === "function" + const constructor = typeof component === 'function' ? component : component.constructor; diff --git a/packages/core/src/ECS/Decorators/TypeDecorators.ts b/packages/core/src/ECS/Decorators/TypeDecorators.ts index ec9ee98d..8e59e8e3 100644 --- a/packages/core/src/ECS/Decorators/TypeDecorators.ts +++ b/packages/core/src/ECS/Decorators/TypeDecorators.ts @@ -1,16 +1,16 @@ -import type {Component} from "../Component"; -import type {EntitySystem} from "../Systems"; -import {ComponentType} from "../../Types"; +import type { Component } from '../Component'; +import type { EntitySystem } from '../Systems'; +import { ComponentType } from '../../Types'; /** * 存储组件类型名称的Symbol键 */ -export const COMPONENT_TYPE_NAME = Symbol("ComponentTypeName"); +export const COMPONENT_TYPE_NAME = Symbol('ComponentTypeName'); /** * 存储系统类型名称的Symbol键 */ -export const SYSTEM_TYPE_NAME = Symbol("SystemTypeName"); +export const SYSTEM_TYPE_NAME = Symbol('SystemTypeName'); /** * 组件类型装饰器 @@ -28,8 +28,8 @@ export const SYSTEM_TYPE_NAME = Symbol("SystemTypeName"); */ export function ECSComponent(typeName: string) { return function Component>(target: T): T { - if (!typeName || typeof typeName !== "string") { - throw new Error("ECSComponent装饰器必须提供有效的类型名称"); + if (!typeName || typeof typeName !== 'string') { + throw new Error('ECSComponent装饰器必须提供有效的类型名称'); } // 在构造函数上存储类型名称 @@ -82,8 +82,8 @@ export interface SystemMetadata { */ export function ECSSystem(typeName: string, metadata?: SystemMetadata) { return function EntitySystem>(target: T): T { - if (!typeName || typeof typeName !== "string") { - throw new Error("ECSSystem装饰器必须提供有效的类型名称"); + if (!typeName || typeof typeName !== 'string') { + throw new Error('ECSSystem装饰器必须提供有效的类型名称'); } // 在构造函数上存储类型名称 @@ -121,7 +121,7 @@ export function getComponentTypeName( } // 回退到constructor.name - return componentType.name || "UnknownComponent"; + return componentType.name || 'UnknownComponent'; } /** @@ -140,7 +140,7 @@ export function getSystemTypeName( } // 回退到constructor.name - return systemType.name || "UnknownSystem"; + return systemType.name || 'UnknownSystem'; } /** diff --git a/packages/core/src/ECS/Decorators/index.ts b/packages/core/src/ECS/Decorators/index.ts index 647ae02b..cc7fd03f 100644 --- a/packages/core/src/ECS/Decorators/index.ts +++ b/packages/core/src/ECS/Decorators/index.ts @@ -8,15 +8,15 @@ export { getSystemMetadata, COMPONENT_TYPE_NAME, SYSTEM_TYPE_NAME -} from "./TypeDecorators"; +} from './TypeDecorators'; -export type {SystemMetadata} from "./TypeDecorators"; +export type { SystemMetadata } from './TypeDecorators'; export { EntityRef, getEntityRefMetadata, hasEntityRef, ENTITY_REF_METADATA -} from "./EntityRefDecorator"; +} from './EntityRefDecorator'; -export type {EntityRefMetadata} from "./EntityRefDecorator"; +export type { EntityRefMetadata } from './EntityRefDecorator'; diff --git a/packages/core/src/ECS/Entity.ts b/packages/core/src/ECS/Entity.ts index c05b60eb..78c8d65b 100644 --- a/packages/core/src/ECS/Entity.ts +++ b/packages/core/src/ECS/Entity.ts @@ -1,10 +1,10 @@ -import {Component} from "./Component"; -import {ComponentRegistry, ComponentType} from "./Core/ComponentStorage"; -import {EventBus} from "./Core/EventBus"; -import {BitMask64Utils, BitMask64Data} from "./Utils/BigIntCompatibility"; -import {createLogger} from "../Utils/Logger"; -import {getComponentInstanceTypeName, getComponentTypeName} from "./Decorators"; -import type {IScene} from "./IScene"; +import { Component } from './Component'; +import { ComponentRegistry, ComponentType } from './Core/ComponentStorage'; +import { EventBus } from './Core/EventBus'; +import { BitMask64Utils, BitMask64Data } from './Utils/BigIntCompatibility'; +import { createLogger } from '../Utils/Logger'; +import { getComponentInstanceTypeName, getComponentTypeName } from './Decorators'; +import type { IScene } from './IScene'; /** * 实体比较器 @@ -58,7 +58,7 @@ export class Entity { /** * Entity专用日志器 */ - private static _logger = createLogger("Entity"); + private static _logger = createLogger('Entity'); /** * 实体比较器实例 @@ -402,11 +402,11 @@ export class Entity { const componentType = component.constructor as ComponentType; if (!this.scene) { - throw new Error("Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()"); + throw new Error('Entity must be added to Scene before adding components. Use scene.createEntity() instead of new Entity()'); } if (!this.scene.componentStorageManager) { - throw new Error("Scene does not have componentStorageManager"); + throw new Error('Scene does not have componentStorageManager'); } if (this.hasComponent(componentType)) { @@ -426,7 +426,7 @@ export class Entity { if (Entity.eventBus) { Entity.eventBus.emitComponentAdded({ timestamp: Date.now(), - source: "Entity", + source: 'Entity', entityId: this.id, entityName: this.name, entityTag: this.tag?.toString(), @@ -561,7 +561,7 @@ export class Entity { if (Entity.eventBus) { Entity.eventBus.emitComponentRemoved({ timestamp: Date.now(), - source: "Entity", + source: 'Entity', entityId: this.id, entityName: this.name, entityTag: this.tag?.toString(), @@ -705,7 +705,7 @@ export class Entity { */ public addChild(child: Entity): Entity { if (child === this) { - throw new Error("Entity cannot be its own child"); + throw new Error('Entity cannot be its own child'); } if (child._parent === this) { @@ -882,13 +882,13 @@ export class Entity { */ private onActiveChanged(): void { for (const component of this.components) { - if ("onActiveChanged" in component && typeof component.onActiveChanged === "function") { + if ('onActiveChanged' in component && typeof component.onActiveChanged === 'function') { (component as any).onActiveChanged(); } } if (this.scene && this.scene.eventSystem) { - this.scene.eventSystem.emitSync("entity:activeChanged", { + this.scene.eventSystem.emitSync('entity:activeChanged', { entity: this, active: this._active, activeInHierarchy: this.activeInHierarchy diff --git a/packages/core/src/ECS/IScene.ts b/packages/core/src/ECS/IScene.ts index 337da588..16bb91a0 100644 --- a/packages/core/src/ECS/IScene.ts +++ b/packages/core/src/ECS/IScene.ts @@ -1,15 +1,15 @@ -import {Entity} from "./Entity"; -import {EntityList} from "./Utils/EntityList"; -import {IdentifierPool} from "./Utils/IdentifierPool"; -import {EntitySystem} from "./Systems/EntitySystem"; -import {ComponentStorageManager} from "./Core/ComponentStorage"; -import {QuerySystem} from "./Core/QuerySystem"; -import {TypeSafeEventSystem} from "./Core/EventSystem"; -import type {ReferenceTracker} from "./Core/ReferenceTracker"; -import type {ServiceContainer, ServiceType} from "../Core/ServiceContainer"; -import type {TypedQueryBuilder} from "./Core/Query/TypedQuery"; -import type {SceneSerializationOptions, SceneDeserializationOptions} from "./Serialization/SceneSerializer"; -import type {IncrementalSnapshot, IncrementalSerializationOptions} from "./Serialization/IncrementalSerializer"; +import { Entity } from './Entity'; +import { EntityList } from './Utils/EntityList'; +import { IdentifierPool } from './Utils/IdentifierPool'; +import { EntitySystem } from './Systems/EntitySystem'; +import { ComponentStorageManager } from './Core/ComponentStorage'; +import { QuerySystem } from './Core/QuerySystem'; +import { TypeSafeEventSystem } from './Core/EventSystem'; +import type { ReferenceTracker } from './Core/ReferenceTracker'; +import type { ServiceContainer, ServiceType } from '../Core/ServiceContainer'; +import type { TypedQueryBuilder } from './Core/Query/TypedQuery'; +import type { SceneSerializationOptions, SceneDeserializationOptions } from './Serialization/SceneSerializer'; +import type { IncrementalSnapshot, IncrementalSerializationOptions } from './Serialization/IncrementalSerializer'; /** * 场景接口定义 diff --git a/packages/core/src/ECS/Scene.ts b/packages/core/src/ECS/Scene.ts index b5e1c4f5..c4288125 100644 --- a/packages/core/src/ECS/Scene.ts +++ b/packages/core/src/ECS/Scene.ts @@ -1,22 +1,22 @@ -import {Entity} from "./Entity"; -import {EntityList} from "./Utils/EntityList"; -import {IdentifierPool} from "./Utils/IdentifierPool"; -import {EntitySystem} from "./Systems/EntitySystem"; -import {ComponentStorageManager, ComponentRegistry} from "./Core/ComponentStorage"; -import {QuerySystem} from "./Core/QuerySystem"; -import {TypeSafeEventSystem} from "./Core/EventSystem"; -import {EventBus} from "./Core/EventBus"; -import {ReferenceTracker} from "./Core/ReferenceTracker"; -import {IScene, ISceneConfig} from "./IScene"; -import {getComponentInstanceTypeName, getSystemInstanceTypeName, getSystemMetadata} from "./Decorators"; -import {TypedQueryBuilder} from "./Core/Query/TypedQuery"; -import {SceneSerializer, SceneSerializationOptions, SceneDeserializationOptions} from "./Serialization/SceneSerializer"; -import {IncrementalSerializer, IncrementalSnapshot, IncrementalSerializationOptions} from "./Serialization/IncrementalSerializer"; -import {ComponentPoolManager} from "./Core/ComponentPool"; -import {PerformanceMonitor} from "../Utils/PerformanceMonitor"; -import {ServiceContainer, type ServiceType} from "../Core/ServiceContainer"; -import {createInstance, isInjectable, injectProperties} from "../Core/DI"; -import {createLogger} from "../Utils/Logger"; +import { Entity } from './Entity'; +import { EntityList } from './Utils/EntityList'; +import { IdentifierPool } from './Utils/IdentifierPool'; +import { EntitySystem } from './Systems/EntitySystem'; +import { ComponentStorageManager, ComponentRegistry } from './Core/ComponentStorage'; +import { QuerySystem } from './Core/QuerySystem'; +import { TypeSafeEventSystem } from './Core/EventSystem'; +import { EventBus } from './Core/EventBus'; +import { ReferenceTracker } from './Core/ReferenceTracker'; +import { IScene, ISceneConfig } from './IScene'; +import { getComponentInstanceTypeName, getSystemInstanceTypeName, getSystemMetadata } from './Decorators'; +import { TypedQueryBuilder } from './Core/Query/TypedQuery'; +import { SceneSerializer, SceneSerializationOptions, SceneDeserializationOptions } from './Serialization/SceneSerializer'; +import { IncrementalSerializer, IncrementalSnapshot, IncrementalSerializationOptions } from './Serialization/IncrementalSerializer'; +import { ComponentPoolManager } from './Core/ComponentPool'; +import { PerformanceMonitor } from '../Utils/PerformanceMonitor'; +import { ServiceContainer, type ServiceType } from '../Core/ServiceContainer'; +import { createInstance, isInjectable, injectProperties } from '../Core/DI'; +import { createLogger } from '../Utils/Logger'; /** * 游戏场景默认实现类 @@ -30,7 +30,7 @@ export class Scene implements IScene { * * 用于标识和调试的友好名称。 */ - public name: string = ""; + public name: string = ''; /** * 场景自定义数据 @@ -207,7 +207,7 @@ export class Scene implements IScene { this.eventSystem = new TypeSafeEventSystem(); this.referenceTracker = new ReferenceTracker(); this._services = new ServiceContainer(); - this.logger = createLogger("Scene"); + this.logger = createLogger('Scene'); if (config?.name) { this.name = config.name; @@ -219,7 +219,7 @@ export class Scene implements IScene { if (Entity.eventBus) { Entity.eventBus.onComponentAdded((data: unknown) => { - this.eventSystem.emitSync("component:added", data); + this.eventSystem.emitSync('component:added', data); }); } } @@ -340,7 +340,7 @@ export class Scene implements IScene { public createEntity(name: string) { const entity = new Entity(name, this.identifierPool.checkOut()); - this.eventSystem.emitSync("entity:created", {entityName: name, entity, scene: this}); + this.eventSystem.emitSync('entity:created', { entityName: name, entity, scene: this }); return this.addEntity(entity); } @@ -373,7 +373,7 @@ export class Scene implements IScene { } // 触发实体添加事件 - this.eventSystem.emitSync("entity:added", {entity, scene: this}); + this.eventSystem.emitSync('entity:added', { entity, scene: this }); return entity; } @@ -384,7 +384,7 @@ export class Scene implements IScene { * @param namePrefix 实体名称前缀 * @returns 创建的实体列表 */ - public createEntities(count: number, namePrefix: string = "Entity"): Entity[] { + public createEntities(count: number, namePrefix: string = 'Entity'): Entity[] { const entities: Entity[] = []; // 批量创建实体对象,不立即添加到系统 @@ -403,7 +403,7 @@ export class Scene implements IScene { this.querySystem.addEntitiesUnchecked(entities); // 批量触发事件(可选,减少事件开销) - this.eventSystem.emitSync("entities:batch_added", {entities, scene: this, count}); + this.eventSystem.emitSync('entities:batch_added', { entities, scene: this, count }); return entities; } @@ -583,7 +583,7 @@ export class Scene implements IScene { let system: T; let constructor: any; - if (typeof systemTypeOrInstance === "function") { + if (typeof systemTypeOrInstance === 'function') { constructor = systemTypeOrInstance; if (this._services.isRegistered(constructor)) { @@ -609,7 +609,7 @@ export class Scene implements IScene { } else { this.logger.warn( `Attempting to register a different instance of ${constructor.name}, ` + - "but type is already registered. Returning existing instance." + 'but type is already registered. Returning existing instance.' ); return existingSystem as T; } @@ -907,7 +907,7 @@ export class Scene implements IScene { */ public serializeIncremental(options?: IncrementalSerializationOptions): IncrementalSnapshot { if (!this._incrementalBaseSnapshot) { - throw new Error("必须先调用 createIncrementalSnapshot() 创建基础快照"); + throw new Error('必须先调用 createIncrementalSnapshot() 创建基础快照'); } return IncrementalSerializer.computeIncremental( @@ -941,7 +941,7 @@ export class Scene implements IScene { incremental: IncrementalSnapshot | string | Uint8Array, componentRegistry?: Map ): void { - const isSerializedData = typeof incremental === "string" || + const isSerializedData = typeof incremental === 'string' || incremental instanceof Uint8Array; const snapshot = isSerializedData diff --git a/packages/core/src/ECS/SceneManager.ts b/packages/core/src/ECS/SceneManager.ts index a9f7d180..dd9953b7 100644 --- a/packages/core/src/ECS/SceneManager.ts +++ b/packages/core/src/ECS/SceneManager.ts @@ -1,10 +1,10 @@ -import {IScene} from "./IScene"; -import {ECSFluentAPI, createECSAPI} from "./Core/FluentAPI"; -import {Time} from "../Utils/Time"; -import {createLogger} from "../Utils/Logger"; -import type {IService} from "../Core/ServiceContainer"; -import {World} from "./World"; -import {PerformanceMonitor} from "../Utils/PerformanceMonitor"; +import { IScene } from './IScene'; +import { ECSFluentAPI, createECSAPI } from './Core/FluentAPI'; +import { Time } from '../Utils/Time'; +import { createLogger } from '../Utils/Logger'; +import type { IService } from '../Core/ServiceContainer'; +import { World } from './World'; +import { PerformanceMonitor } from '../Utils/PerformanceMonitor'; /** * 单场景管理器 @@ -67,7 +67,7 @@ export class SceneManager implements IService { /** * 日志器 */ - private _logger = createLogger("SceneManager"); + private _logger = createLogger('SceneManager'); /** * 场景切换回调函数 @@ -82,10 +82,10 @@ export class SceneManager implements IService { /** * 默认场景ID */ - private static readonly DEFAULT_SCENE_ID = "__main__"; + private static readonly DEFAULT_SCENE_ID = '__main__'; constructor(performanceMonitor?: PerformanceMonitor) { - this._defaultWorld = new World({name: "__default__"}); + this._defaultWorld = new World({ name: '__default__' }); this._defaultWorld.start(); this._performanceMonitor = performanceMonitor || null; } @@ -238,13 +238,13 @@ export class SceneManager implements IService { * 通常在应用程序关闭时调用。 */ public destroy(): void { - this._logger.info("SceneManager destroying"); + this._logger.info('SceneManager destroying'); this._defaultWorld.destroy(); this._nextScene = null; this._ecsAPI = null; - this._logger.info("SceneManager destroyed"); + this._logger.info('SceneManager destroyed'); } /** diff --git a/packages/core/src/ECS/Serialization/ComponentSerializer.ts b/packages/core/src/ECS/Serialization/ComponentSerializer.ts index 12508d66..6b38a88d 100644 --- a/packages/core/src/ECS/Serialization/ComponentSerializer.ts +++ b/packages/core/src/ECS/Serialization/ComponentSerializer.ts @@ -4,12 +4,12 @@ * 负责组件的序列化和反序列化操作 */ -import {Component} from "../Component"; -import {ComponentType} from "../Core/ComponentStorage"; -import {getComponentTypeName} from "../Decorators"; +import { Component } from '../Component'; +import { ComponentType } from '../Core/ComponentStorage'; +import { getComponentTypeName } from '../Decorators'; import { getSerializationMetadata -} from "./SerializationDecorators"; +} from './SerializationDecorators'; /** * 可序列化的值类型 @@ -22,9 +22,9 @@ export type SerializableValue = | undefined | SerializableValue[] | { [key: string]: SerializableValue } - | { __type: "Date"; value: string } - | { __type: "Map"; value: Array<[SerializableValue, SerializableValue]> } - | { __type: "Set"; value: SerializableValue[] }; + | { __type: 'Date'; value: string } + | { __type: 'Map'; value: Array<[SerializableValue, SerializableValue]> } + | { __type: 'Set'; value: SerializableValue[] }; /** * 序列化后的组件数据 @@ -70,7 +70,7 @@ export class ComponentSerializer { // 序列化标记的字段 for (const [fieldName, options] of metadata.fields) { - const fieldKey = typeof fieldName === "symbol" ? fieldName.toString() : fieldName; + const fieldKey = typeof fieldName === 'symbol' ? fieldName.toString() : fieldName; const value = (component as unknown as Record)[fieldName]; // 跳过忽略的字段 @@ -125,7 +125,7 @@ export class ComponentSerializer { // 反序列化字段 for (const [fieldName, options] of metadata.fields) { - const fieldKey = typeof fieldName === "symbol" ? fieldName.toString() : fieldName; + const fieldKey = typeof fieldName === 'symbol' ? fieldName.toString() : fieldName; const key = options.alias || fieldKey; const serializedValue = serializedData.data[key]; @@ -198,14 +198,14 @@ export class ComponentSerializer { // 基本类型 const type = typeof value; - if (type === "string" || type === "number" || type === "boolean") { + if (type === 'string' || type === 'number' || type === 'boolean') { return value; } // 日期 if (value instanceof Date) { return { - __type: "Date", + __type: 'Date', value: value.toISOString() }; } @@ -218,7 +218,7 @@ export class ComponentSerializer { // Map (如果没有使用@SerializeMap装饰器) if (value instanceof Map) { return { - __type: "Map", + __type: 'Map', value: Array.from(value.entries()) }; } @@ -226,13 +226,13 @@ export class ComponentSerializer { // Set if (value instanceof Set) { return { - __type: "Set", + __type: 'Set', value: Array.from(value) }; } // 普通对象 - if (type === "object" && typeof value === "object" && !Array.isArray(value)) { + if (type === 'object' && typeof value === 'object' && !Array.isArray(value)) { const result: Record = {}; const obj = value as Record; for (const key in obj) { @@ -257,20 +257,20 @@ export class ComponentSerializer { // 基本类型直接返回 const type = typeof value; - if (type === "string" || type === "number" || type === "boolean") { + if (type === 'string' || type === 'number' || type === 'boolean') { return value; } // 处理特殊类型标记 - if (type === "object" && typeof value === "object" && "__type" in value) { + if (type === 'object' && typeof value === 'object' && '__type' in value) { const typedValue = value as { __type: string; value: SerializableValue }; switch (typedValue.__type) { - case "Date": - return {__type: "Date", value: typeof typedValue.value === "string" ? typedValue.value : String(typedValue.value)}; - case "Map": - return {__type: "Map", value: typedValue.value as Array<[SerializableValue, SerializableValue]>}; - case "Set": - return {__type: "Set", value: typedValue.value as SerializableValue[]}; + case 'Date': + return { __type: 'Date', value: typeof typedValue.value === 'string' ? typedValue.value : String(typedValue.value) }; + case 'Map': + return { __type: 'Map', value: typedValue.value as Array<[SerializableValue, SerializableValue]> }; + case 'Set': + return { __type: 'Set', value: typedValue.value as SerializableValue[] }; } } @@ -280,7 +280,7 @@ export class ComponentSerializer { } // 普通对象 - if (type === "object" && typeof value === "object" && !Array.isArray(value)) { + if (type === 'object' && typeof value === 'object' && !Array.isArray(value)) { const result: Record = {}; const obj = value as Record; for (const key in obj) { @@ -325,7 +325,7 @@ export class ComponentSerializer { if (!metadata) { return { - type: "unknown", + type: 'unknown', version: 0, fields: [], ignoredFields: [], @@ -333,7 +333,7 @@ export class ComponentSerializer { }; } - const componentType = typeof component === "function" + const componentType = typeof component === 'function' ? component : (component.constructor as ComponentType); @@ -341,10 +341,10 @@ export class ComponentSerializer { type: metadata.options.typeId || getComponentTypeName(componentType), version: metadata.options.version, 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) => - typeof k === "symbol" ? k.toString() : k + typeof k === 'symbol' ? k.toString() : k ), isSerializable: true }; diff --git a/packages/core/src/ECS/Serialization/EntitySerializer.ts b/packages/core/src/ECS/Serialization/EntitySerializer.ts index c4ea1db2..46aafb5f 100644 --- a/packages/core/src/ECS/Serialization/EntitySerializer.ts +++ b/packages/core/src/ECS/Serialization/EntitySerializer.ts @@ -4,10 +4,10 @@ * 负责实体的序列化和反序列化操作 */ -import {Entity} from "../Entity"; -import {ComponentType} from "../Core/ComponentStorage"; -import {ComponentSerializer, SerializedComponent} from "./ComponentSerializer"; -import {IScene} from "../IScene"; +import { Entity } from '../Entity'; +import { ComponentType } from '../Core/ComponentStorage'; +import { ComponentSerializer, SerializedComponent } from './ComponentSerializer'; +import { IScene } from '../IScene'; /** * 序列化后的实体数据 diff --git a/packages/core/src/ECS/Serialization/IncrementalSerializer.ts b/packages/core/src/ECS/Serialization/IncrementalSerializer.ts index da86b8c0..b00d2ef7 100644 --- a/packages/core/src/ECS/Serialization/IncrementalSerializer.ts +++ b/packages/core/src/ECS/Serialization/IncrementalSerializer.ts @@ -5,31 +5,31 @@ * 适用于网络同步、大场景存档、时间回溯等场景 */ -import type {IScene} from "../IScene"; -import {Entity} from "../Entity"; -import {ComponentSerializer, SerializedComponent} from "./ComponentSerializer"; -import {SerializedEntity} from "./EntitySerializer"; -import {ComponentType} from "../Core/ComponentStorage"; -import {BinarySerializer} from "../../Utils/BinarySerializer"; +import type { IScene } from '../IScene'; +import { Entity } from '../Entity'; +import { ComponentSerializer, SerializedComponent } from './ComponentSerializer'; +import { SerializedEntity } from './EntitySerializer'; +import { ComponentType } from '../Core/ComponentStorage'; +import { BinarySerializer } from '../../Utils/BinarySerializer'; /** * 变更操作类型 */ export enum ChangeOperation { /** 添加新实体 */ - EntityAdded = "entity_added", + EntityAdded = 'entity_added', /** 删除实体 */ - EntityRemoved = "entity_removed", + EntityRemoved = 'entity_removed', /** 实体属性更新 */ - EntityUpdated = "entity_updated", + EntityUpdated = 'entity_updated', /** 添加组件 */ - ComponentAdded = "component_added", + ComponentAdded = 'component_added', /** 删除组件 */ - ComponentRemoved = "component_removed", + ComponentRemoved = 'component_removed', /** 组件数据更新 */ - ComponentUpdated = "component_updated", + ComponentUpdated = 'component_updated', /** 场景数据更新 */ - SceneDataUpdated = "scene_data_updated" + SceneDataUpdated = 'scene_data_updated' } /** @@ -120,7 +120,7 @@ interface SceneSnapshot { /** * 增量序列化格式 */ -export type IncrementalSerializationFormat = "json" | "binary"; +export type IncrementalSerializationFormat = 'json' | 'binary'; /** * 增量序列化选项 @@ -203,7 +203,7 @@ export class IncrementalSerializer { active: entity.active, enabled: entity.enabled, updateOrder: entity.updateOrder, - ...(entity.parent && {parentId: entity.parent.id}) + ...(entity.parent && { parentId: entity.parent.id }) }); // 快照组件 @@ -285,7 +285,7 @@ export class IncrementalSerializer { active: entity.active, enabled: entity.enabled, updateOrder: entity.updateOrder, - ...(entity.parent && {parentId: entity.parent.id}), + ...(entity.parent && { parentId: entity.parent.id }), components: [], children: [] } @@ -324,7 +324,7 @@ export class IncrementalSerializer { active: entity.active, enabled: entity.enabled, updateOrder: entity.updateOrder, - ...(entity.parent && {parentId: entity.parent.id}) + ...(entity.parent && { parentId: entity.parent.id }) } }); } @@ -511,7 +511,7 @@ export class IncrementalSerializer { private static applyEntityAdded(scene: IScene, change: EntityChange): void { if (!change.entityData) return; - const entity = new Entity(change.entityName || "Entity", change.entityId); + const entity = new Entity(change.entityName || 'Entity', change.entityId); entity.tag = change.entityData.tag || 0; entity.active = change.entityData.active ?? true; entity.enabled = change.entityData.enabled ?? true; @@ -632,12 +632,12 @@ export class IncrementalSerializer { options?: { format?: IncrementalSerializationFormat; pretty?: boolean } ): string | Uint8Array { const opts = { - format: "json" as IncrementalSerializationFormat, + format: 'json' as IncrementalSerializationFormat, pretty: false, ...options }; - if (opts.format === "binary") { + if (opts.format === 'binary') { return BinarySerializer.encode(incremental); } else { return opts.pretty @@ -662,7 +662,7 @@ export class IncrementalSerializer { * ``` */ public static deserializeIncremental(data: string | Uint8Array): IncrementalSnapshot { - if (typeof data === "string") { + if (typeof data === 'string') { return JSON.parse(data); } else { return BinarySerializer.decode(data) as IncrementalSnapshot; diff --git a/packages/core/src/ECS/Serialization/SceneSerializer.ts b/packages/core/src/ECS/Serialization/SceneSerializer.ts index 971f5701..f0cd83e8 100644 --- a/packages/core/src/ECS/Serialization/SceneSerializer.ts +++ b/packages/core/src/ECS/Serialization/SceneSerializer.ts @@ -4,23 +4,23 @@ * 负责整个场景的序列化和反序列化,包括实体、组件等 */ -import type {IScene} from "../IScene"; -import {Entity} from "../Entity"; -import {ComponentType, ComponentRegistry} from "../Core/ComponentStorage"; -import {EntitySerializer, SerializedEntity} from "./EntitySerializer"; -import {getComponentTypeName} from "../Decorators"; -import {getSerializationMetadata} from "./SerializationDecorators"; -import {BinarySerializer} from "../../Utils/BinarySerializer"; +import type { IScene } from '../IScene'; +import { Entity } from '../Entity'; +import { ComponentType, ComponentRegistry } from '../Core/ComponentStorage'; +import { EntitySerializer, SerializedEntity } from './EntitySerializer'; +import { getComponentTypeName } from '../Decorators'; +import { getSerializationMetadata } from './SerializationDecorators'; +import { BinarySerializer } from '../../Utils/BinarySerializer'; /** * 场景序列化格式 */ -export type SerializationFormat = "json" | "binary"; +export type SerializationFormat = 'json' | 'binary'; /** * 场景序列化策略 */ -export type DeserializationStrategy = "merge" | "replace"; +export type DeserializationStrategy = 'merge' | 'replace'; /** * 版本迁移函数 @@ -158,7 +158,7 @@ export class SceneSerializer { public static serialize(scene: IScene, options?: SceneSerializationOptions): string | Uint8Array { const opts: SceneSerializationOptions = { systems: false, - format: "json", + format: 'json', pretty: true, includeMetadata: true, ...options @@ -199,7 +199,7 @@ export class SceneSerializer { }; } - if (opts.format === "json") { + if (opts.format === 'json') { return opts.pretty ? JSON.stringify(serializedScene, null, 2) : JSON.stringify(serializedScene); @@ -221,14 +221,14 @@ export class SceneSerializer { options?: SceneDeserializationOptions ): void { const opts: SceneDeserializationOptions = { - strategy: "replace", + strategy: 'replace', preserveIds: false, ...options }; let serializedScene: SerializedScene; try { - if (typeof saveData === "string") { + if (typeof saveData === 'string') { serializedScene = JSON.parse(saveData); } else { serializedScene = BinarySerializer.decode(saveData) as SerializedScene; @@ -250,7 +250,7 @@ export class SceneSerializer { const componentRegistry = opts.componentRegistry || this.getGlobalComponentRegistry(); // 根据策略处理场景 - if (opts.strategy === "replace") { + if (opts.strategy === 'replace') { // 清空场景 scene.destroyAllEntities(); } @@ -342,23 +342,23 @@ export class SceneSerializer { // 基本类型 const type = typeof value; - if (type === "string" || type === "number" || type === "boolean") { + if (type === 'string' || type === 'number' || type === 'boolean') { return value; } // Date if (value instanceof Date) { - return {__type: "Date", value: value.toISOString()}; + return { __type: 'Date', value: value.toISOString() }; } // Map if (value instanceof Map) { - return {__type: "Map", value: Array.from(value.entries())}; + return { __type: 'Map', value: Array.from(value.entries()) }; } // Set if (value instanceof Set) { - return {__type: "Set", value: Array.from(value)}; + return { __type: 'Set', value: Array.from(value) }; } // 数组 @@ -367,7 +367,7 @@ export class SceneSerializer { } // 普通对象 - if (type === "object") { + if (type === 'object') { const result: Record = {}; for (const key in value) { if (Object.prototype.hasOwnProperty.call(value, key)) { @@ -391,18 +391,18 @@ export class SceneSerializer { // 基本类型 const type = typeof value; - if (type === "string" || type === "number" || type === "boolean") { + if (type === 'string' || type === 'number' || type === 'boolean') { return value; } // 处理特殊类型标记 - if (type === "object" && value.__type) { + if (type === 'object' && value.__type) { switch (value.__type) { - case "Date": + case 'Date': return new Date(value.value); - case "Map": + case 'Map': return new Map(value.value); - case "Set": + case 'Set': return new Set(value.value); } } @@ -413,7 +413,7 @@ export class SceneSerializer { } // 普通对象 - if (type === "object") { + if (type === 'object') { const result: Record = {}; for (const key in value) { if (Object.prototype.hasOwnProperty.call(value, key)) { @@ -499,21 +499,21 @@ export class SceneSerializer { const data = JSON.parse(saveData); if (!data.version) { - errors.push("Missing version field"); + errors.push('Missing version field'); } if (!data.entities || !Array.isArray(data.entities)) { - errors.push("Missing or invalid entities field"); + errors.push('Missing or invalid entities field'); } if (!data.componentTypeRegistry || !Array.isArray(data.componentTypeRegistry)) { - errors.push("Missing or invalid componentTypeRegistry field"); + errors.push('Missing or invalid componentTypeRegistry field'); } return { valid: errors.length === 0, version: data.version, - ...(errors.length > 0 && {errors}) + ...(errors.length > 0 && { errors }) }; } catch (error) { return { @@ -542,7 +542,7 @@ export class SceneSerializer { return { name: data.name, version: data.version, - ...(data.timestamp !== undefined && {timestamp: data.timestamp}), + ...(data.timestamp !== undefined && { timestamp: data.timestamp }), entityCount: data.metadata?.entityCount || data.entities.length, componentTypeCount: data.componentTypeRegistry.length }; diff --git a/packages/core/src/ECS/Serialization/SerializationDecorators.ts b/packages/core/src/ECS/Serialization/SerializationDecorators.ts index 35a444ea..e9969e7a 100644 --- a/packages/core/src/ECS/Serialization/SerializationDecorators.ts +++ b/packages/core/src/ECS/Serialization/SerializationDecorators.ts @@ -4,14 +4,14 @@ * 提供组件级别的序列化支持,包括字段级装饰器和类级装饰器 */ -import {Component} from "../Component"; +import { Component } from '../Component'; /** * 序列化元数据的Symbol键 */ -export const SERIALIZABLE_METADATA = Symbol("SerializableMetadata"); -export const SERIALIZE_FIELD = Symbol("SerializeField"); -export const SERIALIZE_OPTIONS = Symbol("SerializeOptions"); +export const SERIALIZABLE_METADATA = Symbol('SerializableMetadata'); +export const SERIALIZE_FIELD = Symbol('SerializeField'); +export const SERIALIZE_OPTIONS = Symbol('SerializeOptions'); /** * 可序列化配置选项 @@ -76,8 +76,8 @@ export interface SerializationMetadata { */ export function Serializable(options: SerializableOptions) { return function Component>(target: T): T { - if (!options || typeof options.version !== "number") { - throw new Error("Serializable装饰器必须提供有效的版本号"); + if (!options || typeof options.version !== 'number') { + throw new Error('Serializable装饰器必须提供有效的版本号'); } // 初始化或获取现有元数据 @@ -121,7 +121,7 @@ export function Serialize(options?: FieldSerializeOptions) { let metadata: SerializationMetadata = constructor[SERIALIZABLE_METADATA]; if (!metadata) { metadata = { - options: {version: 1}, // 默认版本 + options: { version: 1 }, // 默认版本 fields: new Map(), ignoredFields: new Set() }; @@ -212,7 +212,7 @@ export function IgnoreSerialization() { let metadata: SerializationMetadata = constructor[SERIALIZABLE_METADATA]; if (!metadata) { metadata = { - options: {version: 1}, + options: { version: 1 }, fields: new Map(), ignoredFields: new Set() }; @@ -236,7 +236,7 @@ export function getSerializationMetadata(componentClass: any): SerializationMeta } // 如果是实例,获取其构造函数 - const constructor = typeof componentClass === "function" + const constructor = typeof componentClass === 'function' ? componentClass : componentClass.constructor; diff --git a/packages/core/src/ECS/Serialization/VersionMigration.ts b/packages/core/src/ECS/Serialization/VersionMigration.ts index ce59f921..23f666af 100644 --- a/packages/core/src/ECS/Serialization/VersionMigration.ts +++ b/packages/core/src/ECS/Serialization/VersionMigration.ts @@ -4,8 +4,8 @@ * 提供组件和场景数据的版本迁移支持 */ -import {SerializedComponent} from "./ComponentSerializer"; -import {SerializedScene} from "./SceneSerializer"; +import { SerializedComponent } from './ComponentSerializer'; +import { SerializedScene } from './SceneSerializer'; /** * 组件迁移函数 @@ -127,7 +127,7 @@ export class VersionMigrationManager { return component; } - const migratedData = {...component}; + const migratedData = { ...component }; let version = currentVersion; // 执行迁移链 @@ -163,7 +163,7 @@ export class VersionMigrationManager { return scene; // 版本相同,无需迁移 } - let migratedScene = {...scene}; + let migratedScene = { ...scene }; let version = currentVersion; // 执行场景级迁移 @@ -191,7 +191,7 @@ export class VersionMigrationManager { * 迁移场景中所有组件的版本 */ private static migrateSceneComponents(scene: SerializedScene): SerializedScene { - const migratedScene = {...scene}; + const migratedScene = { ...scene }; migratedScene.entities = scene.entities.map((entity) => ({ ...entity, diff --git a/packages/core/src/ECS/Serialization/index.ts b/packages/core/src/ECS/Serialization/index.ts index 3a0a861d..154c9df1 100644 --- a/packages/core/src/ECS/Serialization/index.ts +++ b/packages/core/src/ECS/Serialization/index.ts @@ -16,24 +16,24 @@ export { SERIALIZABLE_METADATA, SERIALIZE_FIELD, SERIALIZE_OPTIONS -} from "./SerializationDecorators"; +} from './SerializationDecorators'; export type { SerializableOptions, FieldSerializeOptions, SerializationMetadata -} from "./SerializationDecorators"; +} from './SerializationDecorators'; // 组件序列化器 -export {ComponentSerializer} from "./ComponentSerializer"; -export type {SerializedComponent} from "./ComponentSerializer"; +export { ComponentSerializer } from './ComponentSerializer'; +export type { SerializedComponent } from './ComponentSerializer'; // 实体序列化器 -export {EntitySerializer} from "./EntitySerializer"; -export type {SerializedEntity} from "./EntitySerializer"; +export { EntitySerializer } from './EntitySerializer'; +export type { SerializedEntity } from './EntitySerializer'; // 场景序列化器 -export {SceneSerializer} from "./SceneSerializer"; +export { SceneSerializer } from './SceneSerializer'; export type { SerializedScene, SerializationFormat, @@ -41,17 +41,17 @@ export type { MigrationFunction, SceneSerializationOptions, SceneDeserializationOptions -} from "./SceneSerializer"; +} from './SceneSerializer'; // 版本迁移 -export {VersionMigrationManager, MigrationBuilder} from "./VersionMigration"; +export { VersionMigrationManager, MigrationBuilder } from './VersionMigration'; export type { ComponentMigrationFunction, SceneMigrationFunction -} from "./VersionMigration"; +} from './VersionMigration'; // 增量序列化 -export {IncrementalSerializer, ChangeOperation} from "./IncrementalSerializer"; +export { IncrementalSerializer, ChangeOperation } from './IncrementalSerializer'; export type { IncrementalSnapshot, IncrementalSerializationOptions, @@ -59,4 +59,4 @@ export type { EntityChange, ComponentChange, SceneDataChange -} from "./IncrementalSerializer"; +} from './IncrementalSerializer'; diff --git a/packages/core/src/ECS/Systems/EntitySystem.ts b/packages/core/src/ECS/Systems/EntitySystem.ts index 4df55de9..46b3302a 100644 --- a/packages/core/src/ECS/Systems/EntitySystem.ts +++ b/packages/core/src/ECS/Systems/EntitySystem.ts @@ -1,15 +1,15 @@ -import {Entity} from "../Entity"; -import {PerformanceMonitor} from "../../Utils/PerformanceMonitor"; -import {Matcher, type QueryCondition} from "../Utils/Matcher"; -import type {Scene} from "../Scene"; -import type {ISystemBase} from "../../Types"; -import type {QuerySystem} from "../Core/QuerySystem"; -import {getSystemInstanceTypeName} from "../Decorators"; -import {createLogger} from "../../Utils/Logger"; -import type {EventListenerConfig, TypeSafeEventSystem, EventHandler} from "../Core/EventSystem"; -import type {ComponentConstructor, ComponentInstance} from "../../Types/TypeHelpers"; -import type {IService} from "../../Core/ServiceContainer"; -import type {ComponentType} from "../Core/ComponentStorage"; +import { Entity } from '../Entity'; +import { PerformanceMonitor } from '../../Utils/PerformanceMonitor'; +import { Matcher, type QueryCondition } from '../Utils/Matcher'; +import type { Scene } from '../Scene'; +import type { ISystemBase } from '../../Types'; +import type { QuerySystem } from '../Core/QuerySystem'; +import { getSystemInstanceTypeName } from '../Decorators'; +import { createLogger } from '../../Utils/Logger'; +import type { EventListenerConfig, TypeSafeEventSystem, EventHandler } from '../Core/EventSystem'; +import type { ComponentConstructor, ComponentInstance } from '../../Types/TypeHelpers'; +import type { IService } from '../../Core/ServiceContainer'; +import type { ComponentType } from '../Core/ComponentStorage'; /** * 事件监听器记录 @@ -699,7 +699,7 @@ export abstract class EntitySystem< public toString(): string { const entityCount = this.entities.length; const perfData = this.getPerformanceData(); - const perfInfo = perfData ? ` (${perfData.executionTime.toFixed(2)}ms)` : ""; + const perfInfo = perfData ? ` (${perfData.executionTime.toFixed(2)}ms)` : ''; return `${this._systemName}[${entityCount} entities]${perfInfo}`; } @@ -812,7 +812,7 @@ export abstract class EntitySystem< this._eventListeners.push({ eventSystem: this.scene.eventSystem, eventType, - handler, + handler: handler as EventHandler, listenerRef }); } diff --git a/packages/core/src/ECS/Systems/IntervalSystem.ts b/packages/core/src/ECS/Systems/IntervalSystem.ts index dba9ebcf..c78fd18d 100644 --- a/packages/core/src/ECS/Systems/IntervalSystem.ts +++ b/packages/core/src/ECS/Systems/IntervalSystem.ts @@ -1,6 +1,6 @@ -import {EntitySystem} from "./EntitySystem"; -import {Matcher} from "../Utils/Matcher"; -import {Time} from "../../Utils/Time"; +import { EntitySystem } from './EntitySystem'; +import { Matcher } from '../Utils/Matcher'; +import { Time } from '../../Utils/Time'; /** * 间隔系统抽象类 diff --git a/packages/core/src/ECS/Systems/PassiveSystem.ts b/packages/core/src/ECS/Systems/PassiveSystem.ts index 9cc103c6..762db644 100644 --- a/packages/core/src/ECS/Systems/PassiveSystem.ts +++ b/packages/core/src/ECS/Systems/PassiveSystem.ts @@ -1,6 +1,6 @@ -import {EntitySystem} from "./EntitySystem"; -import {Entity} from "../Entity"; -import {Matcher} from "../Utils/Matcher"; +import { EntitySystem } from './EntitySystem'; +import { Entity } from '../Entity'; +import { Matcher } from '../Utils/Matcher'; /** * 被动实体系统 diff --git a/packages/core/src/ECS/Systems/ProcessingSystem.ts b/packages/core/src/ECS/Systems/ProcessingSystem.ts index 1291378f..9b6f7e9f 100644 --- a/packages/core/src/ECS/Systems/ProcessingSystem.ts +++ b/packages/core/src/ECS/Systems/ProcessingSystem.ts @@ -1,6 +1,6 @@ -import {EntitySystem} from "./EntitySystem"; -import {Entity} from "../Entity"; -import {Matcher} from "../Utils/Matcher"; +import { EntitySystem } from './EntitySystem'; +import { Entity } from '../Entity'; +import { Matcher } from '../Utils/Matcher'; /** * 处理系统抽象类 diff --git a/packages/core/src/ECS/Systems/WorkerEntitySystem.ts b/packages/core/src/ECS/Systems/WorkerEntitySystem.ts index 29c7d069..617ef435 100644 --- a/packages/core/src/ECS/Systems/WorkerEntitySystem.ts +++ b/packages/core/src/ECS/Systems/WorkerEntitySystem.ts @@ -1,10 +1,10 @@ -import {Entity} from "../Entity"; -import {EntitySystem} from "./EntitySystem"; -import {Matcher} from "../Utils/Matcher"; -import {Time} from "../../Utils/Time"; -import {PlatformManager} from "../../Platform/PlatformManager"; -import type {IPlatformAdapter, PlatformWorker} from "../../Platform/IPlatformAdapter"; -import {getSystemInstanceTypeName} from "../Decorators"; +import { Entity } from '../Entity'; +import { EntitySystem } from './EntitySystem'; +import { Matcher } from '../Utils/Matcher'; +import { Time } from '../../Utils/Time'; +import { PlatformManager } from '../../Platform/PlatformManager'; +import type { IPlatformAdapter, PlatformWorker } from '../../Platform/IPlatformAdapter'; +import { getSystemInstanceTypeName } from '../Decorators'; /** * Worker处理函数类型 @@ -188,7 +188,7 @@ export type SharedArrayBufferProcessFunction = ( * ``` */ export abstract class WorkerEntitySystem extends EntitySystem { - protected config: Required> & { + protected config: Required> & { systemConfig?: any; entitiesPerWorker?: number; }; @@ -219,7 +219,7 @@ export abstract class WorkerEntitySystem extends EntitySystem enableWorker: config.enableWorker ?? true, workerCount: validatedWorkerCount, systemConfig: config.systemConfig, - ...(config.entitiesPerWorker !== undefined && {entitiesPerWorker: config.entitiesPerWorker}), + ...(config.entitiesPerWorker !== undefined && { entitiesPerWorker: config.entitiesPerWorker }), useSharedArrayBuffer: config.useSharedArrayBuffer ?? this.isSharedArrayBufferSupported(), entityDataSize: config.entityDataSize ?? this.getDefaultEntityDataSize(), maxEntities: config.maxEntities ?? 10000 @@ -305,7 +305,7 @@ export abstract class WorkerEntitySystem extends EntitySystem // 在WorkerEntitySystem中处理平台相关逻辑 const workers: PlatformWorker[] = []; const platformConfig = this.platformAdapter.getPlatformConfig(); - const fullScript = (platformConfig.workerScriptPrefix || "") + script; + const fullScript = (platformConfig.workerScriptPrefix || '') + script; for (let i = 0; i < this.config.workerCount; i++) { try { @@ -336,7 +336,7 @@ export abstract class WorkerEntitySystem extends EntitySystem // 提取函数体部分(去掉方法签名) const functionBodyMatch = methodStr.match(/\{([\s\S]*)\}/); if (!functionBodyMatch) { - throw new Error("无法解析workerProcess方法"); + throw new Error('无法解析workerProcess方法'); } const functionBody = functionBodyMatch[1]; @@ -344,13 +344,13 @@ export abstract class WorkerEntitySystem extends EntitySystem // 获取SharedArrayBuffer处理函数的字符串 const sharedProcessMethod = this.getSharedArrayBufferProcessFunction?.() || null; - let sharedProcessFunctionBody = ""; + let sharedProcessFunctionBody = ''; if (sharedProcessMethod) { const sharedMethodStr = sharedProcessMethod.toString(); const sharedFunctionBodyMatch = sharedMethodStr.match(/\{([\s\S]*)\}/); if (sharedFunctionBodyMatch) { - sharedProcessFunctionBody = sharedFunctionBodyMatch[1] ?? ""; + sharedProcessFunctionBody = sharedFunctionBodyMatch[1] ?? ''; } } @@ -414,7 +414,7 @@ export abstract class WorkerEntitySystem extends EntitySystem ${sharedProcessFunctionBody} }; userProcessFunction(sharedFloatArray, startIndex, endIndex, deltaTime, systemConfig); - ` : ""} + ` : ''} } `; } @@ -465,7 +465,7 @@ export abstract class WorkerEntitySystem extends EntitySystem */ private async processWithSharedArrayBuffer(entities: readonly Entity[]): Promise { if (!this.sharedFloatArray) { - throw new Error("SharedArrayBuffer not initialized"); + throw new Error('SharedArrayBuffer not initialized'); } // 1. 将实体数据写入SharedArrayBuffer @@ -533,7 +533,7 @@ export abstract class WorkerEntitySystem extends EntitySystem // 3. 结果应用阶段 // 处理Promise返回值 - if (results && typeof (results as any).then === "function") { + if (results && typeof (results as any).then === 'function') { (results as Promise).then((finalResults) => { entities.forEach((entity, index) => { this.applyResult(entity, finalResults[index]!); @@ -721,7 +721,7 @@ export abstract class WorkerEntitySystem extends EntitySystem * 更新Worker配置 */ public updateConfig(newConfig: Partial): void { - const oldConfig = {...this.config}; + const oldConfig = { ...this.config }; // 如果更新了workerCount,需要验证并调整 if (newConfig.workerCount !== undefined) { @@ -812,22 +812,22 @@ export abstract class WorkerEntitySystem extends EntitySystem isProcessing: boolean; sharedArrayBufferSupported: 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.useSharedArrayBuffer && this.sharedFloatArray && this.isSharedArrayBufferSupported()) { - currentMode = "shared-buffer"; + currentMode = 'shared-buffer'; } else { - currentMode = "worker"; + currentMode = 'worker'; } } return { enabled: this.config.enableWorker, workerCount: this.config.workerCount, - ...(this.config.entitiesPerWorker !== undefined && {entitiesPerWorker: this.config.entitiesPerWorker}), + ...(this.config.entitiesPerWorker !== undefined && { entitiesPerWorker: this.config.entitiesPerWorker }), maxSystemWorkerCount: this.getMaxSystemWorkerCount(), isProcessing: this.isProcessing, sharedArrayBufferSupported: this.isSharedArrayBufferSupported(), @@ -890,7 +890,7 @@ class PlatformWorkerPool { return new Promise((resolve, reject) => { const task = { id: `shared-task-${++this.taskCounter}`, - data: {...data, type: "shared"}, + data: { ...data, type: 'shared' }, resolve: () => resolve(), // SharedArrayBuffer不需要返回数据 reject }; diff --git a/packages/core/src/ECS/Systems/index.ts b/packages/core/src/ECS/Systems/index.ts index 68c7f85e..3548a3e3 100644 --- a/packages/core/src/ECS/Systems/index.ts +++ b/packages/core/src/ECS/Systems/index.ts @@ -1,13 +1,13 @@ // ECS系统导出 -export {EntitySystem} from "./EntitySystem"; -export {ProcessingSystem} from "./ProcessingSystem"; -export {PassiveSystem} from "./PassiveSystem"; -export {IntervalSystem} from "./IntervalSystem"; -export {WorkerEntitySystem} from "./WorkerEntitySystem"; +export { EntitySystem } from './EntitySystem'; +export { ProcessingSystem } from './ProcessingSystem'; +export { PassiveSystem } from './PassiveSystem'; +export { IntervalSystem } from './IntervalSystem'; +export { WorkerEntitySystem } from './WorkerEntitySystem'; // Worker系统相关类型导出 export type { WorkerProcessFunction, WorkerSystemConfig, SharedArrayBufferProcessFunction -} from "./WorkerEntitySystem"; +} from './WorkerEntitySystem'; diff --git a/packages/core/src/ECS/TypedEntity.ts b/packages/core/src/ECS/TypedEntity.ts index effa1336..a61d3763 100644 --- a/packages/core/src/ECS/TypedEntity.ts +++ b/packages/core/src/ECS/TypedEntity.ts @@ -4,10 +4,10 @@ * 提供类型安全的组件操作工具函数,无需修改Entity类 */ -import {Entity} from "./Entity"; -import type {Component} from "./Component"; -import type {ComponentType} from "./Core/ComponentStorage"; -import type {ComponentConstructor, ComponentInstance} from "../Types/TypeHelpers"; +import { Entity } from './Entity'; +import type { Component } from './Component'; +import type { ComponentType } from './Core/ComponentStorage'; +import type { ComponentConstructor, ComponentInstance } from '../Types/TypeHelpers'; /** * 获取组件,如果不存在则抛出错误 diff --git a/packages/core/src/ECS/Utils/BigIntCompatibility.ts b/packages/core/src/ECS/Utils/BigIntCompatibility.ts index c6b9fff7..b68e88ef 100644 --- a/packages/core/src/ECS/Utils/BigIntCompatibility.ts +++ b/packages/core/src/ECS/Utils/BigIntCompatibility.ts @@ -25,7 +25,7 @@ export interface BitMask64Data { export class BitMask64Utils { /** 零掩码常量,所有位都为0 */ - public static readonly ZERO: Readonly = {base: [0, 0]}; + public static readonly ZERO: Readonly = { base: [0, 0] }; /** * 根据位索引创建64位掩码 @@ -37,7 +37,7 @@ export class BitMask64Utils { if (bitIndex < 0) { throw new Error(`Bit index ${bitIndex} out of range [0, ∞)`); } - const mask: BitMask64Data = {base: [0, 0]}; + const mask: BitMask64Data = { base: [0, 0] }; BitMask64Utils.setBit(mask, bitIndex); return mask; } @@ -48,7 +48,7 @@ export class BitMask64Utils { * @returns 低32位为输入值、高32位为0的掩码 */ public static fromNumber(value: number): BitMask64Data { - return {base: [value >>> 0, 0]}; + return { base: [value >>> 0, 0] }; } /** @@ -382,7 +382,7 @@ export class BitMask64Utils { public static clone(mask: BitMask64Data): BitMask64Data { return { 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) }) }; } @@ -396,7 +396,7 @@ export class BitMask64Utils { public static toString(mask: BitMask64Data, radix: 2 | 16 = 2, printHead: boolean = false): string { if(radix != 2 && radix != 16) radix = 2; const totalLength = mask.segments?.length ?? 0; - let result: string = ""; + let result: string = ''; if(printHead){ let paddingLength = 0; if(radix === 2){ @@ -405,38 +405,38 @@ export class BitMask64Utils { paddingLength = 16 + 2 + 1; } for (let i = 0; i <= totalLength; i++) { - const title = i === 0 ? "0 (Base):" : `${i} (${64 * i}):`; + const title = i === 0 ? '0 (Base):' : `${i} (${64 * i}):`; result += title.toString().padEnd(paddingLength); } - result += "\n"; + result += '\n'; } for (let i = -1; i < totalLength; i++) { - let segResult = ""; + let segResult = ''; const bitMaskData = i == -1 ? mask.base : mask.segments![i]!; const hi = bitMaskData[SegmentPart.HIGH]; const lo = bitMaskData[SegmentPart.LOW]; if(radix == 2){ - const hiBits = hi.toString(2).padStart(32, "0"); - const loBits = lo.toString(2).padStart(32, "0"); - segResult = hiBits + "_" + loBits; //高低位之间使用_隔离 + const hiBits = hi.toString(2).padStart(32, '0'); + const loBits = lo.toString(2).padStart(32, '0'); + segResult = hiBits + '_' + loBits; //高低位之间使用_隔离 }else{ - let hiBits = hi ? hi.toString(16).toUpperCase() : ""; + let hiBits = hi ? hi.toString(16).toUpperCase() : ''; if(printHead){ // 存在标头,则输出高位之前需要补齐位数 - hiBits = hiBits.padStart(8, "0"); + hiBits = hiBits.padStart(8, '0'); } let loBits = lo.toString(16).toUpperCase(); if(hiBits){ // 存在高位 则输出低位之前需要补齐位数 - loBits = loBits.padStart(8, "0"); + loBits = loBits.padStart(8, '0'); } - segResult = "0x" + hiBits + loBits; + segResult = '0x' + hiBits + loBits; } if(i === -1) result += segResult; else - result += " " + segResult; // 不同段之间使用空格隔离 + result += ' ' + segResult; // 不同段之间使用空格隔离 } return result; } diff --git a/packages/core/src/ECS/Utils/BitMaskHashMap.ts b/packages/core/src/ECS/Utils/BitMaskHashMap.ts index 0456ca2f..113a2253 100644 --- a/packages/core/src/ECS/Utils/BitMaskHashMap.ts +++ b/packages/core/src/ECS/Utils/BitMaskHashMap.ts @@ -1,4 +1,4 @@ -import {BitMask64Data} from "./BigIntCompatibility"; +import { BitMask64Data } from './BigIntCompatibility'; // FlatHashMapFast.ts diff --git a/packages/core/src/ECS/Utils/Bits.ts b/packages/core/src/ECS/Utils/Bits.ts index f586e839..d030e6a2 100644 --- a/packages/core/src/ECS/Utils/Bits.ts +++ b/packages/core/src/ECS/Utils/Bits.ts @@ -1,4 +1,4 @@ -import {SegmentPart, BitMask64Data, BitMask64Utils} from "./BigIntCompatibility"; +import { SegmentPart, BitMask64Data, BitMask64Utils } from './BigIntCompatibility'; /** * 位集合类,用于高效的位操作 @@ -13,11 +13,11 @@ export class Bits { * @param initialValue 初始值,可以是BitMask64Data对象、数字或字符串 */ constructor(initialValue?: BitMask64Data | number | string) { - if (initialValue && typeof initialValue === "object") { + if (initialValue && typeof initialValue === 'object') { this._value = BitMask64Utils.clone(initialValue); - } else if (typeof initialValue === "number") { + } else if (typeof initialValue === 'number') { this._value = BitMask64Utils.fromNumber(initialValue); - } else if (typeof initialValue === "string") { + } else if (typeof initialValue === 'string') { const num = parseInt(initialValue, 10); this._value = BitMask64Utils.fromNumber(num); } else { @@ -33,7 +33,7 @@ export class Bits { */ public set(index: number): void { if (index < 0) { - throw new Error("Bit index cannot be negative"); + throw new Error('Bit index cannot be negative'); } BitMask64Utils.setBit(this._value, index); @@ -46,7 +46,7 @@ export class Bits { */ public clear(index: number): void { if (index < 0) { - throw new Error("Bit index cannot be negative"); + throw new Error('Bit index cannot be negative'); } BitMask64Utils.clearBit(this._value, index); @@ -207,9 +207,9 @@ export class Bits { * @param value 新值,可以是BitMask64Data对象、数字或字符串 */ public setValue(value: BitMask64Data | number | string): void { - if (typeof value === "object") { + if (typeof value === 'object') { BitMask64Utils.copy(value, this._value); - } else if (typeof value === "number") { + } else if (typeof value === 'number') { this._value = BitMask64Utils.fromNumber(value); } else { const num = parseInt(value, 10); @@ -228,7 +228,7 @@ export class Bits { bits.push(i.toString()); } } - return `Bits[${bits.join(", ")}]`; + return `Bits[${bits.join(', ')}]`; } /** @@ -240,11 +240,11 @@ export class Bits { if(maxBits == 0){ maxBits = 64 + (this._value.segments ? this._value.segments.length * 64 : 0); } - let result = ""; + let result = ''; for (let i = maxBits - 1; i >= 0; i--) { - result += this.get(i) ? "1" : "0"; + result += this.get(i) ? '1' : '0'; if (i % 8 === 0 && i > 0) { - result += " "; + result += ' '; } } return result; @@ -264,17 +264,17 @@ export class Bits { * @returns 新的位集合对象 */ public static fromBinaryString(binaryString: string): Bits { - const cleanString = binaryString.replace(/\s/g, ""); + const cleanString = binaryString.replace(/\s/g, ''); let data: BitMask64Data; if (cleanString.length <= 32) { const num = parseInt(cleanString, 2); - data = {base: [num >>> 0, 0]}; + data = { base: [num >>> 0, 0] }; } else { const loBits = cleanString.substring(cleanString.length - 32); const hiBits = cleanString.substring(0, cleanString.length - 32); const lo = parseInt(loBits, 2); const hi = parseInt(hiBits, 2); - data = {base: [lo >>> 0, hi >>> 0]}; + data = { base: [lo >>> 0, hi >>> 0] }; } return new Bits(data); } @@ -285,17 +285,17 @@ export class Bits { * @returns 新的位集合对象 */ public static fromHexString(hexString: string): Bits { - const cleanString = hexString.replace(/^0x/i, ""); + const cleanString = hexString.replace(/^0x/i, ''); let data: BitMask64Data; if (cleanString.length <= 8) { const num = parseInt(cleanString, 16); - data = {base: [num >>> 0, 0]}; + data = { base: [num >>> 0, 0] }; } else { const loBits = cleanString.substring(cleanString.length - 8); const hiBits = cleanString.substring(0, cleanString.length - 8); const lo = parseInt(loBits, 16); const hi = parseInt(hiBits, 16); - data = {base: [lo >>> 0, hi >>> 0]}; + data = { base: [lo >>> 0, hi >>> 0] }; } return new Bits(data); } diff --git a/packages/core/src/ECS/Utils/ComponentSparseSet.ts b/packages/core/src/ECS/Utils/ComponentSparseSet.ts index e4f247f5..84d927b2 100644 --- a/packages/core/src/ECS/Utils/ComponentSparseSet.ts +++ b/packages/core/src/ECS/Utils/ComponentSparseSet.ts @@ -1,9 +1,9 @@ -import {Entity} from "../Entity"; -import {ComponentType, ComponentRegistry} from "../Core/ComponentStorage"; -import {BitMask64Utils, BitMask64Data} from "./BigIntCompatibility"; -import {SparseSet} from "./SparseSet"; -import {Pool} from "../../Utils/Pool/Pool"; -import {IPoolable} from "../../Utils/Pool/IPoolable"; +import { Entity } from '../Entity'; +import { ComponentType, ComponentRegistry } from '../Core/ComponentStorage'; +import { BitMask64Utils, BitMask64Data } from './BigIntCompatibility'; +import { SparseSet } from './SparseSet'; +import { Pool } from '../../Utils/Pool/Pool'; +import { IPoolable } from '../../Utils/Pool/IPoolable'; /** * 可池化的实体集合 diff --git a/packages/core/src/ECS/Utils/EntityList.ts b/packages/core/src/ECS/Utils/EntityList.ts index 7cee2cb3..a7f0938a 100644 --- a/packages/core/src/ECS/Utils/EntityList.ts +++ b/packages/core/src/ECS/Utils/EntityList.ts @@ -1,5 +1,5 @@ -import {Entity} from "../Entity"; -import {Component} from "../Component"; +import { Entity } from '../Entity'; +import { Component } from '../Component'; /** * 高性能实体列表管理器 diff --git a/packages/core/src/ECS/Utils/EntityProcessorList.ts b/packages/core/src/ECS/Utils/EntityProcessorList.ts index 088b495f..cdf8a05d 100644 --- a/packages/core/src/ECS/Utils/EntityProcessorList.ts +++ b/packages/core/src/ECS/Utils/EntityProcessorList.ts @@ -1,13 +1,13 @@ -import {EntitySystem} from "../Systems/EntitySystem"; -import {createLogger} from "../../Utils/Logger"; -import {getSystemInstanceTypeName} from "../Decorators"; +import { EntitySystem } from '../Systems/EntitySystem'; +import { createLogger } from '../../Utils/Logger'; +import { getSystemInstanceTypeName } from '../Decorators'; /** * 实体处理器列表管理器 * 管理场景中的所有实体系统 */ export class EntityProcessorList { - private static readonly _logger = createLogger("EntityProcessorList"); + private static readonly _logger = createLogger('EntityProcessorList'); private _processors: EntitySystem[] = []; private _isDirty = false; diff --git a/packages/core/src/ECS/Utils/IdentifierPool.ts b/packages/core/src/ECS/Utils/IdentifierPool.ts index 27fb4c76..f991e854 100644 --- a/packages/core/src/ECS/Utils/IdentifierPool.ts +++ b/packages/core/src/ECS/Utils/IdentifierPool.ts @@ -117,8 +117,8 @@ export class IdentifierPool { if (this._nextAvailableIndex > IdentifierPool.MAX_INDEX) { throw new Error( `实体索引已达到框架设计限制 (${IdentifierPool.MAX_INDEX})。` + - "这意味着您已经分配了超过65535个不同的实体索引。" + - "这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。" + '这意味着您已经分配了超过65535个不同的实体索引。' + + '这是16位索引设计的限制,考虑优化实体回收策略或升级到64位ID设计。' ); } diff --git a/packages/core/src/ECS/Utils/Matcher.ts b/packages/core/src/ECS/Utils/Matcher.ts index feffb887..31e97580 100644 --- a/packages/core/src/ECS/Utils/Matcher.ts +++ b/packages/core/src/ECS/Utils/Matcher.ts @@ -1,5 +1,5 @@ -import {ComponentType} from "../Core/ComponentStorage"; -import {getComponentTypeName} from "../Decorators"; +import { ComponentType } from '../Core/ComponentStorage'; +import { getComponentTypeName } from '../Decorators'; /** * 查询条件类型 @@ -209,9 +209,9 @@ export class Matcher { all: [...this.condition.all], any: [...this.condition.any], none: [...this.condition.none], - ...(this.condition.tag !== undefined && {tag: this.condition.tag}), - ...(this.condition.name !== undefined && {name: this.condition.name}), - ...(this.condition.component !== undefined && {component: this.condition.component}) + ...(this.condition.tag !== undefined && { tag: this.condition.tag }), + ...(this.condition.name !== undefined && { name: this.condition.name }), + ...(this.condition.component !== undefined && { component: this.condition.component }) }; } @@ -267,15 +267,15 @@ export class Matcher { const parts: string[] = []; 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) { - 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) { - 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) { @@ -290,7 +290,7 @@ export class Matcher { parts.push(`component(${getComponentTypeName(this.condition.component)})`); } - return `Matcher[${parts.join(" & ")}]`; + return `Matcher[${parts.join(' & ')}]`; } } diff --git a/packages/core/src/ECS/Utils/index.ts b/packages/core/src/ECS/Utils/index.ts index af6fe921..cf2feef7 100644 --- a/packages/core/src/ECS/Utils/index.ts +++ b/packages/core/src/ECS/Utils/index.ts @@ -1,9 +1,9 @@ // ECS工具类导出 -export {EntityList} from "./EntityList"; -export {EntityProcessorList} from "./EntityProcessorList"; -export {IdentifierPool} from "./IdentifierPool"; -export {Matcher} from "./Matcher"; -export {Bits} from "./Bits"; -export {BitMask64Utils, BitMask64Data} from "./BigIntCompatibility"; -export {SparseSet} from "./SparseSet"; -export {ComponentSparseSet} from "./ComponentSparseSet"; +export { EntityList } from './EntityList'; +export { EntityProcessorList } from './EntityProcessorList'; +export { IdentifierPool } from './IdentifierPool'; +export { Matcher } from './Matcher'; +export { Bits } from './Bits'; +export { BitMask64Utils, BitMask64Data } from './BigIntCompatibility'; +export { SparseSet } from './SparseSet'; +export { ComponentSparseSet } from './ComponentSparseSet'; diff --git a/packages/core/src/ECS/World.ts b/packages/core/src/ECS/World.ts index e648f4fa..60f57881 100644 --- a/packages/core/src/ECS/World.ts +++ b/packages/core/src/ECS/World.ts @@ -1,8 +1,8 @@ -import {IScene} from "./IScene"; -import {Scene} from "./Scene"; -import {createLogger} from "../Utils/Logger"; +import { IScene } from './IScene'; +import { Scene } from './Scene'; +import { createLogger } from '../Utils/Logger'; -const logger = createLogger("World"); +const logger = createLogger('World'); /** * 全局系统接口 @@ -93,7 +93,7 @@ export class World { constructor(config: IWorldConfig = {}) { this._config = { - name: "World", + name: 'World', debug: false, maxScenes: 10, autoCleanup: true, @@ -122,10 +122,10 @@ export class World { const scene = sceneInstance || (new Scene() as unknown as T); // 设置Scene的标识 - if ("id" in scene) { + if ('id' in scene) { (scene as any).id = sceneId; } - if ("name" in scene && !scene.name) { + if ('name' in scene && !scene.name) { scene.name = sceneId; } @@ -407,7 +407,7 @@ export class World { activeSceneCount: this._activeScenes.size, globalSystemCount: this._globalSystems.length, createdAt: this._createdAt, - config: {...this._config}, + config: { ...this._config }, scenes: Array.from(this._scenes.keys()).map((sceneId) => ({ id: sceneId, isActive: this._activeScenes.has(sceneId), diff --git a/packages/core/src/ECS/WorldManager.ts b/packages/core/src/ECS/WorldManager.ts index 431c3049..d4930ad0 100644 --- a/packages/core/src/ECS/WorldManager.ts +++ b/packages/core/src/ECS/WorldManager.ts @@ -1,8 +1,8 @@ -import {World, IWorldConfig} from "./World"; -import {createLogger} from "../Utils/Logger"; -import type {IService} from "../Core/ServiceContainer"; +import { World, IWorldConfig } from './World'; +import { createLogger } from '../Utils/Logger'; +import type { IService } from '../Core/ServiceContainer'; -const logger = createLogger("WorldManager"); +const logger = createLogger('WorldManager'); /** * WorldManager配置接口 @@ -81,7 +81,7 @@ export class WorldManager implements IService { // 默认启动运行状态 this._isRunning = true; - logger.info("WorldManager已初始化", { + logger.info('WorldManager已初始化', { maxWorlds: this._config.maxWorlds, autoCleanup: this._config.autoCleanup, cleanupInterval: this._config.cleanupInterval @@ -96,8 +96,8 @@ export class WorldManager implements IService { * 创建新World */ public createWorld(worldId: string, config?: IWorldConfig): World { - if (!worldId || typeof worldId !== "string" || worldId.trim() === "") { - throw new Error("World ID不能为空"); + if (!worldId || typeof worldId !== 'string' || worldId.trim() === '') { + throw new Error('World ID不能为空'); } if (this._worlds.has(worldId)) { @@ -110,9 +110,9 @@ export class WorldManager implements IService { const worldConfig: IWorldConfig = { name: worldId, - ...(this._config.debug !== undefined && {debug: this._config.debug}), - ...(config?.maxScenes !== undefined && {maxScenes: config.maxScenes}), - ...(config?.autoCleanup !== undefined && {autoCleanup: config.autoCleanup}) + ...(this._config.debug !== undefined && { debug: this._config.debug }), + ...(config?.maxScenes !== undefined && { maxScenes: config.maxScenes }), + ...(config?.autoCleanup !== undefined && { autoCleanup: config.autoCleanup }) }; const world = new World(worldConfig); @@ -247,7 +247,7 @@ export class WorldManager implements IService { this.setWorldActive(worldId, true); } - logger.info("启动所有World"); + logger.info('启动所有World'); } /** @@ -260,7 +260,7 @@ export class WorldManager implements IService { this.setWorldActive(worldId, false); } - logger.info("停止所有World"); + logger.info('停止所有World'); } /** @@ -302,7 +302,7 @@ export class WorldManager implements IService { totalSystems: 0, memoryUsage: 0, isRunning: this._isRunning, - config: {...this._config}, + config: { ...this._config }, worlds: [] as any[] }; @@ -367,7 +367,7 @@ export class WorldManager implements IService { * 销毁WorldManager */ public destroy(): void { - logger.info("正在销毁WorldManager..."); + logger.info('正在销毁WorldManager...'); // 停止清理定时器 this.stopCleanupTimer(); @@ -385,7 +385,7 @@ export class WorldManager implements IService { this._activeWorlds.clear(); this._isRunning = false; - logger.info("WorldManager已销毁"); + logger.info('WorldManager已销毁'); } /** @@ -420,7 +420,7 @@ export class WorldManager implements IService { if (this._cleanupTimer) { clearInterval(this._cleanupTimer); this._cleanupTimer = null; - logger.debug("停止World清理定时器"); + logger.debug('停止World清理定时器'); } } @@ -483,6 +483,6 @@ export class WorldManager implements IService { * 获取配置 */ public get config(): IWorldManagerConfig { - return {...this._config}; + return { ...this._config }; } } diff --git a/packages/core/src/ECS/index.ts b/packages/core/src/ECS/index.ts index 6fd38040..4c37f576 100644 --- a/packages/core/src/ECS/index.ts +++ b/packages/core/src/ECS/index.ts @@ -1,20 +1,20 @@ -export {Entity} from "./Entity"; -export {Component} from "./Component"; -export {ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator} from "./CoreEvents"; -export * from "./Systems"; -export * from "./Utils"; -export * from "./Decorators"; -export {Scene} from "./Scene"; -export {IScene, ISceneFactory, ISceneConfig} from "./IScene"; -export {SceneManager} from "./SceneManager"; -export {World, IWorldConfig} from "./World"; -export {WorldManager, IWorldManagerConfig} from "./WorldManager"; -export * from "./Core/Events"; -export * from "./Core/Query"; -export * from "./Core/Storage"; -export * from "./Core/StorageDecorators"; -export * from "./Serialization"; -export {ReferenceTracker, getSceneByEntityId} from "./Core/ReferenceTracker"; -export type {EntityRefRecord} from "./Core/ReferenceTracker"; -export {ReactiveQuery, ReactiveQueryChangeType} from "./Core/ReactiveQuery"; -export type {ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig} from "./Core/ReactiveQuery"; +export { Entity } from './Entity'; +export { Component } from './Component'; +export { ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator } from './CoreEvents'; +export * from './Systems'; +export * from './Utils'; +export * from './Decorators'; +export { Scene } from './Scene'; +export { IScene, ISceneFactory, ISceneConfig } from './IScene'; +export { SceneManager } from './SceneManager'; +export { World, IWorldConfig } from './World'; +export { WorldManager, IWorldManagerConfig } from './WorldManager'; +export * from './Core/Events'; +export * from './Core/Query'; +export * from './Core/Storage'; +export * from './Core/StorageDecorators'; +export * from './Serialization'; +export { ReferenceTracker, getSceneByEntityId } from './Core/ReferenceTracker'; +export type { EntityRefRecord } from './Core/ReferenceTracker'; +export { ReactiveQuery, ReactiveQueryChangeType } from './Core/ReactiveQuery'; +export type { ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig } from './Core/ReactiveQuery'; diff --git a/packages/core/src/Platform/IPlatformAdapter.ts b/packages/core/src/Platform/IPlatformAdapter.ts index a0e5387d..45a86b82 100644 --- a/packages/core/src/Platform/IPlatformAdapter.ts +++ b/packages/core/src/Platform/IPlatformAdapter.ts @@ -64,12 +64,12 @@ export interface WorkerCreationOptions { /** * Worker类型 */ - type?: "classic" | "module"; + type?: 'classic' | 'module'; /** * 凭据模式 */ - credentials?: "omit" | "same-origin" | "include"; + credentials?: 'omit' | 'same-origin' | 'include'; /** * Worker名称(用于调试) @@ -104,7 +104,7 @@ export interface PlatformWorker { /** * Worker状态 */ - readonly state: "running" | "terminated"; + readonly state: 'running' | 'terminated'; } /** @@ -179,7 +179,7 @@ export interface PlatformDetectionResult { /** * 平台类型 */ - platform: "browser" | "wechat-minigame" | "bytedance-minigame" | "alipay-minigame" | "baidu-minigame" | "nodejs" | "unknown"; + platform: 'browser' | 'wechat-minigame' | 'bytedance-minigame' | 'alipay-minigame' | 'baidu-minigame' | 'nodejs' | 'unknown'; /** * 是否确定检测结果 diff --git a/packages/core/src/Platform/PlatformDetector.ts b/packages/core/src/Platform/PlatformDetector.ts index 20588304..61f9f134 100644 --- a/packages/core/src/Platform/PlatformDetector.ts +++ b/packages/core/src/Platform/PlatformDetector.ts @@ -1,4 +1,4 @@ -import type {PlatformDetectionResult} from "./IPlatformAdapter"; +import type { PlatformDetectionResult } from './IPlatformAdapter'; /** * 平台检测器 @@ -10,96 +10,96 @@ export class PlatformDetector { */ public static detect(): PlatformDetectionResult { const features: string[] = []; - let platform: PlatformDetectionResult["platform"] = "unknown"; + let platform: PlatformDetectionResult['platform'] = 'unknown'; let confident = false; let adapterClass: string | undefined; // 检查全局对象和API - if (typeof globalThis !== "undefined") { - features.push("globalThis"); + if (typeof globalThis !== 'undefined') { + features.push('globalThis'); } - if (typeof window !== "undefined") { - features.push("window"); + if (typeof window !== 'undefined') { + features.push('window'); } - if (typeof self !== "undefined") { - features.push("self"); + if (typeof self !== 'undefined') { + features.push('self'); } // 检测Node.js环境(优先级最高,因为Node.js可能包含全局对象模拟) if (this.isNodeJS()) { - platform = "nodejs"; + platform = 'nodejs'; confident = true; - adapterClass = "NodeAdapter"; - features.push("nodejs", "process", "require"); + adapterClass = 'NodeAdapter'; + features.push('nodejs', 'process', 'require'); } // 检测微信小游戏环境 else if (this.isWeChatMiniGame()) { - platform = "wechat-minigame"; + platform = 'wechat-minigame'; confident = true; - adapterClass = "WeChatMiniGameAdapter"; - features.push("wx", "wechat-minigame"); + adapterClass = 'WeChatMiniGameAdapter'; + features.push('wx', 'wechat-minigame'); } // 检测字节跳动小游戏环境 else if (this.isByteDanceMiniGame()) { - platform = "bytedance-minigame"; + platform = 'bytedance-minigame'; confident = true; - adapterClass = "ByteDanceMiniGameAdapter"; - features.push("tt", "bytedance-minigame"); + adapterClass = 'ByteDanceMiniGameAdapter'; + features.push('tt', 'bytedance-minigame'); } // 检测支付宝小游戏环境 else if (this.isAlipayMiniGame()) { - platform = "alipay-minigame"; + platform = 'alipay-minigame'; confident = true; - adapterClass = "AlipayMiniGameAdapter"; - features.push("my", "alipay-minigame"); + adapterClass = 'AlipayMiniGameAdapter'; + features.push('my', 'alipay-minigame'); } // 检测百度小游戏环境 else if (this.isBaiduMiniGame()) { - platform = "baidu-minigame"; + platform = 'baidu-minigame'; confident = true; - adapterClass = "BaiduMiniGameAdapter"; - features.push("swan", "baidu-minigame"); + adapterClass = 'BaiduMiniGameAdapter'; + features.push('swan', 'baidu-minigame'); } // 检测浏览器环境 else if (this.isBrowser()) { - platform = "browser"; + platform = 'browser'; confident = true; - adapterClass = "BrowserAdapter"; - features.push("browser"); + adapterClass = 'BrowserAdapter'; + features.push('browser'); } // 添加功能检测特征 - if (typeof Worker !== "undefined") { - features.push("Worker"); + if (typeof Worker !== 'undefined') { + features.push('Worker'); } - if (typeof SharedArrayBuffer !== "undefined") { - features.push("SharedArrayBuffer"); + if (typeof SharedArrayBuffer !== 'undefined') { + features.push('SharedArrayBuffer'); } - if (typeof navigator !== "undefined" && navigator.hardwareConcurrency) { - features.push("hardwareConcurrency"); + if (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) { + features.push('hardwareConcurrency'); } - if (typeof performance !== "undefined" && typeof performance.now === "function") { - features.push("performance.now"); + if (typeof performance !== 'undefined' && typeof performance.now === 'function') { + features.push('performance.now'); } - if (typeof Blob !== "undefined") { - features.push("Blob"); + if (typeof Blob !== 'undefined') { + features.push('Blob'); } - if (typeof URL !== "undefined" && typeof URL.createObjectURL === "function") { - features.push("URL.createObjectURL"); + if (typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function') { + features.push('URL.createObjectURL'); } return { platform, confident, features, - ...(adapterClass && {adapterClass}) + ...(adapterClass && { adapterClass }) }; } @@ -108,7 +108,7 @@ export class PlatformDetector { */ private static isWeChatMiniGame(): boolean { // 检查wx全局对象 - if (typeof (globalThis as any).wx !== "undefined") { + if (typeof (globalThis as any).wx !== 'undefined') { const wx = (globalThis as any).wx; // 检查微信小游戏特有的API return !!(wx.getSystemInfo && wx.createCanvas && wx.createImage); @@ -121,7 +121,7 @@ export class PlatformDetector { */ private static isByteDanceMiniGame(): boolean { // 检查tt全局对象 - if (typeof (globalThis as any).tt !== "undefined") { + if (typeof (globalThis as any).tt !== 'undefined') { const tt = (globalThis as any).tt; // 检查字节跳动小游戏特有的API return !!(tt.getSystemInfo && tt.createCanvas && tt.createImage); @@ -136,15 +136,15 @@ export class PlatformDetector { try { // 检查Node.js特有的全局对象和模块 return !!( - typeof process !== "undefined" && + typeof process !== 'undefined' && process.versions && process.versions.node && - typeof require !== "undefined" && - typeof module !== "undefined" && - typeof exports !== "undefined" && + typeof require !== 'undefined' && + typeof module !== 'undefined' && + typeof exports !== 'undefined' && // 确保不是在浏览器环境中的Node.js模拟 - typeof window === "undefined" && - typeof document === "undefined" + typeof window === 'undefined' && + typeof document === 'undefined' ); } catch { return false; @@ -156,7 +156,7 @@ export class PlatformDetector { */ private static isAlipayMiniGame(): boolean { // 检查my全局对象 - if (typeof (globalThis as any).my !== "undefined") { + if (typeof (globalThis as any).my !== 'undefined') { const my = (globalThis as any).my; // 检查支付宝小游戏特有的API return !!(my.getSystemInfo && my.createCanvas); @@ -169,7 +169,7 @@ export class PlatformDetector { */ private static isBaiduMiniGame(): boolean { // 检查swan全局对象 - if (typeof (globalThis as any).swan !== "undefined") { + if (typeof (globalThis as any).swan !== 'undefined') { const swan = (globalThis as any).swan; // 检查百度小游戏特有的API return !!(swan.getSystemInfo && swan.createCanvas); @@ -182,9 +182,9 @@ export class PlatformDetector { */ private static isBrowser(): boolean { // 检查浏览器特有的对象和API - return typeof window !== "undefined" && - typeof document !== "undefined" && - typeof navigator !== "undefined" && + return typeof window !== 'undefined' && + typeof document !== 'undefined' && + typeof navigator !== 'undefined' && window.location !== undefined; } @@ -195,42 +195,42 @@ export class PlatformDetector { const info: Record = {}; // 基础检测 - info["userAgent"] = typeof navigator !== "undefined" ? navigator.userAgent : "unknown"; - info["platform"] = typeof navigator !== "undefined" ? navigator.platform : "unknown"; + info['userAgent'] = typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown'; + info['platform'] = typeof navigator !== 'undefined' ? navigator.platform : 'unknown'; // 全局对象检测 - info["globalObjects"] = { - window: typeof window !== "undefined", - document: typeof document !== "undefined", - navigator: typeof navigator !== "undefined", - wx: typeof (globalThis as any).wx !== "undefined", - tt: typeof (globalThis as any).tt !== "undefined", - my: typeof (globalThis as any).my !== "undefined", - swan: typeof (globalThis as any).swan !== "undefined" + info['globalObjects'] = { + window: typeof window !== 'undefined', + document: typeof document !== 'undefined', + navigator: typeof navigator !== 'undefined', + wx: typeof (globalThis as any).wx !== 'undefined', + tt: typeof (globalThis as any).tt !== 'undefined', + my: typeof (globalThis as any).my !== 'undefined', + swan: typeof (globalThis as any).swan !== 'undefined' }; // Worker相关检测 - info["workerSupport"] = { - Worker: typeof Worker !== "undefined", - SharedWorker: typeof SharedWorker !== "undefined", - ServiceWorker: typeof navigator !== "undefined" && "serviceWorker" in navigator, - SharedArrayBuffer: typeof SharedArrayBuffer !== "undefined", - crossOriginIsolated: typeof self !== "undefined" ? self.crossOriginIsolated : false + info['workerSupport'] = { + Worker: typeof Worker !== 'undefined', + SharedWorker: typeof SharedWorker !== 'undefined', + ServiceWorker: typeof navigator !== 'undefined' && 'serviceWorker' in navigator, + SharedArrayBuffer: typeof SharedArrayBuffer !== 'undefined', + crossOriginIsolated: typeof self !== 'undefined' ? self.crossOriginIsolated : false }; // 性能相关检测 - info["performance"] = { - performanceNow: typeof performance !== "undefined" && typeof performance.now === "function", - hardwareConcurrency: typeof navigator !== "undefined" ? navigator.hardwareConcurrency : undefined + info['performance'] = { + performanceNow: typeof performance !== 'undefined' && typeof performance.now === 'function', + hardwareConcurrency: typeof navigator !== 'undefined' ? navigator.hardwareConcurrency : undefined }; // 其他API检测 - info["apiSupport"] = { - Blob: typeof Blob !== "undefined", - URL: typeof URL !== "undefined", - createObjectURL: typeof URL !== "undefined" && typeof URL.createObjectURL === "function", - ArrayBuffer: typeof ArrayBuffer !== "undefined", - TypedArrays: typeof Float32Array !== "undefined" + info['apiSupport'] = { + Blob: typeof Blob !== 'undefined', + URL: typeof URL !== 'undefined', + createObjectURL: typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function', + ArrayBuffer: typeof ArrayBuffer !== 'undefined', + TypedArrays: typeof Float32Array !== 'undefined' }; return info; diff --git a/packages/core/src/Platform/PlatformManager.ts b/packages/core/src/Platform/PlatformManager.ts index 86e168ad..0bbaa4c5 100644 --- a/packages/core/src/Platform/PlatformManager.ts +++ b/packages/core/src/Platform/PlatformManager.ts @@ -1,5 +1,5 @@ -import type {IPlatformAdapter} from "./IPlatformAdapter"; -import {createLogger, type ILogger} from "../Utils/Logger"; +import type { IPlatformAdapter } from './IPlatformAdapter'; +import { createLogger, type ILogger } from '../Utils/Logger'; /** * 平台管理器 @@ -11,7 +11,7 @@ export class PlatformManager { private readonly logger: ILogger; private constructor() { - this.logger = createLogger("PlatformManager"); + this.logger = createLogger('PlatformManager'); } /** @@ -29,7 +29,7 @@ export class PlatformManager { */ public getAdapter(): IPlatformAdapter { if (!this.adapter) { - throw new Error("平台适配器未注册,请调用 registerAdapter() 注册适配器"); + throw new Error('平台适配器未注册,请调用 registerAdapter() 注册适配器'); } return this.adapter; } @@ -70,19 +70,19 @@ export class PlatformManager { /** * 检查当前平台是否支持特定功能 */ - public supportsFeature(feature: "worker" | "shared-array-buffer" | "transferable-objects" | "module-worker"): boolean { + public supportsFeature(feature: 'worker' | 'shared-array-buffer' | 'transferable-objects' | 'module-worker'): boolean { if (!this.adapter) return false; const config = this.adapter.getPlatformConfig(); switch (feature) { - case "worker": + case 'worker': return this.adapter.isWorkerSupported(); - case "shared-array-buffer": + case 'shared-array-buffer': return this.adapter.isSharedArrayBufferSupported(); - case "transferable-objects": + case 'transferable-objects': return config.supportsTransferableObjects; - case "module-worker": + case 'module-worker': return config.supportsModuleWorker; default: return false; @@ -123,11 +123,11 @@ export class PlatformManager { */ public async getFullPlatformConfig(): Promise { if (!this.adapter) { - throw new Error("平台适配器未注册"); + throw new Error('平台适配器未注册'); } // 如果适配器支持异步获取配置,使用异步方法 - if (typeof this.adapter.getPlatformConfigAsync === "function") { + if (typeof this.adapter.getPlatformConfigAsync === 'function') { return await this.adapter.getPlatformConfigAsync(); } diff --git a/packages/core/src/Platform/index.ts b/packages/core/src/Platform/index.ts index 28db5c4a..f1b40242 100644 --- a/packages/core/src/Platform/index.ts +++ b/packages/core/src/Platform/index.ts @@ -9,17 +9,17 @@ export type { WorkerCreationOptions, PlatformConfig, PlatformDetectionResult -} from "./IPlatformAdapter"; +} from './IPlatformAdapter'; // 平台检测器 -export {PlatformDetector} from "./PlatformDetector"; +export { PlatformDetector } from './PlatformDetector'; // 平台管理器 -export {PlatformManager} from "./PlatformManager"; +export { PlatformManager } from './PlatformManager'; // 内部导入用于便利函数 -import {PlatformManager} from "./PlatformManager"; -import type {IPlatformAdapter} from "./IPlatformAdapter"; +import { PlatformManager } from './PlatformManager'; +import type { IPlatformAdapter } from './IPlatformAdapter'; // 便利函数 export function registerPlatformAdapter(adapter: IPlatformAdapter) { @@ -38,7 +38,7 @@ export function getFullPlatformConfig() { return PlatformManager.getInstance().getFullPlatformConfig(); } -export function supportsFeature(feature: "worker" | "shared-array-buffer" | "transferable-objects" | "module-worker") { +export function supportsFeature(feature: 'worker' | 'shared-array-buffer' | 'transferable-objects' | 'module-worker') { return PlatformManager.getInstance().supportsFeature(feature); } diff --git a/packages/core/src/Plugins/DebugPlugin.ts b/packages/core/src/Plugins/DebugPlugin.ts index 4a40d12e..5603a0e7 100644 --- a/packages/core/src/Plugins/DebugPlugin.ts +++ b/packages/core/src/Plugins/DebugPlugin.ts @@ -1,15 +1,15 @@ -import type {Core} from "../Core"; -import type {ServiceContainer} from "../Core/ServiceContainer"; -import {IPlugin} from "../Core/Plugin"; -import {createLogger} from "../Utils/Logger"; -import type {IScene} from "../ECS/IScene"; -import type {Entity} from "../ECS/Entity"; -import type {EntitySystem} from "../ECS/Systems/EntitySystem"; -import {WorldManager} from "../ECS/WorldManager"; -import {Injectable} from "../Core/DI/Decorators"; -import type {IService} from "../Core/ServiceContainer"; +import type { Core } from '../Core'; +import type { ServiceContainer } from '../Core/ServiceContainer'; +import { IPlugin } from '../Core/Plugin'; +import { createLogger } from '../Utils/Logger'; +import type { IScene } from '../ECS/IScene'; +import type { Entity } from '../ECS/Entity'; +import type { EntitySystem } from '../ECS/Systems/EntitySystem'; +import { WorldManager } from '../ECS/WorldManager'; +import { Injectable } from '../Core/DI/Decorators'; +import type { IService } from '../Core/ServiceContainer'; -const logger = createLogger("DebugPlugin"); +const logger = createLogger('DebugPlugin'); /** * ECS 调试插件统计信息 @@ -91,8 +91,8 @@ export interface ComponentDebugInfo { */ @Injectable() export class DebugPlugin implements IPlugin, IService { - readonly name = "@esengine/debug-plugin"; - readonly version = "1.0.0"; + readonly name = '@esengine/debug-plugin'; + readonly version = '1.0.0'; private worldManager: WorldManager | null = null; private updateInterval: number; @@ -115,7 +115,7 @@ export class DebugPlugin implements IPlugin, IService { async install(_core: Core, services: ServiceContainer): Promise { this.worldManager = services.resolve(WorldManager); - logger.info("ECS Debug Plugin installed"); + logger.info('ECS Debug Plugin installed'); if (this.autoStart) { this.start(); @@ -129,7 +129,7 @@ export class DebugPlugin implements IPlugin, IService { this.stop(); this.worldManager = null; - logger.info("ECS Debug Plugin uninstalled"); + logger.info('ECS Debug Plugin uninstalled'); } /** @@ -145,11 +145,11 @@ export class DebugPlugin implements IPlugin, IService { */ public start(): void { if (this.updateTimer) { - logger.warn("Debug monitoring already started"); + logger.warn('Debug monitoring already started'); return; } - logger.info("Starting debug monitoring"); + logger.info('Starting debug monitoring'); this.updateTimer = setInterval(() => { this.logStats(); @@ -163,7 +163,7 @@ export class DebugPlugin implements IPlugin, IService { if (this.updateTimer) { clearInterval(this.updateTimer); this.updateTimer = null; - logger.info("Debug monitoring stopped"); + logger.info('Debug monitoring stopped'); } } @@ -172,7 +172,7 @@ export class DebugPlugin implements IPlugin, IService { */ public getStats(): ECSDebugStats { if (!this.worldManager) { - throw new Error("Plugin not installed"); + throw new Error('Plugin not installed'); } const scenes: SceneDebugInfo[] = []; @@ -230,7 +230,7 @@ export class DebugPlugin implements IPlugin, IService { enabled: system.enabled, updateOrder: system.updateOrder, entityCount: system.entities.length, - ...(performance !== undefined && {performance}) + ...(performance !== undefined && { performance }) }; } @@ -258,15 +258,15 @@ export class DebugPlugin implements IPlugin, IService { const data: any = {}; for (const key of Object.keys(component)) { - if (!key.startsWith("_")) { + if (!key.startsWith('_')) { const value = component[key]; - if (typeof value !== "function") { + if (typeof value !== 'function') { data[key] = value; } } } - return {type, data}; + return { type, data }; } /** @@ -281,7 +281,7 @@ export class DebugPlugin implements IPlugin, IService { hasComponent?: string; }): EntityDebugInfo[] { if (!this.worldManager) { - throw new Error("Plugin not installed"); + throw new Error('Plugin not installed'); } const results: EntityDebugInfo[] = []; @@ -325,7 +325,7 @@ export class DebugPlugin implements IPlugin, IService { private logStats(): void { const stats = this.getStats(); - logger.info("=== ECS Debug Stats ==="); + logger.info('=== ECS Debug Stats ==='); logger.info(`Total Entities: ${stats.totalEntities}`); logger.info(`Total Systems: ${stats.totalSystems}`); logger.info(`Scenes: ${stats.scenes.length}`); @@ -338,14 +338,14 @@ export class DebugPlugin implements IPlugin, IService { for (const system of scene.systems) { const perfStr = system.performance ? ` | Avg: ${system.performance.avgExecutionTime.toFixed(2)}ms, Max: ${system.performance.maxExecutionTime.toFixed(2)}ms` - : ""; + : ''; logger.info( - ` - ${system.name} (${system.enabled ? "enabled" : "disabled"}) | Entities: ${system.entityCount}${perfStr}` + ` - ${system.name} (${system.enabled ? 'enabled' : 'disabled'}) | Entities: ${system.entityCount}${perfStr}` ); } } - logger.info("========================\n"); + logger.info('========================\n'); } /** diff --git a/packages/core/src/Plugins/index.ts b/packages/core/src/Plugins/index.ts index 0ff9e25c..90bac8a8 100644 --- a/packages/core/src/Plugins/index.ts +++ b/packages/core/src/Plugins/index.ts @@ -1 +1 @@ -export * from "./DebugPlugin"; +export * from './DebugPlugin'; diff --git a/packages/core/src/Types/IUpdatable.ts b/packages/core/src/Types/IUpdatable.ts index 1d99cd12..e5c50a2b 100644 --- a/packages/core/src/Types/IUpdatable.ts +++ b/packages/core/src/Types/IUpdatable.ts @@ -16,5 +16,5 @@ export interface IUpdatable { * 检查对象是否实现了IUpdatable接口 */ export function isUpdatable(obj: any): obj is IUpdatable { - return obj && typeof obj.update === "function"; + return obj && typeof obj.update === 'function'; } diff --git a/packages/core/src/Types/TypeHelpers.ts b/packages/core/src/Types/TypeHelpers.ts index 1884827e..b86577d5 100644 --- a/packages/core/src/Types/TypeHelpers.ts +++ b/packages/core/src/Types/TypeHelpers.ts @@ -4,8 +4,8 @@ * 提供高级类型推断和类型安全的工具类型 */ -import type {IComponent} from "./index"; -import {Component} from "../ECS/Component"; +import type { IComponent } from './index'; +import { Component } from '../ECS/Component'; /** * 组件类型提取器 @@ -240,7 +240,7 @@ export interface TypedQueryCondition< export function isComponentType( value: any ): value is ComponentConstructor { - return typeof value === "function" && value.prototype instanceof Component; + return typeof value === 'function' && value.prototype instanceof Component; } /** diff --git a/packages/core/src/Types/index.ts b/packages/core/src/Types/index.ts index 63e7f594..f35e1d44 100644 --- a/packages/core/src/Types/index.ts +++ b/packages/core/src/Types/index.ts @@ -2,11 +2,11 @@ * 框架核心类型定义 */ -import type {IWorldManagerConfig} from "../ECS"; +import type { IWorldManagerConfig } from '../ECS'; // 导出TypeScript类型增强工具 -export * from "./TypeHelpers"; -export * from "./IUpdatable"; +export * from './TypeHelpers'; +export * from './IUpdatable'; /** * 组件接口 diff --git a/packages/core/src/Utils/BinarySerializer.ts b/packages/core/src/Utils/BinarySerializer.ts index eaca519b..63884004 100644 --- a/packages/core/src/Utils/BinarySerializer.ts +++ b/packages/core/src/Utils/BinarySerializer.ts @@ -1,4 +1,4 @@ -import {strToU8, strFromU8, zlibSync, unzlibSync} from "fflate"; +import { strToU8, strFromU8, zlibSync, unzlibSync } from 'fflate'; /** * 二进制序列化器 diff --git a/packages/core/src/Utils/Debug/ComponentDataCollector.ts b/packages/core/src/Utils/Debug/ComponentDataCollector.ts index b4bf7ec2..22b79d57 100644 --- a/packages/core/src/Utils/Debug/ComponentDataCollector.ts +++ b/packages/core/src/Utils/Debug/ComponentDataCollector.ts @@ -1,7 +1,7 @@ -import {IComponentDebugData} from "../../Types"; -import {ComponentPoolManager} from "../../ECS/Core/ComponentPool"; -import {getComponentInstanceTypeName} from "../../ECS/Decorators"; -import {IScene} from "../../ECS/IScene"; +import { IComponentDebugData } from '../../Types'; +import { ComponentPoolManager } from '../../ECS/Core/ComponentPool'; +import { getComponentInstanceTypeName } from '../../ECS/Decorators'; +import { IScene } from '../../ECS/IScene'; /** * 组件数据收集器 @@ -38,7 +38,7 @@ export class ComponentDataCollector { if (entity.components) { entity.components.forEach((component: any) => { const typeName = getComponentInstanceTypeName(component); - const stats = componentStats.get(typeName) || {count: 0, entities: 0}; + const stats = componentStats.get(typeName) || { count: 0, entities: 0 }; stats.count++; totalInstances++; componentStats.set(typeName, stats); @@ -122,13 +122,13 @@ export class ComponentDataCollector { } private calculateQuickObjectSize(obj: any): number { - if (!obj || typeof obj !== "object") return 8; + if (!obj || typeof obj !== 'object') return 8; let size = 32; const visited = new WeakSet(); const calculate = (item: any, depth: number = 0): number => { - if (!item || typeof item !== "object" || visited.has(item) || depth > 3) { + if (!item || typeof item !== 'object' || visited.has(item) || depth > 3) { return 0; } visited.add(item); @@ -139,18 +139,18 @@ export class ComponentDataCollector { const keys = Object.keys(item); for (let i = 0; i < Math.min(keys.length, 20); i++) { const key = keys[i]; - if (!key || key === "entity" || key === "_entity" || key === "constructor") continue; + if (!key || key === 'entity' || key === '_entity' || key === 'constructor') continue; const value = item[key]; itemSize += key.length * 2; - if (typeof value === "string") { + if (typeof value === 'string') { itemSize += Math.min(value.length * 2, 200); - } else if (typeof value === "number") { + } else if (typeof value === 'number') { itemSize += 8; - } else if (typeof value === "boolean") { + } else if (typeof value === 'boolean') { itemSize += 4; - } else if (typeof value === "object" && value !== null) { + } else if (typeof value === 'object' && value !== null) { itemSize += calculate(value, depth + 1); } } @@ -206,16 +206,16 @@ export class ComponentDataCollector { const type = typeof obj; switch (type) { - case "boolean": + case 'boolean': size = 4; break; - case "number": + case 'number': size = 8; break; - case "string": + case 'string': size = 24 + Math.min(obj.length * 2, 1000); break; - case "object": + case 'object': visited.add(obj); if (Array.isArray(obj)) { @@ -235,12 +235,12 @@ export class ComponentDataCollector { const key = ownKeys[i]; if (!key) continue; - if (key === "constructor" || - key === "__proto__" || - key === "entity" || - key === "_entity" || - key.startsWith("_cc_") || - key.startsWith("__")) { + if (key === 'constructor' || + key === '__proto__' || + key === 'entity' || + key === '_entity' || + key.startsWith('_cc_') || + key.startsWith('__')) { continue; } diff --git a/packages/core/src/Utils/Debug/DebugConfigService.ts b/packages/core/src/Utils/Debug/DebugConfigService.ts index 0f5b8801..a15d8d6f 100644 --- a/packages/core/src/Utils/Debug/DebugConfigService.ts +++ b/packages/core/src/Utils/Debug/DebugConfigService.ts @@ -1,6 +1,6 @@ -import {IECSDebugConfig} from "../../Types"; -import {Injectable} from "../../Core/DI/Decorators"; -import type {IService} from "../../Core/ServiceContainer"; +import { IECSDebugConfig } from '../../Types'; +import { Injectable } from '../../Core/DI/Decorators'; +import type { IService } from '../../Core/ServiceContainer'; /** * 调试配置服务 @@ -14,7 +14,7 @@ export class DebugConfigService implements IService { constructor() { this._config = { enabled: false, - websocketUrl: "", + websocketUrl: '', debugFrameRate: 30, autoReconnect: true, channels: { diff --git a/packages/core/src/Utils/Debug/DebugManager.ts b/packages/core/src/Utils/Debug/DebugManager.ts index 19fdf72e..d4772615 100644 --- a/packages/core/src/Utils/Debug/DebugManager.ts +++ b/packages/core/src/Utils/Debug/DebugManager.ts @@ -1,20 +1,20 @@ -import {IECSDebugConfig, IECSDebugData} from "../../Types"; -import {EntityDataCollector} from "./EntityDataCollector"; -import {SystemDataCollector} from "./SystemDataCollector"; -import {PerformanceDataCollector} from "./PerformanceDataCollector"; -import {ComponentDataCollector} from "./ComponentDataCollector"; -import {SceneDataCollector} from "./SceneDataCollector"; -import {WebSocketManager} from "./WebSocketManager"; -import {Component} from "../../ECS/Component"; -import {ComponentPoolManager} from "../../ECS/Core/ComponentPool"; -import {Pool} from "../../Utils/Pool"; -import {getComponentInstanceTypeName, getSystemInstanceTypeName} from "../../ECS/Decorators"; -import type {IService} from "../../Core/ServiceContainer"; -import type {IUpdatable} from "../../Types/IUpdatable"; -import {SceneManager} from "../../ECS/SceneManager"; -import {PerformanceMonitor} from "../PerformanceMonitor"; -import {Injectable, Inject, Updatable} from "../../Core/DI/Decorators"; -import {DebugConfigService} from "./DebugConfigService"; +import { IECSDebugConfig, IECSDebugData } from '../../Types'; +import { EntityDataCollector } from './EntityDataCollector'; +import { SystemDataCollector } from './SystemDataCollector'; +import { PerformanceDataCollector } from './PerformanceDataCollector'; +import { ComponentDataCollector } from './ComponentDataCollector'; +import { SceneDataCollector } from './SceneDataCollector'; +import { WebSocketManager } from './WebSocketManager'; +import { Component } from '../../ECS/Component'; +import { ComponentPoolManager } from '../../ECS/Core/ComponentPool'; +import { Pool } from '../../Utils/Pool'; +import { getComponentInstanceTypeName, getSystemInstanceTypeName } from '../../ECS/Decorators'; +import type { IService } from '../../Core/ServiceContainer'; +import type { IUpdatable } from '../../Types/IUpdatable'; +import { SceneManager } from '../../ECS/SceneManager'; +import { PerformanceMonitor } from '../PerformanceMonitor'; +import { Injectable, Inject, Updatable } from '../../Core/DI/Decorators'; +import { DebugConfigService } from './DebugConfigService'; /** * 调试管理器 @@ -106,27 +106,27 @@ export class DebugManager implements IService, IUpdatable { */ private interceptConsole(): void { console.log = (...args: unknown[]) => { - this.sendLog("info", this.formatLogMessage(args)); + this.sendLog('info', this.formatLogMessage(args)); this.originalConsole.log(...args); }; console.debug = (...args: unknown[]) => { - this.sendLog("debug", this.formatLogMessage(args)); + this.sendLog('debug', this.formatLogMessage(args)); this.originalConsole.debug(...args); }; console.info = (...args: unknown[]) => { - this.sendLog("info", this.formatLogMessage(args)); + this.sendLog('info', this.formatLogMessage(args)); this.originalConsole.info(...args); }; console.warn = (...args: unknown[]) => { - this.sendLog("warn", this.formatLogMessage(args)); + this.sendLog('warn', this.formatLogMessage(args)); this.originalConsole.warn(...args); }; console.error = (...args: unknown[]) => { - this.sendLog("error", this.formatLogMessage(args)); + this.sendLog('error', this.formatLogMessage(args)); this.originalConsole.error(...args); }; } @@ -136,11 +136,11 @@ export class DebugManager implements IService, IUpdatable { */ private formatLogMessage(args: unknown[]): string { 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 === null) return "null"; - if (arg === undefined) return "undefined"; - if (typeof arg === "object") { + if (arg === null) return 'null'; + if (arg === undefined) return 'undefined'; + if (typeof arg === 'object') { try { return this.safeStringify(arg, 6); } catch { @@ -148,7 +148,7 @@ export class DebugManager implements IService, IUpdatable { } } return String(arg); - }).join(" "); + }).join(' '); } /** @@ -160,14 +160,14 @@ export class DebugManager implements IService, IUpdatable { const stringify = (value: any, depth: number): any => { if (value === null) return null; if (value === undefined) return undefined; - if (typeof value !== "object") return value; + if (typeof value !== 'object') return value; if (depth >= maxDepth) { - return "[Max Depth Reached]"; + return '[Max Depth Reached]'; } if (seen.has(value)) { - return "[Circular]"; + return '[Circular]'; } seen.add(value); @@ -201,7 +201,7 @@ export class DebugManager implements IService, IUpdatable { try { this.webSocketManager.send({ - type: "log", + type: 'log', data: { level, message, @@ -263,35 +263,35 @@ export class DebugManager implements IService, IUpdatable { private handleMessage(message: any): void { try { switch (message.type) { - case "capture_memory_snapshot": + case 'capture_memory_snapshot': this.handleMemorySnapshotRequest(); break; - case "config_update": + case 'config_update': if (message.config) { - this.updateConfig({...this.config, ...message.config}); + this.updateConfig({ ...this.config, ...message.config }); } break; - case "expand_lazy_object": + case 'expand_lazy_object': this.handleExpandLazyObjectRequest(message); break; - case "get_component_properties": + case 'get_component_properties': this.handleGetComponentPropertiesRequest(message); break; - case "get_raw_entity_list": + case 'get_raw_entity_list': this.handleGetRawEntityListRequest(message); break; - case "get_entity_details": + case 'get_entity_details': this.handleGetEntityDetailsRequest(message); break; - case "ping": + case 'ping': this.webSocketManager.send({ - type: "pong", + type: 'pong', timestamp: Date.now() }); break; @@ -304,7 +304,7 @@ export class DebugManager implements IService, IUpdatable { // console.error('[ECS Debug] 处理消息失败:', error); if (message.requestId) { this.webSocketManager.send({ - type: "error_response", + type: 'error_response', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) }); @@ -317,13 +317,13 @@ export class DebugManager implements IService, IUpdatable { */ private handleExpandLazyObjectRequest(message: any): void { try { - const {entityId, componentIndex, propertyPath, requestId} = message; + const { entityId, componentIndex, propertyPath, requestId } = message; if (entityId === undefined || componentIndex === undefined || !propertyPath) { this.webSocketManager.send({ - type: "expand_lazy_object_response", + type: 'expand_lazy_object_response', requestId, - error: "缺少必要参数" + error: '缺少必要参数' }); return; } @@ -332,13 +332,13 @@ export class DebugManager implements IService, IUpdatable { const expandedData = this.entityCollector.expandLazyObject(entityId, componentIndex, propertyPath, scene); this.webSocketManager.send({ - type: "expand_lazy_object_response", + type: 'expand_lazy_object_response', requestId, data: expandedData }); } catch (error) { this.webSocketManager.send({ - type: "expand_lazy_object_response", + type: 'expand_lazy_object_response', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) }); @@ -350,13 +350,13 @@ export class DebugManager implements IService, IUpdatable { */ private handleGetComponentPropertiesRequest(message: any): void { try { - const {entityId, componentIndex, requestId} = message; + const { entityId, componentIndex, requestId } = message; if (entityId === undefined || componentIndex === undefined) { this.webSocketManager.send({ - type: "get_component_properties_response", + type: 'get_component_properties_response', requestId, - error: "缺少必要参数" + error: '缺少必要参数' }); return; } @@ -365,13 +365,13 @@ export class DebugManager implements IService, IUpdatable { const properties = this.entityCollector.getComponentProperties(entityId, componentIndex, scene); this.webSocketManager.send({ - type: "get_component_properties_response", + type: 'get_component_properties_response', requestId, data: properties }); } catch (error) { this.webSocketManager.send({ - type: "get_component_properties_response", + type: 'get_component_properties_response', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) }); @@ -383,19 +383,19 @@ export class DebugManager implements IService, IUpdatable { */ private handleGetRawEntityListRequest(message: any): void { try { - const {requestId} = message; + const { requestId } = message; const scene = this.sceneManager.currentScene; const rawEntityList = this.entityCollector.getRawEntityList(scene); this.webSocketManager.send({ - type: "get_raw_entity_list_response", + type: 'get_raw_entity_list_response', requestId, data: rawEntityList }); } catch (error) { this.webSocketManager.send({ - type: "get_raw_entity_list_response", + type: 'get_raw_entity_list_response', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) }); @@ -407,13 +407,13 @@ export class DebugManager implements IService, IUpdatable { */ private handleGetEntityDetailsRequest(message: any): void { try { - const {entityId, requestId} = message; + const { entityId, requestId } = message; if (entityId === undefined) { this.webSocketManager.send({ - type: "get_entity_details_response", + type: 'get_entity_details_response', requestId, - error: "缺少实体ID参数" + error: '缺少实体ID参数' }); return; } @@ -422,13 +422,13 @@ export class DebugManager implements IService, IUpdatable { const entityDetails = this.entityCollector.getEntityDetails(entityId, scene); this.webSocketManager.send({ - type: "get_entity_details_response", + type: 'get_entity_details_response', requestId, data: entityDetails }); } catch (error) { this.webSocketManager.send({ - type: "get_entity_details_response", + type: 'get_entity_details_response', requestId: message.requestId, error: error instanceof Error ? error.message : String(error) }); @@ -443,13 +443,13 @@ export class DebugManager implements IService, IUpdatable { try { const memorySnapshot = this.captureMemorySnapshot(); this.webSocketManager.send({ - type: "memory_snapshot_response", + type: 'memory_snapshot_response', data: memorySnapshot }); } catch (error) { this.webSocketManager.send({ - type: "memory_snapshot_error", - error: error instanceof Error ? error.message : "内存快照捕获失败" + type: 'memory_snapshot_error', + error: error instanceof Error ? error.message : '内存快照捕获失败' }); } } @@ -466,7 +466,7 @@ export class DebugManager implements IService, IUpdatable { // 使用专门的内存计算方法收集实体数据 const entityData = this.entityCollector.collectEntityDataWithMemory(scene); - const componentMemoryStats = scene?.entities ? this.collectComponentMemoryStats(scene.entities) : {totalMemory: 0, componentTypes: 0, totalInstances: 0, breakdown: []}; + const componentMemoryStats = scene?.entities ? this.collectComponentMemoryStats(scene.entities) : { totalMemory: 0, componentTypes: 0, totalInstances: 0, breakdown: [] }; const systemMemoryStats = this.collectSystemMemoryStats(); const poolMemoryStats = this.collectPoolMemoryStats(); const performanceStats = this.collectPerformanceStats(); @@ -476,7 +476,7 @@ export class DebugManager implements IService, IUpdatable { return { timestamp, - version: "2.0", + version: '2.0', summary: { totalEntities: entityData.totalEntities, totalMemoryUsage: baseMemoryInfo.usedMemory, @@ -716,7 +716,7 @@ export class DebugManager implements IService, IUpdatable { } private calculateQuickSystemSize(system: unknown): number { - if (!system || typeof system !== "object") return 64; + if (!system || typeof system !== 'object') return 64; let size = 128; @@ -724,20 +724,20 @@ export class DebugManager implements IService, IUpdatable { const keys = Object.keys(system); for (let i = 0; i < Math.min(keys.length, 15); i++) { const key = keys[i]; - if (!key || key === "entities" || key === "scene" || key === "constructor") continue; + if (!key || key === 'entities' || key === 'scene' || key === 'constructor') continue; const value = (system as Record)[key]; size += key.length * 2; - if (typeof value === "string") { + if (typeof value === 'string') { size += Math.min(value.length * 2, 100); - } else if (typeof value === "number") { + } else if (typeof value === 'number') { size += 8; - } else if (typeof value === "boolean") { + } else if (typeof value === 'boolean') { size += 4; } else if (Array.isArray(value)) { size += 40 + Math.min(value.length * 8, 200); - } else if (typeof value === "object" && value !== null) { + } else if (typeof value === 'object' && value !== null) { size += 64; } } @@ -844,7 +844,7 @@ export class DebugManager implements IService, IUpdatable { } { try { if (!this.performanceMonitor) { - return {enabled: false}; + return { enabled: false }; } const stats = this.performanceMonitor.getAllSystemStats(); @@ -865,7 +865,7 @@ export class DebugManager implements IService, IUpdatable { }).sort((a, b) => b.averageTime - a.averageTime).slice(0, 5) }; } catch (error: unknown) { - return {enabled: false, error: error instanceof Error ? error.message : String(error)}; + return { enabled: false, error: error instanceof Error ? error.message : String(error) }; } } @@ -879,10 +879,10 @@ export class DebugManager implements IService, IUpdatable { const debugData: IECSDebugData = { timestamp: currentTime, - frameworkVersion: "1.0.0", // 可以从package.json读取 + frameworkVersion: '1.0.0', // 可以从package.json读取 isRunning: this.isRunning, frameworkLoaded: true, - currentScene: scene?.name || "Unknown" + currentScene: scene?.name || 'Unknown' }; // 根据配置收集各种数据 @@ -933,7 +933,7 @@ export class DebugManager implements IService, IUpdatable { const debugData = this.getDebugData(); // 包装成调试面板期望的消息格式 const message = { - type: "debug_data", + type: 'debug_data', data: debugData }; this.webSocketManager.send(message); diff --git a/packages/core/src/Utils/Debug/EntityDataCollector.ts b/packages/core/src/Utils/Debug/EntityDataCollector.ts index 4a38be53..ae6cad0c 100644 --- a/packages/core/src/Utils/Debug/EntityDataCollector.ts +++ b/packages/core/src/Utils/Debug/EntityDataCollector.ts @@ -1,8 +1,8 @@ -import {IEntityDebugData} from "../../Types"; -import {Entity} from "../../ECS/Entity"; -import {Component} from "../../ECS/Component"; -import {getComponentInstanceTypeName} from "../../ECS/Decorators"; -import {IScene} from "../../ECS/IScene"; +import { IEntityDebugData } from '../../Types'; +import { Entity } from '../../ECS/Entity'; +import { Component } from '../../ECS/Component'; +import { getComponentInstanceTypeName } from '../../ECS/Decorators'; +import { IScene } from '../../ECS/IScene'; /** * 实体数据收集器 @@ -129,7 +129,7 @@ export class EntityDataCollector { } catch (error) { return { error: `获取实体详情失败: ${error instanceof Error ? error.message : String(error)}`, - scene: "获取失败", + scene: '获取失败', components: [], componentCount: 0, componentTypes: [] @@ -138,29 +138,29 @@ export class EntityDataCollector { } private getSceneInfo(scene: any): { name: string; type: string } { - let sceneName = "当前场景"; - let sceneType = "Scene"; + let sceneName = '当前场景'; + let sceneType = 'Scene'; try { - if (scene.name && typeof scene.name === "string" && scene.name.trim()) { + if (scene.name && typeof scene.name === 'string' && scene.name.trim()) { sceneName = scene.name.trim(); } else if (scene.constructor && scene.constructor.name) { sceneName = scene.constructor.name; sceneType = scene.constructor.name; - } else if (scene._name && typeof scene._name === "string" && scene._name.trim()) { + } else if (scene._name && typeof scene._name === 'string' && scene._name.trim()) { sceneName = scene._name.trim(); } else { const sceneClassName = Object.getPrototypeOf(scene)?.constructor?.name; - if (sceneClassName && sceneClassName !== "Object") { + if (sceneClassName && sceneClassName !== 'Object') { sceneName = sceneClassName; sceneType = sceneClassName; } } } catch (error) { - sceneName = "场景名获取失败"; + sceneName = '场景名获取失败'; } - return {name: sceneName, type: sceneType}; + return { name: sceneName, type: sceneType }; } @@ -213,11 +213,11 @@ export class EntityDataCollector { distribution: Array<{ signature: string; count: number; memory: number }>; topEntities: Array<{ id: string; name: string; componentCount: number; memory: number }>; } { - if (scene && scene.archetypeSystem && typeof scene.archetypeSystem.getAllArchetypes === "function") { + if (scene && scene.archetypeSystem && typeof scene.archetypeSystem.getAllArchetypes === 'function') { return this.extractArchetypeStatistics(scene.archetypeSystem); } - const entityContainer = {entities: scene.entities?.buffer || []}; + const entityContainer = { entities: scene.entities?.buffer || [] }; return { distribution: this.getArchetypeDistributionFast(entityContainer), topEntities: this.getTopEntitiesByComponentsFast(entityContainer) @@ -230,13 +230,13 @@ export class EntityDataCollector { if (entityContainer && entityContainer.entities) { entityContainer.entities.forEach((entity: any) => { const componentTypes = entity.components?.map((comp: any) => getComponentInstanceTypeName(comp)) || []; - const signature = componentTypes.length > 0 ? componentTypes.sort().join(", ") : "无组件"; + const signature = componentTypes.length > 0 ? componentTypes.sort().join(', ') : '无组件'; const existing = distribution.get(signature); if (existing) { existing.count++; } else { - distribution.set(signature, {count: 1, componentTypes}); + distribution.set(signature, { count: 1, componentTypes }); } }); } @@ -271,11 +271,11 @@ export class EntityDataCollector { distribution: Array<{ signature: string; count: number; memory: number }>; topEntities: Array<{ id: string; name: string; componentCount: number; memory: number }>; } { - if (scene && scene.archetypeSystem && typeof scene.archetypeSystem.getAllArchetypes === "function") { + if (scene && scene.archetypeSystem && typeof scene.archetypeSystem.getAllArchetypes === 'function') { return this.extractArchetypeStatisticsWithMemory(scene.archetypeSystem); } - const entityContainer = {entities: scene.entities?.buffer || []}; + const entityContainer = { entities: scene.entities?.buffer || [] }; return { distribution: this.getArchetypeDistributionWithMemory(entityContainer), topEntities: this.getTopEntitiesByComponentsWithMemory(entityContainer) @@ -292,7 +292,7 @@ export class EntityDataCollector { const topEntities: Array<{ id: string; name: string; componentCount: number; memory: number }> = []; archetypes.forEach((archetype: any) => { - const signature = archetype.componentTypes?.map((type: any) => type.name).join(",") || "Unknown"; + const signature = archetype.componentTypes?.map((type: any) => type.name).join(',') || 'Unknown'; const entityCount = archetype.entities?.length || 0; distribution.push({ @@ -316,7 +316,7 @@ export class EntityDataCollector { distribution.sort((a, b) => b.count - a.count); topEntities.sort((a, b) => b.componentCount - a.componentCount); - return {distribution, topEntities}; + return { distribution, topEntities }; } @@ -329,7 +329,7 @@ export class EntityDataCollector { const topEntities: Array<{ id: string; name: string; componentCount: number; memory: number }> = []; archetypes.forEach((archetype: any) => { - const signature = archetype.componentTypes?.map((type: any) => type.name).join(",") || "Unknown"; + const signature = archetype.componentTypes?.map((type: any) => type.name).join(',') || 'Unknown'; const entityCount = archetype.entities?.length || 0; let actualMemory = 0; @@ -365,7 +365,7 @@ export class EntityDataCollector { distribution.sort((a, b) => b.count - a.count); topEntities.sort((a, b) => b.componentCount - a.componentCount); - return {distribution, topEntities}; + return { distribution, topEntities }; } @@ -375,7 +375,7 @@ export class EntityDataCollector { if (entityContainer && entityContainer.entities) { entityContainer.entities.forEach((entity: any) => { const componentTypes = entity.components?.map((comp: any) => getComponentInstanceTypeName(comp)) || []; - const signature = componentTypes.length > 0 ? componentTypes.sort().join(", ") : "无组件"; + const signature = componentTypes.length > 0 ? componentTypes.sort().join(', ') : '无组件'; const existing = distribution.get(signature); let memory = this.estimateEntityMemoryUsage(entity); @@ -388,7 +388,7 @@ export class EntityDataCollector { existing.count++; existing.memory += memory; } else { - distribution.set(signature, {count: 1, memory, componentTypes}); + distribution.set(signature, { count: 1, memory, componentTypes }); } }); } @@ -453,14 +453,14 @@ export class EntityDataCollector { try { let totalSize = 0; - const entitySize = this.calculateObjectSize(entity, ["components", "children", "parent"]); + const entitySize = this.calculateObjectSize(entity, ['components', 'children', 'parent']); if (!isNaN(entitySize) && entitySize > 0) { totalSize += entitySize; } if (entity.components && Array.isArray(entity.components)) { entity.components.forEach((component: any) => { - const componentSize = this.calculateObjectSize(component, ["entity"]); + const componentSize = this.calculateObjectSize(component, ['entity']); if (!isNaN(componentSize) && componentSize > 0) { totalSize += componentSize; } @@ -474,13 +474,13 @@ export class EntityDataCollector { } public calculateObjectSize(obj: any, excludeKeys: string[] = []): number { - if (!obj || typeof obj !== "object") return 0; + if (!obj || typeof obj !== 'object') return 0; const visited = new WeakSet(); const maxDepth = 2; const calculate = (item: any, depth: number = 0): number => { - if (!item || typeof item !== "object" || depth >= maxDepth) { + if (!item || typeof item !== 'object' || depth >= maxDepth) { return 0; } @@ -496,25 +496,25 @@ export class EntityDataCollector { for (let i = 0; i < maxKeys; i++) { const key = keys[i]; if (!key || excludeKeys.includes(key) || - key === "constructor" || - key === "__proto__" || - key.startsWith("_cc_") || - key.startsWith("__")) { + key === 'constructor' || + key === '__proto__' || + key.startsWith('_cc_') || + key.startsWith('__')) { continue; } const value = item[key]; itemSize += key.length * 2; - if (typeof value === "string") { + if (typeof value === 'string') { itemSize += Math.min(value.length * 2, 200); - } else if (typeof value === "number") { + } else if (typeof value === 'number') { itemSize += 8; - } else if (typeof value === "boolean") { + } else if (typeof value === 'boolean') { itemSize += 4; } else if (Array.isArray(value)) { itemSize += 40 + Math.min(value.length * 8, 160); - } else if (typeof value === "object" && value !== null) { + } else if (typeof value === 'object' && value !== null) { itemSize += calculate(value, depth + 1); } } @@ -595,7 +595,7 @@ export class EntityDataCollector { } // 优先使用Entity的getDebugInfo方法 - if (typeof entity.getDebugInfo === "function") { + if (typeof entity.getDebugInfo === 'function') { const debugInfo = entity.getDebugInfo(); node = { ...node, @@ -670,7 +670,7 @@ export class EntityDataCollector { sceneType: sceneInfo.type, componentCount: entity.components.length, componentTypes: entity.components.map((component: Component) => getComponentInstanceTypeName(component)), - componentMask: entity.componentMask?.toString() || "0", + componentMask: entity.componentMask?.toString() || '0', parentId: entity.parent?.id || null, childCount: entity.children?.length || 0, childIds: entity.children.map((child: Entity) => child.id) || [], @@ -694,7 +694,7 @@ export class EntityDataCollector { try { const propertyKeys = Object.keys(component); propertyKeys.forEach((propertyKey) => { - if (!propertyKey.startsWith("_") && propertyKey !== "entity" && propertyKey !== "constructor") { + if (!propertyKey.startsWith('_') && propertyKey !== 'entity' && propertyKey !== 'constructor') { const propertyValue = (component as any)[propertyKey]; if (propertyValue !== undefined && propertyValue !== null) { properties[propertyKey] = this.formatPropertyValue(propertyValue); @@ -704,12 +704,12 @@ export class EntityDataCollector { // 如果没有找到任何属性,添加一些调试信息 if (Object.keys(properties).length === 0) { - properties["_info"] = "该组件没有公开属性"; - properties["_componentId"] = getComponentInstanceTypeName(component); + properties['_info'] = '该组件没有公开属性'; + properties['_componentId'] = getComponentInstanceTypeName(component); } } catch (error) { - properties["_error"] = "属性提取失败"; - properties["_componentId"] = getComponentInstanceTypeName(component); + properties['_error'] = '属性提取失败'; + properties['_componentId'] = getComponentInstanceTypeName(component); } return { @@ -740,7 +740,7 @@ export class EntityDataCollector { const propertyKeys = Object.keys(component); propertyKeys.forEach((propertyKey) => { - if (!propertyKey.startsWith("_") && propertyKey !== "entity") { + if (!propertyKey.startsWith('_') && propertyKey !== 'entity') { const propertyValue = (component as any)[propertyKey]; if (propertyValue !== undefined && propertyValue !== null) { properties[propertyKey] = this.formatPropertyValue(propertyValue); @@ -750,7 +750,7 @@ export class EntityDataCollector { return properties; } catch (error) { - return {_error: "属性提取失败"}; + return { _error: '属性提取失败' }; } } @@ -762,8 +762,8 @@ export class EntityDataCollector { return value; } - if (typeof value !== "object") { - if (typeof value === "string" && value.length > 200) { + if (typeof value !== 'object') { + if (typeof value === 'string' && value.length > 200) { return `[长字符串: ${value.length}字符] ${value.substring(0, 100)}...`; } return value; @@ -812,7 +812,7 @@ export class EntityDataCollector { break; } - if (key.startsWith("_") || key.startsWith("$") || typeof obj[key] === "function") { + if (key.startsWith('_') || key.startsWith('$') || typeof obj[key] === 'function') { continue; } @@ -839,7 +839,7 @@ export class EntityDataCollector { */ private createLazyLoadPlaceholder(obj: any): any { try { - const typeName = obj.constructor?.name || "Object"; + const typeName = obj.constructor?.name || 'Object'; const summary = this.getObjectSummary(obj, typeName); return { @@ -851,7 +851,7 @@ export class EntityDataCollector { } catch (error) { return { _isLazyObject: true, - _typeName: "Unknown", + _typeName: 'Unknown', _summary: `无法分析的对象: ${error instanceof Error ? error.message : String(error)}`, _objectId: Math.random().toString(36).substr(2, 9) }; @@ -863,28 +863,28 @@ export class EntityDataCollector { */ private getObjectSummary(obj: any, typeName: string): string { try { - if (typeName.toLowerCase().includes("vec") || typeName.toLowerCase().includes("vector")) { + if (typeName.toLowerCase().includes('vec') || typeName.toLowerCase().includes('vector')) { if (obj.x !== undefined && obj.y !== undefined) { - const z = obj.z !== undefined ? obj.z : ""; - return `${typeName}(${obj.x}, ${obj.y}${z ? ", " + z : ""})`; + const z = obj.z !== undefined ? obj.z : ''; + return `${typeName}(${obj.x}, ${obj.y}${z ? ', ' + z : ''})`; } } - if (typeName.toLowerCase().includes("color")) { + if (typeName.toLowerCase().includes('color')) { if (obj.r !== undefined && obj.g !== undefined && obj.b !== undefined) { const a = obj.a !== undefined ? obj.a : 1; return `${typeName}(${obj.r}, ${obj.g}, ${obj.b}, ${a})`; } } - if (typeName.toLowerCase().includes("node")) { - const name = obj.name || obj._name || "未命名"; + if (typeName.toLowerCase().includes('node')) { + const name = obj.name || obj._name || '未命名'; return `${typeName}: ${name}`; } - if (typeName.toLowerCase().includes("component")) { - const nodeName = obj.node?.name || obj.node?._name || ""; - return `${typeName}${nodeName ? ` on ${nodeName}` : ""}`; + if (typeName.toLowerCase().includes('component')) { + const nodeName = obj.node?.name || obj.node?._name || ''; + return `${typeName}${nodeName ? ` on ${nodeName}` : ''}`; } const keys = Object.keys(obj); @@ -955,16 +955,16 @@ export class EntityDataCollector { private getObjectByPath(root: any, path: string): any { if (!path) return root; - const parts = path.split("."); + const parts = path.split('.'); let current = root; for (const part of parts) { if (current === null || current === undefined) return null; // 处理数组索引 - if (part.includes("[") && part.includes("]")) { - const arrayName = part.substring(0, part.indexOf("[")); - const index = parseInt(part.substring(part.indexOf("[") + 1, part.indexOf("]"))); + if (part.includes('[') && part.includes(']')) { + const arrayName = part.substring(0, part.indexOf('[')); + const index = parseInt(part.substring(part.indexOf('[') + 1, part.indexOf(']'))); if (arrayName) { current = current[arrayName]; diff --git a/packages/core/src/Utils/Debug/PerformanceDataCollector.ts b/packages/core/src/Utils/Debug/PerformanceDataCollector.ts index 742030cc..2e1e190c 100644 --- a/packages/core/src/Utils/Debug/PerformanceDataCollector.ts +++ b/packages/core/src/Utils/Debug/PerformanceDataCollector.ts @@ -1,5 +1,5 @@ -import {IPerformanceDebugData} from "../../Types"; -import {Time} from "../Time"; +import { IPerformanceDebugData } from '../../Types'; +import { Time } from '../Time'; /** * 性能数据收集器 @@ -61,7 +61,7 @@ export class PerformanceDataCollector { private getECSPerformanceData(performanceMonitor: any): { totalExecutionTime: number; systemBreakdown: Array } { // 检查性能监视器是否存在 if (!performanceMonitor) { - return {totalExecutionTime: 0, systemBreakdown: []}; + return { totalExecutionTime: 0, systemBreakdown: [] }; } if (!performanceMonitor.enabled) { @@ -71,7 +71,7 @@ export class PerformanceDataCollector { } catch (error) { // 如果无法启用,返回默认值 } - return {totalExecutionTime: 0, systemBreakdown: []}; + return { totalExecutionTime: 0, systemBreakdown: [] }; } try { @@ -81,7 +81,7 @@ export class PerformanceDataCollector { const stats = performanceMonitor.getAllSystemStats(); if (stats.size === 0) { - return {totalExecutionTime: 0, systemBreakdown: []}; + return { totalExecutionTime: 0, systemBreakdown: [] }; } // 计算各系统的执行时间 @@ -112,7 +112,7 @@ export class PerformanceDataCollector { systemBreakdown: systemBreakdown }; } catch (error) { - return {totalExecutionTime: 0, systemBreakdown: []}; + return { totalExecutionTime: 0, systemBreakdown: [] }; } } @@ -202,7 +202,7 @@ export class PerformanceDataCollector { private updateGCCount(): number { try { // 尝试使用PerformanceObserver来检测GC - if (typeof PerformanceObserver !== "undefined") { + if (typeof PerformanceObserver !== 'undefined') { // 这是一个简化的GC检测方法 // 实际的GC检测需要更复杂的逻辑 return this.gcCollections; diff --git a/packages/core/src/Utils/Debug/SceneDataCollector.ts b/packages/core/src/Utils/Debug/SceneDataCollector.ts index 04503a1f..ae8ff562 100644 --- a/packages/core/src/Utils/Debug/SceneDataCollector.ts +++ b/packages/core/src/Utils/Debug/SceneDataCollector.ts @@ -1,5 +1,5 @@ -import {ISceneDebugData} from "../../Types"; -import {IScene} from "../../ECS/IScene"; +import { ISceneDebugData } from '../../Types'; +import { IScene } from '../../ECS/IScene'; /** * 场景数据收集器 @@ -14,7 +14,7 @@ export class SceneDataCollector { public collectSceneData(scene?: IScene | null): ISceneDebugData { if (!scene) { return { - currentSceneName: "No Scene", + currentSceneName: 'No Scene', isInitialized: false, sceneRunTime: 0, sceneEntityCount: 0, @@ -31,7 +31,7 @@ export class SceneDataCollector { const entityProcessors = (scene as any).entityProcessors; return { - currentSceneName: (scene as any).name || "Unnamed Scene", + currentSceneName: (scene as any).name || 'Unnamed Scene', isInitialized: (scene as any)._didSceneBegin || false, sceneRunTime: runTime, sceneEntityCount: entityList?.buffer?.length || 0, diff --git a/packages/core/src/Utils/Debug/SystemDataCollector.ts b/packages/core/src/Utils/Debug/SystemDataCollector.ts index 1fbda787..7b2a4903 100644 --- a/packages/core/src/Utils/Debug/SystemDataCollector.ts +++ b/packages/core/src/Utils/Debug/SystemDataCollector.ts @@ -1,6 +1,6 @@ -import {ISystemDebugData} from "../../Types"; -import {getSystemInstanceTypeName} from "../../ECS/Decorators"; -import {IScene} from "../../ECS/IScene"; +import { ISystemDebugData } from '../../Types'; +import { getSystemInstanceTypeName } from '../../ECS/Decorators'; +import { IScene } from '../../ECS/IScene'; /** * 系统数据收集器 diff --git a/packages/core/src/Utils/Debug/WebSocketManager.ts b/packages/core/src/Utils/Debug/WebSocketManager.ts index f55597e5..40c0696f 100644 --- a/packages/core/src/Utils/Debug/WebSocketManager.ts +++ b/packages/core/src/Utils/Debug/WebSocketManager.ts @@ -80,9 +80,10 @@ export class WebSocketManager { } try { - const message = typeof data === "string" ? data : JSON.stringify(data); + const message = typeof data === 'string' ? data : JSON.stringify(data); this.ws.send(message); - } catch (error) { + } catch (_error) { + // 发送失败时静默忽略,WebSocket 断开会触发 error 事件 } } @@ -130,7 +131,8 @@ export class WebSocketManager { if (this.messageHandler) { this.messageHandler(message); } - } catch (error) { + } catch (_error) { + // 解析失败时静默忽略,避免非 JSON 消息导致错误 } } diff --git a/packages/core/src/Utils/Debug/index.ts b/packages/core/src/Utils/Debug/index.ts index 234e9d6e..1cfea5cf 100644 --- a/packages/core/src/Utils/Debug/index.ts +++ b/packages/core/src/Utils/Debug/index.ts @@ -1,8 +1,8 @@ -export {EntityDataCollector} from "./EntityDataCollector"; -export {SystemDataCollector} from "./SystemDataCollector"; -export {PerformanceDataCollector} from "./PerformanceDataCollector"; -export {ComponentDataCollector} from "./ComponentDataCollector"; -export {SceneDataCollector} from "./SceneDataCollector"; -export {WebSocketManager} from "./WebSocketManager"; -export {DebugManager} from "./DebugManager"; -export {DebugConfigService} from "./DebugConfigService"; +export { EntityDataCollector } from './EntityDataCollector'; +export { SystemDataCollector } from './SystemDataCollector'; +export { PerformanceDataCollector } from './PerformanceDataCollector'; +export { ComponentDataCollector } from './ComponentDataCollector'; +export { SceneDataCollector } from './SceneDataCollector'; +export { WebSocketManager } from './WebSocketManager'; +export { DebugManager } from './DebugManager'; +export { DebugConfigService } from './DebugConfigService'; diff --git a/packages/core/src/Utils/Emitter.ts b/packages/core/src/Utils/Emitter.ts index 0f8a7787..1c7aa66c 100644 --- a/packages/core/src/Utils/Emitter.ts +++ b/packages/core/src/Utils/Emitter.ts @@ -31,7 +31,7 @@ export class Emitter { * @param handler 监听函数 * @param context 监听上下文 */ - public addObserver(eventType: T, handler: Function, context: TContext) { + public addObserver(eventType: T, handler: EventHandler, context: TContext) { let list = this._messageTable.get(eventType); if (!list) { list = []; @@ -48,7 +48,7 @@ export class Emitter { * @param eventType 事件类型 * @param handler 事件函数 */ - public removeObserver(eventType: T, handler: Function) { + public removeObserver(eventType: T, handler: EventHandler) { const messageData = this._messageTable.get(eventType); if (messageData) { const index = messageData.findIndex((data) => data.func == handler); @@ -76,7 +76,7 @@ export class Emitter { * @param eventType 事件类型 * @param handler 事件函数 */ - public hasObserver(eventType: T, handler: Function): boolean { + public hasObserver(eventType: T, handler: EventHandler): boolean { const list = this._messageTable.get(eventType); return list ? list.some((observer) => observer.func === handler) : false; } diff --git a/packages/core/src/Utils/Extensions/index.ts b/packages/core/src/Utils/Extensions/index.ts index dce4d102..20c06819 100644 --- a/packages/core/src/Utils/Extensions/index.ts +++ b/packages/core/src/Utils/Extensions/index.ts @@ -1,3 +1,3 @@ // 扩展工具类导出 -export {TypeUtils} from "./TypeUtils"; -export {NumberExtension} from "./NumberExtension"; +export { TypeUtils } from './TypeUtils'; +export { NumberExtension } from './NumberExtension'; diff --git a/packages/core/src/Utils/Logger/ConsoleLogger.ts b/packages/core/src/Utils/Logger/ConsoleLogger.ts index 1dd27a4d..961d787d 100644 --- a/packages/core/src/Utils/Logger/ConsoleLogger.ts +++ b/packages/core/src/Utils/Logger/ConsoleLogger.ts @@ -1,5 +1,5 @@ -import {Colors, LogLevel} from "./Constants"; -import {ILogger, LoggerColorConfig, LoggerConfig} from "./Types"; +import { Colors, LogLevel } from './Constants'; +import { ILogger, LoggerColorConfig, LoggerConfig } from './Types'; /** @@ -12,7 +12,7 @@ export class ConsoleLogger implements ILogger { this._config = { level: LogLevel.Info, enableTimestamp: true, - enableColors: typeof window === "undefined", + enableColors: typeof window === 'undefined', ...config }; } diff --git a/packages/core/src/Utils/Logger/Constants.ts b/packages/core/src/Utils/Logger/Constants.ts index e04f22fe..ce36092c 100644 --- a/packages/core/src/Utils/Logger/Constants.ts +++ b/packages/core/src/Utils/Logger/Constants.ts @@ -15,27 +15,27 @@ export enum LogLevel { */ export const Colors = { // 基础颜色 - BLACK: "\x1b[30m", - RED: "\x1b[31m", - GREEN: "\x1b[32m", - YELLOW: "\x1b[33m", - BLUE: "\x1b[34m", - MAGENTA: "\x1b[35m", - CYAN: "\x1b[36m", - WHITE: "\x1b[37m", + BLACK: '\x1b[30m', + RED: '\x1b[31m', + GREEN: '\x1b[32m', + YELLOW: '\x1b[33m', + BLUE: '\x1b[34m', + MAGENTA: '\x1b[35m', + CYAN: '\x1b[36m', + WHITE: '\x1b[37m', // 亮色版本 - BRIGHT_BLACK: "\x1b[90m", - BRIGHT_RED: "\x1b[91m", - BRIGHT_GREEN: "\x1b[92m", - BRIGHT_YELLOW: "\x1b[93m", - BRIGHT_BLUE: "\x1b[94m", - BRIGHT_MAGENTA: "\x1b[95m", - BRIGHT_CYAN: "\x1b[96m", - BRIGHT_WHITE: "\x1b[97m", + BRIGHT_BLACK: '\x1b[90m', + BRIGHT_RED: '\x1b[91m', + BRIGHT_GREEN: '\x1b[92m', + BRIGHT_YELLOW: '\x1b[93m', + BRIGHT_BLUE: '\x1b[94m', + BRIGHT_MAGENTA: '\x1b[95m', + BRIGHT_CYAN: '\x1b[96m', + BRIGHT_WHITE: '\x1b[97m', // 特殊 - RESET: "\x1b[0m", - BOLD: "\x1b[1m", - UNDERLINE: "\x1b[4m" + RESET: '\x1b[0m', + BOLD: '\x1b[1m', + UNDERLINE: '\x1b[4m' } as const; diff --git a/packages/core/src/Utils/Logger/LoggerManager.ts b/packages/core/src/Utils/Logger/LoggerManager.ts index 68799a3d..c8e27848 100644 --- a/packages/core/src/Utils/Logger/LoggerManager.ts +++ b/packages/core/src/Utils/Logger/LoggerManager.ts @@ -1,6 +1,6 @@ -import {ConsoleLogger} from "./ConsoleLogger"; -import {LogLevel} from "./Constants"; -import {ILogger, LoggerColorConfig} from "./Types"; +import { ConsoleLogger } from './ConsoleLogger'; +import { LogLevel } from './Constants'; +import { ILogger, LoggerColorConfig } from './Types'; /** * 日志管理器 @@ -26,7 +26,7 @@ export class LoggerManager { if (this._loggerFactory) { return this._loggerFactory(); } - return new ConsoleLogger({level: this._defaultLevel}); + return new ConsoleLogger({ level: this._defaultLevel }); } /** @@ -53,7 +53,7 @@ export class LoggerManager { if (!this._loggers.has(name)) { const logger = this._loggerFactory ? this._loggerFactory(name) - : new ConsoleLogger({prefix: name, level: this._defaultLevel}); + : new ConsoleLogger({ prefix: name, level: this._defaultLevel }); this._loggers.set(name, logger); } @@ -136,8 +136,8 @@ export class LoggerManager { public setLoggerFactory(factory: (name?: string) => ILogger): void { if (this._defaultLogger || this._loggers.size > 0) { console.warn( - "[LoggerManager] setLoggerFactory 应该在导入 ECS 模块之前调用。" + - "已创建的 logger 引用不会被更新。" + '[LoggerManager] setLoggerFactory 应该在导入 ECS 模块之前调用。' + + '已创建的 logger 引用不会被更新。' ); } diff --git a/packages/core/src/Utils/Logger/Types.ts b/packages/core/src/Utils/Logger/Types.ts index c92148a6..bbdc2073 100644 --- a/packages/core/src/Utils/Logger/Types.ts +++ b/packages/core/src/Utils/Logger/Types.ts @@ -1,4 +1,4 @@ -import type {LogLevel} from "./Constants"; +import type { LogLevel } from './Constants'; /** * 日志接口 diff --git a/packages/core/src/Utils/Logger/index.ts b/packages/core/src/Utils/Logger/index.ts index bd2a02cb..361f0d8a 100644 --- a/packages/core/src/Utils/Logger/index.ts +++ b/packages/core/src/Utils/Logger/index.ts @@ -1,4 +1,4 @@ -export * from "./ConsoleLogger"; -export * from "./Constants"; -export * from "./LoggerManager"; -export * from "./Types"; +export * from './ConsoleLogger'; +export * from './Constants'; +export * from './LoggerManager'; +export * from './Types'; diff --git a/packages/core/src/Utils/PerformanceMonitor.ts b/packages/core/src/Utils/PerformanceMonitor.ts index f6ac134a..63259d8c 100644 --- a/packages/core/src/Utils/PerformanceMonitor.ts +++ b/packages/core/src/Utils/PerformanceMonitor.ts @@ -46,12 +46,12 @@ export interface PerformanceStats { * 性能警告类型 */ export enum PerformanceWarningType { - HIGH_EXECUTION_TIME = "high_execution_time", - HIGH_MEMORY_USAGE = "high_memory_usage", - HIGH_CPU_USAGE = "high_cpu_usage", - FREQUENT_GC = "frequent_gc", - LOW_FPS = "low_fps", - HIGH_ENTITY_COUNT = "high_entity_count" + HIGH_EXECUTION_TIME = 'high_execution_time', + HIGH_MEMORY_USAGE = 'high_memory_usage', + HIGH_CPU_USAGE = 'high_cpu_usage', + FREQUENT_GC = 'frequent_gc', + LOW_FPS = 'low_fps', + HIGH_ENTITY_COUNT = 'high_entity_count' } /** @@ -61,7 +61,7 @@ export interface PerformanceWarning { type: PerformanceWarningType; systemName: string; message: string; - severity: "low" | "medium" | "high" | "critical"; + severity: 'low' | 'medium' | 'high' | 'critical'; timestamp: number; value: number; threshold: number; @@ -99,7 +99,7 @@ export interface PerformanceThresholds { }; } -import type {IService} from "../Core/ServiceContainer"; +import type { IService } from '../Core/ServiceContainer'; /** * 高性能监控器 @@ -276,12 +276,12 @@ export class PerformanceMonitor implements IService { */ public getPerformanceReport(): string { if (!this._isEnabled) { - return "Performance monitoring is disabled."; + return 'Performance monitoring is disabled.'; } const lines: string[] = []; - lines.push("=== ECS Performance Report ==="); - lines.push(""); + lines.push('=== ECS Performance Report ==='); + lines.push(''); // 按平均执行时间排序 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(""); + lines.push(''); } // 总体统计 @@ -310,7 +310,7 @@ export class PerformanceMonitor implements IService { lines.push(`Total Frame Time: ${totalCurrentTime.toFixed(2)}ms`); lines.push(`Systems Count: ${this._systemData.size}`); - return lines.join("\n"); + return lines.join('\n'); } /** diff --git a/packages/core/src/Utils/Pool/Pool.ts b/packages/core/src/Utils/Pool/Pool.ts index 5d14f9e4..e68c84f5 100644 --- a/packages/core/src/Utils/Pool/Pool.ts +++ b/packages/core/src/Utils/Pool/Pool.ts @@ -1,4 +1,4 @@ -import {IPoolable, PoolStats} from "./IPoolable"; +import { IPoolable, PoolStats } from './IPoolable'; type Constructor = new (...args: unknown[]) => T; @@ -48,11 +48,11 @@ export class Pool { maxSize: number = 100, estimatedObjectSize: number = 1024 ): Pool { - let pool = this._pools.get(type); + let pool = this._pools.get(type) as Pool | undefined; if (!pool) { pool = new Pool(() => new type(), maxSize, estimatedObjectSize); - this._pools.set(type, pool); + this._pools.set(type, pool as Pool); } return pool; @@ -104,7 +104,7 @@ export class Pool { * @returns 统计信息对象 */ public getStats(): Readonly { - return {...this._stats}; + return { ...this._stats }; } /** @@ -243,11 +243,11 @@ export class Pool { */ public static getGlobalStatsString(): string { const stats = this.getAllPoolStats(); - const lines: string[] = ["=== Object Pool Global Statistics ===", ""]; + const lines: string[] = ['=== Object Pool Global Statistics ===', '']; if (Object.keys(stats).length === 0) { - lines.push("No pools registered"); - return lines.join("\n"); + lines.push('No pools registered'); + return lines.join('\n'); } for (const [typeName, stat] of Object.entries(stats)) { @@ -257,10 +257,10 @@ export class Pool { lines.push(` Total Created: ${stat.totalCreated}`); lines.push(` Total Obtained: ${stat.totalObtained}`); lines.push(` Memory: ${(stat.estimatedMemoryUsage / 1024).toFixed(1)} KB`); - lines.push(""); + lines.push(''); } - return lines.join("\n"); + return lines.join('\n'); } /** diff --git a/packages/core/src/Utils/Pool/PoolManager.ts b/packages/core/src/Utils/Pool/PoolManager.ts index ec3f058b..b8b06395 100644 --- a/packages/core/src/Utils/Pool/PoolManager.ts +++ b/packages/core/src/Utils/Pool/PoolManager.ts @@ -1,13 +1,13 @@ -import {IPoolable, PoolStats} from "./IPoolable"; -import {Pool} from "./Pool"; -import type {IService} from "../../Core/ServiceContainer"; +import { IPoolable, PoolStats } from './IPoolable'; +import { Pool } from './Pool'; +import type { IService } from '../../Core/ServiceContainer'; /** * 池管理器 * 统一管理所有对象池 */ export class PoolManager implements IService { - private pools = new Map>(); + private pools = new Map>(); private autoCompactInterval = 60000; // 60秒 private lastCompactTime = 0; @@ -30,7 +30,7 @@ export class PoolManager implements IService { * @returns 池实例 */ public getPool(name: string): Pool | null { - return this.pools.get(name) || null; + return (this.pools.get(name) as Pool | undefined) || null; } /** @@ -173,18 +173,18 @@ export class PoolManager implements IService { * @returns 格式化字符串 */ public getStatsString(): string { - const lines: string[] = ["=== Pool Manager Statistics ===", ""]; + const lines: string[] = ['=== Pool Manager Statistics ===', '']; if (this.pools.size === 0) { - lines.push("No pools registered"); - return lines.join("\n"); + lines.push('No pools registered'); + return lines.join('\n'); } const globalStats = this.getGlobalStats(); lines.push(`Total Pools: ${this.pools.size}`); lines.push(`Global Hit Rate: ${(globalStats.hitRate * 100).toFixed(1)}%`); lines.push(`Global Memory Usage: ${(globalStats.estimatedMemoryUsage / 1024).toFixed(1)} KB`); - lines.push(""); + lines.push(''); for (const [name, pool] of this.pools) { const stats = pool.getStats(); @@ -192,10 +192,10 @@ export class PoolManager implements IService { lines.push(` Size: ${stats.size}/${stats.maxSize}`); lines.push(` Hit Rate: ${(stats.hitRate * 100).toFixed(1)}%`); lines.push(` Memory: ${(stats.estimatedMemoryUsage / 1024).toFixed(1)} KB`); - lines.push(""); + lines.push(''); } - return lines.join("\n"); + return lines.join('\n'); } /** diff --git a/packages/core/src/Utils/Pool/index.ts b/packages/core/src/Utils/Pool/index.ts index dbf89afb..8ecafe81 100644 --- a/packages/core/src/Utils/Pool/index.ts +++ b/packages/core/src/Utils/Pool/index.ts @@ -1,3 +1,3 @@ -export * from "./IPoolable"; -export * from "./Pool"; -export * from "./PoolManager"; +export * from './IPoolable'; +export * from './Pool'; +export * from './PoolManager'; diff --git a/packages/core/src/Utils/Timers/Timer.ts b/packages/core/src/Utils/Timers/Timer.ts index e2266d7f..21eca82b 100644 --- a/packages/core/src/Utils/Timers/Timer.ts +++ b/packages/core/src/Utils/Timers/Timer.ts @@ -1,5 +1,5 @@ -import {ITimer} from "./ITimer"; -import {Time} from "../Time"; +import { ITimer } from './ITimer'; +import { Time } from '../Time'; /** * 私有类隐藏ITimer的实现 diff --git a/packages/core/src/Utils/Timers/TimerManager.ts b/packages/core/src/Utils/Timers/TimerManager.ts index f0a27686..d613d5a6 100644 --- a/packages/core/src/Utils/Timers/TimerManager.ts +++ b/packages/core/src/Utils/Timers/TimerManager.ts @@ -1,8 +1,8 @@ -import {Timer} from "./Timer"; -import {ITimer} from "./ITimer"; -import type {IService} from "../../Core/ServiceContainer"; -import type {IUpdatable} from "../../Types/IUpdatable"; -import {Updatable} from "../../Core/DI"; +import { Timer } from './Timer'; +import { ITimer } from './ITimer'; +import type { IService } from '../../Core/ServiceContainer'; +import type { IUpdatable } from '../../Types/IUpdatable'; +import { Updatable } from '../../Core/DI'; /** * 定时器管理器 diff --git a/packages/core/src/Utils/index.ts b/packages/core/src/Utils/index.ts index a9ae40e9..9fd78f2c 100644 --- a/packages/core/src/Utils/index.ts +++ b/packages/core/src/Utils/index.ts @@ -1,9 +1,9 @@ -export * from "./Extensions"; -export * from "./Pool"; -export * from "./Emitter"; -export * from "./GlobalManager"; -export * from "./PerformanceMonitor"; -export {Time} from "./Time"; -export * from "./Debug"; -export * from "./Logger"; -export * from "./BinarySerializer"; +export * from './Extensions'; +export * from './Pool'; +export * from './Emitter'; +export * from './GlobalManager'; +export * from './PerformanceMonitor'; +export { Time } from './Time'; +export * from './Debug'; +export * from './Logger'; +export * from './BinarySerializer'; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3bafaa76..8f203399 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -4,17 +4,17 @@ */ // 核心模块 -export {Core} from "./Core"; -export {ServiceContainer, ServiceLifetime} from "./Core/ServiceContainer"; -export type {IService, ServiceType} from "./Core/ServiceContainer"; +export { Core } from './Core'; +export { ServiceContainer, ServiceLifetime } from './Core/ServiceContainer'; +export type { IService, ServiceType } from './Core/ServiceContainer'; // 插件系统 -export {PluginManager} from "./Core/PluginManager"; -export {PluginState} from "./Core/Plugin"; -export type {IPlugin, IPluginMetadata} from "./Core/Plugin"; +export { PluginManager } from './Core/PluginManager'; +export { PluginState } from './Core/Plugin'; +export type { IPlugin, IPluginMetadata } from './Core/Plugin'; // 内置插件 -export * from "./Plugins"; +export * from './Plugins'; // 依赖注入 export { @@ -25,15 +25,15 @@ export { createInstance, isUpdatable, getUpdatableMetadata -} from "./Core/DI"; -export type {InjectableMetadata, UpdatableMetadata} from "./Core/DI"; +} from './Core/DI'; +export type { InjectableMetadata, UpdatableMetadata } from './Core/DI'; // 核心管理器 -export {Emitter, FuncPack} from "./Utils/Emitter"; -export {GlobalManager} from "./Utils/GlobalManager"; -export {TimerManager} from "./Utils/Timers/TimerManager"; -export {ITimer} from "./Utils/Timers/ITimer"; -export {Timer} from "./Utils/Timers/Timer"; +export { Emitter, FuncPack } from './Utils/Emitter'; +export { GlobalManager } from './Utils/GlobalManager'; +export { TimerManager } from './Utils/Timers/TimerManager'; +export { ITimer } from './Utils/Timers/ITimer'; +export { Timer } from './Utils/Timers/Timer'; // 日志系统 export { @@ -43,25 +43,25 @@ export { createLogger, setGlobalLogLevel, LogLevel -} from "./Utils/Logger"; -export type {ILogger, LoggerConfig} from "./Utils/Logger"; +} from './Utils/Logger'; +export type { ILogger, LoggerConfig } from './Utils/Logger'; // ECS核心组件 -export * from "./ECS"; +export * from './ECS'; // TypeScript类型增强API -export * from "./ECS/TypedEntity"; -export * from "./ECS/Core/Query/TypedQuery"; +export * from './ECS/TypedEntity'; +export * from './ECS/Core/Query/TypedQuery'; // 事件系统 -export {ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator} from "./ECS/CoreEvents"; +export { ECSEventType, EventPriority, EVENT_TYPES, EventTypeValidator } from './ECS/CoreEvents'; // 工具类和类型定义 -export * from "./Utils"; -export * from "./Types"; +export * from './Utils'; +export * from './Types'; // 显式导出ComponentPool类(解决与Types中ComponentPool接口的命名冲突) -export {ComponentPool, ComponentPoolManager} from "./ECS/Core/Storage"; +export { ComponentPool, ComponentPoolManager } from './ECS/Core/Storage'; // 平台适配 -export * from "./Platform"; +export * from './Platform';