feat: 纹理路径稳定 ID 与架构改进 (#305)

* feat(asset-system): 实现路径稳定 ID 生成器

使用 FNV-1a hash 算法为纹理生成稳定的运行时 ID:
- 新增 _pathIdCache 静态缓存,跨 Play/Stop 循环保持稳定
- 新增 getStableIdForPath() 方法,相同路径永远返回相同 ID
- 修改 loadTextureForComponent/loadTextureByGuid 使用稳定 ID
- clearTextureMappings() 不再清除 _pathIdCache

这解决了 Play/Stop 后纹理 ID 失效的根本问题。

* fix(runtime-core): 移除 Play/Stop 循环中的 clearTextureMappings 调用

使用路径稳定 ID 后,不再需要在快照保存/恢复时清除纹理缓存:
- saveSceneSnapshot() 移除 clearTextureMappings() 调用
- restoreSceneSnapshot() 移除 clearTextureMappings() 调用
- 组件保存的 textureId 在 Play/Stop 后仍然有效

* fix(editor-core): 修复场景切换时的资源泄漏

在 openScene() 加载新场景前先卸载旧场景资源:
- 调用 sceneResourceManager.unloadSceneResources() 释放旧资源
- 使用引用计数机制,仅卸载不再被引用的资源
- 路径稳定 ID 缓存不受影响,保持 ID 稳定性

* fix(runtime-core): 修复 PluginManager 组件注册类型错误

将 ComponentRegistry 类改为 GlobalComponentRegistry 实例:
- registerComponents() 期望 IComponentRegistry 接口实例
- GlobalComponentRegistry 是 ComponentRegistry 的全局实例

* refactor(core): 提取 IComponentRegistry 接口

将组件注册表抽象为接口,支持场景级组件注册:
- 新增 IComponentRegistry 接口定义
- Scene 持有独立的 componentRegistry 实例
- 支持从 GlobalComponentRegistry 克隆
- 各系统支持传入自定义注册表

* refactor(engine-core): 改进插件服务注册机制

- 更新 IComponentRegistry 类型引用
- 优化 PluginServiceRegistry 服务管理

* refactor(modules): 适配新的组件注册接口

更新各模块 RuntimeModule 使用 IComponentRegistry 接口:
- audio, behavior-tree, camera
- sprite, tilemap, world-streaming

* fix(physics-rapier2d): 修复物理插件组件注册

- PhysicsEditorPlugin 添加 runtimeModule 引用
- 适配 IComponentRegistry 接口
- 修复物理组件在场景加载时未注册的问题

* feat(editor-core): 添加 UserCodeService 就绪信号机制

- 新增 waitForReady()/signalReady() API
- 支持等待用户脚本编译完成
- 解决场景加载时组件未注册的时序问题

* fix(editor-app): 在编译完成后调用 signalReady()

确保用户脚本编译完成后发出就绪信号:
- 编译成功后调用 userCodeService.signalReady()
- 编译失败也要发出信号,避免阻塞场景加载

* feat(editor-core): 改进编辑器核心服务

- EntityStoreService 添加调试日志
- AssetRegistryService 优化资产注册
- PluginManager 改进插件管理
- IFileAPI 添加 getFileMtime 接口

* feat(engine): 改进 Rust 纹理管理器

- 支持任意 ID 的纹理加载(非递增)
- 添加纹理状态追踪 API
- 优化纹理缓存清理机制
- 更新 TypeScript 绑定

* feat(ui): 添加场景切换和文本闪烁组件

新增组件:
- SceneLoadTriggerComponent: 场景切换触发器
- TextBlinkComponent: 文本闪烁效果

新增系统:
- SceneLoadTriggerSystem: 处理场景切换逻辑
- TextBlinkSystem: 处理文本闪烁动画

其他改进:
- UIRuntimeModule 适配新组件注册接口
- UI 渲染系统优化

* feat(editor-app): 添加外部文件修改检测

- 新增 ExternalModificationDialog 组件
- TauriFileAPI 支持 getFileMtime
- 场景文件被外部修改时提示用户

* feat(editor-app): 添加渲染调试面板

- 新增 RenderDebugService 和调试面板 UI
- App/ContentBrowser 添加调试日志
- TitleBar/Viewport 优化
- DialogManager 改进

* refactor(editor-app): 编辑器服务和组件优化

- EngineService 改进引擎集成
- EditorEngineSync 同步优化
- AssetFileInspector 改进
- VectorFieldEditors 优化
- InstantiatePrefabCommand 改进

* feat(i18n): 更新国际化翻译

- 添加新功能相关翻译
- 更新中文、英文、西班牙文

* feat(tauri): 添加文件修改时间查询命令

- 新增 get_file_mtime 命令
- 支持检测文件外部修改

* refactor(particle): 粒子系统改进

- 适配新的组件注册接口
- ParticleSystem 优化
- 添加单元测试

* refactor(platform): 平台适配层优化

- BrowserRuntime 改进
- 新增 RuntimeSceneManager 服务
- 导出优化

* refactor(asset-system-editor): 资产元数据改进

- AssetMetaFile 优化
- 导出调整

* fix(asset-system): 移除未使用的 TextureLoader 导入

* fix(tests): 更新测试以使用 GlobalComponentRegistry 实例

修复多个测试文件以适配 ComponentRegistry 从静态类变为实例类的变更:
- ComponentStorage.test.ts: 使用 GlobalComponentRegistry.reset()
- EntitySerializer.test.ts: 使用 GlobalComponentRegistry 实例
- IncrementalSerialization.test.ts: 使用 GlobalComponentRegistry 实例
- SceneSerializer.test.ts: 使用 GlobalComponentRegistry 实例
- ComponentRegistry.extended.test.ts: 使用 GlobalComponentRegistry,同时注册到 scene.componentRegistry
- SystemTypes.test.ts: 在 Scene 创建前注册组件
- QuerySystem.test.ts: mockScene 添加 componentRegistry
This commit is contained in:
YHH
2025-12-16 12:46:14 +08:00
committed by GitHub
parent d834ca5e77
commit ed8f6e283b
107 changed files with 7399 additions and 847 deletions

View File

@@ -879,11 +879,10 @@ export class GameRuntime {
* Save scene snapshot
*
* 使用二进制格式提升序列化性能,并支持 EntityRef 的正确序列化。
* 在保存前清除纹理缓存,确保恢复时能够从干净状态重新加载纹理
* 使用路径稳定 ID 后,不再需要清除纹理缓存
*
* Uses binary format for better serialization performance and supports proper
* EntityRef serialization. Clears texture cache before saving to ensure
* clean reload on restore.
* EntityRef serialization. With path-stable IDs, no need to clear texture cache.
*
* @param options 可选配置
* @param options.useJson 是否使用 JSON 格式(用于调试),默认 false 使用二进制
@@ -895,13 +894,10 @@ export class GameRuntime {
}
try {
// 清除所有纹理缓存(确保恢复时重新加载)
// Clear all texture caches (ensures reload on restore)
// clearTextureMappings() 内部会同时清除 Rust 层和 JS 层的纹理缓存
// clearTextureMappings() internally clears both Rust and JS layer texture caches
if (this._engineIntegration) {
this._engineIntegration.clearTextureMappings();
}
// 使用路径稳定 ID 后,不再清除纹理缓存
// 组件保存的 textureId 在 Play/Stop 后仍然有效
// With path-stable IDs, no longer clear texture cache
// Component's saved textureId remains valid after Play/Stop
// 使用二进制格式提升性能(默认)或 JSON 用于调试
// Use binary format for performance (default) or JSON for debugging
@@ -927,9 +923,15 @@ export class GameRuntime {
* 1. 创建所有实体和组件
* 2. 解析所有 EntityRef 引用
*
* 使用路径稳定 ID 后,不再需要清除纹理缓存。
* 组件保存的 textureId 在恢复后仍然有效。
*
* Uses two-phase deserialization to ensure EntityRef references are properly restored:
* 1. Create all entities and components
* 2. Resolve all EntityRef references
*
* With path-stable IDs, no need to clear texture cache.
* Component's saved textureId remains valid after restore.
*/
async restoreSceneSnapshot(): Promise<boolean> {
if (!this._scene || !this._sceneSnapshot) {
@@ -938,19 +940,17 @@ export class GameRuntime {
}
try {
// 清除缓存
// 清除 Tilemap 缓存Tilemap 使用独立的缓存机制)
// Clear Tilemap cache (Tilemap uses its own cache mechanism)
const tilemapSystem = this._systemContext?.services.get(TilemapSystemToken);
if (tilemapSystem) {
tilemapSystem.clearCache?.();
}
// 清除所有纹理并重置状态(修复 Play/Stop 后纹理 ID 混乱的问题)
// Clear all textures and reset state (fixes texture ID confusion after Play/Stop)
// clearTextureMappings() 内部会同时清除 Rust 层和 JS 层的纹理缓存
// clearTextureMappings() internally clears both Rust and JS layer texture caches
if (this._engineIntegration) {
this._engineIntegration.clearTextureMappings();
}
// 使用路径稳定 ID 后,不再清除纹理缓存
// 组件保存的 textureId 在 Play/Stop 后仍然有效
// With path-stable IDs, no longer clear texture cache
// Component's saved textureId remains valid after Play/Stop
// 反序列化场景SceneSerializer 内部使用 SerializationContext 处理 EntityRef
// Deserialize scene (SceneSerializer internally uses SerializationContext for EntityRef)

View File

@@ -3,7 +3,7 @@
* 运行时插件管理器
*/
import { ComponentRegistry, ServiceContainer } from '@esengine/ecs-framework';
import { GlobalComponentRegistry, ServiceContainer } from '@esengine/ecs-framework';
import type { IScene } from '@esengine/ecs-framework';
import type { IRuntimePlugin, IRuntimeModule, SystemContext, ModuleManifest } from '@esengine/engine-core';
@@ -60,7 +60,7 @@ export class RuntimePluginManager {
const mod = plugin.runtimeModule;
if (mod?.registerComponents) {
try {
mod.registerComponents(ComponentRegistry);
mod.registerComponents(GlobalComponentRegistry);
} catch (e) {
console.error(`[PluginManager] Failed to register components for ${id}:`, e);
}

View File

@@ -73,6 +73,16 @@ export {
type BrowserFileSystemOptions
} from './services/BrowserFileSystemService';
// Runtime Scene Manager
export {
RuntimeSceneManager,
RuntimeSceneManagerToken,
type IRuntimeSceneManager,
type SceneInfo,
type SceneLoadOptions,
type SceneLoader
} from './services/RuntimeSceneManager';
// Re-export catalog types from asset-system (canonical source)
// 从 asset-system 重新导出目录类型(规范来源)
export type {

View File

@@ -0,0 +1,391 @@
/**
* 运行时场景管理器
* Runtime Scene Manager
*
* 提供场景加载和切换 API供用户脚本使用
* Provides scene loading and transition API for user scripts
*
* @example
* ```typescript
* // 在用户脚本中获取场景管理器
* // Get scene manager in user script
* const sceneManager = services.get(RuntimeSceneManagerToken);
*
* // 加载场景(按名称)
* // Load scene by name
* await sceneManager.loadScene('GameScene');
*
* // 加载场景(按路径)
* // Load scene by path
* await sceneManager.loadSceneByPath('./scenes/Level1.ecs');
* ```
*/
import { createServiceToken } from '@esengine/ecs-framework';
/**
* 场景信息
* Scene info
*/
export interface SceneInfo {
/** 场景名称 | Scene name */
name: string;
/** 场景路径(相对于构建输出目录)| Scene path (relative to build output) */
path: string;
}
/**
* 场景加载选项
* Scene load options
*/
export interface SceneLoadOptions {
/**
* 是否显示加载界面
* Whether to show loading screen
*/
showLoading?: boolean;
/**
* 过渡效果类型
* Transition effect type
*/
transition?: 'none' | 'fade' | 'slide';
/**
* 过渡持续时间(毫秒)
* Transition duration in milliseconds
*/
transitionDuration?: number;
}
/**
* 场景加载器函数类型
* Scene loader function type
*/
export type SceneLoader = (url: string) => Promise<void>;
/**
* 运行时场景管理器接口
* Runtime Scene Manager Interface
*
* 继承 IService 的 dispose 模式以兼容 ServiceContainer。
* Follows IService dispose pattern for ServiceContainer compatibility.
*/
export interface IRuntimeSceneManager {
/**
* 获取当前场景名称
* Get current scene name
*/
readonly currentSceneName: string | null;
/**
* 获取可用场景列表
* Get available scene list
*/
readonly availableScenes: readonly SceneInfo[];
/**
* 是否正在加载场景
* Whether a scene is currently loading
*/
readonly isLoading: boolean;
/**
* 注册可用场景
* Register available scenes
*/
registerScenes(scenes: SceneInfo[]): void;
/**
* 按名称加载场景
* Load scene by name
*/
loadScene(sceneName: string, options?: SceneLoadOptions): Promise<void>;
/**
* 按路径加载场景
* Load scene by path
*/
loadSceneByPath(path: string, options?: SceneLoadOptions): Promise<void>;
/**
* 重新加载当前场景
* Reload current scene
*/
reloadCurrentScene(options?: SceneLoadOptions): Promise<void>;
/**
* 添加场景加载开始监听器
* Add scene load start listener
*/
onLoadStart(callback: (sceneName: string) => void): () => void;
/**
* 添加场景加载完成监听器
* Add scene load complete listener
*/
onLoadComplete(callback: (sceneName: string) => void): () => void;
/**
* 添加场景加载错误监听器
* Add scene load error listener
*/
onLoadError(callback: (error: Error, sceneName: string) => void): () => void;
/**
* 释放资源IService 兼容)
* Dispose resources (IService compatible)
*/
dispose(): void;
}
/**
* 运行时场景管理器服务令牌
* Runtime Scene Manager Service Token
*/
export const RuntimeSceneManagerToken = createServiceToken<IRuntimeSceneManager>('runtimeSceneManager');
/**
* 运行时场景管理器实现
* Runtime Scene Manager Implementation
*
* 实现 IService 接口以兼容 ServiceContainer。
* Implements IService for ServiceContainer compatibility.
*/
export class RuntimeSceneManager implements IRuntimeSceneManager {
private _scenes = new Map<string, SceneInfo>();
private _currentSceneName: string | null = null;
private _currentScenePath: string | null = null;
private _isLoading = false;
private _sceneLoader: SceneLoader | null = null;
private _baseUrl: string;
private _disposed = false;
// 事件监听器 | Event listeners
private _loadStartListeners = new Set<(sceneName: string) => void>();
private _loadCompleteListeners = new Set<(sceneName: string) => void>();
private _loadErrorListeners = new Set<(error: Error, sceneName: string) => void>();
/**
* 创建运行时场景管理器
* Create runtime scene manager
*
* @param sceneLoader 场景加载函数 | Scene loader function
* @param baseUrl 场景文件基础 URL | Scene files base URL
*/
constructor(sceneLoader: SceneLoader, baseUrl: string = './scenes') {
this._sceneLoader = sceneLoader;
this._baseUrl = baseUrl;
}
get currentSceneName(): string | null {
return this._currentSceneName;
}
get availableScenes(): readonly SceneInfo[] {
return Array.from(this._scenes.values());
}
get isLoading(): boolean {
return this._isLoading;
}
/**
* 设置场景加载器
* Set scene loader
*/
setSceneLoader(loader: SceneLoader): void {
this._sceneLoader = loader;
}
/**
* 设置基础 URL
* Set base URL
*/
setBaseUrl(baseUrl: string): void {
this._baseUrl = baseUrl;
}
registerScenes(scenes: SceneInfo[]): void {
for (const scene of scenes) {
this._scenes.set(scene.name, scene);
}
}
/**
* 从目录或配置自动发现场景
* Auto-discover scenes from catalog or config
*/
registerScenesFromCatalog(
catalog: { scenes?: Array<{ name: string; path: string }> }
): void {
if (catalog.scenes) {
this.registerScenes(catalog.scenes);
}
}
async loadScene(sceneName: string, options?: SceneLoadOptions): Promise<void> {
const sceneInfo = this._scenes.get(sceneName);
if (!sceneInfo) {
// 尝试使用场景名作为路径
// Try using scene name as path
const guessedPath = `${this._baseUrl}/${sceneName}.ecs`;
return this.loadSceneByPath(guessedPath, options);
}
return this.loadSceneByPath(sceneInfo.path, options);
}
async loadSceneByPath(path: string, options?: SceneLoadOptions): Promise<void> {
if (!this._sceneLoader) {
throw new Error('[RuntimeSceneManager] Scene loader not set');
}
if (this._isLoading) {
console.warn('[RuntimeSceneManager] Scene is already loading, ignoring request');
return;
}
// 构建完整 URL | Build full URL
// Check if path is already absolute (http, relative ./, Unix /, or Windows drive letter)
// 检查路径是否已经是绝对路径http、相对 ./、Unix /、或 Windows 驱动器号)
let fullPath = path;
const isAbsolutePath = path.startsWith('http') ||
path.startsWith('./') ||
path.startsWith('/') ||
(path.length > 1 && path[1] === ':'); // Windows absolute path like C:\ or F:\
if (!isAbsolutePath) {
fullPath = `${this._baseUrl}/${path}`;
}
// 提取场景名称 | Extract scene name
const sceneName = this._extractSceneName(path);
this._isLoading = true;
this._notifyLoadStart(sceneName);
try {
// TODO: 实现过渡效果 | TODO: Implement transition effects
// if (options?.transition && options.transition !== 'none') {
// await this._startTransition(options.transition, options.transitionDuration);
// }
await this._sceneLoader(fullPath);
this._currentSceneName = sceneName;
this._currentScenePath = fullPath;
this._isLoading = false;
this._notifyLoadComplete(sceneName);
console.log(`[RuntimeSceneManager] Scene loaded: ${sceneName}`);
} catch (error) {
this._isLoading = false;
const err = error instanceof Error ? error : new Error(String(error));
this._notifyLoadError(err, sceneName);
throw err;
}
}
async reloadCurrentScene(options?: SceneLoadOptions): Promise<void> {
if (!this._currentScenePath) {
throw new Error('[RuntimeSceneManager] No current scene to reload');
}
return this.loadSceneByPath(this._currentScenePath, options);
}
onLoadStart(callback: (sceneName: string) => void): () => void {
this._loadStartListeners.add(callback);
return () => this._loadStartListeners.delete(callback);
}
onLoadComplete(callback: (sceneName: string) => void): () => void {
this._loadCompleteListeners.add(callback);
return () => this._loadCompleteListeners.delete(callback);
}
onLoadError(callback: (error: Error, sceneName: string) => void): () => void {
this._loadErrorListeners.add(callback);
return () => this._loadErrorListeners.delete(callback);
}
/**
* 检查场景是否已注册
* Check if scene is registered
*/
hasScene(sceneName: string): boolean {
return this._scenes.has(sceneName);
}
/**
* 获取场景路径
* Get scene path
*/
getScenePath(sceneName: string): string | null {
return this._scenes.get(sceneName)?.path ?? null;
}
// ==================== 私有方法 | Private Methods ====================
private _extractSceneName(path: string): string {
// 从路径中提取场景名称 | Extract scene name from path
// ./scenes/Level1.ecs -> Level1
// scenes/GameScene.ecs -> GameScene
const fileName = path.split('/').pop() || path;
return fileName.replace(/\.ecs$/, '');
}
private _notifyLoadStart(sceneName: string): void {
for (const listener of this._loadStartListeners) {
try {
listener(sceneName);
} catch (e) {
console.error('[RuntimeSceneManager] Error in load start listener:', e);
}
}
}
private _notifyLoadComplete(sceneName: string): void {
for (const listener of this._loadCompleteListeners) {
try {
listener(sceneName);
} catch (e) {
console.error('[RuntimeSceneManager] Error in load complete listener:', e);
}
}
}
private _notifyLoadError(error: Error, sceneName: string): void {
for (const listener of this._loadErrorListeners) {
try {
listener(error, sceneName);
} catch (e) {
console.error('[RuntimeSceneManager] Error in load error listener:', e);
}
}
}
// ==================== IService 实现 | IService Implementation ====================
/**
* 释放资源
* Dispose resources
*
* 实现 IService 接口,清理所有监听器和状态。
* Implements IService interface, cleans up all listeners and state.
*/
dispose(): void {
if (this._disposed) return;
this._loadStartListeners.clear();
this._loadCompleteListeners.clear();
this._loadErrorListeners.clear();
this._scenes.clear();
this._sceneLoader = null;
this._currentSceneName = null;
this._currentScenePath = null;
this._disposed = true;
}
}