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

593 lines
17 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 { ECSFluentAPI, createECSAPI } from './ECS/Core/FluentAPI';
2025-08-12 09:39:07 +08:00
import { IScene } from './ECS/IScene';
import { WorldManager, IWorldManagerConfig } from './ECS/WorldManager';
import { DebugManager } from './Utils/Debug';
2025-06-30 20:43:11 +08:00
import { ICoreConfig, IECSDebugConfig } from './Types';
import { createLogger } from './Utils/Logger';
/**
*
*
*
2025-06-12 09:42:35 +08:00
*
*
* @example
* ```typescript
* // 创建核心实例
* const core = Core.create(true);
*
* // 设置场景
* Core.scene = new MyScene();
*
2025-06-12 09:42:35 +08:00
* // 在游戏循环中更新Laya引擎示例
* Laya.timer.frameLoop(1, this, () => {
* const deltaTime = Laya.timer.delta / 1000;
* Core.update(deltaTime);
* });
*
* // 调度定时器
* Core.schedule(1.0, false, null, (timer) => {
* Core._logger.info("1秒后执行");
* });
* ```
*/
export class Core {
/**
*
*
* true时
*/
public static paused = false;
/**
* World ID
*
* Scene模式的默认World标识
*/
private static readonly DEFAULT_WORLD_ID = '__default__';
/**
* Scene ID
*
* Scene模式的默认Scene标识
*/
private static readonly DEFAULT_SCENE_ID = '__main__';
/**
*
*/
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;
/**
* ECS流式API
*
* 便ECS操作接口
*/
public _ecsAPI?: ECSFluentAPI;
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
/**
* World管理器
*
* World实例/
*/
public _worldManager?: WorldManager;
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();
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;
}
/**
* 访
*
* @returns null
*/
2025-08-12 09:39:07 +08:00
public static get scene(): IScene | null {
return this.getScene();
}
/**
*
*
* @returns null
*/
public static getScene<T extends IScene>(): T | null {
if (!this._instance) {
return null;
}
// 确保默认World存在
this._instance.ensureDefaultWorld();
const defaultWorld = this._instance._worldManager!.getWorld(this.DEFAULT_WORLD_ID);
return defaultWorld?.getScene(this.DEFAULT_SCENE_ID) as T || null;
}
2025-08-12 09:39:07 +08:00
/**
*
2025-08-12 09:39:07 +08:00
*
* @param scene -
* @returns 便
2025-08-12 09:39:07 +08:00
*/
public static setScene<T extends IScene>(scene: T): T {
if (!this._instance) {
throw new Error("Core实例未创建请先调用Core.create()");
}
// 确保默认World存在
this._instance.ensureDefaultWorld();
const defaultWorld = this._instance._worldManager!.getWorld(this.DEFAULT_WORLD_ID)!;
// 移除旧的主Scene如果存在
if (defaultWorld.getScene(this.DEFAULT_SCENE_ID)) {
defaultWorld.removeScene(this.DEFAULT_SCENE_ID);
2025-08-12 09:39:07 +08:00
}
// 添加新Scene到默认World
defaultWorld.createScene(this.DEFAULT_SCENE_ID, scene);
defaultWorld.setSceneActive(this.DEFAULT_SCENE_ID, true);
// 触发场景切换回调
this._instance.onSceneChanged();
2025-08-12 09:39:07 +08:00
return scene;
}
/**
* Core实例
*
*
*
2025-06-17 00:32:16 +08:00
* @param config - Core配置boolean表示debug模式
* @returns Core实例
*/
2025-06-17 00:32:16 +08:00
public static create(config: ICoreConfig | boolean = true): Core {
if (this._instance == null) {
2025-06-17 00:32:16 +08:00
// 向后兼容如果传入boolean转换为配置对象
const coreConfig: ICoreConfig = typeof config === 'boolean'
? { debug: config, enableEntitySystems: true }
: config;
this._instance = new Core(coreConfig);
}
return this._instance;
}
2025-06-12 09:42:35 +08:00
/**
*
*
*
*
* @param deltaTime -
*
* @example
* ```typescript
* // Laya引擎
* Laya.timer.frameLoop(1, this, () => {
* const deltaTime = Laya.timer.delta / 1000;
* Core.update(deltaTime);
* });
*
* // Cocos Creator
* update(deltaTime: number) {
* Core.update(deltaTime);
* }
*
2025-06-12 09:47:25 +08:00
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;
}
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
*/
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);
}
/**
* ECS流式API
*
* @returns ECS API实例null
*/
public static get ecsAPI(): ECSFluentAPI | null {
return this._instance?._ecsAPI || null;
}
2023-03-14 11:22:09 +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;
}
}
/**
*
*
* @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
}
/**
*
*
* @returns
*/
public static get isDebugEnabled(): boolean {
return this._instance?._config.debugConfig?.enabled || false;
}
2025-08-12 09:39:07 +08:00
/**
* WorldManager实例
*
* @param config WorldManager配置
* @returns WorldManager实例
2025-08-12 09:39:07 +08:00
*/
public static getWorldManager(config?: Partial<IWorldManagerConfig>): WorldManager {
if (!this._instance) {
throw new Error("Core实例未创建请先调用Core.create()");
}
if (!this._instance._worldManager) {
// 多World模式的配置用户主动获取WorldManager
const defaultConfig = {
maxWorlds: 50,
autoCleanup: true,
cleanupInterval: 60000,
debug: this._instance._config.debug
};
this._instance._worldManager = WorldManager.getInstance({
...defaultConfig,
...config // 用户传入的配置会覆盖默认配置
});
}
return this._instance._worldManager;
}
/**
* World管理
*
* World功能/
*
* @param config WorldManager配置
*/
public static enableWorldManager(config?: Partial<IWorldManagerConfig>): WorldManager {
return this.getWorldManager(config);
}
/**
* World存在
*
* World
*/
private ensureDefaultWorld(): void {
if (!this._worldManager) {
this._worldManager = WorldManager.getInstance({
maxWorlds: 1, // 单场景用户只需要1个World
autoCleanup: false, // 单场景不需要自动清理
cleanupInterval: 0, // 禁用清理定时器
debug: this._config.debug
});
}
// 检查默认World是否存在
if (!this._worldManager.getWorld(Core.DEFAULT_WORLD_ID)) {
this._worldManager.createWorld(Core.DEFAULT_WORLD_ID, {
name: 'DefaultWorld',
maxScenes: 1,
autoCleanup: false
});
this._worldManager.setWorldActive(Core.DEFAULT_WORLD_ID, true);
}
2025-08-12 09:39:07 +08:00
}
/**
*
*
*
*/
public onSceneChanged() {
Time.sceneChanged();
// 获取当前Scene从默认World
const currentScene = Core.getScene();
// 初始化ECS API如果场景支持
if (currentScene && currentScene.querySystem && currentScene.eventSystem) {
this._ecsAPI = createECSAPI(currentScene, currentScene.querySystem, currentScene.eventSystem);
}
2025-06-17 00:32:16 +08:00
2025-08-12 09:39:07 +08:00
// 延迟调试管理器通知,避免在场景初始化过程中干扰属性
if (this._debugManager) {
queueMicrotask(() => {
this._debugManager?.onSceneChanged();
});
2025-06-17 00:32:16 +08:00
}
}
/**
*
*
*
*/
protected initialize() {
// 核心系统初始化
}
/**
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();
// 更新所有World
if (this._worldManager) {
const worldsStartTime = this._performanceMonitor.startMonitoring('Worlds.update');
const activeWorlds = this._worldManager.getActiveWorlds();
let totalWorldEntities = 0;
for (const world of activeWorlds) {
// 更新World的全局System
world.updateGlobalSystems();
// 更新World中的所有Scene
world.updateScenes();
// 统计实体数量(用于性能监控)
const worldStats = world.getStats();
totalWorldEntities += worldStats.totalEntities;
}
2022-03-12 23:49:14 +08:00
this._performanceMonitor.endMonitoring('Worlds.update', worldsStartTime, totalWorldEntities);
}
// 更新调试管理器基于FPS的数据发送
if (this._debugManager) {
this._debugManager.onFrameUpdate(deltaTime);
}
// 结束性能监控
this._performanceMonitor.endMonitoring('Core.update', frameStartTime);
}
}