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:
@@ -197,14 +197,6 @@ impl Engine {
|
||||
colors: &[u32],
|
||||
material_ids: &[u32],
|
||||
) -> Result<()> {
|
||||
// Debug: log once
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
static LOGGED: AtomicBool = AtomicBool::new(false);
|
||||
if !LOGGED.swap(true, Ordering::Relaxed) {
|
||||
let sprite_count = texture_ids.len();
|
||||
log::info!("Engine submit_sprite_batch: {} sprites, texture_ids: {:?}", sprite_count, texture_ids);
|
||||
}
|
||||
|
||||
self.renderer.submit_batch(
|
||||
transforms,
|
||||
texture_ids,
|
||||
@@ -382,6 +374,24 @@ impl Engine {
|
||||
self.texture_manager.clear_all();
|
||||
}
|
||||
|
||||
/// 获取纹理加载状态
|
||||
/// Get texture loading state
|
||||
pub fn get_texture_state(&self, id: u32) -> crate::renderer::texture::TextureState {
|
||||
self.texture_manager.get_texture_state(id)
|
||||
}
|
||||
|
||||
/// 检查纹理是否已就绪
|
||||
/// Check if texture is ready to use
|
||||
pub fn is_texture_ready(&self, id: u32) -> bool {
|
||||
self.texture_manager.is_texture_ready(id)
|
||||
}
|
||||
|
||||
/// 获取正在加载中的纹理数量
|
||||
/// Get the number of textures currently loading
|
||||
pub fn get_texture_loading_count(&self) -> u32 {
|
||||
self.texture_manager.get_loading_count()
|
||||
}
|
||||
|
||||
/// Check if a key is currently pressed.
|
||||
/// 检查某个键是否当前被按下。
|
||||
pub fn is_key_down(&self, key_code: &str) -> bool {
|
||||
|
||||
@@ -224,6 +224,42 @@ impl GameEngine {
|
||||
.map_err(|e| JsValue::from_str(&e.to_string()))
|
||||
}
|
||||
|
||||
/// 获取纹理加载状态
|
||||
/// Get texture loading state
|
||||
///
|
||||
/// # Arguments | 参数
|
||||
/// * `id` - Texture ID | 纹理ID
|
||||
///
|
||||
/// # Returns | 返回
|
||||
/// State string: "loading", "ready", or "failed:reason"
|
||||
/// 状态字符串:"loading"、"ready" 或 "failed:原因"
|
||||
#[wasm_bindgen(js_name = getTextureState)]
|
||||
pub fn get_texture_state(&self, id: u32) -> String {
|
||||
use crate::renderer::texture::TextureState;
|
||||
match self.engine.get_texture_state(id) {
|
||||
TextureState::Loading => "loading".to_string(),
|
||||
TextureState::Ready => "ready".to_string(),
|
||||
TextureState::Failed(reason) => format!("failed:{}", reason),
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查纹理是否已就绪
|
||||
/// Check if texture is ready to use
|
||||
///
|
||||
/// # Arguments | 参数
|
||||
/// * `id` - Texture ID | 纹理ID
|
||||
#[wasm_bindgen(js_name = isTextureReady)]
|
||||
pub fn is_texture_ready(&self, id: u32) -> bool {
|
||||
self.engine.is_texture_ready(id)
|
||||
}
|
||||
|
||||
/// 获取正在加载中的纹理数量
|
||||
/// Get the number of textures currently loading
|
||||
#[wasm_bindgen(js_name = getTextureLoadingCount)]
|
||||
pub fn get_texture_loading_count(&self) -> u32 {
|
||||
self.engine.get_texture_loading_count()
|
||||
}
|
||||
|
||||
/// Check if a key is currently pressed.
|
||||
/// 检查某个键是否当前被按下。
|
||||
///
|
||||
|
||||
@@ -5,4 +5,4 @@ mod texture;
|
||||
mod texture_manager;
|
||||
|
||||
pub use texture::Texture;
|
||||
pub use texture_manager::TextureManager;
|
||||
pub use texture_manager::{TextureManager, TextureState};
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Texture loading and management.
|
||||
//! 纹理加载和管理。
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen::JsCast;
|
||||
use web_sys::{HtmlImageElement, WebGl2RenderingContext, WebGlTexture};
|
||||
@@ -9,6 +11,21 @@ use web_sys::{HtmlImageElement, WebGl2RenderingContext, WebGlTexture};
|
||||
use crate::core::error::{EngineError, Result};
|
||||
use super::Texture;
|
||||
|
||||
/// 纹理加载状态
|
||||
/// Texture loading state
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum TextureState {
|
||||
/// 正在加载中
|
||||
/// Loading in progress
|
||||
Loading,
|
||||
/// 加载完成,可以使用
|
||||
/// Loaded and ready to use
|
||||
Ready,
|
||||
/// 加载失败
|
||||
/// Load failed
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Texture manager for loading and caching textures.
|
||||
/// 用于加载和缓存纹理的纹理管理器。
|
||||
pub struct TextureManager {
|
||||
@@ -31,6 +48,10 @@ pub struct TextureManager {
|
||||
/// Default white texture for untextured rendering.
|
||||
/// 用于无纹理渲染的默认白色纹理。
|
||||
default_texture: Option<WebGlTexture>,
|
||||
|
||||
/// 纹理加载状态(使用 Rc<RefCell<>> 以便闭包可以修改)
|
||||
/// Texture loading states (using Rc<RefCell<>> so closures can modify)
|
||||
texture_states: Rc<RefCell<HashMap<u32, TextureState>>>,
|
||||
}
|
||||
|
||||
impl TextureManager {
|
||||
@@ -43,6 +64,7 @@ impl TextureManager {
|
||||
path_to_id: HashMap::new(),
|
||||
next_id: 1, // Start from 1, 0 is reserved for default
|
||||
default_texture: None,
|
||||
texture_states: Rc::new(RefCell::new(HashMap::new())),
|
||||
};
|
||||
|
||||
// Create default white texture | 创建默认白色纹理
|
||||
@@ -90,17 +112,22 @@ impl TextureManager {
|
||||
/// 从URL加载纹理。
|
||||
///
|
||||
/// Note: This is an async operation. The texture will be available
|
||||
/// after the image loads.
|
||||
/// 注意:这是一个异步操作。纹理在图片加载后可用。
|
||||
/// after the image loads. Use `get_texture_state` to check loading status.
|
||||
/// 注意:这是一个异步操作。纹理在图片加载后可用。使用 `get_texture_state` 检查加载状态。
|
||||
pub fn load_texture(&mut self, id: u32, url: &str) -> Result<()> {
|
||||
// 设置初始状态为 Loading | Set initial state to Loading
|
||||
self.texture_states.borrow_mut().insert(id, TextureState::Loading);
|
||||
|
||||
// Create placeholder texture | 创建占位纹理
|
||||
let texture = self.gl
|
||||
.create_texture()
|
||||
.ok_or_else(|| EngineError::TextureLoadFailed("Failed to create texture".into()))?;
|
||||
|
||||
// Set up temporary 1x1 texture | 设置临时1x1纹理
|
||||
// Set up temporary 1x1 transparent texture | 设置临时1x1透明纹理
|
||||
// 使用透明而非灰色,这样未加载完成时不会显示奇怪的颜色
|
||||
// Use transparent instead of gray, so incomplete textures don't show strange colors
|
||||
self.gl.bind_texture(WebGl2RenderingContext::TEXTURE_2D, Some(&texture));
|
||||
let placeholder: [u8; 4] = [128, 128, 128, 255];
|
||||
let placeholder: [u8; 4] = [0, 0, 0, 0];
|
||||
let _ = self.gl.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_u8_array(
|
||||
WebGl2RenderingContext::TEXTURE_2D,
|
||||
0,
|
||||
@@ -119,6 +146,10 @@ impl TextureManager {
|
||||
// Store texture with placeholder size | 存储带占位符尺寸的纹理
|
||||
self.textures.insert(id, Texture::new(texture, 1, 1));
|
||||
|
||||
// Clone state map for closures | 克隆状态映射用于闭包
|
||||
let states_for_onload = Rc::clone(&self.texture_states);
|
||||
let states_for_onerror = Rc::clone(&self.texture_states);
|
||||
|
||||
// Load actual image asynchronously | 异步加载实际图片
|
||||
let gl = self.gl.clone();
|
||||
|
||||
@@ -130,6 +161,7 @@ impl TextureManager {
|
||||
|
||||
// Clone image for use in closure | 克隆图片用于闭包
|
||||
let image_clone = image.clone();
|
||||
let texture_id = id;
|
||||
|
||||
// Set up load callback | 设置加载回调
|
||||
let onload = Closure::wrap(Box::new(move || {
|
||||
@@ -146,7 +178,9 @@ impl TextureManager {
|
||||
);
|
||||
|
||||
if let Err(e) = result {
|
||||
log::error!("Failed to upload texture: {:?} | 纹理上传失败: {:?}", e, e);
|
||||
log::error!("Failed to upload texture {}: {:?} | 纹理 {} 上传失败: {:?}", texture_id, e, texture_id, e);
|
||||
states_for_onload.borrow_mut().insert(texture_id, TextureState::Failed(format!("{:?}", e)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Set texture parameters | 设置纹理参数
|
||||
@@ -171,10 +205,22 @@ impl TextureManager {
|
||||
WebGl2RenderingContext::LINEAR as i32,
|
||||
);
|
||||
|
||||
// 标记为就绪 | Mark as ready
|
||||
states_for_onload.borrow_mut().insert(texture_id, TextureState::Ready);
|
||||
|
||||
}) as Box<dyn Fn()>);
|
||||
|
||||
// Set up error callback | 设置错误回调
|
||||
let url_for_error = url.to_string();
|
||||
let onerror = Closure::wrap(Box::new(move || {
|
||||
let error_msg = format!("Failed to load image: {}", url_for_error);
|
||||
states_for_onerror.borrow_mut().insert(texture_id, TextureState::Failed(error_msg));
|
||||
}) as Box<dyn Fn()>);
|
||||
|
||||
image.set_onload(Some(onload.as_ref().unchecked_ref()));
|
||||
image.set_onerror(Some(onerror.as_ref().unchecked_ref()));
|
||||
onload.forget(); // Prevent closure from being dropped | 防止闭包被销毁
|
||||
onerror.forget();
|
||||
|
||||
image.set_src(url);
|
||||
|
||||
@@ -223,6 +269,56 @@ impl TextureManager {
|
||||
self.textures.contains_key(&id)
|
||||
}
|
||||
|
||||
/// 获取纹理加载状态
|
||||
/// Get texture loading state
|
||||
///
|
||||
/// 返回纹理的当前加载状态:Loading、Ready 或 Failed。
|
||||
/// Returns the current loading state of the texture: Loading, Ready, or Failed.
|
||||
#[inline]
|
||||
pub fn get_texture_state(&self, id: u32) -> TextureState {
|
||||
// ID 0 是默认纹理,始终就绪
|
||||
// ID 0 is default texture, always ready
|
||||
if id == 0 {
|
||||
return TextureState::Ready;
|
||||
}
|
||||
|
||||
self.texture_states
|
||||
.borrow()
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.unwrap_or(TextureState::Failed("Texture not found".to_string()))
|
||||
}
|
||||
|
||||
/// 检查纹理是否已就绪可用
|
||||
/// Check if texture is ready to use
|
||||
///
|
||||
/// 这是 `get_texture_state() == TextureState::Ready` 的便捷方法。
|
||||
/// This is a convenience method for `get_texture_state() == TextureState::Ready`.
|
||||
#[inline]
|
||||
pub fn is_texture_ready(&self, id: u32) -> bool {
|
||||
// ID 0 是默认纹理,始终就绪
|
||||
// ID 0 is default texture, always ready
|
||||
if id == 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
matches!(
|
||||
self.texture_states.borrow().get(&id),
|
||||
Some(TextureState::Ready)
|
||||
)
|
||||
}
|
||||
|
||||
/// 获取正在加载中的纹理数量
|
||||
/// Get the number of textures currently loading
|
||||
#[inline]
|
||||
pub fn get_loading_count(&self) -> u32 {
|
||||
self.texture_states
|
||||
.borrow()
|
||||
.values()
|
||||
.filter(|s| matches!(s, TextureState::Loading))
|
||||
.count() as u32
|
||||
}
|
||||
|
||||
/// Remove texture.
|
||||
/// 移除纹理。
|
||||
pub fn remove_texture(&mut self, id: u32) {
|
||||
@@ -231,6 +327,8 @@ impl TextureManager {
|
||||
}
|
||||
// Also remove from path mapping | 同时从路径映射中移除
|
||||
self.path_to_id.retain(|_, &mut v| v != id);
|
||||
// Remove state | 移除状态
|
||||
self.texture_states.borrow_mut().remove(&id);
|
||||
}
|
||||
|
||||
/// Load texture by path, returning texture ID.
|
||||
@@ -308,6 +406,9 @@ impl TextureManager {
|
||||
// Clear path mapping | 清除路径映射
|
||||
self.path_to_id.clear();
|
||||
|
||||
// Clear texture states | 清除纹理状态
|
||||
self.texture_states.borrow_mut().clear();
|
||||
|
||||
// Reset ID counter (1 is reserved for first texture, 0 for default)
|
||||
// 重置ID计数器(1保留给第一个纹理,0给默认纹理)
|
||||
self.next_id = 1;
|
||||
|
||||
Reference in New Issue
Block a user