Files
esengine/packages/core/src/Core.ts

543 lines
15 KiB
TypeScript
Raw Normal View History

import { GlobalManager } from './Utils/GlobalManager';
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';
2025-06-30 20:43:11 +08:00
import { ICoreConfig, IECSDebugConfig } from './Types';
import { createLogger } from './Utils/Logger';
import { SceneManager } from './ECS/SceneManager';
import { IScene } from './ECS/IScene';
/**
*
*
*
* - TimerPerformancePool等
* - SceneManager
* -
* -
*
* @example
* ```typescript
* // 初始化并设置场景
* Core.create({ debug: true });
* Core.setScene(new GameScene());
*
* // 游戏循环(自动更新全局服务和场景)
* function gameLoop(deltaTime: number) {
2025-06-12 09:42:35 +08:00
* Core.update(deltaTime);
* }
*
* // 使用定时器
* Core.schedule(1.0, false, null, (timer) => {
* console.log("1秒后执行");
* });
*
* // 切换场景
* Core.loadScene(new MenuScene()); // 延迟切换
* Core.setScene(new GameScene()); // 立即切换
*
* // 获取当前场景
* const currentScene = Core.scene;
* ```
*/
export class Core {
/**
*
*
* true时
*/
public static paused = false;
/**
*
*/
private static _instance: Core;
/**
* Core专用日志器
*/
private static _logger = createLogger('Core');
/**
*
*
* ECS实体系统功能
*/
public static entitySystemsEnabled: boolean;
/**
*
*
*
*/
public readonly debug: boolean;
/**
*
*
*
*/
public _globalManagers: GlobalManager[] = [];
/**
*
*
*
*/
public _timerManager: TimerManager;
2022-03-12 23:49:14 +08:00
/**
*
*
*
*/
public _performanceMonitor: PerformanceMonitor;
/**
*
*
*
*/
public _poolManager: PoolManager;
2025-06-17 00:32:16 +08:00
/**
*
*
2025-06-17 00:32:16 +08:00
*
*/
public _debugManager?: DebugManager;
2025-06-17 00:32:16 +08:00
/**
*
*
*
*/
private _sceneManager: SceneManager;
2025-06-17 00:32:16 +08:00
/**
* Core配置
*/
private _config: ICoreConfig;
/**
*
*
2025-06-17 00:32:16 +08:00
* @param config - Core配置对象
*/
2025-06-17 00:32:16 +08:00
private constructor(config: ICoreConfig = {}) {
Core._instance = this;
2025-06-17 00:32:16 +08:00
// 保存配置
this._config = {
debug: true,
enableEntitySystems: true,
...config
};
// 初始化定时器管理器
this._timerManager = new TimerManager();
Core.registerGlobalManager(this._timerManager);
// 初始化性能监控器
this._performanceMonitor = PerformanceMonitor.instance;
2025-06-17 00:32:16 +08:00
// 在调试模式下启用性能监控
if (this._config.debug) {
this._performanceMonitor.enable();
}
// 初始化对象池管理器
this._poolManager = PoolManager.getInstance();
// 初始化场景管理器
this._sceneManager = new SceneManager();
Core.entitySystemsEnabled = this._config.enableEntitySystems ?? true;
this.debug = this._config.debug ?? true;
2025-06-17 00:32:16 +08:00
// 初始化调试管理器
2025-06-17 00:32:16 +08:00
if (this._config.debugConfig?.enabled) {
this._debugManager = new DebugManager(this, this._config.debugConfig);
2025-06-17 00:32:16 +08:00
}
this.initialize();
}
/**
*
*
* @returns
*/
public static get Instance() {
return this._instance;
}
/**
* Core实例
*
*
*
* @param config - Core配置boolean表示debug模式
* @returns Core实例
*
* @example
* ```typescript
* // 方式1使用配置对象
* Core.create({
* debug: true,
* enableEntitySystems: true,
* debugConfig: {
* enabled: true,
* websocketUrl: 'ws://localhost:9229'
* }
* });
*
* // 方式2简单模式向后兼容
* Core.create(true); // debug = true
* ```
*/
public static create(config: ICoreConfig | boolean = true): Core {
if (this._instance == null) {
// 向后兼容如果传入boolean转换为配置对象
const coreConfig: ICoreConfig = typeof config === 'boolean'
? { debug: config, enableEntitySystems: true }
: config;
this._instance = new Core(coreConfig);
} else {
this._logger.warn('Core实例已创建返回现有实例');
}
return this._instance;
}
/**
*
*
* @param scene -
* @returns
*
* @example
* ```typescript
* Core.create({ debug: true });
*
* // 创建并设置场景
* const gameScene = new GameScene();
* Core.setScene(gameScene);
* ```
*/
public static setScene<T extends IScene>(scene: T): T {
if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()");
throw new Error("Core实例未创建");
}
return this._instance._sceneManager.setScene(scene);
}
2025-08-12 09:39:07 +08:00
/**
*
*
* @returns null
2025-08-12 09:39:07 +08:00
*/
public static get scene(): IScene | null {
if (!this._instance) {
return null;
}
return this._instance._sceneManager.currentScene;
}
/**
* ECS流式API
*
* @returns ECS API实例null
*
* @example
* ```typescript
* // 使用流式API创建实体
* const player = Core.ecsAPI?.createEntity('Player')
* .addComponent(Position, 100, 100)
* .addComponent(Velocity, 50, 0);
*
* // 查询实体
* const enemies = Core.ecsAPI?.query(Enemy, Transform);
*
* // 发射事件
* Core.ecsAPI?.emit('game:start', { level: 1 });
* ```
*/
public static get ecsAPI() {
if (!this._instance) {
return null;
2025-08-12 09:39:07 +08:00
}
return this._instance._sceneManager.api;
2025-08-12 09:39:07 +08:00
}
/**
*
*
* @param scene -
*
* @example
* ```typescript
* // 延迟切换场景(在下一帧生效)
* Core.loadScene(new MenuScene());
* ```
*/
public static loadScene<T extends IScene>(scene: T): void {
if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()");
return;
}
this._instance._sceneManager.loadScene(scene);
}
2025-06-12 09:42:35 +08:00
/**
*
*
2025-06-12 09:42:35 +08:00
*
*
*
2025-06-12 09:42:35 +08:00
* @param deltaTime -
*
2025-06-12 09:42:35 +08:00
* @example
* ```typescript
* // 初始化
* Core.create({ debug: true });
* Core.setScene(new GameScene());
*
* // Laya引擎集成
2025-06-12 09:42:35 +08:00
* Laya.timer.frameLoop(1, this, () => {
* const deltaTime = Laya.timer.delta / 1000;
* Core.update(deltaTime); // 自动更新全局服务和场景
2025-06-12 09:42:35 +08:00
* });
*
* // Cocos Creator集成
2025-06-12 09:42:35 +08:00
* update(deltaTime: number) {
* Core.update(deltaTime); // 自动更新全局服务和场景
2025-06-12 09:42:35 +08:00
* }
* ```
*/
public static update(deltaTime: number): void {
if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()");
2025-06-12 09:42:35 +08:00
return;
}
2025-06-12 09:42:35 +08:00
this._instance.updateInternal(deltaTime);
}
/**
*
*
*
*
* @param manager -
*/
public static registerGlobalManager(manager: GlobalManager) {
this._instance._globalManagers.push(manager);
manager.enabled = true;
}
/**
*
*
*
*
* @param manager -
*/
public static unregisterGlobalManager(manager: GlobalManager) {
this._instance._globalManagers.splice(this._instance._globalManagers.indexOf(manager), 1);
manager.enabled = false;
}
2022-03-12 23:49:14 +08:00
/**
*
*
* @param type -
* @returns null
*/
public static getGlobalManager<T extends GlobalManager>(type: new (...args: unknown[]) => T): T | null {
for (const manager of this._instance._globalManagers) {
if (manager instanceof type)
return manager as T;
}
return null;
}
/**
*
*
*
*
* @param timeInSeconds -
* @param repeats - false
* @param context - null
* @param onTime -
* @returns
*
* @example
* ```typescript
* // 一次性定时器
* Core.schedule(1.0, false, null, (timer) => {
* console.log("1秒后执行一次");
* });
*
* // 重复定时器
* Core.schedule(0.5, true, null, (timer) => {
* console.log("每0.5秒执行一次");
* });
* ```
*/
2025-08-12 09:39:07 +08:00
public static schedule<TContext = unknown>(timeInSeconds: number, repeats: boolean = false, context?: TContext, onTime?: (timer: ITimer<TContext>) => void): Timer<TContext> {
if (!onTime) {
throw new Error('onTime callback is required');
}
return this._instance._timerManager.schedule(timeInSeconds, repeats, context as TContext, onTime);
}
2025-06-17 00:32:16 +08:00
/**
*
*
2025-06-17 00:32:16 +08:00
* @param config
*/
public static enableDebug(config: IECSDebugConfig): void {
if (!this._instance) {
Core._logger.warn("Core实例未创建请先调用Core.create()");
2025-06-17 00:32:16 +08:00
return;
}
if (this._instance._debugManager) {
this._instance._debugManager.updateConfig(config);
2025-06-17 00:32:16 +08:00
} else {
this._instance._debugManager = new DebugManager(this._instance, config);
2025-06-17 00:32:16 +08:00
}
// 更新Core配置
this._instance._config.debugConfig = config;
}
/**
*
*/
public static disableDebug(): void {
if (!this._instance) return;
if (this._instance._debugManager) {
this._instance._debugManager.stop();
this._instance._debugManager = undefined;
2025-06-17 00:32:16 +08:00
}
// 更新Core配置
if (this._instance._config.debugConfig) {
this._instance._config.debugConfig.enabled = false;
}
}
/**
*
*
2025-06-17 00:32:16 +08:00
* @returns null
*/
2025-08-12 09:39:07 +08:00
public static getDebugData(): unknown {
if (!this._instance?._debugManager) {
2025-06-17 00:32:16 +08:00
return null;
}
return this._instance._debugManager.getDebugData();
2025-06-17 00:32:16 +08:00
}
/**
*
*
2025-06-17 00:32:16 +08:00
* @returns
*/
public static get isDebugEnabled(): boolean {
return this._instance?._config.debugConfig?.enabled || false;
}
/**
*
*
*
*/
protected initialize() {
// 核心系统初始化
Core._logger.info('Core initialized', {
debug: this.debug,
entitySystemsEnabled: Core.entitySystemsEnabled,
debugEnabled: this._config.debugConfig?.enabled || false
});
}
/**
2025-06-12 09:42:35 +08:00
*
*
2025-06-12 09:42:35 +08:00
* @param deltaTime -
*/
2025-06-12 09:42:35 +08:00
private updateInternal(deltaTime: number): void {
if (Core.paused) return;
// 开始性能监控
const frameStartTime = this._performanceMonitor.startMonitoring('Core.update');
2025-06-12 09:42:35 +08:00
// 更新时间系统
Time.update(deltaTime);
2021-04-20 15:46:18 +08:00
// 更新FPS监控如果性能监控器支持
2025-08-12 09:39:07 +08:00
if ('updateFPS' in this._performanceMonitor && typeof this._performanceMonitor.updateFPS === 'function') {
this._performanceMonitor.updateFPS(Time.deltaTime);
}
2023-03-14 14:03:41 +08:00
// 更新全局管理器
const managersStartTime = this._performanceMonitor.startMonitoring('GlobalManagers.update');
for (const globalManager of this._globalManagers) {
if (globalManager.enabled)
globalManager.update();
}
this._performanceMonitor.endMonitoring('GlobalManagers.update', managersStartTime, this._globalManagers.length);
// 更新对象池管理器
this._poolManager.update();
// 更新场景
this._sceneManager.update();
// 更新调试管理器基于FPS的数据发送
if (this._debugManager) {
this._debugManager.onFrameUpdate(deltaTime);
}
// 结束性能监控
this._performanceMonitor.endMonitoring('Core.update', frameStartTime);
}
/**
* Core实例
*
*
*/
public static destroy(): void {
if (!this._instance) return;
// 停止调试管理器
if (this._instance._debugManager) {
this._instance._debugManager.stop();
}
// 清理全局管理器
for (const manager of this._instance._globalManagers) {
manager.enabled = false;
}
this._instance._globalManagers = [];
Core._logger.info('Core destroyed');
// @ts-ignore - 清空实例引用
this._instance = null;
}
}