A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor: split 6 oversized files into focused modules
esengine653b9695f9f2
diff --git a/CMakeLists.txt b/CMakeLists.txtindex c7b63175e..df7955976 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -63,6 +63,7 @@ set(ESENGINE_SOURCESsrc/esengine/platform/input/Input.cppsrc/esengine/platform/PathResolver.cppsrc/esengine/animation/TweenSystem.cpp+ src/esengine/ecs/UILayoutSystem.cpp)if(ES_ENABLE_POSTPROCESS)@@ -533,6 +534,10 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}if(ES_ENABLE_BOX2D)add_executable(physics_modulesrc/esengine/bindings/PhysicsModuleEntry.cpp+ src/esengine/bindings/PhysicsContext.cpp+ src/esengine/bindings/PhysicsShapes.cpp+ src/esengine/bindings/PhysicsJoints.cpp+ src/esengine/bindings/PhysicsQueries.cpp)target_link_libraries(physics_module PRIVATE box2d)target_include_directories(physics_module PRIVATE@@ -571,6 +576,10 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}if(ES_ENABLE_BOX2D AND ES_BUILD_SIDE_MODULE)add_executable(physics_side_modulesrc/esengine/bindings/PhysicsModuleEntry.cpp+ src/esengine/bindings/PhysicsContext.cpp+ src/esengine/bindings/PhysicsShapes.cpp+ src/esengine/bindings/PhysicsJoints.cpp+ src/esengine/bindings/PhysicsQueries.cpp)target_link_libraries(physics_side_module PRIVATE box2d)target_include_directories(physics_side_module PRIVATEdiff --git a/desktop/src-tauri/src/compiler.rs b/desktop/src-tauri/src/compiler.rsindex 076103430..3517ece23 100644--- a/desktop/src-tauri/src/compiler.rs+++ b/desktop/src-tauri/src/compiler.rs@@ -1,7 +1,5 @@-//! Toolchain management and WASM compilation.+//! WASM compilation commands.-use futures_util::StreamExt;-use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::path::{Path, PathBuf};use tauri::{AppHandle, Emitter, Manager};@@ -14,1046 +12,16 @@ use std::os::windows::process::CommandExt;#[cfg(windows)]const CREATE_NO_WINDOW: u32 = 0x08000000;-// =============================================================================-// Types-// =============================================================================--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ToolchainStatus {- pub installed: bool,- pub emsdk_path: Option<String>,- pub emscripten_version: Option<String>,- pub emscripten_ok: bool,- pub cmake_found: bool,- pub cmake_version: Option<String>,- pub cmake_ok: bool,- pub python_found: bool,- pub python_version: Option<String>,- pub python_ok: bool,- pub corrupted: bool,- pub missing_tools: Vec<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct FeatureFlags {- pub tilemap: bool,- pub particles: bool,- pub timeline: bool,- pub postprocess: bool,- pub bitmap_text: bool,- pub spine: bool,-}--impl Default for FeatureFlags {- fn default() -> Self {- Self {- tilemap: true,- particles: true,- timeline: true,- postprocess: true,- bitmap_text: true,- spine: true,- }- }-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CompileOptions {- pub features: FeatureFlags,- pub target: String,- pub debug: bool,- pub optimization: String,- #[serde(default)]- pub enable_physics: bool,- #[serde(default)]- pub spine_versions: Vec<String>,- #[serde(default)]- pub clean_build: bool,-}--impl Default for CompileOptions {- fn default() -> Self {- Self {- features: FeatureFlags::default(),- target: "web".to_string(),- debug: false,- optimization: "-Oz".to_string(),- enable_physics: false,- spine_versions: Vec::new(),- clean_build: false,- }- }-}--#[derive(Clone, Serialize)]-struct CompileProgress {- stage: String,- message: String,- progress: f32,-}--#[derive(Serialize)]-pub struct SpineModuleResult {- pub version: String,- pub js_path: String,- pub wasm_path: String,-}--#[derive(Serialize)]-pub struct CompileResult {- pub success: bool,- pub wasm_path: Option<String>,- pub js_path: Option<String>,- pub wasm_size: Option<u64>,- pub error: Option<String>,- pub cache_key: String,- pub spine_modules: Vec<SpineModuleResult>,- pub physics_js_path: Option<String>,- pub physics_wasm_path: Option<String>,-}--const EMSDK_VERSION: &str = "5.0.0";-const EMSDK_DOWNLOAD_BASE: &str = "https://github.com/esengine/emsdk-releases/releases/download";-const NINJA_VERSION: &str = "1.13.2";--const MIN_EMSCRIPTEN_VERSION: &str = "5.0.0";-const MIN_CMAKE_VERSION: &str = "3.16";-const MIN_PYTHON_VERSION: &str = "3.0";--fn toolchain_archive_url() -> String {- let (os, ext) = if cfg!(target_os = "windows") {- ("win", "zip")- } else if cfg!(target_os = "macos") {- ("mac", "tar.gz")- } else {- ("linux", "tar.gz")- };- format!(- "{}/v{}/emsdk-{}-{}.{}",- EMSDK_DOWNLOAD_BASE, EMSDK_VERSION, EMSDK_VERSION, os, ext- )-}--fn version_ge(actual: &str, required: &str) -> bool {- let parse = |s: &str| -> Vec<u32> {- s.split('.')- .filter_map(|p| p.trim().parse::<u32>().ok())- .collect()- };- let a = parse(actual);- let r = parse(required);- for i in 0..r.len() {- let av = a.get(i).copied().unwrap_or(0);- let rv = r[i];- if av > rv { return true; }- if av < rv { return false; }- }- true-}--// =============================================================================-// Toolchain settings persistence-// =============================================================================--fn toolchain_config_path(app: &AppHandle) -> PathBuf {- app.path()- .app_data_dir()- .unwrap_or_else(|_| PathBuf::from("."))- .join("toolchain.json")-}--#[derive(Debug, Clone, Serialize, Deserialize, Default)]-struct ToolchainConfig {- emsdk_path: Option<String>,-}--fn load_config(app: &AppHandle) -> ToolchainConfig {- let path = toolchain_config_path(app);- std::fs::read_to_string(&path)- .ok()- .and_then(|s| serde_json::from_str(&s).ok())- .unwrap_or_default()-}--fn save_config(app: &AppHandle, config: &ToolchainConfig) -> Result<(), String> {- let path = toolchain_config_path(app);- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;- }- let json = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;- std::fs::write(&path, json).map_err(|e| e.to_string())-}--// =============================================================================-// Toolchain discovery-// =============================================================================--fn find_emcc_in_emsdk(emsdk_path: &Path) -> Option<PathBuf> {- let emcc = emsdk_path.join("upstream/emscripten/emcc");- if emcc.exists() {- return Some(emcc);- }- let emcc_bat = emsdk_path.join("upstream/emscripten/emcc.bat");- if emcc_bat.exists() {- return Some(emcc_bat);- }- None-}--fn validate_emsdk(emsdk_path: &Path) -> bool {- find_emcc_in_emsdk(emsdk_path).is_some()-}--fn validate_emsdk_integrity(emsdk_path: &Path) -> Vec<String> {- let ninja_name = if cfg!(windows) { "ninja.exe" } else { "ninja" };- let required = [- ("upstream/bin", ninja_name, "ninja"),- ("upstream/emscripten", if cfg!(windows) { "emcc.bat" } else { "emcc" }, "emcc"),- (".emscripten", "", ".emscripten config"),- ];-- let mut missing = Vec::new();- for (dir, file, label) in &required {- let path = if file.is_empty() {- emsdk_path.join(dir)- } else {- emsdk_path.join(dir).join(file)- };- if !path.exists() {- missing.push(label.to_string());- }- }- missing-}--fn get_emcc_version(emsdk_path: &Path) -> Option<String> {- let emcc = find_emcc_in_emsdk(emsdk_path)?;- let output = silent_command(&emcc)- .arg("--version")- .env("EMSDK", emsdk_path)- .env(- "EM_CONFIG",- emsdk_path.join(".emscripten"),- )- .output()- .ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- let re_version = stdout- .lines()- .find_map(|line| {- line.split_whitespace()- .find(|w| w.chars().next().map_or(false, |c| c.is_ascii_digit()))- })- .map(|s| s.trim_end_matches(|c: char| !c.is_ascii_digit() && c != '.').to_string());- re_version-}--fn find_bundled_cmake(app: &AppHandle) -> Option<PathBuf> {- let cmake_name = if cfg!(windows) { "cmake.exe" } else { "cmake" };-- // Bundled in resources- if let Ok(resource_dir) = app.path().resource_dir() {- let bundled = strip_unc_prefix(resource_dir.join("toolchain/cmake/bin").join(cmake_name));- if bundled.exists() {- return Some(bundled);- }- }-- // Dev mode fallback- let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("toolchain/cmake/bin")- .join(cmake_name);- if dev_path.exists() {- return Some(dev_path);- }-- None-}--fn find_cmake(app: &AppHandle) -> Option<(PathBuf, String)> {- // Prefer bundled cmake- if let Some(bundled) = find_bundled_cmake(app) {- let output = silent_command(&bundled)- .arg("--version")- .output()- .ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- let version = stdout.lines().next()?.split_whitespace().last()?.to_string();- return Some((bundled, version));- }-- // Fall back to system cmake- let cmake = if cfg!(windows) { "cmake.exe" } else { "cmake" };- let output = silent_command(cmake)- .arg("--version")- .output()- .ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- let version = stdout- .lines()- .next()?- .split_whitespace()- .last()?- .to_string();-- let path = which_sync(cmake)?;- Some((path, version))-}--fn find_python() -> Option<(PathBuf, String)> {- for bin in &["python3", "python"] {- let output = silent_command(bin)- .arg("--version")- .output()- .ok();- if let Some(out) = output {- if out.status.success() {- let stdout = String::from_utf8_lossy(&out.stdout);- let stderr = String::from_utf8_lossy(&out.stderr);- let text = if stdout.contains("Python") { stdout } else { stderr };- let version = text- .trim()- .strip_prefix("Python ")- .unwrap_or(text.trim())- .to_string();- if let Some(path) = which_sync(bin) {- return Some((path, version));- }- }- }- }- None-}--fn find_emsdk_python(emsdk_path: &Path) -> Option<(PathBuf, String)> {- // emsdk bundles Python at <emsdk>/python/<version>/bin/python3- let python_dir = emsdk_path.join("python");- if !python_dir.exists() {- return None;- }- let entries = std::fs::read_dir(&python_dir).ok()?;- for entry in entries.flatten() {- let python_bin = if cfg!(windows) {- // Windows: <emsdk>/python/<version>/python.exe (no bin subdirectory)- entry.path().join("python.exe")- } else {- entry.path().join("bin").join("python3")- };- if python_bin.exists() {- let output = silent_command(&python_bin)- .arg("--version")- .output()- .ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- let version = stdout- .trim()- .strip_prefix("Python ")- .unwrap_or(stdout.trim())- .to_string();- return Some((python_bin, version));- }- }- None-}--fn which_sync(bin: &str) -> Option<PathBuf> {- let cmd = if cfg!(windows) { "where" } else { "which" };- let output = silent_command(cmd)- .arg(bin)- .output()- .ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- let path = stdout.lines().next()?.trim();- if path.is_empty() {- None- } else {- Some(PathBuf::from(path))- }-}--fn silent_command(program: &(impl AsRef<std::ffi::OsStr> + ?Sized)) -> std::process::Command {- #[allow(unused_mut)]- let mut cmd = std::process::Command::new(program);- #[cfg(windows)]- cmd.creation_flags(CREATE_NO_WINDOW);- cmd-}--fn strip_unc_prefix(p: PathBuf) -> PathBuf {- let s = p.to_string_lossy();- if s.starts_with(r"\\?\") {- PathBuf::from(&s[4..])- } else {- p- }-}--fn resolve_engine_src(app: &AppHandle) -> Result<PathBuf, String> {- // Bundled engine source in resources (release builds)- let resource_dir = app- .path()- .resource_dir()- .map_err(|e| format!("Failed to resolve resource dir: {}", e))?;-- let engine_src = strip_unc_prefix(resource_dir.join("toolchain/engine-src"));- if engine_src.exists() {- return Ok(engine_src);- }-- // Dev mode fallback- let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent()- .and_then(|p| p.parent())- .map(|root| root.join("desktop/src-tauri/toolchain/engine-src"));-- if let Some(path) = dev_path {- if path.exists() {- return Ok(path);- }- }-- Err("Engine source not found. Rebuild the editor.".to_string())-}--fn project_root() -> Option<PathBuf> {- PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent()- .and_then(|p| p.parent())- .map(|p| p.to_path_buf())-}--// =============================================================================-// Manifest-driven toolchain sync-// =============================================================================--#[derive(Debug, Deserialize)]-struct ToolchainManifest {- engine: EngineManifest,- third_party: ThirdPartyManifest,-}--#[derive(Debug, Deserialize)]-struct EngineManifest {- root_files: Vec<String>,- directories: Vec<String>,-}--#[derive(Debug, Deserialize)]-struct ThirdPartyManifest {- root_files: Vec<String>,- full: Vec<String>,- partial: HashMap<String, Vec<String>>,-}--fn load_manifest(root: &Path) -> Result<ToolchainManifest, String> {- let path = root.join("toolchain.manifest.json");- let content = std::fs::read_to_string(&path)- .map_err(|e| format!("Failed to read toolchain manifest: {}", e))?;- serde_json::from_str(&content)- .map_err(|e| format!("Failed to parse toolchain manifest: {}", e))-}--fn sync_engine_src_if_needed(engine_src: &Path) -> Result<bool, String> {- let root = match project_root() {- Some(r) => r,- None => return Ok(false),- };-- let manifest = match load_manifest(&root) {- Ok(m) => m,- Err(_) => return Ok(false),- };-- let current_hash = compute_manifest_hash(&root, &manifest);- let hash_file = engine_src.join(".sync_hash");- let stored_hash = std::fs::read_to_string(&hash_file).unwrap_or_default();-- if current_hash == stored_hash {- return Ok(false);- }-- sync_from_manifest(&root, engine_src, &manifest)?;- let _ = std::fs::write(&hash_file, ¤t_hash);- Ok(true)-}--fn compute_manifest_hash(root: &Path, manifest: &ToolchainManifest) -> String {- use std::collections::hash_map::DefaultHasher;- use std::hash::Hasher;-- let mut hasher = DefaultHasher::new();-- for file in &manifest.engine.root_files {- hash_file_meta(&mut hasher, &root.join(file));- }- for dir in &manifest.engine.directories {- hash_dir_meta(&mut hasher, &root.join(dir));- }- for file in &manifest.third_party.root_files {- hash_file_meta(&mut hasher, &root.join("third_party").join(file));- }- for dir in &manifest.third_party.full {- hash_file_meta(&mut hasher, &root.join("third_party").join(dir).join("CMakeLists.txt"));- }- for (lib, subdirs) in &manifest.third_party.partial {- for subdir in subdirs {- hash_dir_meta(&mut hasher, &root.join("third_party").join(lib).join(subdir));- }- }-- format!("{:016x}", hasher.finish())-}--fn hash_file_meta(hasher: &mut impl std::hash::Hasher, path: &Path) {- use std::hash::Hash;- if let Ok(meta) = std::fs::metadata(path) {- path.to_string_lossy().hash(hasher);- meta.len().hash(hasher);- if let Ok(modified) = meta.modified() {- modified.hash(hasher);- }- }-}--fn hash_dir_meta(hasher: &mut impl std::hash::Hasher, dir: &Path) {- if let Ok(entries) = collect_all_files(dir) {- for path in entries {- hash_file_meta(hasher, &path);- }- }-}--fn sync_from_manifest(root: &Path, dest: &Path, manifest: &ToolchainManifest) -> Result<(), String> {- // Clean dest (preserve .sync_hash)- let hash_backup = std::fs::read_to_string(dest.join(".sync_hash")).ok();-- if dest.exists() {- std::fs::remove_dir_all(dest).map_err(|e| e.to_string())?;- }- std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;-- if let Some(hash) = hash_backup {- let _ = std::fs::write(dest.join(".sync_hash"), hash);- }-- for file in &manifest.engine.root_files {- let src = root.join(file);- if src.exists() {- std::fs::copy(&src, dest.join(file)).map_err(|e| e.to_string())?;- }- }-- for dir in &manifest.engine.directories {- let src = root.join(dir);- if src.exists() {- copy_dir_recursive(&src, &dest.join(dir))?;- }- }-- let tp_dest = dest.join("third_party");- std::fs::create_dir_all(&tp_dest).map_err(|e| e.to_string())?;-- for file in &manifest.third_party.root_files {- let src = root.join("third_party").join(file);- if src.exists() {- std::fs::copy(&src, tp_dest.join(file)).map_err(|e| e.to_string())?;- }- }-- for dir in &manifest.third_party.full {- let src = root.join("third_party").join(dir);- if src.exists() {- copy_dir_recursive(&src, &tp_dest.join(dir))?;- }- }-- for (lib, subdirs) in &manifest.third_party.partial {- for subdir in subdirs {- let src = root.join("third_party").join(lib).join(subdir);- if src.exists() {- copy_dir_recursive(&src, &tp_dest.join(lib).join(subdir))?;- }- }- }-- Ok(())-}--fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<(), String> {- std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;- for entry in std::fs::read_dir(src).map_err(|e| e.to_string())? {- let entry = entry.map_err(|e| e.to_string())?;- let src_path = entry.path();- let dest_path = dest.join(entry.file_name());- if src_path.is_dir() {- copy_dir_recursive(&src_path, &dest_path)?;- } else {- std::fs::copy(&src_path, &dest_path).map_err(|e| e.to_string())?;- }- }- Ok(())-}--fn auto_detect_emsdk(app: &AppHandle) -> Option<PathBuf> {- // 1. Find emcc via PATH, derive emsdk root (emcc lives at <emsdk>/upstream/emscripten/emcc)- let emcc_bin = if cfg!(windows) { "emcc.bat" } else { "emcc" };- if let Some(emcc_path) = which_sync(emcc_bin) {- if let Some(emsdk_root) = emcc_path.parent()- .and_then(|p| p.parent())- .and_then(|p| p.parent())- {- if validate_emsdk(emsdk_root) {- return Some(emsdk_root.to_path_buf());- }- }- }-- // 2. EMSDK environment variable- if let Ok(emsdk_env) = std::env::var("EMSDK") {- let path = PathBuf::from(&emsdk_env);- if validate_emsdk(&path) {- return Some(path);- }- }-- // 3. Our own install location (from "Install emsdk" button)- let own_install = default_emsdk_install_path(app);- if validate_emsdk(&own_install) {- return Some(own_install);- }-- None-}--fn default_emsdk_install_path(app: &AppHandle) -> PathBuf {- app.path()- .app_data_dir()- .unwrap_or_else(|_| PathBuf::from("."))- .join("emsdk")-}+use crate::engine_sync::{hash_dir_meta, resolve_engine_src, sync_engine_src_if_needed};+use crate::toolchain::{+ emit_progress, find_bundled_cmake, find_emsdk_python, generate_emscripten_config,+ load_config, validate_emsdk, which_sync, CompileOptions, CompileResult, SpineModuleResult,+};// =============================================================================// Tauri commands// =============================================================================-#[tauri::command]-pub async fn get_toolchain_status(app: AppHandle) -> ToolchainStatus {- tokio::task::spawn_blocking(move || get_toolchain_status_sync(&app))- .await- .unwrap_or_else(|_| ToolchainStatus {- installed: false,- emsdk_path: None,- emscripten_version: None,- emscripten_ok: false,- cmake_found: false,- cmake_version: None,- cmake_ok: false,- python_found: false,- python_version: None,- python_ok: false,- corrupted: false,- missing_tools: Vec::new(),- })-}--fn get_toolchain_status_sync(app: &AppHandle) -> ToolchainStatus {- let mut config = load_config(app);-- let (emsdk_path, emscripten_version) = config- .emsdk_path- .as_ref()- .and_then(|p| {- let path = PathBuf::from(p);- if validate_emsdk(&path) {- let version = get_emcc_version(&path);- Some((Some(p.clone()), version))- } else {- None- }- })- .or_else(|| {- let detected = auto_detect_emsdk(app)?;- let version = get_emcc_version(&detected);- let path_str = detected.to_string_lossy().to_string();-- config.emsdk_path = Some(path_str.clone());- let _ = save_config(app, &config);-- Some((Some(path_str), version))- })- .unwrap_or((None, None));-- let (cmake_found, cmake_version) = find_cmake(app)- .map(|(_, v)| (true, Some(v)))- .unwrap_or((false, None));-- let python_from_emsdk = emsdk_path.as_ref().and_then(|p| find_emsdk_python(&PathBuf::from(p)));- let (python_found, python_version) = python_from_emsdk- .map(|(_, v)| (true, Some(v)))- .or_else(|| find_python().map(|(_, v)| (true, Some(v))))- .unwrap_or((false, None));-- let emscripten_ok = emscripten_version- .as_deref()- .map_or(false, |v| version_ge(v, MIN_EMSCRIPTEN_VERSION));- let cmake_ok = cmake_version- .as_deref()- .map_or(false, |v| version_ge(v, MIN_CMAKE_VERSION));- let python_ok = python_version- .as_deref()- .map_or(false, |v| version_ge(v, MIN_PYTHON_VERSION));-- let missing_tools = emsdk_path- .as_ref()- .map(|p| validate_emsdk_integrity(&PathBuf::from(p)))- .unwrap_or_default();- let corrupted = !missing_tools.is_empty();-- ToolchainStatus {- installed: emscripten_ok && cmake_ok && python_ok && !corrupted,- emsdk_path,- emscripten_version,- emscripten_ok,- cmake_found,- cmake_version,- cmake_ok,- python_found,- python_version,- python_ok,- corrupted,- missing_tools,- }-}--#[tauri::command]-pub async fn set_emsdk_path(app: AppHandle, path: String) -> Result<ToolchainStatus, String> {- let emsdk_path = PathBuf::from(&path);- if !validate_emsdk(&emsdk_path) {- return Err(format!(- "Invalid emsdk directory: emcc not found at {}/upstream/emscripten/emcc",- path- ));- }-- let mut config = load_config(&app);- config.emsdk_path = Some(path);- save_config(&app, &config)?;-- Ok(get_toolchain_status(app).await)-}--#[tauri::command]-pub async fn install_emsdk(app: AppHandle) -> Result<ToolchainStatus, String> {- let install_dir = default_emsdk_install_path(&app);- let install_dir_str = install_dir.to_string_lossy().to_string();- let url = toolchain_archive_url();- let is_zip = url.ends_with(".zip");-- emit_progress(&app, "download", "Downloading toolchain...", 0.05);-- // Download archive with progress- let archive_data = download_with_progress(&app, &url).await?;-- // Clean previous install- if install_dir.exists() {- std::fs::remove_dir_all(&install_dir).map_err(|e| e.to_string())?;- }- std::fs::create_dir_all(&install_dir).map_err(|e| e.to_string())?;-- emit_progress(&app, "extract", "Extracting toolchain...", 0.7);-- // Extract archive- let target = install_dir.clone();- tokio::task::spawn_blocking(move || {- if is_zip {- extract_zip(&archive_data, &target)- } else {- extract_tar_gz(&archive_data, &target)- }- })- .await- .map_err(|e| format!("Extract task failed: {}", e))??;-- // Generate .emscripten config- emit_progress(&app, "configure", "Configuring emscripten...", 0.9);- generate_emscripten_config(&install_dir)?;-- emit_progress(&app, "complete", "Toolchain installed!", 1.0);-- // Save path- let mut config = load_config(&app);- config.emsdk_path = Some(install_dir_str);- save_config(&app, &config)?;-- Ok(get_toolchain_status(app).await)-}--fn ninja_download_url() -> String {- let platform = if cfg!(target_os = "windows") {- if cfg!(target_arch = "aarch64") {- "ninja-winarm64"- } else {- "ninja-win"- }- } else if cfg!(target_os = "macos") {- "ninja-mac"- } else if cfg!(target_arch = "aarch64") {- "ninja-linux-aarch64"- } else {- "ninja-linux"- };- format!(- "https://github.com/ninja-build/ninja/releases/download/v{}/{}.zip",- NINJA_VERSION, platform- )-}--#[tauri::command]-pub async fn repair_toolchain(app: AppHandle) -> Result<ToolchainStatus, String> {- let config = load_config(&app);- let emsdk_path = config- .emsdk_path- .ok_or("emsdk path not configured")?;- let emsdk_dir = PathBuf::from(&emsdk_path);-- let missing = validate_emsdk_integrity(&emsdk_dir);- if missing.is_empty() {- return Ok(get_toolchain_status(app).await);- }-- if missing.contains(&"ninja".to_string()) {- let bin_dir = emsdk_dir.join("upstream").join("bin");- let ninja_name = if cfg!(windows) { "ninja.exe" } else { "ninja" };-- emit_progress(&app, "download", "Downloading ninja...", 0.1);-- let url = ninja_download_url();- let data = download_bytes(&url).await?;-- emit_progress(&app, "extract", "Installing ninja...", 0.7);-- let target = bin_dir.clone();- let ninja = ninja_name.to_string();- tokio::task::spawn_blocking(move || {- let cursor = std::io::Cursor::new(&data);- let mut archive =- zip::ZipArchive::new(cursor).map_err(|e| format!("Invalid zip: {}", e))?;- for i in 0..archive.len() {- let mut file = archive.by_index(i).map_err(|e| e.to_string())?;- let name = file.name().to_string();- if name.ends_with(&ninja) {- std::fs::create_dir_all(&target).map_err(|e| e.to_string())?;- let out_path = target.join(&ninja);- let mut out =- std::fs::File::create(&out_path).map_err(|e| e.to_string())?;- std::io::copy(&mut file, &mut out).map_err(|e| e.to_string())?;-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- std::fs::set_permissions(- &out_path,- std::fs::Permissions::from_mode(0o755),- )- .ok();- }- return Ok(());- }- }- Err("ninja not found in archive".to_string())- })- .await- .map_err(|e| format!("Extract task failed: {}", e))??;- }-- emit_progress(&app, "complete", "Toolchain repaired!", 1.0);- Ok(get_toolchain_status(app).await)-}--async fn download_bytes(url: &str) -> Result<Vec<u8>, String> {- let response = reqwest::get(url)- .await- .map_err(|e| format!("Download failed: {}", e))?;- if !response.status().is_success() {- return Err(format!("Download failed: HTTP {}", response.status()));- }- response- .bytes()- .await- .map(|b| b.to_vec())- .map_err(|e| format!("Download failed: {}", e))-}--async fn download_with_progress(app: &AppHandle, url: &str) -> Result<Vec<u8>, String> {- let response = reqwest::get(url)- .await- .map_err(|e| format!("Download failed: {}", e))?;-- if !response.status().is_success() {- return Err(format!("Download failed: HTTP {}", response.status()));- }-- let total_size = response.content_length().unwrap_or(0);- let mut downloaded: u64 = 0;- let mut data = Vec::with_capacity(total_size as usize);- let mut stream = response.bytes_stream();-- while let Some(chunk) = stream.next().await {- let chunk = chunk.map_err(|e| format!("Download interrupted: {}", e))?;- data.extend_from_slice(&chunk);- downloaded += chunk.len() as u64;-- if total_size > 0 {- let pct = (downloaded as f32 / total_size as f32).min(0.65);- let size_mb = downloaded as f32 / 1_048_576.0;- let total_mb = total_size as f32 / 1_048_576.0;- emit_progress(- app,- "download",- &format!("Downloading toolchain... {:.0}/{:.0} MB", size_mb, total_mb),- 0.05 + pct,- );- }- }-- Ok(data)-}--fn generate_emscripten_config(emsdk_dir: &Path) -> Result<(), String> {- let upstream = emsdk_dir.join("upstream");- let emscripten = upstream.join("emscripten");- let node_dir = emsdk_dir.join("node");-- let node_bin = if cfg!(windows) {- find_first_subdir(&node_dir)- .map(|d| d.join("bin").join("node.exe"))- .unwrap_or_else(|| node_dir.join("bin").join("node.exe"))- } else {- find_first_subdir(&node_dir)- .map(|d| d.join("bin").join("node"))- .unwrap_or_else(|| node_dir.join("bin").join("node"))- };-- let to_python_path = |p: &Path| -> String {- let s = p.to_string_lossy().replace('\\', "/");- format!("'{}'", s)- };-- let config = format!(- "import os\nEMSCRIPTEN_ROOT = {}\nLLVM_ROOT = {}\nBINARYEN_ROOT = {}\nNODE_JS = {}\n",- to_python_path(&emscripten),- to_python_path(&upstream.join("bin")),- to_python_path(&upstream),- to_python_path(&node_bin),- );-- let config_path = emsdk_dir.join(".emscripten");- std::fs::write(&config_path, config)- .map_err(|e| format!("Failed to write .emscripten config: {}", e))?;-- Ok(())-}--fn find_first_subdir(dir: &Path) -> Option<std::path::PathBuf> {- if !dir.exists() {- return None;- }- std::fs::read_dir(dir)- .ok()?- .filter_map(|e| e.ok())- .find(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))- .map(|e| e.path())-}--fn extract_zip(data: &[u8], target: &Path) -> Result<(), String> {- let cursor = std::io::Cursor::new(data);- let mut archive = zip::ZipArchive::new(cursor).map_err(|e| format!("Invalid zip: {}", e))?;-- for i in 0..archive.len() {- let mut file = archive.by_index(i).map_err(|e| e.to_string())?;- let name = file.name().to_string();-- // Strip the top-level directory (e.g., "emsdk-5.0.0-win/")- let relative = strip_top_dir(&name);- if relative.is_empty() {- continue;- }-- let out_path = target.join(relative);-- if file.is_dir() {- std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;- } else {- if let Some(parent) = out_path.parent() {- std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;- }- let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;- std::io::copy(&mut file, &mut out).map_err(|e| e.to_string())?;-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- if let Some(mode) = file.unix_mode() {- std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))- .ok();- }- }- }- }- Ok(())-}--fn extract_tar_gz(data: &[u8], target: &Path) -> Result<(), String> {- let cursor = std::io::Cursor::new(data);- let gz = flate2::read::GzDecoder::new(cursor);- let mut archive = tar::Archive::new(gz);-- // Unpack stripping the top-level directory- for entry in archive.entries().map_err(|e| e.to_string())? {- let mut entry = entry.map_err(|e| e.to_string())?;- let path = entry.path().map_err(|e| e.to_string())?.into_owned();- let path_str = path.to_string_lossy().to_string();-- let relative = strip_top_dir(&path_str);- if relative.is_empty() {- continue;- }-- let out_path = target.join(relative);-- if entry.header().entry_type().is_dir() {- std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;- } else {- if let Some(parent) = out_path.parent() {- std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;- }- let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;- std::io::copy(&mut entry, &mut out).map_err(|e| e.to_string())?;-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- if let Some(mode) = entry.header().mode().ok() {- std::fs::set_permissions(- &out_path,- std::fs::Permissions::from_mode(mode),- )- .ok();- }- }- }- }- Ok(())-}--fn strip_top_dir(path: &str) -> &str {- // "emsdk-5.0.0-mac/upstream/emscripten/emcc" → "upstream/emscripten/emcc"- match path.find('/') {- Some(idx) => &path[idx + 1..],- None => "",- }-}-#[tauri::command]pub async fn compile_wasm(app: AppHandle,@@ -1081,7 +49,6 @@ pub async fn compile_wasm(let cache_key = compute_cache_key(&options, &engine_src);- // Build directorylet build_base = app.path().app_data_dir()@@ -1096,7 +63,6 @@ pub async fn compile_wasm(std::fs::create_dir_all(&build_dir).map_err(|e| e.to_string())?;- // Check cache — validate both output existence AND source hashlet source_hash = compute_source_hash(&engine_src);if !options.clean_build {let wasm_output = if options.target == "playable" {@@ -1119,13 +85,11 @@ pub async fn compile_wasm(let env_vars = build_env_vars(&emsdk_dir, &app);- // Resolve cmake binary (bundled or system)let cmake_bin = find_bundled_cmake(&app).or_else(|| which_sync(if cfg!(windows) { "cmake.exe" } else { "cmake" })).ok_or("cmake not found. Run toolchain packaging first.")?;let cmake_str = cmake_bin.to_string_lossy().to_string();- // Configureemit_progress(&app, "configure", "Configuring CMake...", 0.1);let emcmake_name = if cfg!(windows) { "emcmake.bat" } else { "emcmake" };@@ -1152,7 +116,6 @@ pub async fn compile_wasm().await?;- // Buildemit_progress(&app, "compile", "Compiling C++ to WASM...", 0.3);let build_target = match options.target.as_str() {@@ -1177,7 +140,6 @@ pub async fn compile_wasm().await?;- // Build spine modulesif options.features.spine && !options.spine_versions.is_empty() {emit_progress(&app, "compile", "Compiling Spine modules...", 0.5);for version in &options.spine_versions {@@ -1205,7 +167,6 @@ pub async fn compile_wasm(}}- // Build physics module (only if box2d source is available)if options.enable_physics {let box2d_dir = engine_src.join("third_party/box2d");if box2d_dir.exists() {@@ -1230,7 +191,6 @@ pub async fn compile_wasm(}}- // Optimizeif !options.debug {emit_progress(&app, "optimize", "Optimizing WASM...", 0.8);@@ -1264,7 +224,6 @@ pub async fn compile_wasm(}}- // Save source hash for cache invalidationlet hash_file = build_dir.join(".source_hash");if let Err(e) = std::fs::write(&hash_file, &source_hash) {eprintln!("[compiler] Failed to write source hash: {}", e);@@ -1376,24 +335,6 @@ fn compute_source_hash(engine_src: &Path) -> String {format!("{:016x}", hasher.finish())}-fn collect_all_files(dir: &Path) -> Result<Vec<PathBuf>, std::io::Error> {- let mut files = Vec::new();- if !dir.is_dir() {- return Ok(files);- }- for entry in std::fs::read_dir(dir)? {- let entry = entry?;- let path = entry.path();- if path.is_dir() {- files.extend(collect_all_files(&path)?);- } else {- files.push(path);- }- }- files.sort();- Ok(files)-}-fn build_cmake_flags(options: &CompileOptions) -> Vec<String> {let mut flags = vec![format!(@@ -1449,7 +390,6 @@ fn build_env_vars(emsdk_dir: &Path, app: &AppHandle) -> HashMap<String, String>emsdk_dir.join(".emscripten").to_string_lossy().to_string(),);- // Use emsdk-bundled Python so users don't need system Pythonif let Some((python_path, _)) = find_emsdk_python(emsdk_dir) {env.insert("EMSDK_PYTHON".to_string(), python_path.to_string_lossy().to_string());}@@ -1462,7 +402,6 @@ fn build_env_vars(emsdk_dir: &Path, app: &AppHandle) -> HashMap<String, String>upstream_dir.join("bin").to_string_lossy().to_string(),];- // Add bundled cmake to PATHif let Some(bundled_cmake) = find_bundled_cmake(app) {if let Some(cmake_bin_dir) = bundled_cmake.parent() {path_entries.push(cmake_bin_dir.to_string_lossy().to_string());@@ -1474,17 +413,6 @@ fn build_env_vars(emsdk_dir: &Path, app: &AppHandle) -> HashMap<String, String>env}-fn emit_progress(app: &AppHandle, stage: &str, message: &str, progress: f32) {- let _ = app.emit(- "compile-progress",- CompileProgress {- stage: stage.to_string(),- message: message.to_string(),- progress,- },- );-}-async fn run_command_streamed(app: &AppHandle,cmd: &str,@@ -1553,7 +481,6 @@ async fn run_command_streamed(let stderr_lines = stderr_result.unwrap_or_default();let stdout_lines = stdout_result.unwrap_or_default();- // Merge both streams — errors may appear in either stdout or stderrlet mut combined: Vec<&str> = Vec::new();combined.extend(stdout_lines.iter().map(|s| s.as_str()));combined.extend(stderr_lines.iter().map(|s| s.as_str()));@@ -1581,13 +508,8 @@ fn num_cpus() -> usize {.unwrap_or(4)}-/// Build the (program, args) pair for running a command, handling .bat files on Windows.-///-/// On Windows, `.bat` files must be executed via `cmd.exe /C` because the OS-/// cannot spawn batch files directly as processes.fn build_command_for_platform(cmd: &str, args: &[String]) -> (String, Vec<String>) {if cfg!(windows) && cmd.ends_with(".bat") {- // Quote the .bat path if it contains spaceslet quoted_cmd = if cmd.contains(' ') {format!("\"{}\"", cmd)} else {diff --git a/desktop/src-tauri/src/engine_sync.rs b/desktop/src-tauri/src/engine_sync.rsnew file mode 100644index 000000000..21398b905--- /dev/null+++ b/desktop/src-tauri/src/engine_sync.rs@@ -0,0 +1,237 @@+//! Manifest-driven engine source synchronization.++use serde::Deserialize;+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use tauri::{AppHandle, Manager};++use crate::toolchain::strip_unc_prefix;++// =============================================================================+// Types+// =============================================================================++#[derive(Debug, Deserialize)]+struct ToolchainManifest {+ engine: EngineManifest,+ third_party: ThirdPartyManifest,+}++#[derive(Debug, Deserialize)]+struct EngineManifest {+ root_files: Vec<String>,+ directories: Vec<String>,+}++#[derive(Debug, Deserialize)]+struct ThirdPartyManifest {+ root_files: Vec<String>,+ full: Vec<String>,+ partial: HashMap<String, Vec<String>>,+}++// =============================================================================+// Public API+// =============================================================================++pub fn resolve_engine_src(app: &AppHandle) -> Result<PathBuf, String> {+ let resource_dir = app+ .path()+ .resource_dir()+ .map_err(|e| format!("Failed to resolve resource dir: {}", e))?;++ let engine_src = strip_unc_prefix(resource_dir.join("toolchain/engine-src"));+ if engine_src.exists() {+ return Ok(engine_src);+ }++ let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(|p| p.parent())+ .map(|root| root.join("desktop/src-tauri/toolchain/engine-src"));++ if let Some(path) = dev_path {+ if path.exists() {+ return Ok(path);+ }+ }++ Err("Engine source not found. Rebuild the editor.".to_string())+}++pub fn sync_engine_src_if_needed(engine_src: &Path) -> Result<bool, String> {+ let root = match project_root() {+ Some(r) => r,+ None => return Ok(false),+ };++ let manifest = match load_manifest(&root) {+ Ok(m) => m,+ Err(_) => return Ok(false),+ };++ let current_hash = compute_manifest_hash(&root, &manifest);+ let hash_file = engine_src.join(".sync_hash");+ let stored_hash = std::fs::read_to_string(&hash_file).unwrap_or_default();++ if current_hash == stored_hash {+ return Ok(false);+ }++ sync_from_manifest(&root, engine_src, &manifest)?;+ let _ = std::fs::write(&hash_file, ¤t_hash);+ Ok(true)+}++// =============================================================================+// Internals+// =============================================================================++fn project_root() -> Option<PathBuf> {+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(|p| p.parent())+ .map(|p| p.to_path_buf())+}++fn load_manifest(root: &Path) -> Result<ToolchainManifest, String> {+ let path = root.join("toolchain.manifest.json");+ let content = std::fs::read_to_string(&path)+ .map_err(|e| format!("Failed to read toolchain manifest: {}", e))?;+ serde_json::from_str(&content)+ .map_err(|e| format!("Failed to parse toolchain manifest: {}", e))+}++fn compute_manifest_hash(root: &Path, manifest: &ToolchainManifest) -> String {+ use std::collections::hash_map::DefaultHasher;+ use std::hash::Hasher;++ let mut hasher = DefaultHasher::new();++ for file in &manifest.engine.root_files {+ hash_file_meta(&mut hasher, &root.join(file));+ }+ for dir in &manifest.engine.directories {+ hash_dir_meta(&mut hasher, &root.join(dir));+ }+ for file in &manifest.third_party.root_files {+ hash_file_meta(&mut hasher, &root.join("third_party").join(file));+ }+ for dir in &manifest.third_party.full {+ hash_file_meta(&mut hasher, &root.join("third_party").join(dir).join("CMakeLists.txt"));+ }+ for (lib, subdirs) in &manifest.third_party.partial {+ for subdir in subdirs {+ hash_dir_meta(&mut hasher, &root.join("third_party").join(lib).join(subdir));+ }+ }++ format!("{:016x}", hasher.finish())+}++pub fn hash_file_meta(hasher: &mut impl std::hash::Hasher, path: &Path) {+ use std::hash::Hash;+ if let Ok(meta) = std::fs::metadata(path) {+ path.to_string_lossy().hash(hasher);+ meta.len().hash(hasher);+ if let Ok(modified) = meta.modified() {+ modified.hash(hasher);+ }+ }+}++pub fn hash_dir_meta(hasher: &mut impl std::hash::Hasher, dir: &Path) {+ if let Ok(entries) = collect_all_files(dir) {+ for path in entries {+ hash_file_meta(hasher, &path);+ }+ }+}++fn sync_from_manifest(root: &Path, dest: &Path, manifest: &ToolchainManifest) -> Result<(), String> {+ let hash_backup = std::fs::read_to_string(dest.join(".sync_hash")).ok();++ if dest.exists() {+ std::fs::remove_dir_all(dest).map_err(|e| e.to_string())?;+ }+ std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;++ if let Some(hash) = hash_backup {+ let _ = std::fs::write(dest.join(".sync_hash"), hash);+ }++ for file in &manifest.engine.root_files {+ let src = root.join(file);+ if src.exists() {+ std::fs::copy(&src, dest.join(file)).map_err(|e| e.to_string())?;+ }+ }++ for dir in &manifest.engine.directories {+ let src = root.join(dir);+ if src.exists() {+ copy_dir_recursive(&src, &dest.join(dir))?;+ }+ }++ let tp_dest = dest.join("third_party");+ std::fs::create_dir_all(&tp_dest).map_err(|e| e.to_string())?;++ for file in &manifest.third_party.root_files {+ let src = root.join("third_party").join(file);+ if src.exists() {+ std::fs::copy(&src, tp_dest.join(file)).map_err(|e| e.to_string())?;+ }+ }++ for dir in &manifest.third_party.full {+ let src = root.join("third_party").join(dir);+ if src.exists() {+ copy_dir_recursive(&src, &tp_dest.join(dir))?;+ }+ }++ for (lib, subdirs) in &manifest.third_party.partial {+ for subdir in subdirs {+ let src = root.join("third_party").join(lib).join(subdir);+ if src.exists() {+ copy_dir_recursive(&src, &tp_dest.join(lib).join(subdir))?;+ }+ }+ }++ Ok(())+}++fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<(), String> {+ std::fs::create_dir_all(dest).map_err(|e| e.to_string())?;+ for entry in std::fs::read_dir(src).map_err(|e| e.to_string())? {+ let entry = entry.map_err(|e| e.to_string())?;+ let src_path = entry.path();+ let dest_path = dest.join(entry.file_name());+ if src_path.is_dir() {+ copy_dir_recursive(&src_path, &dest_path)?;+ } else {+ std::fs::copy(&src_path, &dest_path).map_err(|e| e.to_string())?;+ }+ }+ Ok(())+}++pub fn collect_all_files(dir: &Path) -> Result<Vec<PathBuf>, std::io::Error> {+ let mut files = Vec::new();+ if !dir.is_dir() {+ return Ok(files);+ }+ for entry in std::fs::read_dir(dir)? {+ let entry = entry?;+ let path = entry.path();+ if path.is_dir() {+ files.extend(collect_all_files(&path)?);+ } else {+ files.push(path);+ }+ }+ files.sort();+ Ok(files)+}diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rsindex a73060824..59cae820a 100644--- a/desktop/src-tauri/src/lib.rs+++ b/desktop/src-tauri/src/lib.rs@@ -3,7 +3,9 @@mod bridge_server;mod compiler;mod embedded_assets;+mod engine_sync;mod preview_server;+mod toolchain;use bridge_server::BridgeServer;use preview_server::PreviewServer;@@ -324,10 +326,10 @@ pub fn run() {get_embedded_asset,check_update,install_update,- compiler::get_toolchain_status,- compiler::set_emsdk_path,- compiler::install_emsdk,- compiler::repair_toolchain,+ toolchain::get_toolchain_status,+ toolchain::set_emsdk_path,+ toolchain::install_emsdk,+ toolchain::repair_toolchain,compiler::compile_wasm,compiler::clear_build_cache,])diff --git a/desktop/src-tauri/src/toolchain.rs b/desktop/src-tauri/src/toolchain.rsnew file mode 100644index 000000000..92c3d625e--- /dev/null+++ b/desktop/src-tauri/src/toolchain.rs@@ -0,0 +1,848 @@+//! Toolchain discovery, configuration, installation, and repair.++use futures_util::StreamExt;+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};+use tauri::{AppHandle, Emitter, Manager};++#[cfg(windows)]+use std::os::windows::process::CommandExt;++#[cfg(windows)]+const CREATE_NO_WINDOW: u32 = 0x08000000;++// =============================================================================+// Types+// =============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ToolchainStatus {+ pub installed: bool,+ pub emsdk_path: Option<String>,+ pub emscripten_version: Option<String>,+ pub emscripten_ok: bool,+ pub cmake_found: bool,+ pub cmake_version: Option<String>,+ pub cmake_ok: bool,+ pub python_found: bool,+ pub python_version: Option<String>,+ pub python_ok: bool,+ pub corrupted: bool,+ pub missing_tools: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FeatureFlags {+ pub tilemap: bool,+ pub particles: bool,+ pub timeline: bool,+ pub postprocess: bool,+ pub bitmap_text: bool,+ pub spine: bool,+}++impl Default for FeatureFlags {+ fn default() -> Self {+ Self {+ tilemap: true,+ particles: true,+ timeline: true,+ postprocess: true,+ bitmap_text: true,+ spine: true,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CompileOptions {+ pub features: FeatureFlags,+ pub target: String,+ pub debug: bool,+ pub optimization: String,+ #[serde(default)]+ pub enable_physics: bool,+ #[serde(default)]+ pub spine_versions: Vec<String>,+ #[serde(default)]+ pub clean_build: bool,+}++impl Default for CompileOptions {+ fn default() -> Self {+ Self {+ features: FeatureFlags::default(),+ target: "web".to_string(),+ debug: false,+ optimization: "-Oz".to_string(),+ enable_physics: false,+ spine_versions: Vec::new(),+ clean_build: false,+ }+ }+}++#[derive(Clone, Serialize)]+pub struct CompileProgress {+ pub stage: String,+ pub message: String,+ pub progress: f32,+}++#[derive(Serialize)]+pub struct SpineModuleResult {+ pub version: String,+ pub js_path: String,+ pub wasm_path: String,+}++#[derive(Serialize)]+pub struct CompileResult {+ pub success: bool,+ pub wasm_path: Option<String>,+ pub js_path: Option<String>,+ pub wasm_size: Option<u64>,+ pub error: Option<String>,+ pub cache_key: String,+ pub spine_modules: Vec<SpineModuleResult>,+ pub physics_js_path: Option<String>,+ pub physics_wasm_path: Option<String>,+}++// =============================================================================+// Constants+// =============================================================================++const EMSDK_VERSION: &str = "5.0.0";+const EMSDK_DOWNLOAD_BASE: &str = "https://github.com/esengine/emsdk-releases/releases/download";+const NINJA_VERSION: &str = "1.13.2";++const MIN_EMSCRIPTEN_VERSION: &str = "5.0.0";+const MIN_CMAKE_VERSION: &str = "3.16";+const MIN_PYTHON_VERSION: &str = "3.0";++// =============================================================================+// Toolchain settings persistence+// =============================================================================++pub fn toolchain_config_path(app: &AppHandle) -> PathBuf {+ app.path()+ .app_data_dir()+ .unwrap_or_else(|_| PathBuf::from("."))+ .join("toolchain.json")+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct ToolchainConfig {+ pub emsdk_path: Option<String>,+}++pub fn load_config(app: &AppHandle) -> ToolchainConfig {+ let path = toolchain_config_path(app);+ std::fs::read_to_string(&path)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_default()+}++pub fn save_config(app: &AppHandle, config: &ToolchainConfig) -> Result<(), String> {+ let path = toolchain_config_path(app);+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let json = serde_json::to_string_pretty(config).map_err(|e| e.to_string())?;+ std::fs::write(&path, json).map_err(|e| e.to_string())+}++// =============================================================================+// Toolchain discovery+// =============================================================================++pub fn find_emcc_in_emsdk(emsdk_path: &Path) -> Option<PathBuf> {+ let emcc = emsdk_path.join("upstream/emscripten/emcc");+ if emcc.exists() {+ return Some(emcc);+ }+ let emcc_bat = emsdk_path.join("upstream/emscripten/emcc.bat");+ if emcc_bat.exists() {+ return Some(emcc_bat);+ }+ None+}++pub fn validate_emsdk(emsdk_path: &Path) -> bool {+ find_emcc_in_emsdk(emsdk_path).is_some()+}++pub fn validate_emsdk_integrity(emsdk_path: &Path) -> Vec<String> {+ let ninja_name = if cfg!(windows) { "ninja.exe" } else { "ninja" };+ let required = [+ ("upstream/bin", ninja_name, "ninja"),+ ("upstream/emscripten", if cfg!(windows) { "emcc.bat" } else { "emcc" }, "emcc"),+ (".emscripten", "", ".emscripten config"),+ ];++ let mut missing = Vec::new();+ for (dir, file, label) in &required {+ let path = if file.is_empty() {+ emsdk_path.join(dir)+ } else {+ emsdk_path.join(dir).join(file)+ };+ if !path.exists() {+ missing.push(label.to_string());+ }+ }+ missing+}++pub fn get_emcc_version(emsdk_path: &Path) -> Option<String> {+ let emcc = find_emcc_in_emsdk(emsdk_path)?;+ let output = silent_command(&emcc)+ .arg("--version")+ .env("EMSDK", emsdk_path)+ .env(+ "EM_CONFIG",+ emsdk_path.join(".emscripten"),+ )+ .output()+ .ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let re_version = stdout+ .lines()+ .find_map(|line| {+ line.split_whitespace()+ .find(|w| w.chars().next().map_or(false, |c| c.is_ascii_digit()))+ })+ .map(|s| s.trim_end_matches(|c: char| !c.is_ascii_digit() && c != '.').to_string());+ re_version+}++pub fn find_bundled_cmake(app: &AppHandle) -> Option<PathBuf> {+ let cmake_name = if cfg!(windows) { "cmake.exe" } else { "cmake" };++ if let Ok(resource_dir) = app.path().resource_dir() {+ let bundled = strip_unc_prefix(resource_dir.join("toolchain/cmake/bin").join(cmake_name));+ if bundled.exists() {+ return Some(bundled);+ }+ }++ let dev_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("toolchain/cmake/bin")+ .join(cmake_name);+ if dev_path.exists() {+ return Some(dev_path);+ }++ None+}++pub fn find_cmake(app: &AppHandle) -> Option<(PathBuf, String)> {+ if let Some(bundled) = find_bundled_cmake(app) {+ let output = silent_command(&bundled)+ .arg("--version")+ .output()+ .ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let version = stdout.lines().next()?.split_whitespace().last()?.to_string();+ return Some((bundled, version));+ }++ let cmake = if cfg!(windows) { "cmake.exe" } else { "cmake" };+ let output = silent_command(cmake)+ .arg("--version")+ .output()+ .ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let version = stdout+ .lines()+ .next()?+ .split_whitespace()+ .last()?+ .to_string();++ let path = which_sync(cmake)?;+ Some((path, version))+}++pub fn find_python() -> Option<(PathBuf, String)> {+ for bin in &["python3", "python"] {+ let output = silent_command(bin)+ .arg("--version")+ .output()+ .ok();+ if let Some(out) = output {+ if out.status.success() {+ let stdout = String::from_utf8_lossy(&out.stdout);+ let stderr = String::from_utf8_lossy(&out.stderr);+ let text = if stdout.contains("Python") { stdout } else { stderr };+ let version = text+ .trim()+ .strip_prefix("Python ")+ .unwrap_or(text.trim())+ .to_string();+ if let Some(path) = which_sync(bin) {+ return Some((path, version));+ }+ }+ }+ }+ None+}++pub fn find_emsdk_python(emsdk_path: &Path) -> Option<(PathBuf, String)> {+ let python_dir = emsdk_path.join("python");+ if !python_dir.exists() {+ return None;+ }+ let entries = std::fs::read_dir(&python_dir).ok()?;+ for entry in entries.flatten() {+ let python_bin = if cfg!(windows) {+ entry.path().join("python.exe")+ } else {+ entry.path().join("bin").join("python3")+ };+ if python_bin.exists() {+ let output = silent_command(&python_bin)+ .arg("--version")+ .output()+ .ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let version = stdout+ .trim()+ .strip_prefix("Python ")+ .unwrap_or(stdout.trim())+ .to_string();+ return Some((python_bin, version));+ }+ }+ None+}++pub fn which_sync(bin: &str) -> Option<PathBuf> {+ let cmd = if cfg!(windows) { "where" } else { "which" };+ let output = silent_command(cmd)+ .arg(bin)+ .output()+ .ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ let path = stdout.lines().next()?.trim();+ if path.is_empty() {+ None+ } else {+ Some(PathBuf::from(path))+ }+}++pub fn silent_command(program: &(impl AsRef<std::ffi::OsStr> + ?Sized)) -> std::process::Command {+ #[allow(unused_mut)]+ let mut cmd = std::process::Command::new(program);+ #[cfg(windows)]+ cmd.creation_flags(CREATE_NO_WINDOW);+ cmd+}++pub fn strip_unc_prefix(p: PathBuf) -> PathBuf {+ let s = p.to_string_lossy();+ if s.starts_with(r"\\?\") {+ PathBuf::from(&s[4..])+ } else {+ p+ }+}++pub fn auto_detect_emsdk(app: &AppHandle) -> Option<PathBuf> {+ let emcc_bin = if cfg!(windows) { "emcc.bat" } else { "emcc" };+ if let Some(emcc_path) = which_sync(emcc_bin) {+ if let Some(emsdk_root) = emcc_path.parent()+ .and_then(|p| p.parent())+ .and_then(|p| p.parent())+ {+ if validate_emsdk(emsdk_root) {+ return Some(emsdk_root.to_path_buf());+ }+ }+ }++ if let Ok(emsdk_env) = std::env::var("EMSDK") {+ let path = PathBuf::from(&emsdk_env);+ if validate_emsdk(&path) {+ return Some(path);+ }+ }++ let own_install = default_emsdk_install_path(app);+ if validate_emsdk(&own_install) {+ return Some(own_install);+ }++ None+}++fn default_emsdk_install_path(app: &AppHandle) -> PathBuf {+ app.path()+ .app_data_dir()+ .unwrap_or_else(|_| PathBuf::from("."))+ .join("emsdk")+}++fn toolchain_archive_url() -> String {+ let (os, ext) = if cfg!(target_os = "windows") {+ ("win", "zip")+ } else if cfg!(target_os = "macos") {+ ("mac", "tar.gz")+ } else {+ ("linux", "tar.gz")+ };+ format!(+ "{}/v{}/emsdk-{}-{}.{}",+ EMSDK_DOWNLOAD_BASE, EMSDK_VERSION, EMSDK_VERSION, os, ext+ )+}++pub fn version_ge(actual: &str, required: &str) -> bool {+ let parse = |s: &str| -> Vec<u32> {+ s.split('.')+ .filter_map(|p| p.trim().parse::<u32>().ok())+ .collect()+ };+ let a = parse(actual);+ let r = parse(required);+ for i in 0..r.len() {+ let av = a.get(i).copied().unwrap_or(0);+ let rv = r[i];+ if av > rv { return true; }+ if av < rv { return false; }+ }+ true+}++// =============================================================================+// Tauri commands+// =============================================================================++#[tauri::command]+pub async fn get_toolchain_status(app: AppHandle) -> ToolchainStatus {+ tokio::task::spawn_blocking(move || get_toolchain_status_sync(&app))+ .await+ .unwrap_or_else(|_| ToolchainStatus {+ installed: false,+ emsdk_path: None,+ emscripten_version: None,+ emscripten_ok: false,+ cmake_found: false,+ cmake_version: None,+ cmake_ok: false,+ python_found: false,+ python_version: None,+ python_ok: false,+ corrupted: false,+ missing_tools: Vec::new(),+ })+}++fn get_toolchain_status_sync(app: &AppHandle) -> ToolchainStatus {+ let mut config = load_config(app);++ let (emsdk_path, emscripten_version) = config+ .emsdk_path+ .as_ref()+ .and_then(|p| {+ let path = PathBuf::from(p);+ if validate_emsdk(&path) {+ let version = get_emcc_version(&path);+ Some((Some(p.clone()), version))+ } else {+ None+ }+ })+ .or_else(|| {+ let detected = auto_detect_emsdk(app)?;+ let version = get_emcc_version(&detected);+ let path_str = detected.to_string_lossy().to_string();++ config.emsdk_path = Some(path_str.clone());+ let _ = save_config(app, &config);++ Some((Some(path_str), version))+ })+ .unwrap_or((None, None));++ let (cmake_found, cmake_version) = find_cmake(app)+ .map(|(_, v)| (true, Some(v)))+ .unwrap_or((false, None));++ let python_from_emsdk = emsdk_path.as_ref().and_then(|p| find_emsdk_python(&PathBuf::from(p)));+ let (python_found, python_version) = python_from_emsdk+ .map(|(_, v)| (true, Some(v)))+ .or_else(|| find_python().map(|(_, v)| (true, Some(v))))+ .unwrap_or((false, None));++ let emscripten_ok = emscripten_version+ .as_deref()+ .map_or(false, |v| version_ge(v, MIN_EMSCRIPTEN_VERSION));+ let cmake_ok = cmake_version+ .as_deref()+ .map_or(false, |v| version_ge(v, MIN_CMAKE_VERSION));+ let python_ok = python_version+ .as_deref()+ .map_or(false, |v| version_ge(v, MIN_PYTHON_VERSION));++ let missing_tools = emsdk_path+ .as_ref()+ .map(|p| validate_emsdk_integrity(&PathBuf::from(p)))+ .unwrap_or_default();+ let corrupted = !missing_tools.is_empty();++ ToolchainStatus {+ installed: emscripten_ok && cmake_ok && python_ok && !corrupted,+ emsdk_path,+ emscripten_version,+ emscripten_ok,+ cmake_found,+ cmake_version,+ cmake_ok,+ python_found,+ python_version,+ python_ok,+ corrupted,+ missing_tools,+ }+}++#[tauri::command]+pub async fn set_emsdk_path(app: AppHandle, path: String) -> Result<ToolchainStatus, String> {+ let emsdk_path = PathBuf::from(&path);+ if !validate_emsdk(&emsdk_path) {+ return Err(format!(+ "Invalid emsdk directory: emcc not found at {}/upstream/emscripten/emcc",+ path+ ));+ }++ let mut config = load_config(&app);+ config.emsdk_path = Some(path);+ save_config(&app, &config)?;++ Ok(get_toolchain_status(app).await)+}++#[tauri::command]+pub async fn install_emsdk(app: AppHandle) -> Result<ToolchainStatus, String> {+ let install_dir = default_emsdk_install_path(&app);+ let install_dir_str = install_dir.to_string_lossy().to_string();+ let url = toolchain_archive_url();+ let is_zip = url.ends_with(".zip");++ emit_progress(&app, "download", "Downloading toolchain...", 0.05);++ let archive_data = download_with_progress(&app, &url).await?;++ if install_dir.exists() {+ std::fs::remove_dir_all(&install_dir).map_err(|e| e.to_string())?;+ }+ std::fs::create_dir_all(&install_dir).map_err(|e| e.to_string())?;++ emit_progress(&app, "extract", "Extracting toolchain...", 0.7);++ let target = install_dir.clone();+ tokio::task::spawn_blocking(move || {+ if is_zip {+ extract_zip(&archive_data, &target)+ } else {+ extract_tar_gz(&archive_data, &target)+ }+ })+ .await+ .map_err(|e| format!("Extract task failed: {}", e))??;++ emit_progress(&app, "configure", "Configuring emscripten...", 0.9);+ generate_emscripten_config(&install_dir)?;++ emit_progress(&app, "complete", "Toolchain installed!", 1.0);++ let mut config = load_config(&app);+ config.emsdk_path = Some(install_dir_str);+ save_config(&app, &config)?;++ Ok(get_toolchain_status(app).await)+}++fn ninja_download_url() -> String {+ let platform = if cfg!(target_os = "windows") {+ if cfg!(target_arch = "aarch64") {+ "ninja-winarm64"+ } else {+ "ninja-win"+ }+ } else if cfg!(target_os = "macos") {+ "ninja-mac"+ } else if cfg!(target_arch = "aarch64") {+ "ninja-linux-aarch64"+ } else {+ "ninja-linux"+ };+ format!(+ "https://github.com/ninja-build/ninja/releases/download/v{}/{}.zip",+ NINJA_VERSION, platform+ )+}++#[tauri::command]+pub async fn repair_toolchain(app: AppHandle) -> Result<ToolchainStatus, String> {+ let config = load_config(&app);+ let emsdk_path = config+ .emsdk_path+ .ok_or("emsdk path not configured")?;+ let emsdk_dir = PathBuf::from(&emsdk_path);++ let missing = validate_emsdk_integrity(&emsdk_dir);+ if missing.is_empty() {+ return Ok(get_toolchain_status(app).await);+ }++ if missing.contains(&"ninja".to_string()) {+ let bin_dir = emsdk_dir.join("upstream").join("bin");+ let ninja_name = if cfg!(windows) { "ninja.exe" } else { "ninja" };++ emit_progress(&app, "download", "Downloading ninja...", 0.1);++ let url = ninja_download_url();+ let data = download_bytes(&url).await?;++ emit_progress(&app, "extract", "Installing ninja...", 0.7);++ let target = bin_dir.clone();+ let ninja = ninja_name.to_string();+ tokio::task::spawn_blocking(move || {+ let cursor = std::io::Cursor::new(&data);+ let mut archive =+ zip::ZipArchive::new(cursor).map_err(|e| format!("Invalid zip: {}", e))?;+ for i in 0..archive.len() {+ let mut file = archive.by_index(i).map_err(|e| e.to_string())?;+ let name = file.name().to_string();+ if name.ends_with(&ninja) {+ std::fs::create_dir_all(&target).map_err(|e| e.to_string())?;+ let out_path = target.join(&ninja);+ let mut out =+ std::fs::File::create(&out_path).map_err(|e| e.to_string())?;+ std::io::copy(&mut file, &mut out).map_err(|e| e.to_string())?;++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(+ &out_path,+ std::fs::Permissions::from_mode(0o755),+ )+ .ok();+ }+ return Ok(());+ }+ }+ Err("ninja not found in archive".to_string())+ })+ .await+ .map_err(|e| format!("Extract task failed: {}", e))??;+ }++ emit_progress(&app, "complete", "Toolchain repaired!", 1.0);+ Ok(get_toolchain_status(app).await)+}++// =============================================================================+// Download / extract helpers+// =============================================================================++pub async fn download_bytes(url: &str) -> Result<Vec<u8>, String> {+ let response = reqwest::get(url)+ .await+ .map_err(|e| format!("Download failed: {}", e))?;+ if !response.status().is_success() {+ return Err(format!("Download failed: HTTP {}", response.status()));+ }+ response+ .bytes()+ .await+ .map(|b| b.to_vec())+ .map_err(|e| format!("Download failed: {}", e))+}++async fn download_with_progress(app: &AppHandle, url: &str) -> Result<Vec<u8>, String> {+ let response = reqwest::get(url)+ .await+ .map_err(|e| format!("Download failed: {}", e))?;++ if !response.status().is_success() {+ return Err(format!("Download failed: HTTP {}", response.status()));+ }++ let total_size = response.content_length().unwrap_or(0);+ let mut downloaded: u64 = 0;+ let mut data = Vec::with_capacity(total_size as usize);+ let mut stream = response.bytes_stream();++ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| format!("Download interrupted: {}", e))?;+ data.extend_from_slice(&chunk);+ downloaded += chunk.len() as u64;++ if total_size > 0 {+ let pct = (downloaded as f32 / total_size as f32).min(0.65);+ let size_mb = downloaded as f32 / 1_048_576.0;+ let total_mb = total_size as f32 / 1_048_576.0;+ emit_progress(+ app,+ "download",+ &format!("Downloading toolchain... {:.0}/{:.0} MB", size_mb, total_mb),+ 0.05 + pct,+ );+ }+ }++ Ok(data)+}++pub fn generate_emscripten_config(emsdk_dir: &Path) -> Result<(), String> {+ let upstream = emsdk_dir.join("upstream");+ let emscripten = upstream.join("emscripten");+ let node_dir = emsdk_dir.join("node");++ let node_bin = if cfg!(windows) {+ find_first_subdir(&node_dir)+ .map(|d| d.join("bin").join("node.exe"))+ .unwrap_or_else(|| node_dir.join("bin").join("node.exe"))+ } else {+ find_first_subdir(&node_dir)+ .map(|d| d.join("bin").join("node"))+ .unwrap_or_else(|| node_dir.join("bin").join("node"))+ };++ let to_python_path = |p: &Path| -> String {+ let s = p.to_string_lossy().replace('\\', "/");+ format!("'{}'", s)+ };++ let config = format!(+ "import os\nEMSCRIPTEN_ROOT = {}\nLLVM_ROOT = {}\nBINARYEN_ROOT = {}\nNODE_JS = {}\n",+ to_python_path(&emscripten),+ to_python_path(&upstream.join("bin")),+ to_python_path(&upstream),+ to_python_path(&node_bin),+ );++ let config_path = emsdk_dir.join(".emscripten");+ std::fs::write(&config_path, config)+ .map_err(|e| format!("Failed to write .emscripten config: {}", e))?;++ Ok(())+}++fn find_first_subdir(dir: &Path) -> Option<std::path::PathBuf> {+ if !dir.exists() {+ return None;+ }+ std::fs::read_dir(dir)+ .ok()?+ .filter_map(|e| e.ok())+ .find(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))+ .map(|e| e.path())+}++pub fn extract_zip(data: &[u8], target: &Path) -> Result<(), String> {+ let cursor = std::io::Cursor::new(data);+ let mut archive = zip::ZipArchive::new(cursor).map_err(|e| format!("Invalid zip: {}", e))?;++ for i in 0..archive.len() {+ let mut file = archive.by_index(i).map_err(|e| e.to_string())?;+ let name = file.name().to_string();++ let relative = strip_top_dir(&name);+ if relative.is_empty() {+ continue;+ }++ let out_path = target.join(relative);++ if file.is_dir() {+ std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;+ } else {+ if let Some(parent) = out_path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;+ std::io::copy(&mut file, &mut out).map_err(|e| e.to_string())?;++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = file.unix_mode() {+ std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))+ .ok();+ }+ }+ }+ }+ Ok(())+}++pub fn extract_tar_gz(data: &[u8], target: &Path) -> Result<(), String> {+ let cursor = std::io::Cursor::new(data);+ let gz = flate2::read::GzDecoder::new(cursor);+ let mut archive = tar::Archive::new(gz);++ for entry in archive.entries().map_err(|e| e.to_string())? {+ let mut entry = entry.map_err(|e| e.to_string())?;+ let path = entry.path().map_err(|e| e.to_string())?.into_owned();+ let path_str = path.to_string_lossy().to_string();++ let relative = strip_top_dir(&path_str);+ if relative.is_empty() {+ continue;+ }++ let out_path = target.join(relative);++ if entry.header().entry_type().is_dir() {+ std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;+ } else {+ if let Some(parent) = out_path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;+ std::io::copy(&mut entry, &mut out).map_err(|e| e.to_string())?;++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = entry.header().mode().ok() {+ std::fs::set_permissions(+ &out_path,+ std::fs::Permissions::from_mode(mode),+ )+ .ok();+ }+ }+ }+ }+ Ok(())+}++fn strip_top_dir(path: &str) -> &str {+ match path.find('/') {+ Some(idx) => &path[idx + 1..],+ None => "",+ }+}++pub fn emit_progress(app: &AppHandle, stage: &str, message: &str, progress: f32) {+ let _ = app.emit(+ "compile-progress",+ CompileProgress {+ stage: stage.to_string(),+ message: message.to_string(),+ progress,+ },+ );+}diff --git a/editor/src/builder/BuildSettingsActions.ts b/editor/src/builder/BuildSettingsActions.tsnew file mode 100644index 000000000..47dd5727d--- /dev/null+++ b/editor/src/builder/BuildSettingsActions.ts@@ -0,0 +1,1140 @@+import { icons } from '../utils/icons';+import {+ type BuildPlatform,+ type BuildConfig,+ type EngineModules,+ PLATFORMS,+ ENGINE_MODULE_INFO,+ createDefaultBuildConfig,+ createDefaultEngineModules,+} from '../types/BuildTypes';+import type { BuildHookPhase, BuildHookType, CopyFilesConfig, RunCommandConfig } from '../types/BuildTypes';+import { getEditorContext } from '../context/EditorContext';+import { getEditorStore } from '../store';+import type { BuildOptions } from './BuildService';+import { BuildProgressReporter } from './BuildProgress';+import { showProgressToast, dismissToast, showToast, showSuccessToast, showErrorToast, updateToast } from '../ui/Toast';+import { downloadConfigsAsFile, uploadConfigsFromFile } from './BuildConfigIO';+import { BUILD_TEMPLATES, createConfigFromTemplate, getAllTemplates, configToTemplate, saveUserTemplate, type UserTemplate } from './BuildTemplates';+import { createDefaultHook } from './BuildHooks';+import { discoverProjectScenes } from './SceneDiscovery';+import { getDefaultTemplate, getTemplateRelPath } from './templates';+import { joinPath, getParentDir } from '../utils/path';+import type { BuildSettingsActionContext } from './BuildSettingsDialog';++export function setupEvents(ctx: BuildSettingsActionContext): void {+ if (!ctx.overlay) return;++ ctx.overlay.addEventListener('click', (e) => {+ const target = e.target as HTMLElement;++ if (target.closest('[data-action="close"]')) {+ ctx.close();+ return;+ }++ const platformEl = target.closest('.es-build-platform') as HTMLElement;+ if (platformEl) {+ const platform = platformEl.dataset.platform as BuildPlatform;+ ctx.settings.activePlatform = platform;+ const firstConfig = ctx.settings.configs.find(c => c.platform === platform);+ if (firstConfig) {+ ctx.settings.activeConfigId = firstConfig.id;+ }+ ctx.render();+ return;+ }++ const configEl = target.closest('.es-build-config-item') as HTMLElement;+ if (configEl && !target.closest('[data-action="delete-config"]')) {+ const configId = configEl.dataset.config;+ if (configId) {+ ctx.settings.activeConfigId = configId;+ ctx.render();+ }+ return;+ }++ const collapseHeader = target.closest('.es-build-collapse-header') as HTMLElement;+ if (collapseHeader) {+ const collapse = collapseHeader.closest('.es-build-collapse') as HTMLElement;+ const section = collapse?.dataset.section;+ if (section) {+ if (ctx.expandedSections.has(section)) {+ ctx.expandedSections.delete(section);+ collapse.classList.remove('es-expanded');+ } else {+ ctx.expandedSections.add(section);+ collapse.classList.add('es-expanded');+ }+ const expanded = ctx.expandedSections.has(section);+ const chevron = collapseHeader.querySelector('svg');+ if (chevron) {+ chevron.outerHTML = expanded ? icons.chevronDown(12) : icons.chevronRight(12);+ }+ const inlineContent = collapse.querySelector('[data-template-ref-content]') as HTMLElement;+ if (inlineContent) {+ inlineContent.style.display = expanded ? 'block' : 'none';+ }+ }+ return;+ }++ const actionEl = target.closest('[data-action]') as HTMLElement;+ if (actionEl) {+ const action = actionEl.dataset.action;+ handleAction(ctx, action, actionEl);+ }+ });++ ctx.overlay.addEventListener('change', (e) => {+ const target = e.target as HTMLInputElement | HTMLSelectElement;+ handleInputChange(ctx, target);+ });++ ctx.overlay.addEventListener('input', (e) => {+ const target = e.target as HTMLInputElement;+ if (target.id === 'config-name-input') {+ const config = ctx.getActiveConfig();+ if (config) {+ config.name = target.value;+ ctx.saveSettings();+ }+ }+ });++ ctx.keyHandler = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ ctx.close();+ }++ if ((e.metaKey || e.ctrlKey) && e.key === 'b') {+ e.preventDefault();+ const config = ctx.getActiveConfig();+ if (config) {+ handleBuild(ctx, config);+ }+ }++ if ((e.metaKey || e.ctrlKey) && e.key === 'd') {+ e.preventDefault();+ const config = ctx.getActiveConfig();+ if (config) {+ duplicateConfig(ctx, config);+ }+ }++ if (e.key === 'Delete' || e.key === 'Backspace') {+ const target = e.target as HTMLElement;+ if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA') {+ const config = ctx.getActiveConfig();+ if (config) {+ deleteConfig(ctx, config.id);+ }+ }+ }+ };+ document.addEventListener('keydown', ctx.keyHandler);+}++export async function handleAction(ctx: BuildSettingsActionContext, action: string | undefined, element: HTMLElement): Promise<void> {+ const config = ctx.getActiveConfig();++ switch (action) {+ case 'add-config':+ showAddConfigDialog(ctx);+ break;++ case 'delete-config': {+ const configId = element.dataset.config;+ if (configId) {+ deleteConfig(ctx, configId);+ }+ break;+ }++ case 'duplicate-config':+ if (config) {+ duplicateConfig(ctx, config);+ }+ break;++ case 'save-as-preset':+ if (config) {+ showSavePresetDialog(ctx, config);+ }+ break;++ case 'add-current-scene':+ if (config) {+ const scenePath = getEditorStore().filePath;+ if (scenePath) {+ const relativePath = toRelativePath(ctx, scenePath);+ if (!config.scenes.includes(relativePath)) {+ config.scenes.push(relativePath);+ await ctx.saveSettings();+ ctx.render();+ }+ }+ }+ break;++ case 'remove-scene': {+ const index = parseInt(element.dataset.index ?? '-1', 10);+ if (config && index >= 0) {+ config.scenes.splice(index, 1);+ await ctx.saveSettings();+ ctx.render();+ }+ break;+ }++ case 'add-all-scenes':+ if (config) {+ await addAllScenes(ctx, config);+ }+ break;++ case 'remove-all-scenes':+ if (config) {+ config.scenes = [];+ await ctx.saveSettings();+ ctx.render();+ }+ break;++ case 'show-scene-picker':+ if (config) {+ await showScenePicker(ctx, config);+ }+ break;++ case 'add-define': {+ const input = ctx.overlay.querySelector('#new-define') as HTMLInputElement;+ const value = input?.value.trim();+ if (config && value && !config.defines.includes(value)) {+ config.defines.push(value);+ await ctx.saveSettings();+ ctx.render();+ }+ break;+ }++ case 'remove-define': {+ const index = parseInt(element.dataset.index ?? '-1', 10);+ if (config && index >= 0) {+ config.defines.splice(index, 1);+ await ctx.saveSettings();+ ctx.render();+ }+ break;+ }++ case 'add-hook': {+ if (config) {+ const hookType = element.dataset.hookType as BuildHookType;+ const hookPhase = element.dataset.hookPhase as BuildHookPhase;+ if (!config.hooks) config.hooks = [];+ config.hooks.push(createDefaultHook(hookType, hookPhase));+ await ctx.saveSettings();+ ctx.render();+ }+ break;+ }++ case 'remove-hook': {+ const hookIdx = parseInt(element.dataset.index ?? '-1', 10);+ if (config && config.hooks && hookIdx >= 0) {+ config.hooks.splice(hookIdx, 1);+ await ctx.saveSettings();+ ctx.render();+ }+ break;+ }++ case 'edit-hook': {+ const editIdx = parseInt(element.dataset.index ?? '-1', 10);+ if (config && config.hooks && editIdx >= 0) {+ showEditHookDialog(ctx, config, editIdx);+ }+ break;+ }++ case 'build':+ if (config) {+ const cleanCheckbox = ctx.overlay.querySelector('[data-action="clean-build"]') as HTMLInputElement | null;+ handleBuild(ctx, config, cleanCheckbox?.checked);+ }+ break;++ case 'build-all':+ handleBuildAll(ctx);+ break;++ case 'import-configs':+ handleImportConfigs(ctx);+ break;++ case 'export-configs':+ downloadConfigsAsFile(ctx.settings.configs);+ break;++ case 'show-templates':+ showTemplatesDialog(ctx);+ break;++ case 'open-output': {+ const path = element.dataset.path;+ if (path) {+ openOutputFolder(path);+ }+ break;+ }++ case 'preview-output': {+ const path = element.dataset.path;+ if (path) {+ previewOutput(path);+ }+ break;+ }++ case 'clear-history':+ if (config) {+ ctx.history.clearHistory(config.id);+ await ctx.history.save();+ ctx.render();+ }+ break;++ case 'browse-startup-scene':+ browseFile(ctx, 'playable-startup-scene', 'Scene File', ['scene']);+ break;++ case 'browse-output':+ browseFile(ctx, 'playable-output', 'HTML File', ['html']);+ break;++ case 'browse-emsdk':+ ctx.handleBrowseEmsdk();+ break;++ case 'install-emsdk':+ ctx.handleInstallEmsdk();+ break;++ case 'repair-toolchain':+ ctx.handleRepairToolchain();+ break;++ case 'copy-emsdk-path':+ if (ctx.toolchainStatus?.emsdk_path) {+ navigator.clipboard.writeText(ctx.toolchainStatus.emsdk_path);+ showSuccessToast('Path copied');+ }+ break;++ case 'open-emsdk-folder':+ if (ctx.toolchainStatus?.emsdk_path) {+ const fs = getEditorContext().fs;+ fs?.openFolder(ctx.toolchainStatus.emsdk_path);+ }+ break;++ case 'export-template': {+ const platform = element.dataset.platform as BuildPlatform;+ if (platform) {+ await handleExportTemplate(ctx, platform);+ }+ break;+ }++ case 'open-template': {+ const platform = element.dataset.platform as BuildPlatform;+ if (platform && config) {+ await handleOpenTemplate(ctx, platform, config);+ }+ break;+ }++ case 'reset-template': {+ const platform = element.dataset.platform as BuildPlatform;+ if (platform && config) {+ await handleResetTemplate(ctx, platform, config);+ }+ break;+ }+ }+}++export function handleInputChange(ctx: BuildSettingsActionContext, target: HTMLInputElement | HTMLSelectElement): void {+ const config = ctx.getActiveConfig();+ if (!config) return;++ const id = target.id;++ if (config.playableSettings) {+ if (id === 'playable-startup-scene') {+ config.playableSettings.startupScene = target.value;+ } else if (id === 'playable-dev') {+ config.playableSettings.isDevelopment = (target as HTMLInputElement).checked;+ } else if (id === 'playable-minify') {+ config.playableSettings.minifyCode = (target as HTMLInputElement).checked;+ } else if (id === 'playable-fonts') {+ config.playableSettings.embedFonts = (target as HTMLInputElement).checked;+ } else if (id === 'playable-output') {+ config.playableSettings.outputPath = target.value;+ } else if (id === 'playable-cta') {+ config.playableSettings.enableBuiltinCTA = (target as HTMLInputElement).checked;+ ctx.render();+ } else if (id === 'playable-cta-url') {+ config.playableSettings.ctaUrl = target.value;+ } else if (id === 'playable-template-path') {+ config.playableSettings.templatePath = target.value || undefined;+ }+ }++ if (config.wechatSettings) {+ if (id === 'wechat-appid') {+ config.wechatSettings.appId = target.value;+ } else if (id === 'wechat-version') {+ config.wechatSettings.version = target.value;+ } else if (id === 'wechat-orientation') {+ config.wechatSettings.orientation = target.value as 'portrait' | 'landscape';+ } else if (id === 'wechat-bundle') {+ config.wechatSettings.bundleMode = target.value as 'subpackage' | 'single' | 'singleFile';+ } else if (id === 'wechat-output') {+ config.wechatSettings.outputDir = target.value;+ } else if (id === 'wechat-template-path') {+ config.wechatSettings.templatePath = target.value || undefined;+ }+ }++ const moduleKey = (target as HTMLElement).dataset?.module as keyof EngineModules | undefined;+ if (moduleKey && moduleKey in ENGINE_MODULE_INFO) {+ if (!config.engineModules) {+ config.engineModules = createDefaultEngineModules();+ }+ config.engineModules[moduleKey] = (target as HTMLInputElement).checked;+ }++ ctx.saveSettings();+}++async function browseFile(ctx: BuildSettingsActionContext, inputId: string, title: string, extensions: string[]): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs?.showOpenDialog) return;++ const result = await fs.showOpenDialog({+ title: `Select ${title}`,+ filters: [{ name: title, extensions }],+ });++ if (result && result.length > 0) {+ const input = ctx.overlay.querySelector(`#${inputId}`) as HTMLInputElement;+ if (input) {+ input.value = result[0];+ input.dispatchEvent(new Event('change', { bubbles: true }));+ }+ }+}++export async function handleBuild(ctx: BuildSettingsActionContext, config: BuildConfig, cleanBuild?: boolean): Promise<void> {+ if (!ctx.toolchainStatus?.installed) {+ showErrorToast('Toolchain not ready. Building requires emsdk, CMake and Python.');+ return;+ }++ const buildBtn = ctx.overlay.querySelector('[data-action="build"]') as HTMLButtonElement;+ const buildAllBtn = ctx.overlay.querySelector('[data-action="build-all"]') as HTMLButtonElement;++ if (buildBtn) {+ buildBtn.disabled = true;+ buildBtn.innerHTML = `${icons.refresh(14)} Building...`;+ }+ if (buildAllBtn) {+ buildAllBtn.disabled = true;+ }++ const platformName = getPlatformName(config.platform);+ const toastId = showProgressToast(+ `Building ${config.name}`,+ `Target: ${platformName}`+ );++ const progress = new BuildProgressReporter();+ progress.onProgress((p) => {+ const task = p.currentTask || p.phase;+ updateToast(toastId, {+ message: task,+ progress: p.overallProgress,+ });+ });++ try {+ const result = await ctx.onBuild(config, { progress, cleanBuild });++ dismissToast(toastId);++ if (result.success && result.outputPath) {+ if (result.outputFiles) {+ ctx.lastBuildOutputFiles.set(config.id, result.outputFiles);+ }+ ctx.history.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration: result.duration || 0,+ status: 'success',+ outputPath: result.outputPath,+ outputSize: result.outputSize,+ });+ await ctx.history.save();++ showToast({+ type: 'success',+ title: 'Build Completed',+ message: `Output: ${getFileName(result.outputPath)}`,+ duration: 0,+ actions: [+ {+ label: 'Open Folder',+ primary: true,+ onClick: () => openOutputFolder(result.outputPath!),+ },+ {+ label: 'Close',+ onClick: () => {},+ },+ ],+ });+ } else if (!result.success) {+ ctx.history.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration: result.duration || 0,+ status: 'failed',+ error: result.error,+ });+ await ctx.history.save();++ showToast({+ type: 'error',+ title: 'Build Failed',+ message: result.error || 'Unknown error',+ duration: 5000,+ });+ }++ ctx.render();+ } catch (err) {+ dismissToast(toastId);+ showToast({+ type: 'error',+ title: 'Build Failed',+ message: String(err),+ duration: 5000,+ });+ } finally {+ if (buildBtn) {+ buildBtn.disabled = false;+ buildBtn.innerHTML = `${icons.play(14)} Build`;+ }+ if (buildAllBtn) {+ buildAllBtn.disabled = false;+ }+ }+}++export async function handleBuildAll(ctx: BuildSettingsActionContext): Promise<void> {+ const buildBtn = ctx.overlay.querySelector('[data-action="build"]') as HTMLButtonElement;+ const buildAllBtn = ctx.overlay.querySelector('[data-action="build-all"]') as HTMLButtonElement;++ if (buildBtn) buildBtn.disabled = true;+ if (buildAllBtn) {+ buildAllBtn.disabled = true;+ buildAllBtn.textContent = 'Building...';+ }++ const toastId = showProgressToast(+ 'Building All Configs',+ `0 / ${ctx.settings.configs.length} completed`+ );++ try {+ const result = await ctx.batchBuilder.buildAll(ctx.settings.configs);++ dismissToast(toastId);++ if (result.success) {+ showToast({+ type: 'success',+ title: 'Build All Completed',+ message: `${result.successCount} succeeded, ${result.failureCount} failed`,+ duration: 5000,+ });+ } else {+ showToast({+ type: 'error',+ title: 'Build All Completed with Errors',+ message: `${result.successCount} succeeded, ${result.failureCount} failed`,+ duration: 5000,+ });+ }++ ctx.render();+ } catch (err) {+ dismissToast(toastId);+ showToast({+ type: 'error',+ title: 'Build All Failed',+ message: String(err),+ duration: 5000,+ });+ } finally {+ if (buildBtn) buildBtn.disabled = false;+ if (buildAllBtn) {+ buildAllBtn.disabled = false;+ buildAllBtn.textContent = 'Build All';+ }+ }+}++function showAddConfigDialog(ctx: BuildSettingsActionContext): void {+ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';+ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 320px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Add Build Config</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body">+ <div class="es-dialog-field">+ <label class="es-dialog-label">Config Name</label>+ <input type="text" class="es-dialog-input" id="config-name" placeholder="My Config">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Target Platform</label>+ <select class="es-dialog-input" id="config-platform">+ ${PLATFORMS.map(p => `<option value="${p.id}">${p.name}</option>`).join('')}+ </select>+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="confirm">Create</button>+ </div>+ </div>+ `;++ ctx.overlay.appendChild(dialog);++ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);+ dialog.querySelector('[data-action="confirm"]')?.addEventListener('click', async () => {+ const nameInput = dialog.querySelector('#config-name') as HTMLInputElement;+ const platformSelect = dialog.querySelector('#config-platform') as HTMLSelectElement;+ const name = nameInput.value.trim() || 'New Config';+ const platform = platformSelect.value as BuildPlatform;++ const newConfig = createDefaultBuildConfig(platform, name);+ ctx.settings.configs.push(newConfig);+ ctx.settings.activeConfigId = newConfig.id;+ await ctx.saveSettings();++ close();+ ctx.render();+ });+}++async function showTemplatesDialog(ctx: BuildSettingsActionContext): Promise<void> {+ const fs = getEditorContext().fs;+ const projectDir = ctx.getProjectDir();+ const allTemplates = fs+ ? await getAllTemplates(fs, projectDir)+ : BUILD_TEMPLATES;++ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';++ const builtinHtml = allTemplates+ .filter(t => !(t as UserTemplate).isUserDefined)+ .map(t => `+ <div class="es-build-template-item" data-template="${t.id}">+ <div class="es-build-template-header">+ <span class="es-build-template-name">${t.name}</span>+ <span class="es-build-template-platform">${t.platform}</span>+ </div>+ <div class="es-build-template-desc">${t.description}</div>+ </div>+ `).join('');++ const userTemplates = allTemplates.filter(t => (t as UserTemplate).isUserDefined);+ const userHtml = userTemplates.length > 0+ ? `<div class="es-build-section-title" style="margin-top: 12px;">Custom Presets</div>` ++ userTemplates.map(t => `+ <div class="es-build-template-item" data-template="${t.id}">+ <div class="es-build-template-header">+ <span class="es-build-template-name">${t.name}</span>+ <span class="es-build-template-platform">${t.platform}</span>+ </div>+ <div class="es-build-template-desc">${t.description}</div>+ </div>+ `).join('')+ : '';++ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 400px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Build Templates</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body" style="max-height: 450px; overflow-y: auto;">+ <div class="es-build-section-title">Built-in</div>+ <div class="es-build-templates-list">+ ${builtinHtml}+ ${userHtml}+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ </div>+ </div>+ `;++ ctx.overlay.appendChild(dialog);++ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);++ dialog.querySelectorAll('.es-build-template-item').forEach(item => {+ item.addEventListener('click', async () => {+ const templateId = (item as HTMLElement).dataset.template;+ const template = allTemplates.find(t => t.id === templateId);+ if (template) {+ const newConfig = createConfigFromTemplate(template);+ ctx.settings.configs.push(newConfig);+ ctx.settings.activeConfigId = newConfig.id;+ await ctx.saveSettings();+ close();+ ctx.render();+ }+ });+ });+}++function showSavePresetDialog(ctx: BuildSettingsActionContext, config: BuildConfig): void {+ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';+ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 360px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Save as Preset</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body">+ <div class="es-dialog-field">+ <label class="es-dialog-label">Preset Name</label>+ <input type="text" class="es-dialog-input" id="preset-name" value="${config.name}" placeholder="My Preset">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Description</label>+ <input type="text" class="es-dialog-input" id="preset-desc" placeholder="Brief description...">+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>+ </div>+ </div>+ `;++ ctx.overlay.appendChild(dialog);+ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);+ dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {+ const name = (dialog.querySelector('#preset-name') as HTMLInputElement).value.trim() || config.name;+ const description = (dialog.querySelector('#preset-desc') as HTMLInputElement).value.trim() || '';+ const fs = getEditorContext().fs;+ if (fs) {+ const template = configToTemplate(config, name, description);+ await saveUserTemplate(fs, ctx.getProjectDir(), template);+ showToast({ type: 'success', title: 'Preset Saved', message: `Saved "${name}"`, duration: 3000 });+ }+ close();+ });+}++async function handleImportConfigs(ctx: BuildSettingsActionContext): Promise<void> {+ const result = await uploadConfigsFromFile();++ if (result.success && result.configs.length > 0) {+ for (const config of result.configs) {+ ctx.settings.configs.push(config);+ }+ await ctx.saveSettings();+ ctx.render();++ showToast({+ type: 'success',+ title: 'Import Successful',+ message: `Imported ${result.configs.length} config(s)`,+ duration: 3000,+ });+ } else if (result.errors.length > 0) {+ showToast({+ type: 'error',+ title: 'Import Failed',+ message: result.errors[0],+ duration: 5000,+ });+ }+}++function duplicateConfig(ctx: BuildSettingsActionContext, config: BuildConfig): void {+ const newConfig: BuildConfig = {+ ...JSON.parse(JSON.stringify(config)),+ id: `${config.platform}-${Date.now()}`,+ name: `${config.name} (Copy)`,+ };++ ctx.settings.configs.push(newConfig);+ ctx.settings.activeConfigId = newConfig.id;+ ctx.saveSettings();+ ctx.render();+}++function deleteConfig(ctx: BuildSettingsActionContext, configId: string): void {+ const idx = ctx.settings.configs.findIndex(c => c.id === configId);+ if (idx >= 0) {+ ctx.settings.configs.splice(idx, 1);+ if (ctx.settings.activeConfigId === configId) {+ ctx.settings.activeConfigId = ctx.settings.configs[0]?.id ?? '';+ }+ ctx.saveSettings();+ ctx.render();+ }+}++async function addAllScenes(ctx: BuildSettingsActionContext, config: BuildConfig): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = ctx.getProjectDir();+ const allScenes = await discoverProjectScenes(fs, projectDir);++ let added = 0;+ for (const scene of allScenes) {+ if (!config.scenes.includes(scene)) {+ config.scenes.push(scene);+ added++;+ }+ }++ if (added > 0) {+ await ctx.saveSettings();+ ctx.render();+ showToast({ type: 'info', title: 'Scenes Added', message: `Added ${added} scene(s)`, duration: 2000 });+ } else if (allScenes.length === 0) {+ showToast({ type: 'info', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });+ } else {+ showToast({ type: 'info', title: 'No New Scenes', message: 'All scenes already added', duration: 2000 });+ }+}++async function showScenePicker(ctx: BuildSettingsActionContext, config: BuildConfig): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = ctx.getProjectDir();+ const allScenes = await discoverProjectScenes(fs, projectDir);++ if (allScenes.length === 0) {+ showToast({ type: 'info', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });+ return;+ }++ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';++ const scenesHtml = allScenes.map(s => {+ const isAdded = config.scenes.includes(s);+ return `+ <label class="es-build-scene-picker-item ${isAdded ? 'es-active' : ''}">+ <input type="checkbox" data-scene-path="${s}" ${isAdded ? 'checked' : ''}>+ <span>${s}</span>+ </label>+ `;+ }).join('');++ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 480px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Scene Picker</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body" style="max-height: 400px; overflow-y: auto;">+ <div class="es-build-scene-picker-list">+ ${scenesHtml}+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="apply">Apply</button>+ </div>+ </div>+ `;++ ctx.overlay.appendChild(dialog);++ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);+ dialog.querySelector('[data-action="apply"]')?.addEventListener('click', async () => {+ const checkboxes = dialog.querySelectorAll('input[data-scene-path]') as NodeListOf<HTMLInputElement>;+ const selected: string[] = [];+ checkboxes.forEach(cb => {+ if (cb.checked) {+ selected.push(cb.dataset.scenePath!);+ }+ });++ const existingOrder = config.scenes.filter(s => selected.includes(s));+ const newScenes = selected.filter(s => !existingOrder.includes(s));+ config.scenes = [...existingOrder, ...newScenes];++ await ctx.saveSettings();+ close();+ ctx.render();+ });+}++export function showEditHookDialog(ctx: BuildSettingsActionContext, config: BuildConfig, index: number): void {+ const hook = config.hooks![index];+ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';++ const isCopy = hook.type === 'copy-files';+ const copyConfig = isCopy ? hook.config as CopyFilesConfig : null;+ const cmdConfig = !isCopy ? hook.config as RunCommandConfig : null;++ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 420px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Edit ${isCopy ? 'Copy Files' : 'Run Command'} Hook</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body">+ <div class="es-dialog-field">+ <label class="es-dialog-label">Phase</label>+ <select class="es-dialog-input" id="hook-phase">+ <option value="pre" ${hook.phase === 'pre' ? 'selected' : ''}>Pre-Build</option>+ <option value="post" ${hook.phase === 'post' ? 'selected' : ''}>Post-Build</option>+ </select>+ </div>+ ${isCopy ? `+ <div class="es-dialog-field">+ <label class="es-dialog-label">From Path</label>+ <input type="text" class="es-dialog-input" id="hook-from" value="${copyConfig?.from ?? ''}" placeholder="\${outputDir}">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">To Path</label>+ <input type="text" class="es-dialog-input" id="hook-to" value="${copyConfig?.to ?? ''}" placeholder="/path/to/dest">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Pattern (optional)</label>+ <input type="text" class="es-dialog-input" id="hook-pattern" value="${copyConfig?.pattern ?? ''}" placeholder="*.png">+ </div>+ ` : `+ <div class="es-dialog-field">+ <label class="es-dialog-label">Command</label>+ <input type="text" class="es-dialog-input" id="hook-command" value="${cmdConfig?.command ?? ''}" placeholder="echo">+ </div>+ <div class="es-dialog-field">+ <label class="es-dialog-label">Arguments (space-separated)</label>+ <input type="text" class="es-dialog-input" id="hook-args" value="${(cmdConfig?.args ?? []).join(' ')}" placeholder="arg1 arg2">+ </div>+ `}+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>+ </div>+ </div>+ `;++ ctx.overlay.appendChild(dialog);+ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);+ dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {+ const phase = (dialog.querySelector('#hook-phase') as HTMLSelectElement).value as BuildHookPhase;+ hook.phase = phase;++ if (isCopy) {+ const from = (dialog.querySelector('#hook-from') as HTMLInputElement).value;+ const to = (dialog.querySelector('#hook-to') as HTMLInputElement).value;+ const pattern = (dialog.querySelector('#hook-pattern') as HTMLInputElement).value;+ hook.config = { from, to, ...(pattern ? { pattern } : {}) } as CopyFilesConfig;+ } else {+ const command = (dialog.querySelector('#hook-command') as HTMLInputElement).value;+ const argsStr = (dialog.querySelector('#hook-args') as HTMLInputElement).value.trim();+ const args = argsStr ? argsStr.split(/\s+/) : [];+ hook.config = { command, args } as RunCommandConfig;+ }++ await ctx.saveSettings();+ close();+ ctx.render();+ });+}++export function setupSceneDragAndDrop(ctx: BuildSettingsActionContext): void {+ const dropZone = ctx.overlay?.querySelector('[data-scene-drop-zone]');+ if (!dropZone) return;++ const items = dropZone.querySelectorAll('[data-scene-drag]');+ items.forEach(item => {+ const el = item as HTMLElement;+ el.addEventListener('dragstart', (e: DragEvent) => {+ ctx.dragSourceIndex = parseInt(el.dataset.sceneDrag ?? '-1', 10);+ el.classList.add('es-dragging');+ e.dataTransfer!.effectAllowed = 'move';+ });+ el.addEventListener('dragend', () => {+ el.classList.remove('es-dragging');+ ctx.dragSourceIndex = -1;+ });+ el.addEventListener('dragover', (e: DragEvent) => {+ e.preventDefault();+ e.dataTransfer!.dropEffect = 'move';+ el.classList.add('es-drag-over');+ });+ el.addEventListener('dragleave', () => {+ el.classList.remove('es-drag-over');+ });+ el.addEventListener('drop', async (e: DragEvent) => {+ e.preventDefault();+ el.classList.remove('es-drag-over');+ const targetIndex = parseInt(el.dataset.sceneDrag ?? '-1', 10);+ if (ctx.dragSourceIndex >= 0 && targetIndex >= 0 && ctx.dragSourceIndex !== targetIndex) {+ const config = ctx.getActiveConfig();+ if (config) {+ const [moved] = config.scenes.splice(ctx.dragSourceIndex, 1);+ config.scenes.splice(targetIndex, 0, moved);+ await ctx.saveSettings();+ ctx.render();+ }+ }+ });+ });+}++async function handleExportTemplate(ctx: BuildSettingsActionContext, platform: BuildPlatform): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = ctx.getProjectDir();+ const relPath = getTemplateRelPath(platform);+ const absPath = joinPath(projectDir, relPath);++ if (await fs.exists(absPath)) {+ showToast({ title: `Template already exists: ${relPath}`, type: 'info' });+ return;+ }++ await fs.createDirectory(getParentDir(absPath));+ const ok = await fs.writeFile(absPath, getDefaultTemplate(platform));+ if (ok) {+ showSuccessToast(`Exported to ${relPath}`);+ } else {+ showErrorToast('Failed to export template');+ }+}++async function handleOpenTemplate(ctx: BuildSettingsActionContext, platform: BuildPlatform, config: BuildConfig): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = ctx.getProjectDir();+ const customPath = platform === 'playable'+ ? config.playableSettings?.templatePath+ : config.wechatSettings?.templatePath;+ const relPath = customPath || getTemplateRelPath(platform);+ const absPath = joinPath(projectDir, relPath);++ if (!await fs.exists(absPath)) {+ showToast({ title: `Template not found: ${relPath}. Export it first.`, type: 'info' });+ return;+ }++ await fs.openFolder(getParentDir(absPath));+}++async function handleResetTemplate(ctx: BuildSettingsActionContext, platform: BuildPlatform, config: BuildConfig): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const projectDir = ctx.getProjectDir();+ const absPath = joinPath(projectDir, getTemplateRelPath(platform));++ await fs.removeFile(absPath);++ if (platform === 'playable' && config.playableSettings) {+ config.playableSettings.templatePath = undefined;+ } else if (platform === 'wechat' && config.wechatSettings) {+ config.wechatSettings.templatePath = undefined;+ }++ await ctx.saveSettings();+ ctx.render();+ showSuccessToast('Template reset to default');+}++function toRelativePath(ctx: BuildSettingsActionContext, absolutePath: string): string {+ const normalized = absolutePath.replace(/\\/g, '/');+ const projectDir = ctx.getProjectDir();+ if (normalized.startsWith(projectDir)) {+ return normalized.substring(projectDir.length + 1);+ }+ return normalized;+}++function getFileName(path: string): string {+ const parts = path.replace(/\\/g, '/').split('/');+ return parts[parts.length - 1] || path;+}++async function openOutputFolder(outputPath: string): Promise<void> {+ try {+ const dirPath = outputPath.replace(/\\/g, '/').split('/').slice(0, -1).join('/');+ const fs = getEditorContext().fs;+ if (fs) {+ await fs.openFolder(dirPath);+ }+ } catch (err) {+ console.error('Failed to open folder:', err);+ }+}++async function previewOutput(outputPath: string): Promise<void> {+ try {+ const fs = getEditorContext().fs;+ if (fs?.openFile) {+ await fs.openFile(outputPath);+ }+ } catch (err) {+ console.error('Failed to preview output:', err);+ }+}++function getPlatformName(platform: BuildPlatform): string {+ return PLATFORMS.find(p => p.id === platform)?.name ?? platform;+}diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.tsindex e273b0edf..82e15bf8a 100644--- a/editor/src/builder/BuildSettingsDialog.ts+++ b/editor/src/builder/BuildSettingsDialog.ts@@ -1,40 +1,16 @@-/**- * @file BuildSettingsDialog.ts- * @brief Build settings dialog UI component with three-column layout- */-import { icons } from '../utils/icons';import {- type BuildPlatform,type BuildConfig,type BuildSettings,- type EngineModules,- PLATFORMS,- ENGINE_MODULE_INFO,- createDefaultBuildConfig,createDefaultBuildSettings,- createDefaultEngineModules,} from '../types/BuildTypes';-import { getEditorContext } from '../context/EditorContext';-import { getEditorStore } from '../store';-import { type BuildResult, type BuildOptions } from './BuildService';-import { BuildProgressReporter } from './BuildProgress';-import { showProgressToast, dismissToast, showToast, showSuccessToast, showErrorToast, updateToast } from '../ui/Toast';-import { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';+import type { BuildResult, BuildOptions } from './BuildService';+import { BuildHistory } from './BuildHistory';import { BuildConfigService, initBuildConfigService } from './BuildConfigService';-import { downloadConfigsAsFile, uploadConfigsFromFile } from './BuildConfigIO';-import { BUILD_TEMPLATES, createConfigFromTemplate, getAllTemplates, configToTemplate, saveUserTemplate, type BuildTemplate, type UserTemplate } from './BuildTemplates';import { BatchBuilder } from './BatchBuilder';-import { formatSize } from './BuildProgress';-import { discoverProjectScenes } from './SceneDiscovery';-import { createDefaultHook } from './BuildHooks';-import type { BuildHook, BuildHookPhase, BuildHookType, CopyFilesConfig, RunCommandConfig } from '../types/BuildTypes';-import { getDefaultTemplate, getTemplateRelPath, getTemplatePlaceholderDocs } from './templates';-import { joinPath, getParentDir } from '../utils/path';--// =============================================================================-// Types-// =============================================================================+import { renderSidebar, renderDetail, renderNoConfig, renderOutputPanel } from './BuildSettingsRenderer';+import { setupEvents, setupSceneDragAndDrop } from './BuildSettingsActions';+import { checkToolchainStatus, handleBrowseEmsdk, handleInstallEmsdk, handleRepairToolchain } from './BuildSettingsToolchain';export interface BuildSettingsDialogOptions {projectPath: string;@@ -42,9 +18,51 @@ export interface BuildSettingsDialogOptions {onClose: () => void;}-// =============================================================================-// BuildSettingsDialog-// =============================================================================+export type ToolchainStatus = {+ installed: boolean;+ emsdk_path: string | null;+ emscripten_version: string | null;+ emscripten_ok: boolean;+ cmake_found: boolean;+ cmake_version: string | null;+ cmake_ok: boolean;+ python_found: boolean;+ python_version: string | null;+ python_ok: boolean;+ corrupted: boolean;+ missing_tools: string[];+};++export interface BuildSettingsRenderContext {+ settings: BuildSettings;+ history: BuildHistory;+ expandedSections: Set<string>;+ lastBuildOutputFiles: Map<string, Array<{ path: string; size: number }>>;+ toolchainStatus: ToolchainStatus | null;+ toolchainError: boolean;+}++export interface BuildSettingsToolchainContext {+ overlay: HTMLElement | null;+ toolchainStatus: ToolchainStatus | null;+ toolchainError: boolean;+}++export interface BuildSettingsActionContext extends BuildSettingsRenderContext {+ overlay: HTMLElement;+ batchBuilder: BatchBuilder;+ keyHandler: ((e: KeyboardEvent) => void) | null;+ dragSourceIndex: number;+ render(): void;+ close(): void;+ saveSettings(): Promise<void>;+ getActiveConfig(): BuildConfig | null;+ getProjectDir(): string;+ onBuild: (config: BuildConfig, options?: BuildOptions) => Promise<BuildResult>;+ handleBrowseEmsdk(): void;+ handleInstallEmsdk(): void;+ handleRepairToolchain(): void;+}export class BuildSettingsDialog {constructor(options: BuildSettingsDialogOptions) {@@ -76,8 +94,8 @@ export class BuildSettingsDialog {document.body.appendChild(this.overlay_);this.render();- this.setupEvents();- this.checkToolchainStatus();+ setupEvents(this.createActionContext());+ checkToolchainStatus(this.createToolchainContext());}dispose(): void {@@ -96,10 +114,22 @@ export class BuildSettingsDialog {return this.settings_.configs.find(c => c.id === this.settings_.activeConfigId) ?? null;}+ private getProjectDir(): string {+ const normalized = this.options_.projectPath.replace(/\\/g, '/');+ const lastSlash = normalized.lastIndexOf('/');+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;+ }++ private close(): void {+ this.dispose();+ this.options_.onClose();+ }+private render(): void {if (!this.overlay_) return;const config = this.getActiveConfig();+ const ctx = this.createRenderContext();this.overlay_.innerHTML = `<div class="es-build-dialog es-build-dialog-wide">@@ -136,1887 +166,70 @@ export class BuildSettingsDialog {</div><div class="es-build-body es-build-body-three-col"><div class="es-build-sidebar">- ${this.renderSidebar()}+ ${renderSidebar(ctx)}</div><div class="es-build-detail">- ${config ? this.renderDetail(config) : this.renderNoConfig()}+ ${config ? renderDetail(ctx, config) : renderNoConfig()}</div><div class="es-build-output">- ${config ? this.renderOutputPanel(config) : ''}+ ${config ? renderOutputPanel(ctx, config) : ''}</div></div></div>`;- this.setupSceneDragAndDrop();- }-- private renderSidebar(): string {- const platformsHtml = PLATFORMS.map(p => {- const isActive = this.settings_.activePlatform === p.id;- const configs = this.settings_.configs.filter(c => c.platform === p.id);-- return `- <div class="es-build-platform ${isActive ? 'es-active' : ''}" data-platform="${p.id}">- <div class="es-build-platform-header">- ${icons[p.icon as keyof typeof icons](14)}- <span>${p.name}</span>- ${isActive ? '<span class="es-build-badge">Active</span>' : ''}- </div>- </div>- ${configs.map(c => this.renderConfigItem(c)).join('')}- `;- }).join('');-- return `- <div class="es-build-section-title">Platforms</div>- ${platformsHtml}- `;- }-- private renderConfigItem(config: BuildConfig): string {- const isActive = this.settings_.activeConfigId === config.id;- const latestBuild = this.history_.getLatest(config.id);- const statusIndicator = latestBuild- ? `<span class="es-build-status-dot es-build-status-${latestBuild.status}"></span>`- : '';-- return `- <div class="es-build-config-item ${isActive ? 'es-active' : ''}" data-config="${config.id}">- ${statusIndicator}- <span class="es-build-config-name">${config.name}</span>- <button class="es-btn-icon es-build-config-delete" data-action="delete-config" data-config="${config.id}" title="Delete">- ${icons.x(10)}- </button>- </div>- `;- }-- private renderNoConfig(): string {- return `- <div class="es-build-empty">- <p>No build config selected</p>- <p>Select a config from the left or create a new one</p>- </div>- `;- }-- private renderDetail(config: BuildConfig): string {- return `- <div class="es-build-detail-header">- <div class="es-build-detail-title">- <input type="text" class="es-build-name-input" id="config-name-input"- value="${config.name}" placeholder="Config Name">- <span class="es-build-detail-platform">${this.getPlatformName(config.platform)}</span>- </div>- <div class="es-build-detail-actions">- <button class="es-btn es-btn-icon" data-action="duplicate-config" title="Duplicate">- ${icons.copy(14)}- </button>- <button class="es-btn es-btn-icon" data-action="save-as-preset" title="Save as Preset">- ${icons.download(14)}- </button>- </div>- </div>- <div class="es-build-detail-content">- <div class="es-build-data-section">- ${this.renderScenesSection(config)}- ${this.renderDefinesSection(config)}- ${this.renderEngineModulesSection(config)}- </div>- <div class="es-build-settings-section">- ${this.renderToolchainSection()}- ${this.renderPlatformSettings(config)}- ${this.renderHooksSection(config)}- </div>- </div>- `;- }-- private renderHooksSection(config: BuildConfig): string {- const isExpanded = this.expandedSections_.has('hooks');- const hooks = config.hooks ?? [];-- const hooksHtml = hooks.length > 0- ? hooks.map((h, i) => {- const phaseLabel = h.phase === 'pre' ? 'Pre-Build' : 'Post-Build';- const typeLabel = h.type === 'copy-files' ? 'Copy Files' : 'Run Command';- let detail = '';- if (h.type === 'copy-files') {- const c = h.config as CopyFilesConfig;- detail = `${c.from} → ${c.to}`;- } else {- const c = h.config as RunCommandConfig;- detail = `${c.command} ${(c.args ?? []).join(' ')}`.trim();- }- return `- <div class="es-build-hook-item">- <span class="es-build-badge es-build-badge-small">${phaseLabel}</span>- <span class="es-build-hook-type">${typeLabel}</span>- <span class="es-build-hook-detail" title="${detail}">${detail || '(not configured)'}</span>- <button class="es-btn-icon" data-action="edit-hook" data-index="${i}" title="Edit">- ${icons.pencil(10)}- </button>- <button class="es-btn-icon" data-action="remove-hook" data-index="${i}" title="Remove">- ${icons.x(10)}- </button>- </div>- `;- }).join('')- : '<div class="es-build-empty-list">No hooks configured</div>';-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="hooks">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Build Hooks</span>- <span class="es-build-collapse-count">${hooks.length}</span>- </div>- <div class="es-build-collapse-content">- <div class="es-build-hooks-list">- ${hooksHtml}- </div>- <div class="es-build-hook-actions">- <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="copy-files" data-hook-phase="post">- ${icons.plus(12)} Add Copy Files Hook- </button>- <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="run-command" data-hook-phase="post">- ${icons.plus(12)} Add Run Command Hook- </button>- </div>- </div>- </div>- `;- }-- private renderOutputPanel(config: BuildConfig): string {- const latestBuild = this.history_.getLatest(config.id);- const recentBuilds = this.history_.getEntries(config.id).slice(0, 5);-- const latestSection = latestBuild ? `- <div class="es-build-output-latest">- <div class="es-build-output-stat">- <span class="es-build-output-label">Last Build</span>- <span class="es-build-output-value">${formatBuildTime(latestBuild.timestamp)}</span>- </div>- <div class="es-build-output-stat">- <span class="es-build-output-label">Status</span>- <span class="es-build-output-value es-build-status-${latestBuild.status}">- ${getBuildStatusIcon(latestBuild.status)} ${latestBuild.status}- </span>- </div>- ${latestBuild.outputSize ? `- <div class="es-build-output-stat">- <span class="es-build-output-label">Size</span>- <span class="es-build-output-value">${formatSize(latestBuild.outputSize)}</span>- </div>- ` : ''}- <div class="es-build-output-stat">- <span class="es-build-output-label">Duration</span>- <span class="es-build-output-value">${formatBuildDuration(latestBuild.duration)}</span>- </div>- ${latestBuild.outputPath ? `- <div class="es-build-output-actions">- <button class="es-btn es-btn-small" data-action="open-output" data-path="${latestBuild.outputPath}">- ${icons.folder(12)} Open- </button>- <button class="es-btn es-btn-small" data-action="preview-output" data-path="${latestBuild.outputPath}">- ${icons.play(12)} Preview- </button>- </div>- ` : ''}- </div>- ` : `- <div class="es-build-output-empty">- No builds yet- </div>- `;-- const historySection = recentBuilds.length > 0 ? `- <div class="es-build-history">- <div class="es-build-section-title">Build History</div>- <div class="es-build-history-list">- ${recentBuilds.map(entry => this.renderHistoryEntry(entry)).join('')}- </div>- </div>- ` : '';-- return `- <div class="es-build-output-header">- <span class="es-build-section-title">Build Output</span>- ${recentBuilds.length > 0 ? `- <button class="es-btn-icon" data-action="clear-history" title="Clear History">- ${icons.trash(12)}- </button>- ` : ''}- </div>- ${latestSection}- ${this.renderOutputFiles(config.id)}- ${historySection}- `;- }-- private renderOutputFiles(configId: string): string {- const files = this.lastBuildOutputFiles_.get(configId);- if (!files || files.length === 0) return '';-- const isExpanded = this.expandedSections_.has('output-files');- const sorted = [...files].sort((a, b) => b.size - a.size);- const totalSize = sorted.reduce((sum, f) => sum + f.size, 0);-- const fileItems = sorted.slice(0, 20).map(f => {- const name = f.path.split('/').pop() ?? f.path;- const dir = f.path.substring(0, f.path.length - name.length);- return `- <div class="es-build-file-item">- <span class="es-build-file-icon">${icons.file(10)}</span>- <span class="es-build-file-path" title="${f.path}">${dir ? `<span class="es-build-file-dir">${dir}</span>` : ''}${name}</span>- <span class="es-build-file-size">${formatSize(f.size)}</span>- </div>- `;- }).join('');-- const moreCount = sorted.length - 20;-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="output-files">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Output Files</span>- <span class="es-build-collapse-count">${files.length} files (${formatSize(totalSize)})</span>- </div>- <div class="es-build-collapse-content">- <div class="es-build-file-list">- ${fileItems}- ${moreCount > 0 ? `<div class="es-build-file-more">and ${moreCount} more files...</div>` : ''}- </div>- </div>- </div>- `;- }-- private renderHistoryEntry(entry: BuildHistoryEntry): string {- const time = new Date(entry.timestamp).toLocaleTimeString();- return `- <div class="es-build-history-item es-build-status-${entry.status}">- <span class="es-build-history-icon">${getBuildStatusIcon(entry.status)}</span>- <span class="es-build-history-time">${time}</span>- <span class="es-build-history-duration">${formatBuildDuration(entry.duration)}</span>- </div>- `;- }-- private renderScenesSection(config: BuildConfig): string {- const isExpanded = this.expandedSections_.has('scenes');- const firstScene = config.scenes[0];- const scenesHtml = config.scenes.length > 0- ? config.scenes.map((s, i) => `- <div class="es-build-scene-item" draggable="true" data-scene-drag="${i}">- <span class="es-build-scene-drag-handle">${icons.grip(10)}</span>- ${i === 0 ? '<span class="es-build-badge es-build-badge-small">Startup</span>' : ''}- <span class="es-build-scene-path">${s}</span>- <button class="es-btn-icon" data-action="remove-scene" data-index="${i}">- ${icons.x(10)}- </button>- </div>- `).join('')- : '<div class="es-build-empty-list">No scenes added. Use buttons below to add scenes.</div>';-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="scenes">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Scenes</span>- <span class="es-build-collapse-count">${config.scenes.length}</span>- </div>- <div class="es-build-collapse-content">- <div class="es-build-scene-list" data-scene-drop-zone>- ${scenesHtml}- </div>- <div class="es-build-scene-actions">- <button class="es-btn es-btn-link" data-action="add-current-scene">- ${icons.plus(12)} Add Current Scene- </button>- <button class="es-btn es-btn-link" data-action="add-all-scenes">- ${icons.plus(12)} Add All Scenes- </button>- <button class="es-btn es-btn-link" data-action="show-scene-picker">- ${icons.list(12)} Scene Picker- </button>- ${config.scenes.length > 0 ? `- <button class="es-btn es-btn-link es-btn-danger" data-action="remove-all-scenes">- ${icons.trash(12)} Remove All- </button>- ` : ''}- </div>- </div>- </div>- `;- }-- private renderDefinesSection(config: BuildConfig): string {- const isExpanded = this.expandedSections_.has('defines');- const definesHtml = config.defines.length > 0- ? config.defines.map((d, i) => `- <div class="es-build-define-item">- <span>${d}</span>- <button class="es-btn-icon" data-action="remove-define" data-index="${i}">- ${icons.x(10)}- </button>- </div>- `).join('')- : '';-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="defines">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Script Defines</span>- <span class="es-build-collapse-count">${config.defines.length}</span>- </div>- <div class="es-build-collapse-content">- <div class="es-build-define-list">- ${definesHtml}- </div>- <div class="es-build-define-add">- <input type="text" class="es-input" id="new-define" placeholder="New define...">- <button class="es-btn-icon" data-action="add-define" title="Add">- ${icons.plus(12)}- </button>- </div>- </div>- </div>- `;+ setupSceneDragAndDrop(this.createActionContext());}- private renderPlatformSettings(config: BuildConfig): string {- const isExpanded = this.expandedSections_.has('platform');-- let settingsHtml = '';- if (config.platform === 'playable' && config.playableSettings) {- const s = config.playableSettings;- settingsHtml = `- <div class="es-build-field">- <label class="es-build-label">Startup Scene</label>- <div class="es-build-path-row">- <input type="text" class="es-input" id="playable-startup-scene"- value="${s.startupScene || ''}" placeholder="assets/scenes/main.scene">- <button class="es-btn" data-action="browse-startup-scene">...</button>- </div>- </div>- <div class="es-build-field">- <label>- <input type="checkbox" id="playable-dev" ${s.isDevelopment ? 'checked' : ''}>- Development Build- </label>- </div>- <div class="es-build-field">- <label>- <input type="checkbox" id="playable-minify" ${s.minifyCode ? 'checked' : ''}>- Minify Code- </label>- </div>- <div class="es-build-field">- <label>- <input type="checkbox" id="playable-fonts" ${s.embedFonts ? 'checked' : ''}>- Embed Fonts- </label>- </div>- <div class="es-build-field">- <label class="es-build-label">Output Path</label>- <div class="es-build-path-row">- <input type="text" class="es-input" id="playable-output" value="${s.outputPath}">- <button class="es-btn" data-action="browse-output">...</button>- </div>- </div>- <div class="es-build-field">- <label>- <input type="checkbox" id="playable-cta" ${s.enableBuiltinCTA ? 'checked' : ''}>- Enable Built-in CTA- </label>- </div>- ${s.enableBuiltinCTA ? `- <div class="es-build-field">- <label class="es-build-label">CTA URL</label>- <input type="text" class="es-input" id="playable-cta-url"- value="${s.ctaUrl || ''}" placeholder="https://play.google.com/store/apps/...">- </div>- ` : ''}- ${this.renderTemplateSection('playable', s.templatePath)}- `;- } else if (config.platform === 'wechat' && config.wechatSettings) {- const s = config.wechatSettings;- settingsHtml = `- <div class="es-build-field">- <label class="es-build-label">AppID</label>- <input type="text" class="es-input" id="wechat-appid" value="${s.appId}" placeholder="wx...">- </div>- <div class="es-build-field">- <label class="es-build-label">Version</label>- <input type="text" class="es-input" id="wechat-version" value="${s.version}">- </div>- <div class="es-build-field">- <label class="es-build-label">Screen Orientation</label>- <select class="es-select" id="wechat-orientation">- <option value="portrait" ${(s.orientation || 'portrait') === 'portrait' ? 'selected' : ''}>Portrait</option>- <option value="landscape" ${s.orientation === 'landscape' ? 'selected' : ''}>Landscape</option>- </select>- </div>- <div class="es-build-field">- <label class="es-build-label">Bundle Mode</label>- <select class="es-select" id="wechat-bundle">- <option value="subpackage" ${s.bundleMode === 'subpackage' ? 'selected' : ''}>Subpackage (Recommended)</option>- <option value="single" ${s.bundleMode === 'single' ? 'selected' : ''}>Single Package</option>- <option value="singleFile" ${s.bundleMode === 'singleFile' ? 'selected' : ''}>Single File (Playable Ad)</option>- </select>- </div>- <div class="es-build-field">- <label class="es-build-label">Output Directory</label>- <div class="es-build-path-row">- <input type="text" class="es-input" id="wechat-output" value="${s.outputDir}">- <button class="es-btn" data-action="browse-output">...</button>- </div>- </div>- ${this.renderTemplateSection('wechat', s.templatePath)}- `;- }-- const platformName = config.platform === 'playable' ? 'Playable' : 'WeChat MiniGame';-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="platform">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>${platformName} Settings</span>- </div>- <div class="es-build-collapse-content">- ${settingsHtml}- </div>- </div>- `;- }-- private renderTemplateSection(platform: BuildPlatform, templatePath?: string): string {- const defaultRelPath = getTemplateRelPath(platform);- const placeholders = getTemplatePlaceholderDocs(platform);- const sectionKey = `template-ref-${platform}`;- const isRefExpanded = this.expandedSections_.has(sectionKey);- const placeholderRows = placeholders.map(p =>- `<tr><td style="font-family:monospace;white-space:nowrap;padding:2px 8px 2px 0">{{${p.key}}}</td><td style="padding:2px 0">${p.description}</td></tr>`- ).join('');-- return `- <div class="es-build-field" style="margin-top:8px;padding-top:8px;border-top:1px solid var(--border)">- <label class="es-build-label">Custom Template</label>- <div class="es-build-path-row">- <input type="text" class="es-input" id="${platform}-template-path"- value="${templatePath || ''}" placeholder="${defaultRelPath}">- </div>- <div style="display:flex;gap:4px;margin-top:4px">- <button class="es-btn es-btn-small" data-action="export-template" data-platform="${platform}">Export Default</button>- <button class="es-btn es-btn-small" data-action="open-template" data-platform="${platform}">Open</button>- <button class="es-btn es-btn-small" data-action="reset-template" data-platform="${platform}">Reset</button>- </div>- </div>- <div class="es-build-collapse ${isRefExpanded ? 'es-expanded' : ''}" data-section="${sectionKey}" style="margin-top:4px">- <div class="es-build-collapse-header">- ${isRefExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Placeholders Reference</span>- </div>- <div style="display:${isRefExpanded ? 'block' : 'none'};padding:8px;font-size:11px" data-template-ref-content="${platform}">- <table style="width:100%">${placeholderRows}</table>- </div>- </div>- `;- }-- private renderEngineModulesSection(config: BuildConfig): string {- const isExpanded = this.expandedSections_.has('engine-modules');- const modules = config.engineModules ?? createDefaultEngineModules();- const enabledCount = Object.values(modules).filter(Boolean).length;- const totalCount = Object.keys(ENGINE_MODULE_INFO).length;-- const modulesHtml = (Object.entries(ENGINE_MODULE_INFO) as [keyof EngineModules, { name: string; description: string }][])- .map(([key, info]) => `- <div class="es-build-module-item">- <label>- <input type="checkbox" data-module="${key}" ${modules[key] ? 'checked' : ''}>- <span class="es-build-module-name">${info.name}</span>- </label>- <span class="es-build-module-desc">${info.description}</span>- </div>- `).join('');-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="engine-modules">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Engine Modules</span>- <span class="es-build-collapse-count">${enabledCount}/${totalCount}</span>- </div>- <div class="es-build-collapse-content">- <div class="es-build-module-list">- <div class="es-build-module-item es-build-module-core">- <label>- <input type="checkbox" checked disabled>- <span class="es-build-module-name">Core</span>- </label>- <span class="es-build-module-desc">ECS, Renderer, Sprite, Text</span>- </div>- ${modulesHtml}- </div>- </div>- </div>- `;- }-- private renderToolchainSection(): string {- const isExpanded = this.expandedSections_.has('toolchain');- const s = this.toolchainStatus_;-- let statusBadge: string;- let infoHtml: string;-- if (this.toolchainError_) {- statusBadge = '';- infoHtml = '<span class="es-build-module-desc">Not available in browser mode</span>';- } else if (!s) {- statusBadge = '';- infoHtml = '<span class="es-build-module-desc">Detecting...</span>';- } else if (s.installed) {- statusBadge = '<span class="es-build-toolchain-badge es-ready">Ready</span>';- infoHtml = this.renderToolchainRows(s);- } else {- statusBadge = '<span class="es-build-toolchain-badge es-not-ready">Not ready</span>';- infoHtml = this.renderToolchainRows(s);- }-- return `- <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="toolchain">- <div class="es-build-collapse-header">- ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>Toolchain (emsdk)</span>- ${statusBadge}- </div>- <div class="es-build-collapse-content">- <div class="es-build-toolchain-info">- ${infoHtml}- </div>- <div class="es-build-toolchain-actions">- <button class="es-btn" data-action="browse-emsdk">- ${icons.folder(12)} Select emsdk- </button>- <button class="es-btn" data-action="install-emsdk">- ${icons.download(12)} Auto Install- </button>- </div>- </div>- </div>- `;- }-- private renderToolchainRows(s: NonNullable<typeof this.toolchainStatus_>): string {- const row = (label: string, value: string | null, ok: boolean, minVersion?: string, note?: string) => {- const cls = ok ? '' : ' es-warning';- let display = value ?? 'not found';- if (value && !ok && minVersion) {- display += ` (requires >= ${minVersion})`;- }- if (note) {- display += ` <span class="es-build-module-desc">(${note})</span>`;- }- return `<div class="es-build-toolchain-row${cls}">${label}: ${display}</div>`;+ private createRenderContext(): BuildSettingsRenderContext {+ return {+ settings: this.settings_,+ history: this.history_,+ expandedSections: this.expandedSections_,+ lastBuildOutputFiles: this.lastBuildOutputFiles_,+ toolchainStatus: this.toolchainStatus_,+ toolchainError: this.toolchainError_,};- const rows = [- row('Emscripten', s.emscripten_version ?? (s.emsdk_path ? 'unknown' : null), s.emscripten_ok, '5.0.0'),- row('CMake', s.cmake_version, s.cmake_ok, '3.16', s.cmake_ok ? 'bundled' : undefined),- row('Python', s.python_version, s.python_ok, '3.0', s.python_ok ? 'from emsdk' : undefined),- ];- if (s.corrupted && s.missing_tools?.length) {- rows.push(`<div class="es-build-toolchain-row es-build-row-error" style="color:var(--error-color,#e54);display:flex;align-items:center;gap:8px">- <span>Missing ${s.missing_tools.join(', ')}</span>- <button class="es-btn es-btn-xs" data-action="repair-toolchain" style="flex-shrink:0">${icons.download(12)} Repair</button>- </div>`);- }- if (s.emsdk_path) {- rows.push(`<div class="es-build-toolchain-row" style="opacity:0.6;font-size:0.85em;display:flex;align-items:center;gap:4px">- <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${s.emsdk_path}">Path: ${s.emsdk_path}</span>- <button class="es-btn es-btn-xs" data-action="copy-emsdk-path" title="Copy path" style="flex-shrink:0;padding:1px 4px">${icons.copy(12)}</button>- <button class="es-btn es-btn-xs" data-action="open-emsdk-folder" title="Open folder" style="flex-shrink:0;padding:1px 4px">${icons.folderOpen(12)}</button>- </div>`);- }- return rows.join('');- }-- private getPlatformName(platform: BuildPlatform): string {- return PLATFORMS.find(p => p.id === platform)?.name ?? platform;}- private close(): void {- this.dispose();- this.options_.onClose();- }-- private setupEvents(): void {- if (!this.overlay_) return;-- this.overlay_.addEventListener('click', (e) => {- const target = e.target as HTMLElement;-- if (target.closest('[data-action="close"]')) {- this.close();- return;- }-- const platformEl = target.closest('.es-build-platform') as HTMLElement;- if (platformEl) {- const platform = platformEl.dataset.platform as BuildPlatform;- this.settings_.activePlatform = platform;- const firstConfig = this.settings_.configs.find(c => c.platform === platform);- if (firstConfig) {- this.settings_.activeConfigId = firstConfig.id;- }- this.render();- return;- }-- const configEl = target.closest('.es-build-config-item') as HTMLElement;- if (configEl && !target.closest('[data-action="delete-config"]')) {- const configId = configEl.dataset.config;- if (configId) {- this.settings_.activeConfigId = configId;- this.render();- }- return;- }-- const collapseHeader = target.closest('.es-build-collapse-header') as HTMLElement;- if (collapseHeader) {- const collapse = collapseHeader.closest('.es-build-collapse') as HTMLElement;- const section = collapse?.dataset.section;- if (section) {- if (this.expandedSections_.has(section)) {- this.expandedSections_.delete(section);- collapse.classList.remove('es-expanded');- } else {- this.expandedSections_.add(section);- collapse.classList.add('es-expanded');- }- const expanded = this.expandedSections_.has(section);- const chevron = collapseHeader.querySelector('svg');- if (chevron) {- chevron.outerHTML = expanded ? icons.chevronDown(12) : icons.chevronRight(12);- }- const inlineContent = collapse.querySelector('[data-template-ref-content]') as HTMLElement;- if (inlineContent) {- inlineContent.style.display = expanded ? 'block' : 'none';- }- }- return;- }-- const actionEl = target.closest('[data-action]') as HTMLElement;- if (actionEl) {- const action = actionEl.dataset.action;- this.handleAction(action, actionEl);- }- });-- this.overlay_.addEventListener('change', (e) => {- const target = e.target as HTMLInputElement | HTMLSelectElement;- this.handleInputChange(target);- });-- this.overlay_.addEventListener('input', (e) => {- const target = e.target as HTMLInputElement;- if (target.id === 'config-name-input') {- const config = this.getActiveConfig();- if (config) {- config.name = target.value;- this.saveSettings();- }- }- });-- this.keyHandler_ = (e: KeyboardEvent) => {- if (e.key === 'Escape') {- this.close();- }-- if ((e.metaKey || e.ctrlKey) && e.key === 'b') {- e.preventDefault();- const config = this.getActiveConfig();- if (config) {- this.handleBuild(config);- }- }-- if ((e.metaKey || e.ctrlKey) && e.key === 'd') {- e.preventDefault();- const config = this.getActiveConfig();- if (config) {- this.duplicateConfig(config);- }- }-- if (e.key === 'Delete' || e.key === 'Backspace') {- const target = e.target as HTMLElement;- if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA') {- const config = this.getActiveConfig();- if (config) {- this.deleteConfig(config.id);- }- }- }+ private createToolchainContext(): BuildSettingsToolchainContext {+ const self = this;+ return {+ get overlay() { return self.overlay_; },+ get toolchainStatus() { return self.toolchainStatus_; },+ set toolchainStatus(v) { self.toolchainStatus_ = v; },+ get toolchainError() { return self.toolchainError_; },+ set toolchainError(v) { self.toolchainError_ = v; },};- document.addEventListener('keydown', this.keyHandler_);- }-- private async handleAction(action: string | undefined, element: HTMLElement): Promise<void> {- const config = this.getActiveConfig();-- switch (action) {- case 'add-config':- this.showAddConfigDialog();- break;-- case 'delete-config': {- const configId = element.dataset.config;- if (configId) {- this.deleteConfig(configId);- }- break;- }-- case 'duplicate-config':- if (config) {- this.duplicateConfig(config);- }- break;-- case 'save-as-preset':- if (config) {- this.showSavePresetDialog(config);- }- break;-- case 'add-current-scene':- if (config) {- const scenePath = getEditorStore().filePath;- if (scenePath) {- const relativePath = this.toRelativePath(scenePath);- if (!config.scenes.includes(relativePath)) {- config.scenes.push(relativePath);- await this.saveSettings();- this.render();- }- }- }- break;-- case 'remove-scene': {- const index = parseInt(element.dataset.index ?? '-1', 10);- if (config && index >= 0) {- config.scenes.splice(index, 1);- await this.saveSettings();- this.render();- }- break;- }-- case 'add-all-scenes':- if (config) {- await this.addAllScenes(config);- }- break;-- case 'remove-all-scenes':- if (config) {- config.scenes = [];- await this.saveSettings();- this.render();- }- break;-- case 'show-scene-picker':- if (config) {- await this.showScenePicker(config);- }- break;-- case 'add-define': {- const input = this.overlay_.querySelector('#new-define') as HTMLInputElement;- const value = input?.value.trim();- if (config && value && !config.defines.includes(value)) {- config.defines.push(value);- await this.saveSettings();- this.render();- }- break;- }-- case 'remove-define': {- const index = parseInt(element.dataset.index ?? '-1', 10);- if (config && index >= 0) {- config.defines.splice(index, 1);- await this.saveSettings();- this.render();- }- break;- }-- case 'add-hook': {- if (config) {- const hookType = element.dataset.hookType as BuildHookType;- const hookPhase = element.dataset.hookPhase as BuildHookPhase;- if (!config.hooks) config.hooks = [];- config.hooks.push(createDefaultHook(hookType, hookPhase));- await this.saveSettings();- this.render();- }- break;- }-- case 'remove-hook': {- const hookIdx = parseInt(element.dataset.index ?? '-1', 10);- if (config && config.hooks && hookIdx >= 0) {- config.hooks.splice(hookIdx, 1);- await this.saveSettings();- this.render();- }- break;- }-- case 'edit-hook': {- const editIdx = parseInt(element.dataset.index ?? '-1', 10);- if (config && config.hooks && editIdx >= 0) {- this.showEditHookDialog(config, editIdx);- }- break;- }-- case 'build':- if (config) {- const cleanCheckbox = this.overlay_.querySelector('[data-action="clean-build"]') as HTMLInputElement | null;- this.handleBuild(config, cleanCheckbox?.checked);- }- break;-- case 'build-all':- this.handleBuildAll();- break;-- case 'import-configs':- this.handleImportConfigs();- break;-- case 'export-configs':- downloadConfigsAsFile(this.settings_.configs);- break;-- case 'show-templates':- this.showTemplatesDialog();- break;-- case 'open-output': {- const path = element.dataset.path;- if (path) {- this.openOutputFolder(path);- }- break;- }-- case 'preview-output': {- const path = element.dataset.path;- if (path) {- this.previewOutput(path);- }- break;- }-- case 'clear-history':- if (config) {- this.history_.clearHistory(config.id);- await this.history_.save();- this.render();- }- break;-- case 'browse-startup-scene':- this.browseFile('playable-startup-scene', 'Scene File', ['scene']);- break;-- case 'browse-output':- this.browseFile('playable-output', 'HTML File', ['html']);- break;-- case 'browse-emsdk':- this.handleBrowseEmsdk();- break;-- case 'install-emsdk':- this.handleInstallEmsdk();- break;-- case 'repair-toolchain':- this.handleRepairToolchain();- break;-- case 'copy-emsdk-path':- if (this.toolchainStatus_?.emsdk_path) {- navigator.clipboard.writeText(this.toolchainStatus_.emsdk_path);- showSuccessToast('Path copied');- }- break;-- case 'open-emsdk-folder':- if (this.toolchainStatus_?.emsdk_path) {- const fs = getEditorContext().fs;- fs?.openFolder(this.toolchainStatus_.emsdk_path);- }- break;-- case 'export-template': {- const platform = element.dataset.platform as BuildPlatform;- if (platform) {- await this.handleExportTemplate(platform);- }- break;- }-- case 'open-template': {- const platform = element.dataset.platform as BuildPlatform;- if (platform && config) {- await this.handleOpenTemplate(platform, config);- }- break;- }-- case 'reset-template': {- const platform = element.dataset.platform as BuildPlatform;- if (platform && config) {- await this.handleResetTemplate(platform, config);- }- break;- }- }- }-- private async browseFile(inputId: string, title: string, extensions: string[]): Promise<void> {- const fs = getEditorContext().fs;- if (!fs?.showOpenDialog) return;-- const result = await fs.showOpenDialog({- title: `Select ${title}`,- filters: [{ name: title, extensions }],- });-- if (result && result.length > 0) {- const input = this.overlay_.querySelector(`#${inputId}`) as HTMLInputElement;- if (input) {- input.value = result[0];- input.dispatchEvent(new Event('change', { bubbles: true }));- }- }- }-- private handleInputChange(target: HTMLInputElement | HTMLSelectElement): void {- const config = this.getActiveConfig();- if (!config) return;-- const id = target.id;-- if (config.playableSettings) {- if (id === 'playable-startup-scene') {- config.playableSettings.startupScene = target.value;- } else if (id === 'playable-dev') {- config.playableSettings.isDevelopment = (target as HTMLInputElement).checked;- } else if (id === 'playable-minify') {- config.playableSettings.minifyCode = (target as HTMLInputElement).checked;- } else if (id === 'playable-fonts') {- config.playableSettings.embedFonts = (target as HTMLInputElement).checked;- } else if (id === 'playable-output') {- config.playableSettings.outputPath = target.value;- } else if (id === 'playable-cta') {- config.playableSettings.enableBuiltinCTA = (target as HTMLInputElement).checked;- this.render();- } else if (id === 'playable-cta-url') {- config.playableSettings.ctaUrl = target.value;- } else if (id === 'playable-template-path') {- config.playableSettings.templatePath = target.value || undefined;- }- }-- if (config.wechatSettings) {- if (id === 'wechat-appid') {- config.wechatSettings.appId = target.value;- } else if (id === 'wechat-version') {- config.wechatSettings.version = target.value;- } else if (id === 'wechat-orientation') {- config.wechatSettings.orientation = target.value as 'portrait' | 'landscape';- } else if (id === 'wechat-bundle') {- config.wechatSettings.bundleMode = target.value as 'subpackage' | 'single' | 'singleFile';- } else if (id === 'wechat-output') {- config.wechatSettings.outputDir = target.value;- } else if (id === 'wechat-template-path') {- config.wechatSettings.templatePath = target.value || undefined;- }- }-- // Engine module checkboxes- const moduleKey = (target as HTMLElement).dataset?.module as keyof EngineModules | undefined;- if (moduleKey && moduleKey in ENGINE_MODULE_INFO) {- if (!config.engineModules) {- config.engineModules = createDefaultEngineModules();- }- config.engineModules[moduleKey] = (target as HTMLInputElement).checked;- }-- this.saveSettings();- }-- private async checkToolchainStatus(): Promise<void> {- try {- const { invoke } = await import('@tauri-apps/api/core');- this.toolchainStatus_ = await invoke('get_toolchain_status');- this.toolchainError_ = false;- } catch {- this.toolchainStatus_ = null;- this.toolchainError_ = true;- }- this.updateToolchainUI();}- private updateToolchainUI(): void {- const section = this.overlay_?.querySelector('[data-section="toolchain"]');- if (!section) return;-- const s = this.toolchainStatus_;- const header = section.querySelector('.es-build-collapse-header');- const badgeEl = section.querySelector('.es-build-toolchain-badge');- const infoEl = section.querySelector('.es-build-toolchain-info');-- if (this.toolchainError_) {- if (badgeEl) badgeEl.remove();- if (infoEl) infoEl.innerHTML = '<span class="es-build-module-desc">Not available in browser mode</span>';- return;- }-- if (!s) {- if (infoEl) infoEl.innerHTML = '<span class="es-build-module-desc">Detecting...</span>';- return;- }-- const badgeClass = s.installed ? 'es-ready' : 'es-not-ready';- const badgeText = s.installed ? 'Ready' : 'Not ready';-- if (badgeEl) {- badgeEl.className = `es-build-toolchain-badge ${badgeClass}`;- badgeEl.textContent = badgeText;- } else if (header) {- header.insertAdjacentHTML('beforeend', `<span class="es-build-toolchain-badge ${badgeClass}">${badgeText}</span>`);- }-- if (infoEl) {- infoEl.innerHTML = this.renderToolchainRows(s);- }-- this.updateBuildButtonState();- }-- private updateBuildButtonState(): void {- const ready = !!this.toolchainStatus_?.installed;- const buildBtn = this.overlay_?.querySelector('[data-action="build"]') as HTMLButtonElement | null;- const buildAllBtn = this.overlay_?.querySelector('[data-action="build-all"]') as HTMLButtonElement | null;- if (buildBtn) {- buildBtn.disabled = !ready;- buildBtn.title = ready ? '' : 'Toolchain not ready';- }- if (buildAllBtn) {- buildAllBtn.disabled = !ready;- buildAllBtn.title = ready ? 'Build All Configs' : 'Toolchain not ready';- }- }-- private async handleBrowseEmsdk(): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const selected = await fs.selectDirectory();- if (!selected) return;-- try {- const { invoke } = await import('@tauri-apps/api/core');- await invoke('set_emsdk_path', { path: selected });- showSuccessToast('emsdk path set');- await this.checkToolchainStatus();- } catch (err: any) {- showErrorToast(err.toString());- }- }-- private async handleInstallEmsdk(): Promise<void> {- const toastId = showProgressToast('Downloading toolchain...');- let unlisten: (() => void) | undefined;- try {- const { invoke } = await import('@tauri-apps/api/core');- const { listen } = await import('@tauri-apps/api/event');- unlisten = await listen<{ stage: string; message: string; progress: number }>('compile-progress', (event) => {- updateToast(toastId, {- message: event.payload.message,- progress: event.payload.progress,- });- });- await invoke('install_emsdk');- dismissToast(toastId);- showSuccessToast('Toolchain installed');- await this.checkToolchainStatus();- } catch (err: any) {- dismissToast(toastId);- showErrorToast(`Install failed: ${err}`);- } finally {- unlisten?.();- }- }-- private async handleRepairToolchain(): Promise<void> {- const toastId = showProgressToast('Repairing toolchain...');- let unlisten: (() => void) | undefined;- try {- const { invoke } = await import('@tauri-apps/api/core');- const { listen } = await import('@tauri-apps/api/event');- unlisten = await listen<{ stage: string; message: string; progress: number }>('compile-progress', (event) => {- updateToast(toastId, {- message: event.payload.message,- progress: event.payload.progress,- });- });- await invoke('repair_toolchain');- dismissToast(toastId);- showSuccessToast('Toolchain repaired');- await this.checkToolchainStatus();- } catch (err: any) {- dismissToast(toastId);- showErrorToast(`Repair failed: ${err}`);- } finally {- unlisten?.();- }- }-- private showAddConfigDialog(): void {- const dialog = document.createElement('div');- dialog.className = 'es-build-add-dialog';- dialog.innerHTML = `- <div class="es-dialog" style="max-width: 320px;">- <div class="es-dialog-header">- <span class="es-dialog-title">Add Build Config</span>- <button class="es-dialog-close" data-action="cancel">×</button>- </div>- <div class="es-dialog-body">- <div class="es-dialog-field">- <label class="es-dialog-label">Config Name</label>- <input type="text" class="es-dialog-input" id="config-name" placeholder="My Config">- </div>- <div class="es-dialog-field">- <label class="es-dialog-label">Target Platform</label>- <select class="es-dialog-input" id="config-platform">- ${PLATFORMS.map(p => `<option value="${p.id}">${p.name}</option>`).join('')}- </select>- </div>- </div>- <div class="es-dialog-footer">- <button class="es-dialog-btn" data-action="cancel">Cancel</button>- <button class="es-dialog-btn es-dialog-btn-primary" data-action="confirm">Create</button>- </div>- </div>- `;-- this.overlay_.appendChild(dialog);-- const close = () => dialog.remove();-- dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);- dialog.querySelector('[data-action="confirm"]')?.addEventListener('click', async () => {- const nameInput = dialog.querySelector('#config-name') as HTMLInputElement;- const platformSelect = dialog.querySelector('#config-platform') as HTMLSelectElement;- const name = nameInput.value.trim() || 'New Config';- const platform = platformSelect.value as BuildPlatform;-- const newConfig = createDefaultBuildConfig(platform, name);- this.settings_.configs.push(newConfig);- this.settings_.activeConfigId = newConfig.id;- await this.saveSettings();-- close();- this.render();- });- }-- private async showTemplatesDialog(): Promise<void> {- const fs = getEditorContext().fs;- const projectDir = this.getProjectDir();- const allTemplates = fs- ? await getAllTemplates(fs, projectDir)- : BUILD_TEMPLATES;-- const dialog = document.createElement('div');- dialog.className = 'es-build-add-dialog';-- const builtinHtml = allTemplates- .filter(t => !(t as UserTemplate).isUserDefined)- .map(t => `- <div class="es-build-template-item" data-template="${t.id}">- <div class="es-build-template-header">- <span class="es-build-template-name">${t.name}</span>- <span class="es-build-template-platform">${t.platform}</span>- </div>- <div class="es-build-template-desc">${t.description}</div>- </div>- `).join('');-- const userTemplates = allTemplates.filter(t => (t as UserTemplate).isUserDefined);- const userHtml = userTemplates.length > 0- ? `<div class="es-build-section-title" style="margin-top: 12px;">Custom Presets</div>` +- userTemplates.map(t => `- <div class="es-build-template-item" data-template="${t.id}">- <div class="es-build-template-header">- <span class="es-build-template-name">${t.name}</span>- <span class="es-build-template-platform">${t.platform}</span>- </div>- <div class="es-build-template-desc">${t.description}</div>- </div>- `).join('')- : '';-- dialog.innerHTML = `- <div class="es-dialog" style="max-width: 400px;">- <div class="es-dialog-header">- <span class="es-dialog-title">Build Templates</span>- <button class="es-dialog-close" data-action="cancel">×</button>- </div>- <div class="es-dialog-body" style="max-height: 450px; overflow-y: auto;">- <div class="es-build-section-title">Built-in</div>- <div class="es-build-templates-list">- ${builtinHtml}- ${userHtml}- </div>- </div>- <div class="es-dialog-footer">- <button class="es-dialog-btn" data-action="cancel">Cancel</button>- </div>- </div>- `;-- this.overlay_.appendChild(dialog);-- const close = () => dialog.remove();-- dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);-- dialog.querySelectorAll('.es-build-template-item').forEach(item => {- item.addEventListener('click', async () => {- const templateId = (item as HTMLElement).dataset.template;- const template = allTemplates.find(t => t.id === templateId);- if (template) {- const newConfig = createConfigFromTemplate(template);- this.settings_.configs.push(newConfig);- this.settings_.activeConfigId = newConfig.id;- await this.saveSettings();- close();- this.render();- }- });- });- }-- private showSavePresetDialog(config: BuildConfig): void {- const dialog = document.createElement('div');- dialog.className = 'es-build-add-dialog';- dialog.innerHTML = `- <div class="es-dialog" style="max-width: 360px;">- <div class="es-dialog-header">- <span class="es-dialog-title">Save as Preset</span>- <button class="es-dialog-close" data-action="cancel">×</button>- </div>- <div class="es-dialog-body">- <div class="es-dialog-field">- <label class="es-dialog-label">Preset Name</label>- <input type="text" class="es-dialog-input" id="preset-name" value="${config.name}" placeholder="My Preset">- </div>- <div class="es-dialog-field">- <label class="es-dialog-label">Description</label>- <input type="text" class="es-dialog-input" id="preset-desc" placeholder="Brief description...">- </div>- </div>- <div class="es-dialog-footer">- <button class="es-dialog-btn" data-action="cancel">Cancel</button>- <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>- </div>- </div>- `;-- this.overlay_.appendChild(dialog);- const close = () => dialog.remove();-- dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);- dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {- const name = (dialog.querySelector('#preset-name') as HTMLInputElement).value.trim() || config.name;- const description = (dialog.querySelector('#preset-desc') as HTMLInputElement).value.trim() || '';- const fs = getEditorContext().fs;- if (fs) {- const template = configToTemplate(config, name, description);- await saveUserTemplate(fs, this.getProjectDir(), template);- showToast({ type: 'success', title: 'Preset Saved', message: `Saved "${name}"`, duration: 3000 });- }- close();- });- }-- private async handleImportConfigs(): Promise<void> {- const result = await uploadConfigsFromFile();-- if (result.success && result.configs.length > 0) {- for (const config of result.configs) {- this.settings_.configs.push(config);- }- await this.saveSettings();- this.render();-- showToast({- type: 'success',- title: 'Import Successful',- message: `Imported ${result.configs.length} config(s)`,- duration: 3000,- });- } else if (result.errors.length > 0) {- showToast({- type: 'error',- title: 'Import Failed',- message: result.errors[0],- duration: 5000,- });- }- }-- private duplicateConfig(config: BuildConfig): void {- const newConfig: BuildConfig = {- ...JSON.parse(JSON.stringify(config)),- id: `${config.platform}-${Date.now()}`,- name: `${config.name} (Copy)`,+ private createActionContext(): BuildSettingsActionContext {+ const self = this;+ return {+ get settings() { return self.settings_; },+ get history() { return self.history_; },+ get expandedSections() { return self.expandedSections_; },+ get lastBuildOutputFiles() { return self.lastBuildOutputFiles_; },+ get toolchainStatus() { return self.toolchainStatus_; },+ get toolchainError() { return self.toolchainError_; },+ get overlay() { return self.overlay_; },+ get batchBuilder() { return self.batchBuilder_; },+ get keyHandler() { return self.keyHandler_; },+ set keyHandler(v) { self.keyHandler_ = v; },+ get dragSourceIndex() { return self.dragSourceIndex_; },+ set dragSourceIndex(v) { self.dragSourceIndex_ = v; },+ render: () => self.render(),+ close: () => self.close(),+ saveSettings: () => self.saveSettings(),+ getActiveConfig: () => self.getActiveConfig(),+ getProjectDir: () => self.getProjectDir(),+ onBuild: (config, options) => self.options_.onBuild(config, options),+ handleBrowseEmsdk: () => handleBrowseEmsdk(self.createToolchainContext()),+ handleInstallEmsdk: () => handleInstallEmsdk(self.createToolchainContext()),+ handleRepairToolchain: () => handleRepairToolchain(self.createToolchainContext()),};-- this.settings_.configs.push(newConfig);- this.settings_.activeConfigId = newConfig.id;- this.saveSettings();- this.render();}- private deleteConfig(configId: string): void {- const idx = this.settings_.configs.findIndex(c => c.id === configId);- if (idx >= 0) {- this.settings_.configs.splice(idx, 1);- if (this.settings_.activeConfigId === configId) {- this.settings_.activeConfigId = this.settings_.configs[0]?.id ?? '';- }- this.saveSettings();- this.render();- }- }-- private async handleBuild(config: BuildConfig, cleanBuild?: boolean): Promise<void> {- if (!this.toolchainStatus_?.installed) {- showErrorToast('Toolchain not ready. Building requires emsdk, CMake and Python.');- return;- }-- const buildBtn = this.overlay_.querySelector('[data-action="build"]') as HTMLButtonElement;- const buildAllBtn = this.overlay_.querySelector('[data-action="build-all"]') as HTMLButtonElement;-- if (buildBtn) {- buildBtn.disabled = true;- buildBtn.innerHTML = `${icons.refresh(14)} Building...`;- }- if (buildAllBtn) {- buildAllBtn.disabled = true;- }-- const platformName = this.getPlatformName(config.platform);- const toastId = showProgressToast(- `Building ${config.name}`,- `Target: ${platformName}`- );-- const progress = new BuildProgressReporter();- progress.onProgress((p) => {- const task = p.currentTask || p.phase;- updateToast(toastId, {- message: task,- progress: p.overallProgress,- });- });-- try {- const result = await this.options_.onBuild(config, { progress, cleanBuild });-- dismissToast(toastId);-- if (result.success && result.outputPath) {- if (result.outputFiles) {- this.lastBuildOutputFiles_.set(config.id, result.outputFiles);- }- this.history_.addEntry({- configId: config.id,- configName: config.name,- platform: config.platform,- timestamp: Date.now(),- duration: result.duration || 0,- status: 'success',- outputPath: result.outputPath,- outputSize: result.outputSize,- });- await this.history_.save();-- showToast({- type: 'success',- title: 'Build Completed',- message: `Output: ${this.getFileName(result.outputPath)}`,- duration: 0,- actions: [- {- label: 'Open Folder',- primary: true,- onClick: () => this.openOutputFolder(result.outputPath!),- },- {- label: 'Close',- onClick: () => {},- },- ],- });- } else if (!result.success) {- this.history_.addEntry({- configId: config.id,- configName: config.name,- platform: config.platform,- timestamp: Date.now(),- duration: result.duration || 0,- status: 'failed',- error: result.error,- });- await this.history_.save();-- showToast({- type: 'error',- title: 'Build Failed',- message: result.error || 'Unknown error',- duration: 5000,- });- }-- this.render();- } catch (err) {- dismissToast(toastId);- showToast({- type: 'error',- title: 'Build Failed',- message: String(err),- duration: 5000,- });- } finally {- if (buildBtn) {- buildBtn.disabled = false;- buildBtn.innerHTML = `${icons.play(14)} Build`;- }- if (buildAllBtn) {- buildAllBtn.disabled = false;- }- }- }-- private async handleBuildAll(): Promise<void> {- const buildBtn = this.overlay_.querySelector('[data-action="build"]') as HTMLButtonElement;- const buildAllBtn = this.overlay_.querySelector('[data-action="build-all"]') as HTMLButtonElement;-- if (buildBtn) buildBtn.disabled = true;- if (buildAllBtn) {- buildAllBtn.disabled = true;- buildAllBtn.textContent = 'Building...';- }-- const toastId = showProgressToast(- 'Building All Configs',- `0 / ${this.settings_.configs.length} completed`- );-- try {- const result = await this.batchBuilder_.buildAll(this.settings_.configs);-- dismissToast(toastId);-- if (result.success) {- showToast({- type: 'success',- title: 'Build All Completed',- message: `${result.successCount} succeeded, ${result.failureCount} failed`,- duration: 5000,- });- } else {- showToast({- type: 'error',- title: 'Build All Completed with Errors',- message: `${result.successCount} succeeded, ${result.failureCount} failed`,- duration: 5000,- });- }-- this.render();- } catch (err) {- dismissToast(toastId);- showToast({- type: 'error',- title: 'Build All Failed',- message: String(err),- duration: 5000,- });- } finally {- if (buildBtn) buildBtn.disabled = false;- if (buildAllBtn) {- buildAllBtn.disabled = false;- buildAllBtn.textContent = 'Build All';- }- }- }-- private getFileName(path: string): string {- const parts = path.replace(/\\/g, '/').split('/');- return parts[parts.length - 1] || path;- }-- private toRelativePath(absolutePath: string): string {- const normalized = absolutePath.replace(/\\/g, '/');- const projectDir = this.getProjectDir();- if (normalized.startsWith(projectDir)) {- return normalized.substring(projectDir.length + 1);- }- return normalized;- }-- private getProjectDir(): string {- const normalized = this.options_.projectPath.replace(/\\/g, '/');- const lastSlash = normalized.lastIndexOf('/');- return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;- }-- private async openOutputFolder(outputPath: string): Promise<void> {- try {- const dirPath = outputPath.replace(/\\/g, '/').split('/').slice(0, -1).join('/');- const fs = getEditorContext().fs;- if (fs) {- await fs.openFolder(dirPath);- }- } catch (err) {- console.error('Failed to open folder:', err);- }- }-- private async previewOutput(outputPath: string): Promise<void> {- try {- const fs = getEditorContext().fs;- if (fs?.openFile) {- await fs.openFile(outputPath);- }- } catch (err) {- console.error('Failed to preview output:', err);- }- }-- // =========================================================================- // Template Management- // =========================================================================-- private async handleExportTemplate(platform: BuildPlatform): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const projectDir = this.getProjectDir();- const relPath = getTemplateRelPath(platform);- const absPath = joinPath(projectDir, relPath);-- if (await fs.exists(absPath)) {- showToast({ title: `Template already exists: ${relPath}`, type: 'info' });- return;- }-- await fs.createDirectory(getParentDir(absPath));- const ok = await fs.writeFile(absPath, getDefaultTemplate(platform));- if (ok) {- showSuccessToast(`Exported to ${relPath}`);- } else {- showErrorToast('Failed to export template');- }- }-- private async handleOpenTemplate(platform: BuildPlatform, config: BuildConfig): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const projectDir = this.getProjectDir();- const customPath = platform === 'playable'- ? config.playableSettings?.templatePath- : config.wechatSettings?.templatePath;- const relPath = customPath || getTemplateRelPath(platform);- const absPath = joinPath(projectDir, relPath);-- if (!await fs.exists(absPath)) {- showToast({ title: `Template not found: ${relPath}. Export it first.`, type: 'info' });- return;- }-- await fs.openFolder(getParentDir(absPath));- }-- private async handleResetTemplate(platform: BuildPlatform, config: BuildConfig): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const projectDir = this.getProjectDir();- const absPath = joinPath(projectDir, getTemplateRelPath(platform));-- await fs.removeFile(absPath);-- if (platform === 'playable' && config.playableSettings) {- config.playableSettings.templatePath = undefined;- } else if (platform === 'wechat' && config.wechatSettings) {- config.wechatSettings.templatePath = undefined;- }-- await this.saveSettings();- this.render();- showSuccessToast('Template reset to default');- }-- // =========================================================================- // Scene Management- // =========================================================================-- private async addAllScenes(config: BuildConfig): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const projectDir = this.getProjectDir();- const allScenes = await discoverProjectScenes(fs, projectDir);-- let added = 0;- for (const scene of allScenes) {- if (!config.scenes.includes(scene)) {- config.scenes.push(scene);- added++;- }- }-- if (added > 0) {- await this.saveSettings();- this.render();- showToast({ type: 'info', title: 'Scenes Added', message: `Added ${added} scene(s)`, duration: 2000 });- } else if (allScenes.length === 0) {- showToast({ type: 'info', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });- } else {- showToast({ type: 'info', title: 'No New Scenes', message: 'All scenes already added', duration: 2000 });- }- }-- private async showScenePicker(config: BuildConfig): Promise<void> {- const fs = getEditorContext().fs;- if (!fs) return;-- const projectDir = this.getProjectDir();- const allScenes = await discoverProjectScenes(fs, projectDir);-- if (allScenes.length === 0) {- showToast({ type: 'info', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });- return;- }-- const dialog = document.createElement('div');- dialog.className = 'es-build-add-dialog';-- const scenesHtml = allScenes.map(s => {- const isAdded = config.scenes.includes(s);- return `- <label class="es-build-scene-picker-item ${isAdded ? 'es-active' : ''}">- <input type="checkbox" data-scene-path="${s}" ${isAdded ? 'checked' : ''}>- <span>${s}</span>- </label>- `;- }).join('');-- dialog.innerHTML = `- <div class="es-dialog" style="max-width: 480px;">- <div class="es-dialog-header">- <span class="es-dialog-title">Scene Picker</span>- <button class="es-dialog-close" data-action="cancel">×</button>- </div>- <div class="es-dialog-body" style="max-height: 400px; overflow-y: auto;">- <div class="es-build-scene-picker-list">- ${scenesHtml}- </div>- </div>- <div class="es-dialog-footer">- <button class="es-dialog-btn" data-action="cancel">Cancel</button>- <button class="es-dialog-btn es-dialog-btn-primary" data-action="apply">Apply</button>- </div>- </div>- `;-- this.overlay_.appendChild(dialog);-- const close = () => dialog.remove();-- dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);- dialog.querySelector('[data-action="apply"]')?.addEventListener('click', async () => {- const checkboxes = dialog.querySelectorAll('input[data-scene-path]') as NodeListOf<HTMLInputElement>;- const selected: string[] = [];- checkboxes.forEach(cb => {- if (cb.checked) {- selected.push(cb.dataset.scenePath!);- }- });-- const existingOrder = config.scenes.filter(s => selected.includes(s));- const newScenes = selected.filter(s => !existingOrder.includes(s));- config.scenes = [...existingOrder, ...newScenes];-- await this.saveSettings();- close();- this.render();- });- }-- private showEditHookDialog(config: BuildConfig, index: number): void {- const hook = config.hooks![index];- const dialog = document.createElement('div');- dialog.className = 'es-build-add-dialog';-- const isCopy = hook.type === 'copy-files';- const copyConfig = isCopy ? hook.config as CopyFilesConfig : null;- const cmdConfig = !isCopy ? hook.config as RunCommandConfig : null;-- dialog.innerHTML = `- <div class="es-dialog" style="max-width: 420px;">- <div class="es-dialog-header">- <span class="es-dialog-title">Edit ${isCopy ? 'Copy Files' : 'Run Command'} Hook</span>- <button class="es-dialog-close" data-action="cancel">×</button>- </div>- <div class="es-dialog-body">- <div class="es-dialog-field">- <label class="es-dialog-label">Phase</label>- <select class="es-dialog-input" id="hook-phase">- <option value="pre" ${hook.phase === 'pre' ? 'selected' : ''}>Pre-Build</option>- <option value="post" ${hook.phase === 'post' ? 'selected' : ''}>Post-Build</option>- </select>- </div>- ${isCopy ? `- <div class="es-dialog-field">- <label class="es-dialog-label">From Path</label>- <input type="text" class="es-dialog-input" id="hook-from" value="${copyConfig?.from ?? ''}" placeholder="\${outputDir}">- </div>- <div class="es-dialog-field">- <label class="es-dialog-label">To Path</label>- <input type="text" class="es-dialog-input" id="hook-to" value="${copyConfig?.to ?? ''}" placeholder="/path/to/dest">- </div>- <div class="es-dialog-field">- <label class="es-dialog-label">Pattern (optional)</label>- <input type="text" class="es-dialog-input" id="hook-pattern" value="${copyConfig?.pattern ?? ''}" placeholder="*.png">- </div>- ` : `- <div class="es-dialog-field">- <label class="es-dialog-label">Command</label>- <input type="text" class="es-dialog-input" id="hook-command" value="${cmdConfig?.command ?? ''}" placeholder="echo">- </div>- <div class="es-dialog-field">- <label class="es-dialog-label">Arguments (space-separated)</label>- <input type="text" class="es-dialog-input" id="hook-args" value="${(cmdConfig?.args ?? []).join(' ')}" placeholder="arg1 arg2">- </div>- `}- </div>- <div class="es-dialog-footer">- <button class="es-dialog-btn" data-action="cancel">Cancel</button>- <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>- </div>- </div>- `;-- this.overlay_.appendChild(dialog);- const close = () => dialog.remove();-- dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);- dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {- const phase = (dialog.querySelector('#hook-phase') as HTMLSelectElement).value as BuildHookPhase;- hook.phase = phase;-- if (isCopy) {- const from = (dialog.querySelector('#hook-from') as HTMLInputElement).value;- const to = (dialog.querySelector('#hook-to') as HTMLInputElement).value;- const pattern = (dialog.querySelector('#hook-pattern') as HTMLInputElement).value;- hook.config = { from, to, ...(pattern ? { pattern } : {}) } as CopyFilesConfig;- } else {- const command = (dialog.querySelector('#hook-command') as HTMLInputElement).value;- const argsStr = (dialog.querySelector('#hook-args') as HTMLInputElement).value.trim();- const args = argsStr ? argsStr.split(/\s+/) : [];- hook.config = { command, args } as RunCommandConfig;- }-- await this.saveSettings();- close();- this.render();- });- }-- private setupSceneDragAndDrop(): void {- const dropZone = this.overlay_?.querySelector('[data-scene-drop-zone]');- if (!dropZone) return;-- const items = dropZone.querySelectorAll('[data-scene-drag]');- items.forEach(item => {- const el = item as HTMLElement;- el.addEventListener('dragstart', (e: DragEvent) => {- this.dragSourceIndex_ = parseInt(el.dataset.sceneDrag ?? '-1', 10);- el.classList.add('es-dragging');- e.dataTransfer!.effectAllowed = 'move';- });- el.addEventListener('dragend', () => {- el.classList.remove('es-dragging');- this.dragSourceIndex_ = -1;- });- el.addEventListener('dragover', (e: DragEvent) => {- e.preventDefault();- e.dataTransfer!.dropEffect = 'move';- el.classList.add('es-drag-over');- });- el.addEventListener('dragleave', () => {- el.classList.remove('es-drag-over');- });- el.addEventListener('drop', async (e: DragEvent) => {- e.preventDefault();- el.classList.remove('es-drag-over');- const targetIndex = parseInt(el.dataset.sceneDrag ?? '-1', 10);- if (this.dragSourceIndex_ >= 0 && targetIndex >= 0 && this.dragSourceIndex_ !== targetIndex) {- const config = this.getActiveConfig();- if (config) {- const [moved] = config.scenes.splice(this.dragSourceIndex_, 1);- config.scenes.splice(targetIndex, 0, moved);- await this.saveSettings();- this.render();- }- }- });- });- }-- // =========================================================================- // Member Variables- // =========================================================================-private overlay_!: HTMLElement;private options_!: BuildSettingsDialogOptions;private settings_!: BuildSettings;@@ -2027,27 +240,10 @@ export class BuildSettingsDialog {private keyHandler_: ((e: KeyboardEvent) => void) | null = null;private dragSourceIndex_ = -1;private lastBuildOutputFiles_: Map<string, Array<{ path: string; size: number }>> = new Map();- private toolchainStatus_: {- installed: boolean;- emsdk_path: string | null;- emscripten_version: string | null;- emscripten_ok: boolean;- cmake_found: boolean;- cmake_version: string | null;- cmake_ok: boolean;- python_found: boolean;- python_version: string | null;- python_ok: boolean;- corrupted: boolean;- missing_tools: string[];- } | null = null;+ private toolchainStatus_: ToolchainStatus | null = null;private toolchainError_ = false;}-// =============================================================================-// Helper Function-// =============================================================================-let activeDialog: BuildSettingsDialog | null = null;export function showBuildSettingsDialog(options: BuildSettingsDialogOptions): BuildSettingsDialog {diff --git a/editor/src/builder/BuildSettingsRenderer.ts b/editor/src/builder/BuildSettingsRenderer.tsnew file mode 100644index 000000000..e0301c3bd--- /dev/null+++ b/editor/src/builder/BuildSettingsRenderer.ts@@ -0,0 +1,616 @@+import { icons } from '../utils/icons';+import {+ type BuildPlatform,+ type BuildConfig,+ type BuildSettings,+ type EngineModules,+ PLATFORMS,+ ENGINE_MODULE_INFO,+ createDefaultEngineModules,+} from '../types/BuildTypes';+import type { CopyFilesConfig, RunCommandConfig } from '../types/BuildTypes';+import { formatSize } from './BuildProgress';+import { formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';+import { getTemplateRelPath, getTemplatePlaceholderDocs } from './templates';+import type { BuildSettingsRenderContext } from './BuildSettingsDialog';++export function renderSidebar(ctx: BuildSettingsRenderContext): string {+ const platformsHtml = PLATFORMS.map(p => {+ const isActive = ctx.settings.activePlatform === p.id;+ const configs = ctx.settings.configs.filter(c => c.platform === p.id);++ return `+ <div class="es-build-platform ${isActive ? 'es-active' : ''}" data-platform="${p.id}">+ <div class="es-build-platform-header">+ ${icons[p.icon as keyof typeof icons](14)}+ <span>${p.name}</span>+ ${isActive ? '<span class="es-build-badge">Active</span>' : ''}+ </div>+ </div>+ ${configs.map(c => renderConfigItem(ctx, c)).join('')}+ `;+ }).join('');++ return `+ <div class="es-build-section-title">Platforms</div>+ ${platformsHtml}+ `;+}++export function renderConfigItem(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isActive = ctx.settings.activeConfigId === config.id;+ const latestBuild = ctx.history.getLatest(config.id);+ const statusIndicator = latestBuild+ ? `<span class="es-build-status-dot es-build-status-${latestBuild.status}"></span>`+ : '';++ return `+ <div class="es-build-config-item ${isActive ? 'es-active' : ''}" data-config="${config.id}">+ ${statusIndicator}+ <span class="es-build-config-name">${config.name}</span>+ <button class="es-btn-icon es-build-config-delete" data-action="delete-config" data-config="${config.id}" title="Delete">+ ${icons.x(10)}+ </button>+ </div>+ `;+}++export function renderNoConfig(): string {+ return `+ <div class="es-build-empty">+ <p>No build config selected</p>+ <p>Select a config from the left or create a new one</p>+ </div>+ `;+}++export function renderDetail(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ return `+ <div class="es-build-detail-header">+ <div class="es-build-detail-title">+ <input type="text" class="es-build-name-input" id="config-name-input"+ value="${config.name}" placeholder="Config Name">+ <span class="es-build-detail-platform">${getPlatformName(config.platform)}</span>+ </div>+ <div class="es-build-detail-actions">+ <button class="es-btn es-btn-icon" data-action="duplicate-config" title="Duplicate">+ ${icons.copy(14)}+ </button>+ <button class="es-btn es-btn-icon" data-action="save-as-preset" title="Save as Preset">+ ${icons.download(14)}+ </button>+ </div>+ </div>+ <div class="es-build-detail-content">+ <div class="es-build-data-section">+ ${renderScenesSection(ctx, config)}+ ${renderDefinesSection(ctx, config)}+ ${renderEngineModulesSection(ctx, config)}+ </div>+ <div class="es-build-settings-section">+ ${renderToolchainSection(ctx)}+ ${renderPlatformSettings(ctx, config)}+ ${renderHooksSection(ctx, config)}+ </div>+ </div>+ `;+}++export function renderScenesSection(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isExpanded = ctx.expandedSections.has('scenes');+ const firstScene = config.scenes[0];+ const scenesHtml = config.scenes.length > 0+ ? config.scenes.map((s, i) => `+ <div class="es-build-scene-item" draggable="true" data-scene-drag="${i}">+ <span class="es-build-scene-drag-handle">${icons.grip(10)}</span>+ ${i === 0 ? '<span class="es-build-badge es-build-badge-small">Startup</span>' : ''}+ <span class="es-build-scene-path">${s}</span>+ <button class="es-btn-icon" data-action="remove-scene" data-index="${i}">+ ${icons.x(10)}+ </button>+ </div>+ `).join('')+ : '<div class="es-build-empty-list">No scenes added. Use buttons below to add scenes.</div>';++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="scenes">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Scenes</span>+ <span class="es-build-collapse-count">${config.scenes.length}</span>+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-scene-list" data-scene-drop-zone>+ ${scenesHtml}+ </div>+ <div class="es-build-scene-actions">+ <button class="es-btn es-btn-link" data-action="add-current-scene">+ ${icons.plus(12)} Add Current Scene+ </button>+ <button class="es-btn es-btn-link" data-action="add-all-scenes">+ ${icons.plus(12)} Add All Scenes+ </button>+ <button class="es-btn es-btn-link" data-action="show-scene-picker">+ ${icons.list(12)} Scene Picker+ </button>+ ${config.scenes.length > 0 ? `+ <button class="es-btn es-btn-link es-btn-danger" data-action="remove-all-scenes">+ ${icons.trash(12)} Remove All+ </button>+ ` : ''}+ </div>+ </div>+ </div>+ `;+}++export function renderDefinesSection(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isExpanded = ctx.expandedSections.has('defines');+ const definesHtml = config.defines.length > 0+ ? config.defines.map((d, i) => `+ <div class="es-build-define-item">+ <span>${d}</span>+ <button class="es-btn-icon" data-action="remove-define" data-index="${i}">+ ${icons.x(10)}+ </button>+ </div>+ `).join('')+ : '';++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="defines">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Script Defines</span>+ <span class="es-build-collapse-count">${config.defines.length}</span>+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-define-list">+ ${definesHtml}+ </div>+ <div class="es-build-define-add">+ <input type="text" class="es-input" id="new-define" placeholder="New define...">+ <button class="es-btn-icon" data-action="add-define" title="Add">+ ${icons.plus(12)}+ </button>+ </div>+ </div>+ </div>+ `;+}++export function renderEngineModulesSection(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isExpanded = ctx.expandedSections.has('engine-modules');+ const modules = config.engineModules ?? createDefaultEngineModules();+ const enabledCount = Object.values(modules).filter(Boolean).length;+ const totalCount = Object.keys(ENGINE_MODULE_INFO).length;++ const modulesHtml = (Object.entries(ENGINE_MODULE_INFO) as [keyof EngineModules, { name: string; description: string }][])+ .map(([key, info]) => `+ <div class="es-build-module-item">+ <label>+ <input type="checkbox" data-module="${key}" ${modules[key] ? 'checked' : ''}>+ <span class="es-build-module-name">${info.name}</span>+ </label>+ <span class="es-build-module-desc">${info.description}</span>+ </div>+ `).join('');++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="engine-modules">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Engine Modules</span>+ <span class="es-build-collapse-count">${enabledCount}/${totalCount}</span>+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-module-list">+ <div class="es-build-module-item es-build-module-core">+ <label>+ <input type="checkbox" checked disabled>+ <span class="es-build-module-name">Core</span>+ </label>+ <span class="es-build-module-desc">ECS, Renderer, Sprite, Text</span>+ </div>+ ${modulesHtml}+ </div>+ </div>+ </div>+ `;+}++export function renderPlatformSettings(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isExpanded = ctx.expandedSections.has('platform');++ let settingsHtml = '';+ if (config.platform === 'playable' && config.playableSettings) {+ const s = config.playableSettings;+ settingsHtml = `+ <div class="es-build-field">+ <label class="es-build-label">Startup Scene</label>+ <div class="es-build-path-row">+ <input type="text" class="es-input" id="playable-startup-scene"+ value="${s.startupScene || ''}" placeholder="assets/scenes/main.scene">+ <button class="es-btn" data-action="browse-startup-scene">...</button>+ </div>+ </div>+ <div class="es-build-field">+ <label>+ <input type="checkbox" id="playable-dev" ${s.isDevelopment ? 'checked' : ''}>+ Development Build+ </label>+ </div>+ <div class="es-build-field">+ <label>+ <input type="checkbox" id="playable-minify" ${s.minifyCode ? 'checked' : ''}>+ Minify Code+ </label>+ </div>+ <div class="es-build-field">+ <label>+ <input type="checkbox" id="playable-fonts" ${s.embedFonts ? 'checked' : ''}>+ Embed Fonts+ </label>+ </div>+ <div class="es-build-field">+ <label class="es-build-label">Output Path</label>+ <div class="es-build-path-row">+ <input type="text" class="es-input" id="playable-output" value="${s.outputPath}">+ <button class="es-btn" data-action="browse-output">...</button>+ </div>+ </div>+ <div class="es-build-field">+ <label>+ <input type="checkbox" id="playable-cta" ${s.enableBuiltinCTA ? 'checked' : ''}>+ Enable Built-in CTA+ </label>+ </div>+ ${s.enableBuiltinCTA ? `+ <div class="es-build-field">+ <label class="es-build-label">CTA URL</label>+ <input type="text" class="es-input" id="playable-cta-url"+ value="${s.ctaUrl || ''}" placeholder="https://play.google.com/store/apps/...">+ </div>+ ` : ''}+ ${renderTemplateSection(ctx, 'playable', s.templatePath)}+ `;+ } else if (config.platform === 'wechat' && config.wechatSettings) {+ const s = config.wechatSettings;+ settingsHtml = `+ <div class="es-build-field">+ <label class="es-build-label">AppID</label>+ <input type="text" class="es-input" id="wechat-appid" value="${s.appId}" placeholder="wx...">+ </div>+ <div class="es-build-field">+ <label class="es-build-label">Version</label>+ <input type="text" class="es-input" id="wechat-version" value="${s.version}">+ </div>+ <div class="es-build-field">+ <label class="es-build-label">Screen Orientation</label>+ <select class="es-select" id="wechat-orientation">+ <option value="portrait" ${(s.orientation || 'portrait') === 'portrait' ? 'selected' : ''}>Portrait</option>+ <option value="landscape" ${s.orientation === 'landscape' ? 'selected' : ''}>Landscape</option>+ </select>+ </div>+ <div class="es-build-field">+ <label class="es-build-label">Bundle Mode</label>+ <select class="es-select" id="wechat-bundle">+ <option value="subpackage" ${s.bundleMode === 'subpackage' ? 'selected' : ''}>Subpackage (Recommended)</option>+ <option value="single" ${s.bundleMode === 'single' ? 'selected' : ''}>Single Package</option>+ <option value="singleFile" ${s.bundleMode === 'singleFile' ? 'selected' : ''}>Single File (Playable Ad)</option>+ </select>+ </div>+ <div class="es-build-field">+ <label class="es-build-label">Output Directory</label>+ <div class="es-build-path-row">+ <input type="text" class="es-input" id="wechat-output" value="${s.outputDir}">+ <button class="es-btn" data-action="browse-output">...</button>+ </div>+ </div>+ ${renderTemplateSection(ctx, 'wechat', s.templatePath)}+ `;+ }++ const platformName = config.platform === 'playable' ? 'Playable' : 'WeChat MiniGame';++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="platform">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>${platformName} Settings</span>+ </div>+ <div class="es-build-collapse-content">+ ${settingsHtml}+ </div>+ </div>+ `;+}++export function renderTemplateSection(ctx: BuildSettingsRenderContext, platform: BuildPlatform, templatePath?: string): string {+ const defaultRelPath = getTemplateRelPath(platform);+ const placeholders = getTemplatePlaceholderDocs(platform);+ const sectionKey = `template-ref-${platform}`;+ const isRefExpanded = ctx.expandedSections.has(sectionKey);+ const placeholderRows = placeholders.map(p =>+ `<tr><td style="font-family:monospace;white-space:nowrap;padding:2px 8px 2px 0">{{${p.key}}}</td><td style="padding:2px 0">${p.description}</td></tr>`+ ).join('');++ return `+ <div class="es-build-field" style="margin-top:8px;padding-top:8px;border-top:1px solid var(--border)">+ <label class="es-build-label">Custom Template</label>+ <div class="es-build-path-row">+ <input type="text" class="es-input" id="${platform}-template-path"+ value="${templatePath || ''}" placeholder="${defaultRelPath}">+ </div>+ <div style="display:flex;gap:4px;margin-top:4px">+ <button class="es-btn es-btn-small" data-action="export-template" data-platform="${platform}">Export Default</button>+ <button class="es-btn es-btn-small" data-action="open-template" data-platform="${platform}">Open</button>+ <button class="es-btn es-btn-small" data-action="reset-template" data-platform="${platform}">Reset</button>+ </div>+ </div>+ <div class="es-build-collapse ${isRefExpanded ? 'es-expanded' : ''}" data-section="${sectionKey}" style="margin-top:4px">+ <div class="es-build-collapse-header">+ ${isRefExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Placeholders Reference</span>+ </div>+ <div style="display:${isRefExpanded ? 'block' : 'none'};padding:8px;font-size:11px" data-template-ref-content="${platform}">+ <table style="width:100%">${placeholderRows}</table>+ </div>+ </div>+ `;+}++export function renderHooksSection(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const isExpanded = ctx.expandedSections.has('hooks');+ const hooks = config.hooks ?? [];++ const hooksHtml = hooks.length > 0+ ? hooks.map((h, i) => {+ const phaseLabel = h.phase === 'pre' ? 'Pre-Build' : 'Post-Build';+ const typeLabel = h.type === 'copy-files' ? 'Copy Files' : 'Run Command';+ let detail = '';+ if (h.type === 'copy-files') {+ const c = h.config as CopyFilesConfig;+ detail = `${c.from} → ${c.to}`;+ } else {+ const c = h.config as RunCommandConfig;+ detail = `${c.command} ${(c.args ?? []).join(' ')}`.trim();+ }+ return `+ <div class="es-build-hook-item">+ <span class="es-build-badge es-build-badge-small">${phaseLabel}</span>+ <span class="es-build-hook-type">${typeLabel}</span>+ <span class="es-build-hook-detail" title="${detail}">${detail || '(not configured)'}</span>+ <button class="es-btn-icon" data-action="edit-hook" data-index="${i}" title="Edit">+ ${icons.pencil(10)}+ </button>+ <button class="es-btn-icon" data-action="remove-hook" data-index="${i}" title="Remove">+ ${icons.x(10)}+ </button>+ </div>+ `;+ }).join('')+ : '<div class="es-build-empty-list">No hooks configured</div>';++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="hooks">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Build Hooks</span>+ <span class="es-build-collapse-count">${hooks.length}</span>+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-hooks-list">+ ${hooksHtml}+ </div>+ <div class="es-build-hook-actions">+ <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="copy-files" data-hook-phase="post">+ ${icons.plus(12)} Add Copy Files Hook+ </button>+ <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="run-command" data-hook-phase="post">+ ${icons.plus(12)} Add Run Command Hook+ </button>+ </div>+ </div>+ </div>+ `;+}++export function renderOutputPanel(ctx: BuildSettingsRenderContext, config: BuildConfig): string {+ const latestBuild = ctx.history.getLatest(config.id);+ const recentBuilds = ctx.history.getEntries(config.id).slice(0, 5);++ const latestSection = latestBuild ? `+ <div class="es-build-output-latest">+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Last Build</span>+ <span class="es-build-output-value">${formatBuildTime(latestBuild.timestamp)}</span>+ </div>+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Status</span>+ <span class="es-build-output-value es-build-status-${latestBuild.status}">+ ${getBuildStatusIcon(latestBuild.status)} ${latestBuild.status}+ </span>+ </div>+ ${latestBuild.outputSize ? `+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Size</span>+ <span class="es-build-output-value">${formatSize(latestBuild.outputSize)}</span>+ </div>+ ` : ''}+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Duration</span>+ <span class="es-build-output-value">${formatBuildDuration(latestBuild.duration)}</span>+ </div>+ ${latestBuild.outputPath ? `+ <div class="es-build-output-actions">+ <button class="es-btn es-btn-small" data-action="open-output" data-path="${latestBuild.outputPath}">+ ${icons.folder(12)} Open+ </button>+ <button class="es-btn es-btn-small" data-action="preview-output" data-path="${latestBuild.outputPath}">+ ${icons.play(12)} Preview+ </button>+ </div>+ ` : ''}+ </div>+ ` : `+ <div class="es-build-output-empty">+ No builds yet+ </div>+ `;++ const historySection = recentBuilds.length > 0 ? `+ <div class="es-build-history">+ <div class="es-build-section-title">Build History</div>+ <div class="es-build-history-list">+ ${recentBuilds.map(entry => renderHistoryEntry(entry)).join('')}+ </div>+ </div>+ ` : '';++ return `+ <div class="es-build-output-header">+ <span class="es-build-section-title">Build Output</span>+ ${recentBuilds.length > 0 ? `+ <button class="es-btn-icon" data-action="clear-history" title="Clear History">+ ${icons.trash(12)}+ </button>+ ` : ''}+ </div>+ ${latestSection}+ ${renderOutputFiles(ctx, config.id)}+ ${historySection}+ `;+}++export function renderOutputFiles(ctx: BuildSettingsRenderContext, configId: string): string {+ const files = ctx.lastBuildOutputFiles.get(configId);+ if (!files || files.length === 0) return '';++ const isExpanded = ctx.expandedSections.has('output-files');+ const sorted = [...files].sort((a, b) => b.size - a.size);+ const totalSize = sorted.reduce((sum, f) => sum + f.size, 0);++ const fileItems = sorted.slice(0, 20).map(f => {+ const name = f.path.split('/').pop() ?? f.path;+ const dir = f.path.substring(0, f.path.length - name.length);+ return `+ <div class="es-build-file-item">+ <span class="es-build-file-icon">${icons.file(10)}</span>+ <span class="es-build-file-path" title="${f.path}">${dir ? `<span class="es-build-file-dir">${dir}</span>` : ''}${name}</span>+ <span class="es-build-file-size">${formatSize(f.size)}</span>+ </div>+ `;+ }).join('');++ const moreCount = sorted.length - 20;++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="output-files">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Output Files</span>+ <span class="es-build-collapse-count">${files.length} files (${formatSize(totalSize)})</span>+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-file-list">+ ${fileItems}+ ${moreCount > 0 ? `<div class="es-build-file-more">and ${moreCount} more files...</div>` : ''}+ </div>+ </div>+ </div>+ `;+}++export function renderHistoryEntry(entry: BuildHistoryEntry): string {+ const time = new Date(entry.timestamp).toLocaleTimeString();+ return `+ <div class="es-build-history-item es-build-status-${entry.status}">+ <span class="es-build-history-icon">${getBuildStatusIcon(entry.status)}</span>+ <span class="es-build-history-time">${time}</span>+ <span class="es-build-history-duration">${formatBuildDuration(entry.duration)}</span>+ </div>+ `;+}++export function renderToolchainSection(ctx: BuildSettingsRenderContext): string {+ const isExpanded = ctx.expandedSections.has('toolchain');+ const s = ctx.toolchainStatus;++ let statusBadge: string;+ let infoHtml: string;++ if (ctx.toolchainError) {+ statusBadge = '';+ infoHtml = '<span class="es-build-module-desc">Not available in browser mode</span>';+ } else if (!s) {+ statusBadge = '';+ infoHtml = '<span class="es-build-module-desc">Detecting...</span>';+ } else if (s.installed) {+ statusBadge = '<span class="es-build-toolchain-badge es-ready">Ready</span>';+ infoHtml = renderToolchainRows(s);+ } else {+ statusBadge = '<span class="es-build-toolchain-badge es-not-ready">Not ready</span>';+ infoHtml = renderToolchainRows(s);+ }++ return `+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="toolchain">+ <div class="es-build-collapse-header">+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}+ <span>Toolchain (emsdk)</span>+ ${statusBadge}+ </div>+ <div class="es-build-collapse-content">+ <div class="es-build-toolchain-info">+ ${infoHtml}+ </div>+ <div class="es-build-toolchain-actions">+ <button class="es-btn" data-action="browse-emsdk">+ ${icons.folder(12)} Select emsdk+ </button>+ <button class="es-btn" data-action="install-emsdk">+ ${icons.download(12)} Auto Install+ </button>+ </div>+ </div>+ </div>+ `;+}++export function renderToolchainRows(s: NonNullable<BuildSettingsRenderContext['toolchainStatus']>): string {+ const row = (label: string, value: string | null, ok: boolean, minVersion?: string, note?: string) => {+ const cls = ok ? '' : ' es-warning';+ let display = value ?? 'not found';+ if (value && !ok && minVersion) {+ display += ` (requires >= ${minVersion})`;+ }+ if (note) {+ display += ` <span class="es-build-module-desc">(${note})</span>`;+ }+ return `<div class="es-build-toolchain-row${cls}">${label}: ${display}</div>`;+ };+ const rows = [+ row('Emscripten', s.emscripten_version ?? (s.emsdk_path ? 'unknown' : null), s.emscripten_ok, '5.0.0'),+ row('CMake', s.cmake_version, s.cmake_ok, '3.16', s.cmake_ok ? 'bundled' : undefined),+ row('Python', s.python_version, s.python_ok, '3.0', s.python_ok ? 'from emsdk' : undefined),+ ];+ if (s.corrupted && s.missing_tools?.length) {+ rows.push(`<div class="es-build-toolchain-row es-build-row-error" style="color:var(--error-color,#e54);display:flex;align-items:center;gap:8px">+ <span>Missing ${s.missing_tools.join(', ')}</span>+ <button class="es-btn es-btn-xs" data-action="repair-toolchain" style="flex-shrink:0">${icons.download(12)} Repair</button>+ </div>`);+ }+ if (s.emsdk_path) {+ rows.push(`<div class="es-build-toolchain-row" style="opacity:0.6;font-size:0.85em;display:flex;align-items:center;gap:4px">+ <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${s.emsdk_path}">Path: ${s.emsdk_path}</span>+ <button class="es-btn es-btn-xs" data-action="copy-emsdk-path" title="Copy path" style="flex-shrink:0;padding:1px 4px">${icons.copy(12)}</button>+ <button class="es-btn es-btn-xs" data-action="open-emsdk-folder" title="Open folder" style="flex-shrink:0;padding:1px 4px">${icons.folderOpen(12)}</button>+ </div>`);+ }+ return rows.join('');+}++function getPlatformName(platform: BuildPlatform): string {+ return PLATFORMS.find(p => p.id === platform)?.name ?? platform;+}diff --git a/editor/src/builder/BuildSettingsToolchain.ts b/editor/src/builder/BuildSettingsToolchain.tsnew file mode 100644index 000000000..748759fb9--- /dev/null+++ b/editor/src/builder/BuildSettingsToolchain.ts@@ -0,0 +1,133 @@+import { icons } from '../utils/icons';+import { getEditorContext } from '../context/EditorContext';+import { showProgressToast, dismissToast, showSuccessToast, showErrorToast, updateToast } from '../ui/Toast';+import { renderToolchainRows } from './BuildSettingsRenderer';+import type { BuildSettingsToolchainContext } from './BuildSettingsDialog';++export async function checkToolchainStatus(ctx: BuildSettingsToolchainContext): Promise<void> {+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ ctx.toolchainStatus = await invoke('get_toolchain_status');+ ctx.toolchainError = false;+ } catch {+ ctx.toolchainStatus = null;+ ctx.toolchainError = true;+ }+ updateToolchainUI(ctx);+}++export function updateToolchainUI(ctx: BuildSettingsToolchainContext): void {+ const section = ctx.overlay?.querySelector('[data-section="toolchain"]');+ if (!section) return;++ const s = ctx.toolchainStatus;+ const header = section.querySelector('.es-build-collapse-header');+ const badgeEl = section.querySelector('.es-build-toolchain-badge');+ const infoEl = section.querySelector('.es-build-toolchain-info');++ if (ctx.toolchainError) {+ if (badgeEl) badgeEl.remove();+ if (infoEl) infoEl.innerHTML = '<span class="es-build-module-desc">Not available in browser mode</span>';+ return;+ }++ if (!s) {+ if (infoEl) infoEl.innerHTML = '<span class="es-build-module-desc">Detecting...</span>';+ return;+ }++ const badgeClass = s.installed ? 'es-ready' : 'es-not-ready';+ const badgeText = s.installed ? 'Ready' : 'Not ready';++ if (badgeEl) {+ badgeEl.className = `es-build-toolchain-badge ${badgeClass}`;+ badgeEl.textContent = badgeText;+ } else if (header) {+ header.insertAdjacentHTML('beforeend', `<span class="es-build-toolchain-badge ${badgeClass}">${badgeText}</span>`);+ }++ if (infoEl) {+ infoEl.innerHTML = renderToolchainRows(s);+ }++ updateBuildButtonState(ctx);+}++export function updateBuildButtonState(ctx: BuildSettingsToolchainContext): void {+ const ready = !!ctx.toolchainStatus?.installed;+ const buildBtn = ctx.overlay?.querySelector('[data-action="build"]') as HTMLButtonElement | null;+ const buildAllBtn = ctx.overlay?.querySelector('[data-action="build-all"]') as HTMLButtonElement | null;+ if (buildBtn) {+ buildBtn.disabled = !ready;+ buildBtn.title = ready ? '' : 'Toolchain not ready';+ }+ if (buildAllBtn) {+ buildAllBtn.disabled = !ready;+ buildAllBtn.title = ready ? 'Build All Configs' : 'Toolchain not ready';+ }+}++export async function handleBrowseEmsdk(ctx: BuildSettingsToolchainContext): Promise<void> {+ const fs = getEditorContext().fs;+ if (!fs) return;++ const selected = await fs.selectDirectory();+ if (!selected) return;++ try {+ const { invoke } = await import('@tauri-apps/api/core');+ await invoke('set_emsdk_path', { path: selected });+ showSuccessToast('emsdk path set');+ await checkToolchainStatus(ctx);+ } catch (err: any) {+ showErrorToast(err.toString());+ }+}++export async function handleInstallEmsdk(ctx: BuildSettingsToolchainContext): Promise<void> {+ const toastId = showProgressToast('Downloading toolchain...');+ let unlisten: (() => void) | undefined;+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const { listen } = await import('@tauri-apps/api/event');+ unlisten = await listen<{ stage: string; message: string; progress: number }>('compile-progress', (event) => {+ updateToast(toastId, {+ message: event.payload.message,+ progress: event.payload.progress,+ });+ });+ await invoke('install_emsdk');+ dismissToast(toastId);+ showSuccessToast('Toolchain installed');+ await checkToolchainStatus(ctx);+ } catch (err: any) {+ dismissToast(toastId);+ showErrorToast(`Install failed: ${err}`);+ } finally {+ unlisten?.();+ }+}++export async function handleRepairToolchain(ctx: BuildSettingsToolchainContext): Promise<void> {+ const toastId = showProgressToast('Repairing toolchain...');+ let unlisten: (() => void) | undefined;+ try {+ const { invoke } = await import('@tauri-apps/api/core');+ const { listen } = await import('@tauri-apps/api/event');+ unlisten = await listen<{ stage: string; message: string; progress: number }>('compile-progress', (event) => {+ updateToast(toastId, {+ message: event.payload.message,+ progress: event.payload.progress,+ });+ });+ await invoke('repair_toolchain');+ dismissToast(toastId);+ showSuccessToast('Toolchain repaired');+ await checkToolchainStatus(ctx);+ } catch (err: any) {+ dismissToast(toastId);+ showErrorToast(`Repair failed: ${err}`);+ } finally {+ unlisten?.();+ }+}diff --git a/editor/src/panels/inspector/ComponentRenderer.ts b/editor/src/panels/inspector/ComponentRenderer.tsnew file mode 100644index 000000000..14efc9ddf--- /dev/null+++ b/editor/src/panels/inspector/ComponentRenderer.ts@@ -0,0 +1,684 @@+import type { Entity } from 'esengine';+import type { ComponentData } from '../../types/SceneTypes';+import type { EditorStore } from '../../store/EditorStore';+import { createPropertyEditor } from '../../property/PropertyEditor';+import {+ getComponentSchema,+ getDefaultComponentData,+ inferPropertyType,+ isComponentRemovable,+} from '../../schemas/ComponentSchemas';+import { icons } from '../../utils/icons';+import { getEditorContext } from '../../context/EditorContext';+import { getPlatformAdapter } from '../../platform/PlatformAdapter';+import { getAssetLibrary, isUUID } from '../../asset/AssetLibrary';+import {+ type EditorInfo,+ getComponentIcon,+ getProjectDir,+} from './InspectorHelpers';+import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';+import { isPropertyOverridden } from '../../prefab';+import {+ getComponentInspector,+} from './InspectorRegistry';+import { deepEqual } from './SharedEditors';+import { visibilityResolver } from '../../schemas/VisibilityResolver';++const COLLAPSED_STORAGE_KEY = 'inspector-collapsed';++function loadCollapsedSet(): Set<string> {+ try {+ const raw = localStorage.getItem(COLLAPSED_STORAGE_KEY);+ return raw ? new Set(JSON.parse(raw)) : new Set();+ } catch {+ return new Set();+ }+}++function saveCollapsedSet(set: Set<string>): void {+ localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify([...set]));+}++const collapsedComponents = loadCollapsedSet();++declare global {+ interface Window {+ __esengine_componentSourceMap?: Map<string, string>;+ }+}++export function renderComponent(+ container: HTMLElement,+ entity: Entity,+ component: ComponentData,+ store: EditorStore,+ editors: EditorInfo[],+ componentIndex: number = 0,+ componentCount: number = 1+): void {+ const schema = getComponentSchema(component.type);+ if (!schema) {+ console.warn(`[Inspector] No schema found for component "${component.type}"`);+ }+ if (schema?.hidden) return;+ if (schema?.category === 'tag') {+ renderTagComponent(container, entity, component, store);+ return;+ }++ const defaults = getDefaultComponentData(component.type);+ const displayTitle = schema?.displayName ?? component.type;++ const section = document.createElement('div');+ const isCollapsed = collapsedComponents.has(component.type);+ section.className = `es-component-section es-collapsible${isCollapsed ? '' : ' es-expanded'}`;++ const icon = getComponentIcon(component.type);+ const removable = isComponentRemovable(component.type);++ const hasEnabled = 'enabled' in defaults;+ const isEnabled = hasEnabled ? (component.data.enabled ?? defaults.enabled) !== false : true;++ if (hasEnabled && !isEnabled) {+ section.dataset.enabled = 'false';+ }++ const header = document.createElement('div');+ header.className = 'es-component-header es-collapsible-header';+ header.innerHTML = `+ <span class="es-collapse-icon">${icons.chevronDown(12)}</span>+ <span class="es-component-icon">${icon}</span>+ <span class="es-component-title">${displayTitle}</span>+ ${hasEnabled ? `<input type="checkbox" class="es-component-enabled-toggle" title="Enable/Disable component" ${isEnabled ? 'checked' : ''}>` : ''}+ ${removable ? `<button class="es-btn es-btn-icon es-btn-remove">${icons.x(12)}</button>` : ''}+ `;++ if (hasEnabled) {+ const toggle = header.querySelector('.es-component-enabled-toggle') as HTMLInputElement;+ toggle?.addEventListener('click', (e) => {+ e.stopPropagation();+ });+ toggle?.addEventListener('change', () => {+ const oldValue = component.data.enabled ?? defaults.enabled;+ store.updateProperty(entity, component.type, 'enabled', oldValue, toggle.checked);+ });+ }++ if (removable) {+ const removeBtn = header.querySelector('.es-btn-remove');+ removeBtn?.addEventListener('click', () => {+ store.removeComponent(entity, component.type);+ });+ }++ header.addEventListener('click', (e) => {+ if ((e.target as HTMLElement).closest('.es-btn-remove')) return;+ if ((e.target as HTMLElement).closest('.es-component-enabled-toggle')) return;+ section.classList.toggle('es-expanded');+ if (section.classList.contains('es-expanded')) {+ collapsedComponents.delete(component.type);+ } else {+ collapsedComponents.add(component.type);+ }+ saveCollapsedSet(collapsedComponents);+ });++ header.addEventListener('contextmenu', (e) => {+ e.preventDefault();+ const menuItems: ContextMenuItem[] = [+ {+ label: 'Reset to Default',+ icon: icons.rotateCcw(14),+ onClick: () => {+ const changes = Object.keys(defaults).map(key => ({+ property: key,+ oldValue: component.data[key] ?? defaults[key],+ newValue: defaults[key],+ }));+ if (changes.length > 0) {+ store.updateProperties(entity, component.type, changes);+ }+ },+ },+ {+ label: 'Copy Component',+ icon: icons.copy(14),+ onClick: () => {+ const payload = JSON.stringify({ type: component.type, data: component.data });+ navigator.clipboard.writeText(payload);+ },+ },+ {+ label: 'Paste Component Values',+ icon: icons.clipboard(14),+ onClick: async () => {+ try {+ const text = await navigator.clipboard.readText();+ const parsed = JSON.parse(text);+ if (parsed.type === component.type && parsed.data) {+ const changes = Object.keys(parsed.data).map(key => ({+ property: key,+ oldValue: component.data[key] ?? defaults[key],+ newValue: parsed.data[key],+ }));+ if (changes.length > 0) {+ store.updateProperties(entity, component.type, changes);+ }+ }+ } catch { /* ignore invalid clipboard data */ }+ },+ },+ { label: '', separator: true },+ {+ label: 'Move Up',+ icon: icons.arrowUp(14),+ disabled: componentIndex <= 0,+ onClick: () => {+ store.reorderComponent(entity, componentIndex, componentIndex - 1);+ },+ },+ {+ label: 'Move Down',+ icon: icons.arrowDown(14),+ disabled: componentIndex >= componentCount - 1,+ onClick: () => {+ store.reorderComponent(entity, componentIndex, componentIndex + 1);+ },+ },+ ];++ if (removable) {+ menuItems.push(+ { label: '', separator: true },+ {+ label: 'Remove',+ icon: icons.trash(14),+ onClick: () => {+ store.removeComponent(entity, component.type);+ },+ }+ );+ }++ showContextMenu({ items: menuItems, x: e.clientX, y: e.clientY });+ });++ if (schema?.category === 'script') {+ header.addEventListener('dblclick', () => {+ const sourceMap = window.__esengine_componentSourceMap;+ const scriptPath = sourceMap?.get(component.type);+ if (!scriptPath) return;+ const projectDir = getProjectDir();+ if (projectDir) {+ getEditorContext().shell?.openInEditor(projectDir, scriptPath);+ }+ });+ }++ section.appendChild(header);++ if (schema?.description) {+ const desc = document.createElement('div');+ desc.className = 'es-component-description es-collapsible-content';+ desc.textContent = schema.description;+ section.appendChild(desc);+ }++ const customInspector = getComponentInspector(component.type);+ if (customInspector) {+ const propsContainer = document.createElement('div');+ propsContainer.className = 'es-component-properties es-collapsible-content';+ const instance = customInspector.render(propsContainer, {+ store,+ entity,+ componentType: component.type,+ componentData: component.data,+ onChange: (property, oldValue, newValue) => {+ store.updateProperty(entity, component.type, property, oldValue, newValue);+ },+ });+ if (instance) {+ editors.push({+ editor: instance,+ componentType: component.type,+ propertyName: '*',+ });+ }+ section.appendChild(propsContainer);+ container.appendChild(section);+ return;+ }++ const entityData = store.getEntityData(entity as number);+ const entityComponents = entityData?.components.map(c => c.type) ?? [];++ if (schema) {+ const propsContainer = document.createElement('div');+ propsContainer.className = 'es-component-properties es-collapsible-content';++ const ungrouped: import('../../property/PropertyEditor').PropertyMeta[] = [];+ const groups = new Map<string, import('../../property/PropertyEditor').PropertyMeta[]>();+ const groupOrder: string[] = [];+ const advancedProps: import('../../property/PropertyEditor').PropertyMeta[] = [];+ for (const propMeta of schema.properties) {+ if (propMeta.advanced) {+ advancedProps.push(propMeta);+ } else if (propMeta.group) {+ if (!groups.has(propMeta.group)) {+ groups.set(propMeta.group, []);+ groupOrder.push(propMeta.group);+ }+ groups.get(propMeta.group)!.push(propMeta);+ } else {+ ungrouped.push(propMeta);+ }+ }++ for (const propMeta of ungrouped) {+ renderPropertyRow(propsContainer, propMeta, entity, component, defaults, store, editors, entityComponents);+ }++ for (const groupName of groupOrder) {+ const groupSection = document.createElement('div');+ groupSection.className = 'es-property-group es-collapsible es-expanded';++ const groupHeader = document.createElement('div');+ groupHeader.className = 'es-property-group-divider es-collapsible-header';+ groupHeader.innerHTML = `+ <span class="es-collapse-icon">${icons.chevronDown(8)}</span>+ <span class="es-property-group-label">${groupName}</span>+ <span class="es-property-group-line"></span>+ `;+ groupHeader.addEventListener('click', () => {+ groupSection.classList.toggle('es-expanded');+ });+ groupSection.appendChild(groupHeader);++ const groupContent = document.createElement('div');+ groupContent.className = 'es-collapsible-content';+ for (const propMeta of groups.get(groupName)!) {+ renderPropertyRow(groupContent, propMeta, entity, component, defaults, store, editors, entityComponents);+ }+ groupSection.appendChild(groupContent);++ propsContainer.appendChild(groupSection);++ if (schema.sections) {+ for (const sec of schema.sections) {+ if (sec.insertAfterGroup === groupName) {+ renderSchemaSection(propsContainer, sec, entity, component, store, editors);+ }+ }+ }+ }++ if (schema.sections) {+ for (const sec of schema.sections) {+ if (!sec.insertAfterGroup) {+ renderSchemaSection(propsContainer, sec, entity, component, store, editors);+ }+ }+ }++ if (advancedProps.length > 0) {+ const advSection = document.createElement('div');+ advSection.className = 'es-property-group es-collapsible';++ const advHeader = document.createElement('div');+ advHeader.className = 'es-property-group-divider es-collapsible-header';+ advHeader.innerHTML = `+ <span class="es-collapse-icon">${icons.chevronDown(8)}</span>+ <span class="es-property-group-label">Advanced</span>+ <span class="es-property-group-line"></span>+ `;+ advHeader.addEventListener('click', () => {+ advSection.classList.toggle('es-expanded');+ });+ advSection.appendChild(advHeader);++ const advContent = document.createElement('div');+ advContent.className = 'es-collapsible-content';+ for (const propMeta of advancedProps) {+ renderPropertyRow(advContent, propMeta, entity, component, defaults, store, editors, entityComponents);+ }+ advSection.appendChild(advContent);++ propsContainer.appendChild(advSection);+ }++ section.appendChild(propsContainer);+ } else {+ const propsContainer = document.createElement('div');+ propsContainer.className = 'es-component-properties es-collapsible-content';++ const fullData = { ...defaults, ...component.data };+ for (const [key, value] of Object.entries(fullData)) {+ const row = document.createElement('div');+ row.className = 'es-property-row';++ const label = document.createElement('label');+ label.className = 'es-property-label';+ label.textContent = key;++ const editorContainer = document.createElement('div');+ editorContainer.className = 'es-property-editor';++ const propMeta: import('../../property/PropertyEditor').PropertyMeta = {+ name: key,+ type: inferPropertyType(value),+ };++ let currentValue = component.data[key];+ if (currentValue === undefined) {+ currentValue = defaults[key];+ }+ const editor = createPropertyEditor(editorContainer, {+ value: currentValue,+ meta: propMeta,+ onChange: (newValue) => {+ const oldValue = component.data[key] ?? currentValue;+ store.updateProperty(entity, component.type, key, oldValue, newValue);+ },+ componentData: component.data,+ getComponentValue: (name: string) => component.data[name],+ getCurrentValue: () => component.data[key] ?? defaults[key],+ entityComponents,+ });++ if (editor) {+ editors.push({+ editor,+ componentType: component.type,+ propertyName: key,+ });+ }++ row.appendChild(label);+ row.appendChild(editorContainer);+ propsContainer.appendChild(row);+ }++ section.appendChild(propsContainer);+ }++ container.appendChild(section);+}++function renderPropertyRow(+ container: HTMLElement,+ propMeta: import('../../property/PropertyEditor').PropertyMeta,+ entity: Entity,+ component: ComponentData,+ defaults: Record<string, unknown>,+ store: EditorStore,+ editors: EditorInfo[],+ entityComponents: string[] = []+): void {+ if (propMeta.name === '*') {+ const editorContainer = document.createElement('div');+ editorContainer.className = 'es-property-editor es-property-editor-full';++ const fullData = { ...defaults, ...component.data };++ const editor = createPropertyEditor(editorContainer, {+ value: fullData,+ meta: propMeta,+ onChange: (changes) => {+ const arr = changes as { property: string; oldValue: unknown; newValue: unknown }[];+ store.updateProperties(entity, component.type, arr);+ },+ componentData: component.data,+ getComponentValue: (name: string) => component.data[name],+ getCurrentValue: () => ({ ...defaults, ...component.data }),+ });++ if (editor) {+ editors.push({+ editor,+ componentType: component.type,+ propertyName: '*',+ });+ }++ container.appendChild(editorContainer);+ return;+ }++ const hasVisibilityRule = propMeta.visibleWhen != null || propMeta.hiddenWhen != null;+ const fullData = { ...defaults, ...component.data };+ const initiallyVisible = visibilityResolver.isVisible(propMeta, fullData, entityComponents);++ if (!initiallyVisible && !hasVisibilityRule) {+ return;+ }++ const row = document.createElement('div');+ row.className = 'es-property-row';+ if (!initiallyVisible) {+ row.style.display = 'none';+ }++ const entityData = store.getEntityData(entity as number);+ if (entityData?.prefab && isPropertyOverridden(+ store.scene,+ entity as number,+ component.type,+ propMeta.name+ )) {+ row.classList.add('es-overridden');+ }++ const label = document.createElement('label');+ label.className = 'es-property-label';+ label.textContent = propMeta.displayName ?? propMeta.name;+ if (propMeta.tooltip) {+ label.dataset.tooltip = propMeta.tooltip;+ }++ const editorContainer = document.createElement('div');+ editorContainer.className = 'es-property-editor';+ if (propMeta.readOnly) {+ editorContainer.classList.add('es-property-readonly');+ }++ let currentValue = component.data[propMeta.name];+ if (currentValue === undefined) {+ currentValue = defaults[propMeta.name];+ }+ const editor = createPropertyEditor(editorContainer, {+ value: currentValue,+ meta: propMeta,+ onChange: propMeta.readOnly ? () => {} : (newValue) => {+ const oldValue = component.data[propMeta.name] ?? currentValue;+ store.updateProperty(+ entity,+ component.type,+ propMeta.name,+ oldValue,+ newValue+ );+ },+ componentData: component.data,+ getComponentValue: (name: string) => component.data[name],+ getCurrentValue: () => component.data[propMeta.name] ?? defaults[propMeta.name],+ entityComponents,+ });++ if (editor) {+ editors.push({+ editor,+ componentType: component.type,+ propertyName: propMeta.name,+ });+ }++ row.appendChild(label);+ row.appendChild(editorContainer);++ const defaultValue = defaults[propMeta.name];+ const isModified = currentValue !== undefined &&+ !deepEqual(currentValue, defaultValue);++ if (isModified) {+ const resetBtn = document.createElement('button');+ resetBtn.className = 'es-property-reset';+ resetBtn.title = `Reset to default`;+ resetBtn.innerHTML = icons.rotateCcw(10);+ resetBtn.addEventListener('click', () => {+ store.updateProperty(+ entity, component.type, propMeta.name,+ component.data[propMeta.name] ?? currentValue,+ defaultValue+ );+ });+ row.appendChild(resetBtn);+ }++ if (component.type === 'Sprite' && propMeta.name === 'size') {+ const resetBtn = createSpriteSizeResetButton(entity, component, store);+ row.appendChild(resetBtn);+ }++ container.appendChild(row);++ if (hasVisibilityRule) {+ editors.push({+ editor: {+ update() {+ const data = { ...defaults, ...component.data };+ const visible = visibilityResolver.isVisible(propMeta, data, entityComponents);+ row.style.display = visible ? '' : 'none';+ },+ dispose() {},+ },+ componentType: component.type,+ propertyName: `__visibility_${propMeta.name}`,+ });+ }+}++function renderSchemaSection(+ container: HTMLElement,+ sec: import('../../schemas/ComponentSchemas').InspectorSectionDef,+ entity: Entity,+ component: ComponentData,+ store: EditorStore,+ editors: EditorInfo[],+): void {+ const wrapper = document.createElement('div');+ if (sec.title) {+ const secSection = document.createElement('div');+ secSection.className = 'es-property-group es-collapsible es-expanded';++ const secHeader = document.createElement('div');+ secHeader.className = 'es-property-group-divider es-collapsible-header';+ secHeader.innerHTML = `+ <span class="es-collapse-icon">${icons.chevronDown(8)}</span>+ <span class="es-property-group-label">${sec.title}</span>+ <span class="es-property-group-line"></span>+ `;+ secHeader.addEventListener('click', () => {+ secSection.classList.toggle('es-expanded');+ });+ secSection.appendChild(secHeader);++ const secContent = document.createElement('div');+ secContent.className = 'es-collapsible-content';+ secSection.appendChild(secContent);++ const instance = sec.render(secContent, {+ entity,+ componentType: component.type,+ componentData: component.data,+ onChange: (property, oldValue, newValue) => {+ store.updateProperty(entity, component.type, property, oldValue, newValue);+ },+ });+ editors.push({+ editor: { update: (v) => instance.update?.(v as Record<string, unknown>), dispose: () => instance.dispose() },+ componentType: component.type,+ propertyName: `__section_${sec.id}`,+ });++ container.appendChild(secSection);+ } else {+ const instance = sec.render(wrapper, {+ entity,+ componentType: component.type,+ componentData: component.data,+ onChange: (property, oldValue, newValue) => {+ store.updateProperty(entity, component.type, property, oldValue, newValue);+ },+ });+ editors.push({+ editor: { update: (v) => instance.update?.(v as Record<string, unknown>), dispose: () => instance.dispose() },+ componentType: component.type,+ propertyName: `__section_${sec.id}`,+ });+ container.appendChild(wrapper);+ }+}++export function renderTagComponent(+ container: HTMLElement,+ entity: Entity,+ component: ComponentData,+ store: EditorStore+): void {+ const row = document.createElement('div');+ row.className = 'es-component-section es-component-tag-row';+ row.innerHTML = `+ <span class="es-component-icon">${icons.tag(14)}</span>+ <span class="es-component-title">${component.type}</span>+ <button class="es-btn es-btn-icon es-btn-remove">${icons.x(12)}</button>+ `;++ const removeBtn = row.querySelector('.es-btn-remove');+ removeBtn?.addEventListener('click', () => {+ store.removeComponent(entity, component.type);+ });++ container.appendChild(row);+}++function resolveTexturePath(ref: string): string {+ if (!ref) return '';+ if (isUUID(ref)) {+ return getAssetLibrary().getPath(ref) ?? ref;+ }+ return ref;+}++function createSpriteSizeResetButton(+ entity: Entity,+ component: ComponentData,+ store: EditorStore+): HTMLButtonElement {+ const btn = document.createElement('button');+ btn.className = 'es-btn es-btn-icon es-btn-reset-size';+ btn.title = 'Set to original image size';+ btn.innerHTML = icons.maximize(12);++ btn.addEventListener('click', () => {+ const texture = component.data.texture;+ if (!texture) return;++ const relativePath = resolveTexturePath(texture as string);+ if (!relativePath) return;++ const projectDir = getProjectDir();+ if (!projectDir) return;++ const absolutePath = `${projectDir}/${relativePath}`;+ const img = new window.Image();+ img.onload = () => {+ const oldSize = component.data.size ?? getDefaultComponentData('Sprite').size;+ const newSize = { x: img.naturalWidth, y: img.naturalHeight };+ store.updateProperty(entity, 'Sprite', 'size', oldSize, newSize);+ };+ img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);+ });++ return btn;+}diff --git a/editor/src/panels/inspector/EntityHeader.ts b/editor/src/panels/inspector/EntityHeader.tsnew file mode 100644index 000000000..fe48a2903--- /dev/null+++ b/editor/src/panels/inspector/EntityHeader.ts@@ -0,0 +1,124 @@+import type { Entity } from 'esengine';+import type { EditorStore } from '../../store/EditorStore';+import { icons } from '../../utils/icons';+import { getNavigationService } from '../../services';+import { getAssetLibrary, isUUID } from '../../asset/AssetLibrary';+import { escapeHtml } from './InspectorHelpers';+import { isPropertyOverridden, hasAnyOverrides } from '../../prefab';++export function renderEntityHeader(+ container: HTMLElement,+ name: string,+ entity: Entity,+ store: EditorStore+): void {+ const isVisible = store.isEntityVisible(entity as number);+ const visibilityIcon = isVisible ? icons.eye(14) : icons.eyeOff(14);++ const entityData = store.getEntityData(entity as number);+ const entityIcon = entityData?.prefab?.isRoot ? icons.package(16) : icons.box(16);++ const header = document.createElement('div');+ header.className = 'es-inspector-entity-header';+ header.innerHTML = `+ <span class="es-entity-icon">${entityIcon}</span>+ <input type="text" class="es-entity-name-input" value="${escapeHtml(name)}">+ <span class="es-entity-visibility">${visibilityIcon}</span>+ <span class="es-entity-id">ID:${entity}</span>+ `;++ const input = header.querySelector('.es-entity-name-input') as HTMLInputElement;+ input.addEventListener('change', () => {+ const newName = input.value.trim();+ if (newName && newName !== name) {+ store.renameEntity(entity, newName);+ }+ });+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ input.blur();+ } else if (e.key === 'Escape') {+ input.value = name;+ input.blur();+ }+ });++ const visBtn = header.querySelector('.es-entity-visibility');+ visBtn?.addEventListener('click', () => {+ store.toggleVisibility(entity as number);+ });++ container.appendChild(header);++ if (entityData?.prefab) {+ renderPrefabInfoBar(container, entity, entityData, store);+ }+}++function renderPrefabInfoBar(+ container: HTMLElement,+ entity: Entity,+ entityData: import('../../types/SceneTypes').EntityData,+ store: EditorStore+): void {+ const prefab = entityData.prefab!;+ const resolvedPath = isUUID(prefab.prefabPath)+ ? (getAssetLibrary().getPath(prefab.prefabPath) ?? prefab.prefabPath)+ : prefab.prefabPath;+ const pathDisplay = resolvedPath.split('/').pop() ?? resolvedPath;++ const bar = document.createElement('div');+ bar.className = 'es-prefab-info-bar';+ bar.innerHTML = `+ ${icons.package(12)}+ <span class="es-prefab-info-path es-prefab-info-link" title="${escapeHtml(resolvedPath)}">${escapeHtml(pathDisplay)}</span>+ `;++ const pathEl = bar.querySelector('.es-prefab-info-link');+ pathEl?.addEventListener('click', () => {+ getNavigationService().navigateToAsset(resolvedPath);+ });++ if (prefab.basePrefab) {+ const baseResolved = isUUID(prefab.basePrefab)+ ? (getAssetLibrary().getPath(prefab.basePrefab) ?? prefab.basePrefab)+ : prefab.basePrefab;+ const baseDisplay = baseResolved.split('/').pop()?.replace('.esprefab', '') ?? baseResolved;+ const variantLabel = document.createElement('span');+ variantLabel.className = 'es-prefab-variant-label';+ variantLabel.textContent = `Variant of: ${baseDisplay}`;+ variantLabel.title = baseResolved;+ variantLabel.style.cursor = 'pointer';+ variantLabel.style.opacity = '0.7';+ variantLabel.style.fontSize = '11px';+ variantLabel.addEventListener('click', () => {+ getNavigationService().navigateToAsset(baseResolved);+ });+ bar.appendChild(variantLabel);+ }++ if (prefab.isRoot) {+ const overridden = hasAnyOverrides(store.scene, prefab.instanceId);++ const revertBtn = document.createElement('button');+ revertBtn.className = 'es-btn';+ revertBtn.textContent = 'Revert';+ revertBtn.disabled = !overridden;+ revertBtn.addEventListener('click', () => {+ store.revertPrefabInstance(prefab.instanceId, prefab.prefabPath);+ });++ const applyBtn = document.createElement('button');+ applyBtn.className = 'es-btn';+ applyBtn.textContent = 'Apply';+ applyBtn.disabled = !overridden;+ applyBtn.addEventListener('click', () => {+ store.applyPrefabOverrides(prefab.instanceId, prefab.prefabPath);+ });++ bar.appendChild(revertBtn);+ bar.appendChild(applyBtn);+ }++ container.appendChild(bar);+}diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.tsindex 1f9d9e6fa..2252d5a4e 100644--- a/editor/src/panels/inspector/EntityInspector.ts+++ b/editor/src/panels/inspector/EntityInspector.ts@@ -1,848 +1,20 @@-/**- * @file EntityInspector.ts- * @brief Entity inspector rendering: header, components, add-component button- */-import type { Entity } from 'esengine';import type { ComponentData } from '../../types/SceneTypes';import type { EditorStore } from '../../store/EditorStore';-import { createPropertyEditor } from '../../property/PropertyEditor';import {- getComponentSchema,- getDefaultComponentData,getInitialComponentData,- inferPropertyType,- isComponentRemovable,} from '../../schemas/ComponentSchemas';import { icons } from '../../utils/icons';import { showAddComponentPopup } from '../AddComponentPopup';-import { getEditorContext } from '../../context/EditorContext';-import { getNavigationService } from '../../services';-import { getPlatformAdapter } from '../../platform/PlatformAdapter';-import { getAssetLibrary, isUUID } from '../../asset/AssetLibrary';+import { escapeHtml } from './InspectorHelpers';import {- type EditorInfo,- escapeHtml,- getComponentIcon,- getProjectDir,-} from './InspectorHelpers';-import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';-import { isPropertyOverridden, hasAnyOverrides } from '../../prefab';--const COLLAPSED_STORAGE_KEY = 'inspector-collapsed';--function loadCollapsedSet(): Set<string> {- try {- const raw = localStorage.getItem(COLLAPSED_STORAGE_KEY);- return raw ? new Set(JSON.parse(raw)) : new Set();- } catch {- return new Set();- }-}--function saveCollapsedSet(set: Set<string>): void {- localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify([...set]));-}--const collapsedComponents = loadCollapsedSet();-import {- getComponentInspector,getInspectorSections,type InspectorContext,type InspectorSectionInstance,} from './InspectorRegistry';-import { deepEqual } from './SharedEditors';-import { visibilityResolver } from '../../schemas/VisibilityResolver';--// =============================================================================-// Global Augmentation-// =============================================================================--declare global {- interface Window {- __esengine_componentSourceMap?: Map<string, string>;- }-}--// =============================================================================-// Entity Header-// =============================================================================--export function renderEntityHeader(- container: HTMLElement,- name: string,- entity: Entity,- store: EditorStore-): void {- const isVisible = store.isEntityVisible(entity as number);- const visibilityIcon = isVisible ? icons.eye(14) : icons.eyeOff(14);-- const entityData = store.getEntityData(entity as number);- const entityIcon = entityData?.prefab?.isRoot ? icons.package(16) : icons.box(16);-- const header = document.createElement('div');- header.className = 'es-inspector-entity-header';- header.innerHTML = `- <span class="es-entity-icon">${entityIcon}</span>- <input type="text" class="es-entity-name-input" value="${escapeHtml(name)}">- <span class="es-entity-visibility">${visibilityIcon}</span>- <span class="es-entity-id">ID:${entity}</span>- `;-- const input = header.querySelector('.es-entity-name-input') as HTMLInputElement;- input.addEventListener('change', () => {- const newName = input.value.trim();- if (newName && newName !== name) {- store.renameEntity(entity, newName);- }- });- input.addEventListener('keydown', (e) => {- if (e.key === 'Enter') {- input.blur();- } else if (e.key === 'Escape') {- input.value = name;- input.blur();- }- });-- const visBtn = header.querySelector('.es-entity-visibility');- visBtn?.addEventListener('click', () => {- store.toggleVisibility(entity as number);- });-- container.appendChild(header);-- if (entityData?.prefab) {- renderPrefabInfoBar(container, entity, entityData, store);- }-}--function renderPrefabInfoBar(- container: HTMLElement,- entity: Entity,- entityData: import('../../types/SceneTypes').EntityData,- store: EditorStore-): void {- const prefab = entityData.prefab!;- const resolvedPath = isUUID(prefab.prefabPath)- ? (getAssetLibrary().getPath(prefab.prefabPath) ?? prefab.prefabPath)- : prefab.prefabPath;- const pathDisplay = resolvedPath.split('/').pop() ?? resolvedPath;-- const bar = document.createElement('div');- bar.className = 'es-prefab-info-bar';- bar.innerHTML = `- ${icons.package(12)}- <span class="es-prefab-info-path es-prefab-info-link" title="${escapeHtml(resolvedPath)}">${escapeHtml(pathDisplay)}</span>- `;-- const pathEl = bar.querySelector('.es-prefab-info-link');- pathEl?.addEventListener('click', () => {- getNavigationService().navigateToAsset(resolvedPath);- });-- if (prefab.basePrefab) {- const baseResolved = isUUID(prefab.basePrefab)- ? (getAssetLibrary().getPath(prefab.basePrefab) ?? prefab.basePrefab)- : prefab.basePrefab;- const baseDisplay = baseResolved.split('/').pop()?.replace('.esprefab', '') ?? baseResolved;- const variantLabel = document.createElement('span');- variantLabel.className = 'es-prefab-variant-label';- variantLabel.textContent = `Variant of: ${baseDisplay}`;- variantLabel.title = baseResolved;- variantLabel.style.cursor = 'pointer';- variantLabel.style.opacity = '0.7';- variantLabel.style.fontSize = '11px';- variantLabel.addEventListener('click', () => {- getNavigationService().navigateToAsset(baseResolved);- });- bar.appendChild(variantLabel);- }-- if (prefab.isRoot) {- const overridden = hasAnyOverrides(store.scene, prefab.instanceId);-- const revertBtn = document.createElement('button');- revertBtn.className = 'es-btn';- revertBtn.textContent = 'Revert';- revertBtn.disabled = !overridden;- revertBtn.addEventListener('click', () => {- store.revertPrefabInstance(prefab.instanceId, prefab.prefabPath);- });-- const applyBtn = document.createElement('button');- applyBtn.className = 'es-btn';- applyBtn.textContent = 'Apply';- applyBtn.disabled = !overridden;- applyBtn.addEventListener('click', () => {- store.applyPrefabOverrides(prefab.instanceId, prefab.prefabPath);- });-- bar.appendChild(revertBtn);- bar.appendChild(applyBtn);- }-- container.appendChild(bar);-}--// =============================================================================-// Component Rendering-// =============================================================================--export function renderComponent(- container: HTMLElement,- entity: Entity,- component: ComponentData,- store: EditorStore,- editors: EditorInfo[],- componentIndex: number = 0,- componentCount: number = 1-): void {- const schema = getComponentSchema(component.type);- if (!schema) {- console.warn(`[Inspector] No schema found for component "${component.type}"`);- }- if (schema?.hidden) return;- if (schema?.category === 'tag') {- renderTagComponent(container, entity, component, store);- return;- }-- const defaults = getDefaultComponentData(component.type);- const displayTitle = schema?.displayName ?? component.type;-- const section = document.createElement('div');- const isCollapsed = collapsedComponents.has(component.type);- section.className = `es-component-section es-collapsible${isCollapsed ? '' : ' es-expanded'}`;-- const icon = getComponentIcon(component.type);- const removable = isComponentRemovable(component.type);-- const hasEnabled = 'enabled' in defaults;- const isEnabled = hasEnabled ? (component.data.enabled ?? defaults.enabled) !== false : true;-- if (hasEnabled && !isEnabled) {- section.dataset.enabled = 'false';- }-- const header = document.createElement('div');- header.className = 'es-component-header es-collapsible-header';- header.innerHTML = `- <span class="es-collapse-icon">${icons.chevronDown(12)}</span>- <span class="es-component-icon">${icon}</span>- <span class="es-component-title">${displayTitle}</span>- ${hasEnabled ? `<input type="checkbox" class="es-component-enabled-toggle" title="Enable/Disable component" ${isEnabled ? 'checked' : ''}>` : ''}- ${removable ? `<button class="es-btn es-btn-icon es-btn-remove">${icons.x(12)}</button>` : ''}- `;-- if (hasEnabled) {- const toggle = header.querySelector('.es-component-enabled-toggle') as HTMLInputElement;- toggle?.addEventListener('click', (e) => {- e.stopPropagation();- });- toggle?.addEventListener('change', () => {- const oldValue = component.data.enabled ?? defaults.enabled;- store.updateProperty(entity, component.type, 'enabled', oldValue, toggle.checked);- });- }-- if (removable) {- const removeBtn = header.querySelector('.es-btn-remove');- removeBtn?.addEventListener('click', () => {- store.removeComponent(entity, component.type);- });- }-- header.addEventListener('click', (e) => {- if ((e.target as HTMLElement).closest('.es-btn-remove')) return;- if ((e.target as HTMLElement).closest('.es-component-enabled-toggle')) return;- section.classList.toggle('es-expanded');- if (section.classList.contains('es-expanded')) {- collapsedComponents.delete(component.type);- } else {- collapsedComponents.add(component.type);- }- saveCollapsedSet(collapsedComponents);- });-- header.addEventListener('contextmenu', (e) => {- e.preventDefault();- const menuItems: ContextMenuItem[] = [- {- label: 'Reset to Default',- icon: icons.rotateCcw(14),- onClick: () => {- const changes = Object.keys(defaults).map(key => ({- property: key,- oldValue: component.data[key] ?? defaults[key],- newValue: defaults[key],- }));- if (changes.length > 0) {- store.updateProperties(entity, component.type, changes);- }- },- },- {- label: 'Copy Component',- icon: icons.copy(14),- onClick: () => {- const payload = JSON.stringify({ type: component.type, data: component.data });- navigator.clipboard.writeText(payload);- },- },- {- label: 'Paste Component Values',- icon: icons.clipboard(14),- onClick: async () => {- try {- const text = await navigator.clipboard.readText();- const parsed = JSON.parse(text);- if (parsed.type === component.type && parsed.data) {- const changes = Object.keys(parsed.data).map(key => ({- property: key,- oldValue: component.data[key] ?? defaults[key],- newValue: parsed.data[key],- }));- if (changes.length > 0) {- store.updateProperties(entity, component.type, changes);- }- }- } catch { /* ignore invalid clipboard data */ }- },- },- { label: '', separator: true },- {- label: 'Move Up',- icon: icons.arrowUp(14),- disabled: componentIndex <= 0,- onClick: () => {- store.reorderComponent(entity, componentIndex, componentIndex - 1);- },- },- {- label: 'Move Down',- icon: icons.arrowDown(14),- disabled: componentIndex >= componentCount - 1,- onClick: () => {- store.reorderComponent(entity, componentIndex, componentIndex + 1);- },- },- ];-- if (removable) {- menuItems.push(- { label: '', separator: true },- {- label: 'Remove',- icon: icons.trash(14),- onClick: () => {- store.removeComponent(entity, component.type);- },- }- );- }-- showContextMenu({ items: menuItems, x: e.clientX, y: e.clientY });- });-- if (schema?.category === 'script') {- header.addEventListener('dblclick', () => {- const sourceMap = window.__esengine_componentSourceMap;- const scriptPath = sourceMap?.get(component.type);- if (!scriptPath) return;- const projectDir = getProjectDir();- if (projectDir) {- getEditorContext().shell?.openInEditor(projectDir, scriptPath);- }- });- }-- section.appendChild(header);-- if (schema?.description) {- const desc = document.createElement('div');- desc.className = 'es-component-description es-collapsible-content';- desc.textContent = schema.description;- section.appendChild(desc);- }-- const customInspector = getComponentInspector(component.type);- if (customInspector) {- const propsContainer = document.createElement('div');- propsContainer.className = 'es-component-properties es-collapsible-content';- const instance = customInspector.render(propsContainer, {- store,- entity,- componentType: component.type,- componentData: component.data,- onChange: (property, oldValue, newValue) => {- store.updateProperty(entity, component.type, property, oldValue, newValue);- },- });- if (instance) {- editors.push({- editor: instance,- componentType: component.type,- propertyName: '*',- });- }- section.appendChild(propsContainer);- container.appendChild(section);- return;- }-- const entityData = store.getEntityData(entity as number);- const entityComponents = entityData?.components.map(c => c.type) ?? [];-- if (schema) {- const propsContainer = document.createElement('div');- propsContainer.className = 'es-component-properties es-collapsible-content';-- const ungrouped: import('../../property/PropertyEditor').PropertyMeta[] = [];- const groups = new Map<string, import('../../property/PropertyEditor').PropertyMeta[]>();- const groupOrder: string[] = [];- const advancedProps: import('../../property/PropertyEditor').PropertyMeta[] = [];- for (const propMeta of schema.properties) {- if (propMeta.advanced) {- advancedProps.push(propMeta);- } else if (propMeta.group) {- if (!groups.has(propMeta.group)) {- groups.set(propMeta.group, []);- groupOrder.push(propMeta.group);- }- groups.get(propMeta.group)!.push(propMeta);- } else {- ungrouped.push(propMeta);- }- }-- for (const propMeta of ungrouped) {- renderPropertyRow(propsContainer, propMeta, entity, component, defaults, store, editors, entityComponents);- }-- for (const groupName of groupOrder) {- const groupSection = document.createElement('div');- groupSection.className = 'es-property-group es-collapsible es-expanded';-- const groupHeader = document.createElement('div');- groupHeader.className = 'es-property-group-divider es-collapsible-header';- groupHeader.innerHTML = `- <span class="es-collapse-icon">${icons.chevronDown(8)}</span>- <span class="es-property-group-label">${groupName}</span>- <span class="es-property-group-line"></span>- `;- groupHeader.addEventListener('click', () => {- groupSection.classList.toggle('es-expanded');- });- groupSection.appendChild(groupHeader);-- const groupContent = document.createElement('div');- groupContent.className = 'es-collapsible-content';- for (const propMeta of groups.get(groupName)!) {- renderPropertyRow(groupContent, propMeta, entity, component, defaults, store, editors, entityComponents);- }- groupSection.appendChild(groupContent);-- propsContainer.appendChild(groupSection);-- if (schema.sections) {- for (const sec of schema.sections) {- if (sec.insertAfterGroup === groupName) {- renderSchemaSection(propsContainer, sec, entity, component, store, editors);- }- }- }- }-- if (schema.sections) {- for (const sec of schema.sections) {- if (!sec.insertAfterGroup) {- renderSchemaSection(propsContainer, sec, entity, component, store, editors);- }- }- }-- if (advancedProps.length > 0) {- const advSection = document.createElement('div');- advSection.className = 'es-property-group es-collapsible';-- const advHeader = document.createElement('div');- advHeader.className = 'es-property-group-divider es-collapsible-header';- advHeader.innerHTML = `- <span class="es-collapse-icon">${icons.chevronDown(8)}</span>- <span class="es-property-group-label">Advanced</span>- <span class="es-property-group-line"></span>- `;- advHeader.addEventListener('click', () => {- advSection.classList.toggle('es-expanded');- });- advSection.appendChild(advHeader);-- const advContent = document.createElement('div');- advContent.className = 'es-collapsible-content';- for (const propMeta of advancedProps) {- renderPropertyRow(advContent, propMeta, entity, component, defaults, store, editors, entityComponents);- }- advSection.appendChild(advContent);- propsContainer.appendChild(advSection);- }-- section.appendChild(propsContainer);- } else {- const propsContainer = document.createElement('div');- propsContainer.className = 'es-component-properties es-collapsible-content';-- const fullData = { ...defaults, ...component.data };- for (const [key, value] of Object.entries(fullData)) {- const row = document.createElement('div');- row.className = 'es-property-row';-- const label = document.createElement('label');- label.className = 'es-property-label';- label.textContent = key;-- const editorContainer = document.createElement('div');- editorContainer.className = 'es-property-editor';-- const propMeta: import('../../property/PropertyEditor').PropertyMeta = {- name: key,- type: inferPropertyType(value),- };-- let currentValue = component.data[key];- if (currentValue === undefined) {- currentValue = defaults[key];- }- const editor = createPropertyEditor(editorContainer, {- value: currentValue,- meta: propMeta,- onChange: (newValue) => {- const oldValue = component.data[key] ?? currentValue;- store.updateProperty(entity, component.type, key, oldValue, newValue);- },- componentData: component.data,- getComponentValue: (name: string) => component.data[name],- getCurrentValue: () => component.data[key] ?? defaults[key],- entityComponents,- });-- if (editor) {- editors.push({- editor,- componentType: component.type,- propertyName: key,- });- }-- row.appendChild(label);- row.appendChild(editorContainer);- propsContainer.appendChild(row);- }-- section.appendChild(propsContainer);- }-- container.appendChild(section);-}--// =============================================================================-// Property Row Rendering-// =============================================================================--function renderPropertyRow(- container: HTMLElement,- propMeta: import('../../property/PropertyEditor').PropertyMeta,- entity: Entity,- component: ComponentData,- defaults: Record<string, unknown>,- store: EditorStore,- editors: EditorInfo[],- entityComponents: string[] = []-): void {- if (propMeta.name === '*') {- const editorContainer = document.createElement('div');- editorContainer.className = 'es-property-editor es-property-editor-full';-- const fullData = { ...defaults, ...component.data };-- const editor = createPropertyEditor(editorContainer, {- value: fullData,- meta: propMeta,- onChange: (changes) => {- const arr = changes as { property: string; oldValue: unknown; newValue: unknown }[];- store.updateProperties(entity, component.type, arr);- },- componentData: component.data,- getComponentValue: (name: string) => component.data[name],- getCurrentValue: () => ({ ...defaults, ...component.data }),- });-- if (editor) {- editors.push({- editor,- componentType: component.type,- propertyName: '*',- });- }-- container.appendChild(editorContainer);- return;- }-- const hasVisibilityRule = propMeta.visibleWhen != null || propMeta.hiddenWhen != null;- const fullData = { ...defaults, ...component.data };- const initiallyVisible = visibilityResolver.isVisible(propMeta, fullData, entityComponents);-- if (!initiallyVisible && !hasVisibilityRule) {- return;- }-- const row = document.createElement('div');- row.className = 'es-property-row';- if (!initiallyVisible) {- row.style.display = 'none';- }-- const entityData = store.getEntityData(entity as number);- if (entityData?.prefab && isPropertyOverridden(- store.scene,- entity as number,- component.type,- propMeta.name- )) {- row.classList.add('es-overridden');- }-- const label = document.createElement('label');- label.className = 'es-property-label';- label.textContent = propMeta.displayName ?? propMeta.name;- if (propMeta.tooltip) {- label.dataset.tooltip = propMeta.tooltip;- }-- const editorContainer = document.createElement('div');- editorContainer.className = 'es-property-editor';- if (propMeta.readOnly) {- editorContainer.classList.add('es-property-readonly');- }-- let currentValue = component.data[propMeta.name];- if (currentValue === undefined) {- currentValue = defaults[propMeta.name];- }- const editor = createPropertyEditor(editorContainer, {- value: currentValue,- meta: propMeta,- onChange: propMeta.readOnly ? () => {} : (newValue) => {- const oldValue = component.data[propMeta.name] ?? currentValue;- store.updateProperty(- entity,- component.type,- propMeta.name,- oldValue,- newValue- );- },- componentData: component.data,- getComponentValue: (name: string) => component.data[name],- getCurrentValue: () => component.data[propMeta.name] ?? defaults[propMeta.name],- entityComponents,- });-- if (editor) {- editors.push({- editor,- componentType: component.type,- propertyName: propMeta.name,- });- }-- row.appendChild(label);- row.appendChild(editorContainer);-- const defaultValue = defaults[propMeta.name];- const isModified = currentValue !== undefined &&- !deepEqual(currentValue, defaultValue);-- if (isModified) {- const resetBtn = document.createElement('button');- resetBtn.className = 'es-property-reset';- resetBtn.title = `Reset to default`;- resetBtn.innerHTML = icons.rotateCcw(10);- resetBtn.addEventListener('click', () => {- store.updateProperty(- entity, component.type, propMeta.name,- component.data[propMeta.name] ?? currentValue,- defaultValue- );- });- row.appendChild(resetBtn);- }-- if (component.type === 'Sprite' && propMeta.name === 'size') {- const resetBtn = createSpriteSizeResetButton(entity, component, store);- row.appendChild(resetBtn);- }-- container.appendChild(row);-- if (hasVisibilityRule) {- editors.push({- editor: {- update() {- const data = { ...defaults, ...component.data };- const visible = visibilityResolver.isVisible(propMeta, data, entityComponents);- row.style.display = visible ? '' : 'none';- },- dispose() {},- },- componentType: component.type,- propertyName: `__visibility_${propMeta.name}`,- });- }-}--// =============================================================================-// Schema Sections (Hybrid Inspector)-// =============================================================================--function renderSchemaSection(- container: HTMLElement,- sec: import('../../schemas/ComponentSchemas').InspectorSectionDef,- entity: Entity,- component: ComponentData,- store: EditorStore,- editors: EditorInfo[],-): void {- const wrapper = document.createElement('div');- if (sec.title) {- const secSection = document.createElement('div');- secSection.className = 'es-property-group es-collapsible es-expanded';-- const secHeader = document.createElement('div');- secHeader.className = 'es-property-group-divider es-collapsible-header';- secHeader.innerHTML = `- <span class="es-collapse-icon">${icons.chevronDown(8)}</span>- <span class="es-property-group-label">${sec.title}</span>- <span class="es-property-group-line"></span>- `;- secHeader.addEventListener('click', () => {- secSection.classList.toggle('es-expanded');- });- secSection.appendChild(secHeader);-- const secContent = document.createElement('div');- secContent.className = 'es-collapsible-content';- secSection.appendChild(secContent);-- const instance = sec.render(secContent, {- entity,- componentType: component.type,- componentData: component.data,- onChange: (property, oldValue, newValue) => {- store.updateProperty(entity, component.type, property, oldValue, newValue);- },- });- editors.push({- editor: { update: (v) => instance.update?.(v as Record<string, unknown>), dispose: () => instance.dispose() },- componentType: component.type,- propertyName: `__section_${sec.id}`,- });-- container.appendChild(secSection);- } else {- const instance = sec.render(wrapper, {- entity,- componentType: component.type,- componentData: component.data,- onChange: (property, oldValue, newValue) => {- store.updateProperty(entity, component.type, property, oldValue, newValue);- },- });- editors.push({- editor: { update: (v) => instance.update?.(v as Record<string, unknown>), dispose: () => instance.dispose() },- componentType: component.type,- propertyName: `__section_${sec.id}`,- });- container.appendChild(wrapper);- }-}--// =============================================================================-// Tag Component-// =============================================================================--export function renderTagComponent(- container: HTMLElement,- entity: Entity,- component: ComponentData,- store: EditorStore-): void {- const row = document.createElement('div');- row.className = 'es-component-section es-component-tag-row';- row.innerHTML = `- <span class="es-component-icon">${icons.tag(14)}</span>- <span class="es-component-title">${component.type}</span>- <button class="es-btn es-btn-icon es-btn-remove">${icons.x(12)}</button>- `;-- const removeBtn = row.querySelector('.es-btn-remove');- removeBtn?.addEventListener('click', () => {- store.removeComponent(entity, component.type);- });-- container.appendChild(row);-}--// =============================================================================-// Sprite Size Reset-// =============================================================================--function resolveTexturePath(ref: string): string {- if (!ref) return '';- if (isUUID(ref)) {- return getAssetLibrary().getPath(ref) ?? ref;- }- return ref;-}--function createSpriteSizeResetButton(- entity: Entity,- component: ComponentData,- store: EditorStore-): HTMLButtonElement {- const btn = document.createElement('button');- btn.className = 'es-btn es-btn-icon es-btn-reset-size';- btn.title = 'Set to original image size';- btn.innerHTML = icons.maximize(12);-- btn.addEventListener('click', () => {- const texture = component.data.texture;- if (!texture) return;-- const relativePath = resolveTexturePath(texture as string);- if (!relativePath) return;-- const projectDir = getProjectDir();- if (!projectDir) return;-- const absolutePath = `${projectDir}/${relativePath}`;- const img = new window.Image();- img.onload = () => {- const oldSize = component.data.size ?? getDefaultComponentData('Sprite').size;- const newSize = { x: img.naturalWidth, y: img.naturalHeight };- store.updateProperty(entity, 'Sprite', 'size', oldSize, newSize);- };- img.src = getPlatformAdapter().convertFilePathToUrl(absolutePath);- });-- return btn;-}--// =============================================================================-// Add Component Button-// =============================================================================+export { renderEntityHeader } from './EntityHeader';+export { renderComponent, renderTagComponent } from './ComponentRenderer';export function renderAddComponentButton(container: HTMLElement,@@ -869,10 +41,6 @@ export function renderAddComponentButton(container.appendChild(wrapper);}-// =============================================================================-// Extension Sections-// =============================================================================-export function renderEntityExtensionSections(container: HTMLElement,entity: Entity,diff --git a/editor/src/panels/timeline/TimelineHitTest.ts b/editor/src/panels/timeline/TimelineHitTest.tsnew file mode 100644index 000000000..71deca7b4--- /dev/null+++ b/editor/src/panels/timeline/TimelineHitTest.ts@@ -0,0 +1,396 @@+import type { TimelineState } from './TimelineState';+import {+ RULER_HEIGHT,+ TRACK_HEIGHT,+} from './TimelineState';+import type {+ TimelineAssetData,+ KeyframeHit,+ SpineClipHit,+ AudioEventHit,+ ActivationRangeHit,+ MarkerHit,+ CustomEventHit,+ SpriteAnimHit,+ AnimFrameHit,+ AnimFrameData,+ NonPropertyHit,+} from './TimelineTypes';++const KEYFRAME_HIT_RADIUS = 6;+const EDGE_RESIZE_ZONE = 8;++export function hitTestKeyframe(+ x: number,+ y: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): KeyframeHit | null {+ if (!assetData) return null;++ const tracks = state.tracks;+ let rowY = RULER_HEIGHT;++ for (let i = 0; i < tracks.length; i++) {+ const track = tracks[i];+ const assetTrack = assetData.tracks[track.index];++ if (assetTrack?.type === 'property' && assetTrack.channels) {+ if (y >= rowY && y < rowY + TRACK_HEIGHT) {+ const hit = hitTestChannelKeyframes(assetTrack.channels, x, rowY, track.index, state);+ if (hit) return hit;+ }+ }+ rowY += TRACK_HEIGHT;++ if (track.expanded && track.channelCount > 0 && assetTrack?.type === 'property') {+ for (let c = 0; c < track.channelCount; c++) {+ if (y >= rowY && y < rowY + TRACK_HEIGHT) {+ const channel = assetTrack.channels?.[c];+ if (channel) {+ const hit = hitTestSingleChannel(channel.keyframes, x, rowY, track.index, c, state);+ if (hit) return hit;+ }+ }+ rowY += TRACK_HEIGHT;+ }+ }+ }++ return null;+}++function hitTestChannelKeyframes(+ channels: { keyframes: { time: number }[] }[],+ x: number,+ rowY: number,+ trackIndex: number,+ state: TimelineState,+): KeyframeHit | null {+ for (let c = 0; c < channels.length; c++) {+ const hit = hitTestSingleChannel(channels[c].keyframes, x, rowY, trackIndex, c, state);+ if (hit) return hit;+ }+ return null;+}++function hitTestSingleChannel(+ keyframes: { time: number }[],+ x: number,+ rowY: number,+ trackIndex: number,+ channelIndex: number,+ state: TimelineState,+): KeyframeHit | null {+ const cy = rowY + TRACK_HEIGHT / 2;++ for (let ki = 0; ki < keyframes.length; ki++) {+ const kf = keyframes[ki];+ const kx = state.timeToX(kf.time);+ const dx = x - kx;+ const dy = (rowY + TRACK_HEIGHT / 2) - cy;++ if (Math.abs(dx) <= KEYFRAME_HIT_RADIUS && Math.abs(dy) <= KEYFRAME_HIT_RADIUS) {+ return { trackIndex, channelIndex, keyframeIndex: ki, time: kf.time };+ }+ }+ return null;+}++export function hitTestSpineClip(+ x: number,+ y: number,+ trackIndex: number,+ rowY: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): SpineClipHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'spine' || !track.clips) return null;+ if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;++ for (let i = 0; i < track.clips.length; i++) {+ const clip = track.clips[i];+ const x1 = state.timeToX(clip.start);+ const x2 = state.timeToX(clip.start + clip.duration);+ if (x >= x1 && x <= x2) {+ const zone = (x2 - x) <= EDGE_RESIZE_ZONE ? 'resize' : 'body';+ return { trackIndex, clipIndex: i, zone };+ }+ }+ return null;+}++export function hitTestAudioEvent(+ x: number,+ y: number,+ trackIndex: number,+ rowY: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): AudioEventHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'audio' || !track.events) return null;+ if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;++ for (let i = 0; i < track.events.length; i++) {+ const ex = state.timeToX(track.events[i].time);+ if (Math.abs(x - ex) <= KEYFRAME_HIT_RADIUS) {+ return { trackIndex, eventIndex: i };+ }+ }+ return null;+}++export function hitTestActivationRange(+ x: number,+ y: number,+ trackIndex: number,+ rowY: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): ActivationRangeHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'activation' || !track.ranges) return null;+ if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;++ for (let i = 0; i < track.ranges.length; i++) {+ const range = track.ranges[i];+ const x1 = state.timeToX(range.start);+ const x2 = state.timeToX(range.end);+ if (x >= x1 && x <= x2) {+ const zone = (x - x1) <= EDGE_RESIZE_ZONE ? 'left'+ : (x2 - x) <= EDGE_RESIZE_ZONE ? 'right'+ : 'body';+ return { trackIndex, rangeIndex: i, zone };+ }+ }+ return null;+}++export function hitTestMarker(+ x: number,+ trackIndex: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): MarkerHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'marker' || !track.markers) return null;++ for (let i = 0; i < track.markers.length; i++) {+ const mx = state.timeToX(track.markers[i].time);+ if (Math.abs(x - mx) <= KEYFRAME_HIT_RADIUS) {+ return { trackIndex, markerIndex: i };+ }+ }+ return null;+}++export function hitTestCustomEvent(+ x: number,+ trackIndex: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): CustomEventHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'customEvent' || !track.events) return null;++ for (let i = 0; i < track.events.length; i++) {+ const ex = state.timeToX(track.events[i].time);+ if (Math.abs(x - ex) <= KEYFRAME_HIT_RADIUS) {+ return { trackIndex, eventIndex: i };+ }+ }+ return null;+}++export function hitTestSpriteAnim(+ x: number,+ trackIndex: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): SpriteAnimHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'spriteAnim' || track.startTime == null) return null;++ const sx = state.timeToX(track.startTime);+ if (Math.abs(x - sx) <= KEYFRAME_HIT_RADIUS) {+ return { trackIndex };+ }+ return null;+}++export function hitTestAnimFrame(+ x: number,+ trackIndex: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): AnimFrameHit | null {+ if (!assetData) return null;+ const track = assetData.tracks[trackIndex];+ if (!track || track.type !== 'animFrames' || !track.animFrames) return null;++ const fps = state.animClipFps;+ const defaultDur = 1 / fps;+ let time = 0;++ for (let i = 0; i < track.animFrames.length; i++) {+ const dur = (track.animFrames[i] as AnimFrameData).duration ?? defaultDur;+ const x1 = state.timeToX(time);+ const x2 = state.timeToX(time + dur);++ if (x >= x1 && x <= x2) {+ const zone = (x2 - x) <= EDGE_RESIZE_ZONE ? 'resize' : 'body';+ return { trackIndex, frameIndex: i, zone };+ }+ time += dur;+ }+ return null;+}++export function hitTestNonPropertyTrack(+ x: number,+ y: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): NonPropertyHit | null {+ if (!assetData) return null;++ const tracks = state.tracks;+ let rowY = RULER_HEIGHT;++ for (let i = 0; i < tracks.length; i++) {+ const track = tracks[i];+ const assetTrack = assetData.tracks[track.index];++ if (y >= rowY && y < rowY + TRACK_HEIGHT && assetTrack) {+ if (assetTrack.type === 'spine') {+ const hit = hitTestSpineClip(x, y, track.index, rowY, state, assetData);+ if (hit) return { type: 'spine', hit };+ } else if (assetTrack.type === 'audio') {+ const hit = hitTestAudioEvent(x, y, track.index, rowY, state, assetData);+ if (hit) return { type: 'audio', hit };+ } else if (assetTrack.type === 'activation') {+ const hit = hitTestActivationRange(x, y, track.index, rowY, state, assetData);+ if (hit) return { type: 'activation', hit };+ } else if (assetTrack.type === 'marker') {+ const hit = hitTestMarker(x, track.index, state, assetData);+ if (hit) return { type: 'marker', hit };+ } else if (assetTrack.type === 'customEvent') {+ const hit = hitTestCustomEvent(x, track.index, state, assetData);+ if (hit) return { type: 'customEvent', hit };+ } else if (assetTrack.type === 'spriteAnim') {+ const hit = hitTestSpriteAnim(x, track.index, state, assetData);+ if (hit) return { type: 'spriteAnim', hit };+ } else if (assetTrack.type === 'animFrames') {+ const hit = hitTestAnimFrame(x, track.index, state, assetData);+ if (hit) return { type: 'animFrames', hit };+ }+ }+ rowY += TRACK_HEIGHT;++ if (track.expanded && track.channelCount > 0) {+ rowY += track.channelCount * TRACK_HEIGHT;+ }+ }+ return null;+}++export function collectKeyframesInRect(+ x1: number, y1: number, x2: number, y2: number,+ state: TimelineState,+ assetData: TimelineAssetData | null,+): KeyframeHit[] {+ if (!assetData) return [];++ const minX = Math.min(x1, x2);+ const maxX = Math.max(x1, x2);+ const minY = Math.min(y1, y2);+ const maxY = Math.max(y1, y2);+ const hits: KeyframeHit[] = [];++ const tracks = state.tracks;+ let rowY = RULER_HEIGHT;++ for (let i = 0; i < tracks.length; i++) {+ const track = tracks[i];+ const assetTrack = assetData.tracks[track.index];++ if (assetTrack?.type === 'property' && assetTrack.channels) {+ if (rowY + TRACK_HEIGHT > minY && rowY < maxY) {+ for (let c = 0; c < assetTrack.channels.length; c++) {+ collectChannelKeyframesInRange(+ assetTrack.channels[c].keyframes, minX, maxX,+ track.index, c, hits, state,+ );+ }+ }+ }+ rowY += TRACK_HEIGHT;++ if (track.expanded && track.channelCount > 0 && assetTrack?.type === 'property') {+ for (let c = 0; c < track.channelCount; c++) {+ if (rowY + TRACK_HEIGHT > minY && rowY < maxY) {+ const channel = assetTrack.channels?.[c];+ if (channel) {+ collectChannelKeyframesInRange(+ channel.keyframes, minX, maxX,+ track.index, c, hits, state,+ );+ }+ }+ rowY += TRACK_HEIGHT;+ }+ }+ }++ return hits;+}++function collectChannelKeyframesInRange(+ keyframes: { time: number }[],+ minX: number, maxX: number,+ trackIndex: number, channelIndex: number,+ out: KeyframeHit[],+ state: TimelineState,+): void {+ for (let ki = 0; ki < keyframes.length; ki++) {+ const kx = state.timeToX(keyframes[ki].time);+ if (kx >= minX && kx <= maxX) {+ out.push({ trackIndex, channelIndex, keyframeIndex: ki, time: keyframes[ki].time });+ }+ }+}++export function getTrackAtY(+ y: number,+ state: TimelineState,+): { trackIndex: number; channelIndex: number; isChannel: boolean } | null {+ const tracks = state.tracks;+ let rowY = RULER_HEIGHT;++ for (let i = 0; i < tracks.length; i++) {+ const track = tracks[i];++ if (y >= rowY && y < rowY + TRACK_HEIGHT) {+ return { trackIndex: track.index, channelIndex: -1, isChannel: false };+ }+ rowY += TRACK_HEIGHT;++ if (track.expanded && track.channelCount > 0) {+ for (let c = 0; c < track.channelCount; c++) {+ if (y >= rowY && y < rowY + TRACK_HEIGHT) {+ return { trackIndex: track.index, channelIndex: c, isChannel: true };+ }+ rowY += TRACK_HEIGHT;+ }+ }+ }+ return null;+}diff --git a/editor/src/panels/timeline/TimelineKeyframeArea.ts b/editor/src/panels/timeline/TimelineKeyframeArea.tsindex 6c4c55289..81a4a0fea 100644--- a/editor/src/panels/timeline/TimelineKeyframeArea.ts+++ b/editor/src/panels/timeline/TimelineKeyframeArea.ts@@ -2,7 +2,6 @@ import type { TimelineState } from './TimelineState';import {RULER_HEIGHT,TRACK_HEIGHT,- KEYFRAME_SIZE,MIN_PIXELS_PER_SECOND,MAX_PIXELS_PER_SECOND,} from './TimelineState';@@ -43,178 +42,61 @@ import {ReorderAnimFrameCommand,ResizeAnimFrameCommand,} from './TimelineTrackCommands';-import { isUUID, getAssetLibrary } from '../../asset/AssetDatabase';--const RULER_BG = '#1e1e1e';-const RULER_TEXT = '#888888';-const RULER_LINE = '#333333';-const TRACK_BG_EVEN = '#252525';-const TRACK_BG_ODD = '#2a2a2a';-const TRACK_SELECTED_BG = '#2c3e50';-const KEYFRAME_COLOR = '#e5c07b';-const KEYFRAME_SELECTED = '#61afef';-const PLAYHEAD_COLOR = '#e06c75';-const SPINE_CLIP_COLOR = 'rgba(97, 175, 239, 0.3)';-const SPINE_CLIP_BORDER = '#61afef';-const ACTIVATION_COLOR = 'rgba(152, 195, 121, 0.3)';-const ACTIVATION_BORDER = '#98c379';-const AUDIO_EVENT_COLOR = '#d19a66';-const CHANNEL_BG = '#1e1e1e';-const KEYFRAME_HIT_RADIUS = 6;-const EDGE_RESIZE_ZONE = 8;-const FRAME_STEP = 1 / 60;-const RUBBERBAND_COLOR = 'rgba(97, 175, 239, 0.2)';-const RUBBERBAND_BORDER = 'rgba(97, 175, 239, 0.6)';-const MARKER_COLOR = '#c678dd';-const CUSTOM_EVENT_COLOR = '#56b6c2';-const SPRITE_ANIM_COLOR = 'rgba(229, 192, 123, 0.3)';-const SPRITE_ANIM_BORDER = '#e5c07b';-const DURATION_LINE_COLOR = '#e5c07b';-const BEYOND_DURATION_COLOR = 'rgba(0, 0, 0, 0.2)';-const ANIM_FRAME_COLORS = ['#61afef', '#c678dd', '#e5c07b', '#98c379', '#d19a66', '#56b6c2', '#e06c75'];-const ANIM_FRAME_BORDER = '#ffffff30';--interface SpineClipHit {- trackIndex: number;- clipIndex: number;- zone: 'body' | 'resize';-}--interface AudioEventHit {- trackIndex: number;- eventIndex: number;-}--interface ActivationRangeHit {- trackIndex: number;- rangeIndex: number;- zone: 'body' | 'left' | 'right';-}--interface MarkerHit {- trackIndex: number;- markerIndex: number;-}--interface CustomEventHit {- trackIndex: number;- eventIndex: number;-}--interface SpriteAnimHit {- trackIndex: number;-}--interface AnimFrameHit {- trackIndex: number;- frameIndex: number;- zone: 'body' | 'resize';-}--export interface TimelineAssetData {- tracks: TimelineTrackData[];- duration: number;-}--export interface TimelineKeyframe {- time: number;- value: number;- inTangent?: number;- outTangent?: number;- interpolation?: string;-}--export interface TimelineChannel {- property: string;- keyframes: TimelineKeyframe[];-}--export interface TimelineSpineClip {- start: number;- duration: number;- animation: string;-}--export interface TimelineAudioEvent {- time: number;- clip: string;-}--export interface TimelineCustomEvent {- time: number;- name: string;- payload: Record<string, unknown>;-}--export interface TimelineActivationRange {- start: number;- end: number;-}--export interface TimelineMarker {- time: number;- name: string;-}--export interface AnimFrameData {- texture: string;- duration?: number;- thumbnailUrl?: string;-}--export interface TimelineTrackData {- type: string;- name: string;- childPath?: string;- component?: string;- channels?: TimelineChannel[];- clips?: TimelineSpineClip[];- events?: (TimelineAudioEvent | TimelineCustomEvent)[];- ranges?: TimelineActivationRange[];- markers?: TimelineMarker[];- clip?: string;- startTime?: number;- animFrames?: AnimFrameData[];-}--interface KeyframeHit {- trackIndex: number;- channelIndex: number;- keyframeIndex: number;- time: number;-}--export interface TimelinePanelHost {- get assetData(): TimelineAssetData | null;- executeCommand(cmd: import('../../commands/Command').Command): void;- onAssetDataChanged(): void;- readPropertyValue(trackIndex: number, channelIndex: number): number;-}--export interface SelectedKeyframeInfo {- trackIndex: number;- channelIndex: number;- keyframeIndex: number;- time: number;- value: number;-}--export interface SelectionSummary {- count: number;- single: SelectedKeyframeInfo | null;-}--export type KeyframeSelectionCallback = (summary: SelectionSummary) => void;+import {+ kfKey,+ type KeyframeHit,+ type SpineClipHit,+ type AudioEventHit,+ type ActivationRangeHit,+ type MarkerHit,+ type CustomEventHit,+ type SpriteAnimHit,+ type AnimFrameHit,+ type TimelineAssetData,+ type TimelineCustomEvent,+ type AnimFrameData,+ type KeyframeSelectionCallback,+ type NonPropertyHit,+} from './TimelineTypes';+import {+ drawRuler,+ drawTracks,+ drawPlayhead,+ drawDurationEnd,+ drawRubberBand,+ type TimelineRenderContext,+} from './TimelineRenderer';+import {+ hitTestKeyframe,+ hitTestNonPropertyTrack,+ collectKeyframesInRect,+ getTrackAtY,+} from './TimelineHitTest';++export type {+ TimelineAssetData,+ TimelineKeyframe,+ TimelineChannel,+ TimelineSpineClip,+ TimelineAudioEvent,+ TimelineCustomEvent,+ TimelineActivationRange,+ TimelineMarker,+ AnimFrameData,+ TimelineTrackData,+ TimelinePanelHost,+ SelectedKeyframeInfo,+ SelectionSummary,+ KeyframeSelectionCallback,+} from './TimelineTypes';-function kfKey(trackIndex: number, channelIndex: number, keyframeIndex: number): string {- return `${trackIndex}:${channelIndex}:${keyframeIndex}`;-}+const FRAME_STEP = 1 / 60;export class TimelineKeyframeArea {private canvas_: HTMLCanvasElement;private ctx_: CanvasRenderingContext2D;private state_: TimelineState;- private host_: TimelinePanelHost | null;+ private host_: import('./TimelineTypes').TimelinePanelHost | null;private assetData_: TimelineAssetData | null = null;private unsub_: (() => void) | null = null;private resizeObserver_: ResizeObserver | null = null;@@ -225,7 +107,7 @@ export class TimelineKeyframeArea {private clipboard_: { channelIndex: number; relativeTime: number; value: number; inTangent: number; outTangent: number }[] = [];private frameImageCache_: Map<string, HTMLImageElement> | null = null;- constructor(container: HTMLElement, state: TimelineState, host?: TimelinePanelHost) {+ constructor(container: HTMLElement, state: TimelineState, host?: import('./TimelineTypes').TimelinePanelHost) {this.state_ = state;this.host_ = host ?? null;@@ -271,7 +153,7 @@ export class TimelineKeyframeArea {this.notifySelectionChange();}- private selectNpItem(npHit: { type: string; hit: SpineClipHit | AudioEventHit | ActivationRangeHit | MarkerHit | CustomEventHit | SpriteAnimHit | AnimFrameHit }): void {+ private selectNpItem(npHit: NonPropertyHit): void {this.selectedKeyframes_.clear();const hit = npHit.hit;let itemIndex = -1;@@ -383,175 +265,17 @@ export class TimelineKeyframeArea {this.draw();}- draw(): void {- const ctx = this.ctx_;- const w = this.canvas_.clientWidth;- const h = this.canvas_.clientHeight;- const dpr = window.devicePixelRatio || 1;-- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- ctx.clearRect(0, 0, w, h);-- this.drawRuler(ctx, w);- this.drawTracks(ctx, w, h);- this.drawDurationEnd(ctx, w, h);- this.drawPlayhead(ctx, w, h);- this.drawRubberBand(ctx);- }-- private drawRuler(ctx: CanvasRenderingContext2D, width: number): void {- ctx.fillStyle = RULER_BG;- ctx.fillRect(0, 0, width, RULER_HEIGHT);-- ctx.strokeStyle = RULER_LINE;- ctx.lineWidth = 1;- ctx.beginPath();- ctx.moveTo(0, RULER_HEIGHT - 0.5);- ctx.lineTo(width, RULER_HEIGHT - 0.5);- ctx.stroke();-- const pps = this.state_.pixelsPerSecond;- const startTime = this.state_.scrollX / pps;- const endTime = startTime + width / pps;-- const step = this.calculateRulerStep(pps);- const firstTick = Math.floor(startTime / step) * step;-- ctx.fillStyle = RULER_TEXT;- ctx.font = '10px monospace';- ctx.textAlign = 'center';-- for (let t = firstTick; t <= endTime; t += step) {- const x = this.state_.timeToX(t);- if (x < -50 || x > width + 50) continue;-- ctx.strokeStyle = RULER_LINE;- ctx.beginPath();- ctx.moveTo(Math.round(x) + 0.5, RULER_HEIGHT - 8);- ctx.lineTo(Math.round(x) + 0.5, RULER_HEIGHT);- ctx.stroke();-- ctx.fillText(this.state_.formatTime(Math.max(0, t)), x, RULER_HEIGHT - 10);-- const subStep = step / 5;- for (let st = t + subStep; st < t + step - subStep / 2; st += subStep) {- const sx = this.state_.timeToX(st);- if (sx < 0 || sx > width) continue;- ctx.strokeStyle = RULER_LINE;- ctx.beginPath();- ctx.moveTo(Math.round(sx) + 0.5, RULER_HEIGHT - 4);- ctx.lineTo(Math.round(sx) + 0.5, RULER_HEIGHT);- ctx.stroke();- }- }- }-- private calculateRulerStep(pps: number): number {- const minPixelsBetweenLabels = 80;- const steps = [0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60];- for (const s of steps) {- if (s * pps >= minPixelsBetweenLabels) return s;- }- return 60;- }-- private drawTracks(ctx: CanvasRenderingContext2D, width: number, height: number): void {- const tracks = this.state_.tracks;- let y = RULER_HEIGHT;-- for (let i = 0; i < tracks.length; i++) {- if (y > height) break;- const track = tracks[i];-- const bg = track.index === this.state_.selectedTrackIndex- ? TRACK_SELECTED_BG- : i % 2 === 0 ? TRACK_BG_EVEN : TRACK_BG_ODD;-- ctx.fillStyle = bg;- ctx.fillRect(0, y, width, TRACK_HEIGHT);-- ctx.strokeStyle = RULER_LINE;- ctx.lineWidth = 1;- ctx.beginPath();- ctx.moveTo(0, y + TRACK_HEIGHT - 0.5);- ctx.lineTo(width, y + TRACK_HEIGHT - 0.5);- ctx.stroke();-- this.drawTrackContent(ctx, track, y, width);- y += TRACK_HEIGHT;-- if (track.expanded && track.channelCount > 0) {- const assetTrack = this.assetData_?.tracks[track.index];- const channels = (assetTrack as any)?.channels ?? [];- for (let c = 0; c < track.channelCount; c++) {- if (y > height) break;- ctx.fillStyle = CHANNEL_BG;- ctx.fillRect(0, y, width, TRACK_HEIGHT);-- ctx.strokeStyle = RULER_LINE;- ctx.beginPath();- ctx.moveTo(0, y + TRACK_HEIGHT - 0.5);- ctx.lineTo(width, y + TRACK_HEIGHT - 0.5);- ctx.stroke();-- const channel = channels[c];- if (channel) {- this.drawKeyframes(ctx, channel.keyframes, y, track.index, c);- }- y += TRACK_HEIGHT;- }- }- }- }-- private drawTrackContent(- ctx: CanvasRenderingContext2D,- track: { type: string; index: number },- y: number,- width: number,- ): void {- if (!this.assetData_) return;- const assetTrack = this.assetData_.tracks[track.index];- if (!assetTrack) return;-- switch (assetTrack.type) {- case 'property':- if (!track.type) break;- for (let c = 0; c < (assetTrack.channels ?? []).length; c++) {- this.drawKeyframes(ctx, assetTrack.channels![c].keyframes, y, track.index, c);- }- break;-- case 'spine':- this.drawSpineClips(ctx, assetTrack.clips ?? [], y, width);- break;-- case 'spriteAnim':- if (assetTrack.startTime != null) {- this.drawSpriteAnimClip(ctx, assetTrack.startTime, assetTrack.clip ?? '', y, width);- }- break;-- case 'audio':- this.drawAudioEvents(ctx, assetTrack.events ?? [], y);- break;-- case 'activation':- this.drawActivationRanges(ctx, assetTrack.ranges ?? [], y, width);- break;-- case 'marker':- this.drawMarkers(ctx, assetTrack.markers ?? [], y, track.index);- break;-- case 'customEvent':- this.drawCustomEvents(ctx, (assetTrack.events ?? []) as TimelineCustomEvent[], y, track.index);- break;-- case 'animFrames':- this.drawAnimFrames(ctx, assetTrack.animFrames ?? [], y, width, track.index);- break;- }+ private createRenderContext(): TimelineRenderContext {+ return {+ state: this.state_,+ assetData: this.assetData_,+ canvasWidth: this.canvas_.clientWidth,+ isKeyframeSelected: (ti, ci, ki) => this.isKeyframeSelected(ti, ci, ki),+ isNpItemSelected: (type, ti, ii) => this.isNpItemSelected(type, ti, ii),+ frameImageCache: this.frameImageCache_,+ setFrameImageCache: (cache) => { this.frameImageCache_ = cache; },+ requestRedraw: () => this.draw(),+ };}private isNpItemSelected(type: string, trackIndex: number, itemIndex: number): boolean {@@ -559,682 +283,21 @@ export class TimelineKeyframeArea {return sel != null && sel.type === type && sel.trackIndex === trackIndex && sel.itemIndex === itemIndex;}- private drawCustomEvents(- ctx: CanvasRenderingContext2D,- events: TimelineCustomEvent[],- y: number,- trackIndex: number,- ): void {- for (let i = 0; i < events.length; i++) {- const event = events[i];- const x = this.state_.timeToX(event.time);- const selected = this.isNpItemSelected('customEvent', trackIndex, i);-- ctx.fillStyle = selected ? KEYFRAME_SELECTED : CUSTOM_EVENT_COLOR;- ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);-- ctx.beginPath();- ctx.arc(x, y + 6, 4, 0, Math.PI * 2);- ctx.fill();-- if (selected) {- ctx.strokeStyle = '#ffffff';- ctx.lineWidth = 1.5;- ctx.beginPath();- ctx.arc(x, y + 6, 5.5, 0, Math.PI * 2);- ctx.stroke();- }-- ctx.fillStyle = selected ? '#ffffff' : '#cccccc';- ctx.font = '9px monospace';- ctx.textAlign = 'left';- ctx.fillText(event.name, x + 6, y + TRACK_HEIGHT / 2 + 3);- }- }-- private drawMarkers(- ctx: CanvasRenderingContext2D,- markers: { time: number; name: string }[],- y: number,- trackIndex: number,- ): void {- for (let i = 0; i < markers.length; i++) {- const marker = markers[i];- const x = this.state_.timeToX(marker.time);- const selected = this.isNpItemSelected('marker', trackIndex, i);-- ctx.fillStyle = selected ? KEYFRAME_SELECTED : MARKER_COLOR;- ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);-- ctx.beginPath();- ctx.moveTo(x - 5, y + 2);- ctx.lineTo(x + 5, y + 2);- ctx.lineTo(x, y + 8);- ctx.closePath();- ctx.fill();-- if (selected) {- ctx.strokeStyle = '#ffffff';- ctx.lineWidth = 1.5;- ctx.beginPath();- ctx.moveTo(x - 6.5, y + 1);- ctx.lineTo(x + 6.5, y + 1);- ctx.lineTo(x, y + 9.5);- ctx.closePath();- ctx.stroke();- }-- ctx.fillStyle = selected ? '#ffffff' : '#cccccc';- ctx.font = '9px monospace';- ctx.textAlign = 'left';- ctx.fillText(marker.name, x + 6, y + TRACK_HEIGHT / 2 + 3);- }- }-- private drawAnimFrames(- ctx: CanvasRenderingContext2D,- frames: AnimFrameData[],- y: number,- width: number,- trackIndex: number,- ): void {- if (frames.length === 0) return;- const fps = this.state_.animClipFps;- const defaultDur = 1 / fps;- let time = 0;-- for (let i = 0; i < frames.length; i++) {- const frame = frames[i];- const dur = frame.duration ?? defaultDur;- const x1 = this.state_.timeToX(time);- const x2 = this.state_.timeToX(time + dur);- const fw = x2 - x1;-- if (x2 >= 0 && x1 <= width) {- const color = ANIM_FRAME_COLORS[i % ANIM_FRAME_COLORS.length];- const selected = this.isNpItemSelected('animFrames', trackIndex, i);-- ctx.fillStyle = selected ? color : color + '60';- ctx.fillRect(x1, y + 1, fw, TRACK_HEIGHT - 2);-- ctx.strokeStyle = selected ? '#ffffff' : ANIM_FRAME_BORDER;- ctx.lineWidth = 1;- ctx.strokeRect(x1 + 0.5, y + 1.5, fw - 1, TRACK_HEIGHT - 3);-- if (frame.thumbnailUrl && fw > 20) {- let img = this.frameImageCache_?.get(frame.thumbnailUrl);- if (!img) {- img = new Image();- img.src = frame.thumbnailUrl;- if (!this.frameImageCache_) this.frameImageCache_ = new Map();- this.frameImageCache_.set(frame.thumbnailUrl, img);- img.onload = () => this.draw();- }- if (img.complete && img.naturalWidth > 0) {- const imgH = TRACK_HEIGHT - 4;- const imgW = Math.min(imgH, fw - 2);- ctx.drawImage(img, x1 + 1, y + 2, imgW, imgH);- }- }-- if (fw > 30) {- ctx.fillStyle = selected ? '#ffffff' : '#cccccc';- ctx.font = '9px monospace';- ctx.textAlign = 'left';- const label = String(i).padStart(2, '0');- const textX = frame.thumbnailUrl && fw > 20 ? x1 + TRACK_HEIGHT - 2 : x1 + 4;- ctx.fillText(label, textX, y + TRACK_HEIGHT / 2 + 3);-- const durMs = Math.round(dur * 1000);- const durLabel = durMs + 'ms';- ctx.fillStyle = selected ? 'rgba(255,255,255,0.6)' : 'rgba(200,200,200,0.5)';- ctx.textAlign = 'right';- ctx.fillText(durLabel, x2 - 4, y + TRACK_HEIGHT / 2 + 3);- ctx.textAlign = 'left';- }-- if (fw > 4) {- ctx.fillStyle = selected ? 'rgba(255,255,255,0.4)' : 'rgba(200,200,200,0.25)';- ctx.fillRect(x2 - 3, y + 3, 2, TRACK_HEIGHT - 6);- }- }- time += dur;- }- }-- private drawKeyframes(- ctx: CanvasRenderingContext2D,- keyframes: { time: number }[],- y: number,- trackIndex: number,- channelIndex: number,- ): void {- const cy = y + TRACK_HEIGHT / 2;- const half = KEYFRAME_SIZE / 2;-- for (let ki = 0; ki < keyframes.length; ki++) {- const kf = keyframes[ki];- const x = this.state_.timeToX(kf.time);- if (x < -KEYFRAME_SIZE || x > this.canvas_.clientWidth + KEYFRAME_SIZE) continue;-- const isSelected = this.isKeyframeSelected(trackIndex, channelIndex, ki);-- ctx.fillStyle = isSelected ? KEYFRAME_SELECTED : KEYFRAME_COLOR;- ctx.beginPath();- ctx.moveTo(x, cy - half);- ctx.lineTo(x + half, cy);- ctx.lineTo(x, cy + half);- ctx.lineTo(x - half, cy);- ctx.closePath();- ctx.fill();- }- }-- private drawSpineClips(- ctx: CanvasRenderingContext2D,- clips: { start: number; duration: number; animation: string }[],- y: number,- _width: number,- ): void {- const clipY = y + 3;- const clipH = TRACK_HEIGHT - 6;-- for (const clip of clips) {- const x1 = this.state_.timeToX(clip.start);- const x2 = this.state_.timeToX(clip.start + clip.duration);- const w = x2 - x1;- if (w < 1) continue;-- ctx.fillStyle = SPINE_CLIP_COLOR;- ctx.fillRect(x1, clipY, w, clipH);- ctx.strokeStyle = SPINE_CLIP_BORDER;- ctx.lineWidth = 1;- ctx.strokeRect(x1 + 0.5, clipY + 0.5, w - 1, clipH - 1);-- ctx.fillStyle = '#cccccc';- ctx.font = '10px monospace';- ctx.textAlign = 'left';- const textX = Math.max(x1 + 4, 4);- ctx.save();- ctx.beginPath();- ctx.rect(x1, clipY, w, clipH);- ctx.clip();- ctx.fillText(clip.animation, textX, clipY + clipH / 2 + 3);- ctx.restore();- }- }-- private drawSpriteAnimClip(- ctx: CanvasRenderingContext2D,- startTime: number,- clipName: string,- y: number,- width: number,- ): void {- const x1 = this.state_.timeToX(startTime);- const x2 = Math.min(this.state_.timeToX(this.state_.duration), width);- const clipY = y + 3;- const clipH = TRACK_HEIGHT - 6;-- if (x2 > x1) {- ctx.fillStyle = SPRITE_ANIM_COLOR;- ctx.fillRect(x1, clipY, x2 - x1, clipH);- ctx.strokeStyle = SPRITE_ANIM_BORDER;- ctx.lineWidth = 1;- ctx.strokeRect(x1 + 0.5, clipY + 0.5, x2 - x1 - 1, clipH - 1);- }-- ctx.fillStyle = SPRITE_ANIM_BORDER;- ctx.fillRect(x1 - 1, y + 2, 3, TRACK_HEIGHT - 4);-- if (clipName) {- const resolvedPath = isUUID(clipName)- ? (getAssetLibrary().getPath(clipName) ?? clipName)- : clipName;- const displayName = resolvedPath.includes('/')- ? resolvedPath.slice(resolvedPath.lastIndexOf('/') + 1)- : resolvedPath;- ctx.fillStyle = '#cccccc';- ctx.font = '10px monospace';- ctx.textAlign = 'left';- const textX = Math.max(x1 + 6, 6);- ctx.save();- if (x2 > x1) {- ctx.beginPath();- ctx.rect(x1, clipY, x2 - x1, clipH);- ctx.clip();- }- ctx.fillText(displayName, textX, clipY + clipH / 2 + 3);- ctx.restore();- }- }-- private drawAudioEvents(- ctx: CanvasRenderingContext2D,- events: { time: number; clip?: string }[],- y: number,- ): void {- for (const event of events) {- const x = this.state_.timeToX(event.time);- ctx.fillStyle = AUDIO_EVENT_COLOR;- ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);-- ctx.beginPath();- ctx.moveTo(x - 4, y + 2);- ctx.lineTo(x + 4, y + 2);- ctx.lineTo(x, y + 8);- ctx.closePath();- ctx.fill();-- if (event.clip) {- const clipPath = isUUID(event.clip)- ? (getAssetLibrary().getPath(event.clip) ?? event.clip)- : event.clip;- const label = clipPath.includes('/')- ? clipPath.slice(clipPath.lastIndexOf('/') + 1)- : clipPath;- ctx.fillStyle = '#aaaaaa';- ctx.font = '9px monospace';- ctx.textAlign = 'left';- ctx.fillText(label, x + 6, y + TRACK_HEIGHT / 2 + 3);- }- }- }-- private drawActivationRanges(- ctx: CanvasRenderingContext2D,- ranges: { start: number; end: number }[],- y: number,- _width: number,- ): void {- const rangeY = y + 4;- const rangeH = TRACK_HEIGHT - 8;-- for (const range of ranges) {- const x1 = this.state_.timeToX(range.start);- const x2 = this.state_.timeToX(range.end);- const w = x2 - x1;- if (w < 1) continue;-- ctx.fillStyle = ACTIVATION_COLOR;- ctx.fillRect(x1, rangeY, w, rangeH);- ctx.strokeStyle = ACTIVATION_BORDER;- ctx.lineWidth = 1;- ctx.strokeRect(x1 + 0.5, rangeY + 0.5, w - 1, rangeH - 1);- }- }-- private drawPlayhead(ctx: CanvasRenderingContext2D, _width: number, height: number): void {- const x = this.state_.timeToX(this.state_.playheadTime);- if (x < -10 || x > this.canvas_.clientWidth + 10) return;-- ctx.strokeStyle = PLAYHEAD_COLOR;- ctx.lineWidth = 1;- ctx.beginPath();- ctx.moveTo(Math.round(x) + 0.5, 0);- ctx.lineTo(Math.round(x) + 0.5, height);- ctx.stroke();-- ctx.fillStyle = PLAYHEAD_COLOR;- ctx.beginPath();- ctx.moveTo(x - 5, 0);- ctx.lineTo(x + 5, 0);- ctx.lineTo(x, 8);- ctx.closePath();- ctx.fill();- }-- private drawDurationEnd(ctx: CanvasRenderingContext2D, width: number, height: number): void {- const x = this.state_.timeToX(this.state_.duration);- if (x < 0) return;-- if (x < width) {- ctx.strokeStyle = DURATION_LINE_COLOR;- ctx.lineWidth = 1;- ctx.setLineDash([4, 4]);- ctx.beginPath();- ctx.moveTo(Math.round(x) + 0.5, RULER_HEIGHT);- ctx.lineTo(Math.round(x) + 0.5, height);- ctx.stroke();- ctx.setLineDash([]);- }-- const overlayX = Math.max(x, 0);- if (overlayX < width) {- ctx.fillStyle = BEYOND_DURATION_COLOR;- ctx.fillRect(overlayX, RULER_HEIGHT, width - overlayX, height - RULER_HEIGHT);- }- }-- private drawRubberBand(ctx: CanvasRenderingContext2D): void {- if (!this.rubberBand_) return;- const rb = this.rubberBand_;- const x = Math.min(rb.startX, rb.endX);- const y = Math.min(rb.startY, rb.endY);- const w = Math.abs(rb.endX - rb.startX);- const h = Math.abs(rb.endY - rb.startY);-- ctx.fillStyle = RUBBERBAND_COLOR;- ctx.fillRect(x, y, w, h);- ctx.strokeStyle = RUBBERBAND_BORDER;- ctx.lineWidth = 1;- ctx.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1);- }-- private hitTestKeyframe(x: number, y: number): KeyframeHit | null {- if (!this.assetData_) return null;-- const tracks = this.state_.tracks;- let rowY = RULER_HEIGHT;-- for (let i = 0; i < tracks.length; i++) {- const track = tracks[i];- const assetTrack = this.assetData_.tracks[track.index];-- if (assetTrack?.type === 'property' && assetTrack.channels) {- if (y >= rowY && y < rowY + TRACK_HEIGHT) {- const hit = this.hitTestChannelKeyframes(assetTrack.channels, x, rowY, track.index);- if (hit) return hit;- }- }- rowY += TRACK_HEIGHT;-- if (track.expanded && track.channelCount > 0 && assetTrack?.type === 'property') {- for (let c = 0; c < track.channelCount; c++) {- if (y >= rowY && y < rowY + TRACK_HEIGHT) {- const channel = assetTrack.channels?.[c];- if (channel) {- const hit = this.hitTestSingleChannel(channel.keyframes, x, rowY, track.index, c);- if (hit) return hit;- }- }- rowY += TRACK_HEIGHT;- }- }- }-- return null;- }-- private hitTestChannelKeyframes(- channels: { keyframes: { time: number }[] }[],- x: number,- rowY: number,- trackIndex: number,- ): KeyframeHit | null {- for (let c = 0; c < channels.length; c++) {- const hit = this.hitTestSingleChannel(channels[c].keyframes, x, rowY, trackIndex, c);- if (hit) return hit;- }- return null;- }-- private hitTestSingleChannel(- keyframes: { time: number }[],- x: number,- rowY: number,- trackIndex: number,- channelIndex: number,- ): KeyframeHit | null {- const cy = rowY + TRACK_HEIGHT / 2;-- for (let ki = 0; ki < keyframes.length; ki++) {- const kf = keyframes[ki];- const kx = this.state_.timeToX(kf.time);- const dx = x - kx;- const dy = (rowY + TRACK_HEIGHT / 2) - cy;-- if (Math.abs(dx) <= KEYFRAME_HIT_RADIUS && Math.abs(dy) <= KEYFRAME_HIT_RADIUS) {- return { trackIndex, channelIndex, keyframeIndex: ki, time: kf.time };- }- }- return null;- }-- private hitTestSpineClip(x: number, y: number, trackIndex: number, rowY: number): SpineClipHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'spine' || !track.clips) return null;- if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;-- for (let i = 0; i < track.clips.length; i++) {- const clip = track.clips[i];- const x1 = this.state_.timeToX(clip.start);- const x2 = this.state_.timeToX(clip.start + clip.duration);- if (x >= x1 && x <= x2) {- const zone = (x2 - x) <= EDGE_RESIZE_ZONE ? 'resize' : 'body';- return { trackIndex, clipIndex: i, zone };- }- }- return null;- }-- private hitTestAudioEvent(x: number, y: number, trackIndex: number, rowY: number): AudioEventHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'audio' || !track.events) return null;- if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;-- for (let i = 0; i < track.events.length; i++) {- const ex = this.state_.timeToX(track.events[i].time);- if (Math.abs(x - ex) <= KEYFRAME_HIT_RADIUS) {- return { trackIndex, eventIndex: i };- }- }- return null;- }-- private hitTestActivationRange(x: number, y: number, trackIndex: number, rowY: number): ActivationRangeHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'activation' || !track.ranges) return null;- if (y < rowY || y >= rowY + TRACK_HEIGHT) return null;-- for (let i = 0; i < track.ranges.length; i++) {- const range = track.ranges[i];- const x1 = this.state_.timeToX(range.start);- const x2 = this.state_.timeToX(range.end);- if (x >= x1 && x <= x2) {- const zone = (x - x1) <= EDGE_RESIZE_ZONE ? 'left'- : (x2 - x) <= EDGE_RESIZE_ZONE ? 'right'- : 'body';- return { trackIndex, rangeIndex: i, zone };- }- }- return null;- }-- private hitTestMarker(x: number, trackIndex: number): MarkerHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'marker' || !track.markers) return null;-- for (let i = 0; i < track.markers.length; i++) {- const mx = this.state_.timeToX(track.markers[i].time);- if (Math.abs(x - mx) <= KEYFRAME_HIT_RADIUS) {- return { trackIndex, markerIndex: i };- }- }- return null;- }-- private hitTestCustomEvent(x: number, trackIndex: number): CustomEventHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'customEvent' || !track.events) return null;-- for (let i = 0; i < track.events.length; i++) {- const ex = this.state_.timeToX(track.events[i].time);- if (Math.abs(x - ex) <= KEYFRAME_HIT_RADIUS) {- return { trackIndex, eventIndex: i };- }- }- return null;- }-- private hitTestSpriteAnim(x: number, trackIndex: number): SpriteAnimHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'spriteAnim' || track.startTime == null) return null;-- const sx = this.state_.timeToX(track.startTime);- if (Math.abs(x - sx) <= KEYFRAME_HIT_RADIUS) {- return { trackIndex };- }- return null;- }-- private hitTestAnimFrame(x: number, trackIndex: number): AnimFrameHit | null {- if (!this.assetData_) return null;- const track = this.assetData_.tracks[trackIndex];- if (!track || track.type !== 'animFrames' || !track.animFrames) return null;-- const fps = this.state_.animClipFps;- const defaultDur = 1 / fps;- let time = 0;-- for (let i = 0; i < track.animFrames.length; i++) {- const dur = (track.animFrames[i] as AnimFrameData).duration ?? defaultDur;- const x1 = this.state_.timeToX(time);- const x2 = this.state_.timeToX(time + dur);-- if (x >= x1 && x <= x2) {- const zone = (x2 - x) <= EDGE_RESIZE_ZONE ? 'resize' : 'body';- return { trackIndex, frameIndex: i, zone };- }- time += dur;- }- return null;- }-- private hitTestNonPropertyTrack(x: number, y: number): { type: string; hit: SpineClipHit | AudioEventHit | ActivationRangeHit | MarkerHit | CustomEventHit | SpriteAnimHit | AnimFrameHit } | null {- if (!this.assetData_) return null;-- const tracks = this.state_.tracks;- let rowY = RULER_HEIGHT;-- for (let i = 0; i < tracks.length; i++) {- const track = tracks[i];- const assetTrack = this.assetData_.tracks[track.index];-- if (y >= rowY && y < rowY + TRACK_HEIGHT && assetTrack) {- if (assetTrack.type === 'spine') {- const hit = this.hitTestSpineClip(x, y, track.index, rowY);- if (hit) return { type: 'spine', hit };- } else if (assetTrack.type === 'audio') {- const hit = this.hitTestAudioEvent(x, y, track.index, rowY);- if (hit) return { type: 'audio', hit };- } else if (assetTrack.type === 'activation') {- const hit = this.hitTestActivationRange(x, y, track.index, rowY);- if (hit) return { type: 'activation', hit };- } else if (assetTrack.type === 'marker') {- const hit = this.hitTestMarker(x, track.index);- if (hit) return { type: 'marker', hit };- } else if (assetTrack.type === 'customEvent') {- const hit = this.hitTestCustomEvent(x, track.index);- if (hit) return { type: 'customEvent', hit };- } else if (assetTrack.type === 'spriteAnim') {- const hit = this.hitTestSpriteAnim(x, track.index);- if (hit) return { type: 'spriteAnim', hit };- } else if (assetTrack.type === 'animFrames') {- const hit = this.hitTestAnimFrame(x, track.index);- if (hit) return { type: 'animFrames', hit };- }- }- rowY += TRACK_HEIGHT;-- if (track.expanded && track.channelCount > 0) {- rowY += track.channelCount * TRACK_HEIGHT;- }- }- return null;- }-- private collectKeyframesInRect(- x1: number, y1: number, x2: number, y2: number,- ): KeyframeHit[] {- if (!this.assetData_) return [];-- const minX = Math.min(x1, x2);- const maxX = Math.max(x1, x2);- const minY = Math.min(y1, y2);- const maxY = Math.max(y1, y2);- const hits: KeyframeHit[] = [];-- const tracks = this.state_.tracks;- let rowY = RULER_HEIGHT;-- for (let i = 0; i < tracks.length; i++) {- const track = tracks[i];- const assetTrack = this.assetData_.tracks[track.index];-- if (assetTrack?.type === 'property' && assetTrack.channels) {- if (rowY + TRACK_HEIGHT > minY && rowY < maxY) {- for (let c = 0; c < assetTrack.channels.length; c++) {- this.collectChannelKeyframesInRange(- assetTrack.channels[c].keyframes, minX, maxX,- track.index, c, hits,- );- }- }- }- rowY += TRACK_HEIGHT;-- if (track.expanded && track.channelCount > 0 && assetTrack?.type === 'property') {- for (let c = 0; c < track.channelCount; c++) {- if (rowY + TRACK_HEIGHT > minY && rowY < maxY) {- const channel = assetTrack.channels?.[c];- if (channel) {- this.collectChannelKeyframesInRange(- channel.keyframes, minX, maxX,- track.index, c, hits,- );- }- }- rowY += TRACK_HEIGHT;- }- }- }-- return hits;- }-- private collectChannelKeyframesInRange(- keyframes: { time: number }[],- minX: number, maxX: number,- trackIndex: number, channelIndex: number,- out: KeyframeHit[],- ): void {- for (let ki = 0; ki < keyframes.length; ki++) {- const kx = this.state_.timeToX(keyframes[ki].time);- if (kx >= minX && kx <= maxX) {- out.push({ trackIndex, channelIndex, keyframeIndex: ki, time: keyframes[ki].time });- }- }- }-- private getTrackAtY(y: number): { trackIndex: number; channelIndex: number; isChannel: boolean } | null {- const tracks = this.state_.tracks;- let rowY = RULER_HEIGHT;-- for (let i = 0; i < tracks.length; i++) {- const track = tracks[i];+ draw(): void {+ const ctx = this.ctx_;+ const w = this.canvas_.clientWidth;+ const h = this.canvas_.clientHeight;+ const dpr = window.devicePixelRatio || 1;- if (y >= rowY && y < rowY + TRACK_HEIGHT) {- return { trackIndex: track.index, channelIndex: -1, isChannel: false };- }- rowY += TRACK_HEIGHT;+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, w, h);- if (track.expanded && track.channelCount > 0) {- for (let c = 0; c < track.channelCount; c++) {- if (y >= rowY && y < rowY + TRACK_HEIGHT) {- return { trackIndex: track.index, channelIndex: c, isChannel: true };- }- rowY += TRACK_HEIGHT;- }- }- }- return null;+ const rc = this.createRenderContext();+ drawRuler(ctx, w, rc);+ drawTracks(ctx, w, h, rc);+ drawDurationEnd(ctx, w, h, rc);+ drawPlayhead(ctx, w, h, rc);+ drawRubberBand(ctx, this.rubberBand_);}private onMouseDown(e: MouseEvent): void {@@ -1253,7 +316,7 @@ export class TimelineKeyframeArea {return;}- const hit = this.hitTestKeyframe(x, y);+ const hit = hitTestKeyframe(x, y, this.state_, this.assetData_);if (hit) {const key = kfKey(hit.trackIndex, hit.channelIndex, hit.keyframeIndex);@@ -1274,7 +337,7 @@ export class TimelineKeyframeArea {return;}- const npHit = this.hitTestNonPropertyTrack(x, y);+ const npHit = hitTestNonPropertyTrack(x, y, this.state_, this.assetData_);if (npHit) {this.clearSelection();this.selectNpItem(npHit);@@ -1302,7 +365,7 @@ export class TimelineKeyframeArea {}this.draw();- const trackInfo = this.getTrackAtY(y);+ const trackInfo = getTrackAtY(y, this.state_);if (trackInfo) {this.state_.selectedTrackIndex = trackInfo.trackIndex;this.state_.notify();@@ -1638,7 +701,7 @@ export class TimelineKeyframeArea {const h = Math.abs(rb.endY - rb.startY);if (w > 3 || h > 3) {- const hits = this.collectKeyframesInRect(rb.startX, rb.startY, rb.endX, rb.endY);+ const hits = collectKeyframesInRect(rb.startX, rb.startY, rb.endX, rb.endY, this.state_, this.assetData_);if (!isAdditive) {this.selectedKeyframes_.clear();}@@ -1665,13 +728,13 @@ export class TimelineKeyframeArea {if (y < RULER_HEIGHT) return;- const hit = this.hitTestKeyframe(x, y);+ const hit = hitTestKeyframe(x, y, this.state_, this.assetData_);if (hit) return;- const npHit = this.hitTestNonPropertyTrack(x, y);+ const npHit = hitTestNonPropertyTrack(x, y, this.state_, this.assetData_);if (npHit) return;- const trackInfo = this.getTrackAtY(y);+ const trackInfo = getTrackAtY(y, this.state_);if (!trackInfo) return;const assetTrack = this.assetData_.tracks[trackInfo.trackIndex];@@ -1970,8 +1033,8 @@ export class TimelineKeyframeArea {const y = e.clientY - rect.top;if (y < RULER_HEIGHT) return;- const hit = this.hitTestKeyframe(x, y);- const trackInfo = this.getTrackAtY(y);+ const hit = hitTestKeyframe(x, y, this.state_, this.assetData_);+ const trackInfo = getTrackAtY(y, this.state_);const menu = document.createElement('div');menu.className = 'es-timeline-dropdown';@@ -1979,7 +1042,7 @@ export class TimelineKeyframeArea {menu.style.left = `${e.clientX}px`;menu.style.top = `${e.clientY}px`;- const npHit = this.hitTestNonPropertyTrack(x, y);+ const npHit = hitTestNonPropertyTrack(x, y, this.state_, this.assetData_);if (hit) {const key = kfKey(hit.trackIndex, hit.channelIndex, hit.keyframeIndex);@@ -2079,7 +1142,7 @@ export class TimelineKeyframeArea {private buildNonPropertyContextMenu(menu: HTMLElement,- npHit: { type: string; hit: SpineClipHit | AudioEventHit | ActivationRangeHit | MarkerHit | CustomEventHit | SpriteAnimHit | AnimFrameHit },+ npHit: NonPropertyHit,): void {if (!this.assetData_ || !this.host_) return;@@ -2405,7 +1468,7 @@ export class TimelineKeyframeArea {return;}- const npHit = this.hitTestNonPropertyTrack(x, y);+ const npHit = hitTestNonPropertyTrack(x, y, this.state_, this.assetData_);if (npHit) {if (npHit.type === 'animFrames' && (npHit.hit as AnimFrameHit).zone === 'resize') {this.canvas_.style.cursor = 'ew-resize';diff --git a/editor/src/panels/timeline/TimelineRenderer.ts b/editor/src/panels/timeline/TimelineRenderer.tsnew file mode 100644index 000000000..beb145d44--- /dev/null+++ b/editor/src/panels/timeline/TimelineRenderer.ts@@ -0,0 +1,587 @@+import type { TimelineState } from './TimelineState';+import {+ RULER_HEIGHT,+ TRACK_HEIGHT,+ KEYFRAME_SIZE,+} from './TimelineState';+import type {+ TimelineAssetData,+ TimelineCustomEvent,+ AnimFrameData,+} from './TimelineTypes';+import { isUUID, getAssetLibrary } from '../../asset/AssetDatabase';++export const RULER_BG = '#1e1e1e';+export const RULER_TEXT = '#888888';+export const RULER_LINE = '#333333';+export const TRACK_BG_EVEN = '#252525';+export const TRACK_BG_ODD = '#2a2a2a';+export const TRACK_SELECTED_BG = '#2c3e50';+export const KEYFRAME_COLOR = '#e5c07b';+export const KEYFRAME_SELECTED = '#61afef';+export const PLAYHEAD_COLOR = '#e06c75';+export const SPINE_CLIP_COLOR = 'rgba(97, 175, 239, 0.3)';+export const SPINE_CLIP_BORDER = '#61afef';+export const ACTIVATION_COLOR = 'rgba(152, 195, 121, 0.3)';+export const ACTIVATION_BORDER = '#98c379';+export const AUDIO_EVENT_COLOR = '#d19a66';+export const CHANNEL_BG = '#1e1e1e';+export const RUBBERBAND_COLOR = 'rgba(97, 175, 239, 0.2)';+export const RUBBERBAND_BORDER = 'rgba(97, 175, 239, 0.6)';+export const MARKER_COLOR = '#c678dd';+export const CUSTOM_EVENT_COLOR = '#56b6c2';+export const SPRITE_ANIM_COLOR = 'rgba(229, 192, 123, 0.3)';+export const SPRITE_ANIM_BORDER = '#e5c07b';+export const DURATION_LINE_COLOR = '#e5c07b';+export const BEYOND_DURATION_COLOR = 'rgba(0, 0, 0, 0.2)';+export const ANIM_FRAME_COLORS = ['#61afef', '#c678dd', '#e5c07b', '#98c379', '#d19a66', '#56b6c2', '#e06c75'];+export const ANIM_FRAME_BORDER = '#ffffff30';++export interface TimelineRenderContext {+ state: TimelineState;+ assetData: TimelineAssetData | null;+ canvasWidth: number;+ isKeyframeSelected: (trackIndex: number, channelIndex: number, keyframeIndex: number) => boolean;+ isNpItemSelected: (type: string, trackIndex: number, itemIndex: number) => boolean;+ frameImageCache: Map<string, HTMLImageElement> | null;+ setFrameImageCache: (cache: Map<string, HTMLImageElement>) => void;+ requestRedraw: () => void;+}++export function drawRuler(ctx: CanvasRenderingContext2D, width: number, rc: TimelineRenderContext): void {+ ctx.fillStyle = RULER_BG;+ ctx.fillRect(0, 0, width, RULER_HEIGHT);++ ctx.strokeStyle = RULER_LINE;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(0, RULER_HEIGHT - 0.5);+ ctx.lineTo(width, RULER_HEIGHT - 0.5);+ ctx.stroke();++ const pps = rc.state.pixelsPerSecond;+ const startTime = rc.state.scrollX / pps;+ const endTime = startTime + width / pps;++ const step = calculateRulerStep(pps);+ const firstTick = Math.floor(startTime / step) * step;++ ctx.fillStyle = RULER_TEXT;+ ctx.font = '10px monospace';+ ctx.textAlign = 'center';++ for (let t = firstTick; t <= endTime; t += step) {+ const x = rc.state.timeToX(t);+ if (x < -50 || x > width + 50) continue;++ ctx.strokeStyle = RULER_LINE;+ ctx.beginPath();+ ctx.moveTo(Math.round(x) + 0.5, RULER_HEIGHT - 8);+ ctx.lineTo(Math.round(x) + 0.5, RULER_HEIGHT);+ ctx.stroke();++ ctx.fillText(rc.state.formatTime(Math.max(0, t)), x, RULER_HEIGHT - 10);++ const subStep = step / 5;+ for (let st = t + subStep; st < t + step - subStep / 2; st += subStep) {+ const sx = rc.state.timeToX(st);+ if (sx < 0 || sx > width) continue;+ ctx.strokeStyle = RULER_LINE;+ ctx.beginPath();+ ctx.moveTo(Math.round(sx) + 0.5, RULER_HEIGHT - 4);+ ctx.lineTo(Math.round(sx) + 0.5, RULER_HEIGHT);+ ctx.stroke();+ }+ }+}++function calculateRulerStep(pps: number): number {+ const minPixelsBetweenLabels = 80;+ const steps = [0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60];+ for (const s of steps) {+ if (s * pps >= minPixelsBetweenLabels) return s;+ }+ return 60;+}++export function drawTracks(+ ctx: CanvasRenderingContext2D,+ width: number,+ height: number,+ rc: TimelineRenderContext,+): void {+ const tracks = rc.state.tracks;+ let y = RULER_HEIGHT;++ for (let i = 0; i < tracks.length; i++) {+ if (y > height) break;+ const track = tracks[i];++ const bg = track.index === rc.state.selectedTrackIndex+ ? TRACK_SELECTED_BG+ : i % 2 === 0 ? TRACK_BG_EVEN : TRACK_BG_ODD;++ ctx.fillStyle = bg;+ ctx.fillRect(0, y, width, TRACK_HEIGHT);++ ctx.strokeStyle = RULER_LINE;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(0, y + TRACK_HEIGHT - 0.5);+ ctx.lineTo(width, y + TRACK_HEIGHT - 0.5);+ ctx.stroke();++ drawTrackContent(ctx, track, y, width, rc);+ y += TRACK_HEIGHT;++ if (track.expanded && track.channelCount > 0) {+ const assetTrack = rc.assetData?.tracks[track.index];+ const channels = (assetTrack as any)?.channels ?? [];+ for (let c = 0; c < track.channelCount; c++) {+ if (y > height) break;+ ctx.fillStyle = CHANNEL_BG;+ ctx.fillRect(0, y, width, TRACK_HEIGHT);++ ctx.strokeStyle = RULER_LINE;+ ctx.beginPath();+ ctx.moveTo(0, y + TRACK_HEIGHT - 0.5);+ ctx.lineTo(width, y + TRACK_HEIGHT - 0.5);+ ctx.stroke();++ const channel = channels[c];+ if (channel) {+ drawKeyframes(ctx, channel.keyframes, y, track.index, c, rc);+ }+ y += TRACK_HEIGHT;+ }+ }+ }+}++function drawTrackContent(+ ctx: CanvasRenderingContext2D,+ track: { type: string; index: number },+ y: number,+ width: number,+ rc: TimelineRenderContext,+): void {+ if (!rc.assetData) return;+ const assetTrack = rc.assetData.tracks[track.index];+ if (!assetTrack) return;++ switch (assetTrack.type) {+ case 'property':+ if (!track.type) break;+ for (let c = 0; c < (assetTrack.channels ?? []).length; c++) {+ drawKeyframes(ctx, assetTrack.channels![c].keyframes, y, track.index, c, rc);+ }+ break;++ case 'spine':+ drawSpineClips(ctx, assetTrack.clips ?? [], y, width, rc);+ break;++ case 'spriteAnim':+ if (assetTrack.startTime != null) {+ drawSpriteAnimClip(ctx, assetTrack.startTime, assetTrack.clip ?? '', y, width, rc);+ }+ break;++ case 'audio':+ drawAudioEvents(ctx, assetTrack.events ?? [], y, rc);+ break;++ case 'activation':+ drawActivationRanges(ctx, assetTrack.ranges ?? [], y, width, rc);+ break;++ case 'marker':+ drawMarkers(ctx, assetTrack.markers ?? [], y, track.index, rc);+ break;++ case 'customEvent':+ drawCustomEvents(ctx, (assetTrack.events ?? []) as TimelineCustomEvent[], y, track.index, rc);+ break;++ case 'animFrames':+ drawAnimFrames(ctx, assetTrack.animFrames ?? [], y, width, track.index, rc);+ break;+ }+}++function drawCustomEvents(+ ctx: CanvasRenderingContext2D,+ events: TimelineCustomEvent[],+ y: number,+ trackIndex: number,+ rc: TimelineRenderContext,+): void {+ for (let i = 0; i < events.length; i++) {+ const event = events[i];+ const x = rc.state.timeToX(event.time);+ const selected = rc.isNpItemSelected('customEvent', trackIndex, i);++ ctx.fillStyle = selected ? KEYFRAME_SELECTED : CUSTOM_EVENT_COLOR;+ ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);++ ctx.beginPath();+ ctx.arc(x, y + 6, 4, 0, Math.PI * 2);+ ctx.fill();++ if (selected) {+ ctx.strokeStyle = '#ffffff';+ ctx.lineWidth = 1.5;+ ctx.beginPath();+ ctx.arc(x, y + 6, 5.5, 0, Math.PI * 2);+ ctx.stroke();+ }++ ctx.fillStyle = selected ? '#ffffff' : '#cccccc';+ ctx.font = '9px monospace';+ ctx.textAlign = 'left';+ ctx.fillText(event.name, x + 6, y + TRACK_HEIGHT / 2 + 3);+ }+}++function drawMarkers(+ ctx: CanvasRenderingContext2D,+ markers: { time: number; name: string }[],+ y: number,+ trackIndex: number,+ rc: TimelineRenderContext,+): void {+ for (let i = 0; i < markers.length; i++) {+ const marker = markers[i];+ const x = rc.state.timeToX(marker.time);+ const selected = rc.isNpItemSelected('marker', trackIndex, i);++ ctx.fillStyle = selected ? KEYFRAME_SELECTED : MARKER_COLOR;+ ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);++ ctx.beginPath();+ ctx.moveTo(x - 5, y + 2);+ ctx.lineTo(x + 5, y + 2);+ ctx.lineTo(x, y + 8);+ ctx.closePath();+ ctx.fill();++ if (selected) {+ ctx.strokeStyle = '#ffffff';+ ctx.lineWidth = 1.5;+ ctx.beginPath();+ ctx.moveTo(x - 6.5, y + 1);+ ctx.lineTo(x + 6.5, y + 1);+ ctx.lineTo(x, y + 9.5);+ ctx.closePath();+ ctx.stroke();+ }++ ctx.fillStyle = selected ? '#ffffff' : '#cccccc';+ ctx.font = '9px monospace';+ ctx.textAlign = 'left';+ ctx.fillText(marker.name, x + 6, y + TRACK_HEIGHT / 2 + 3);+ }+}++function drawAnimFrames(+ ctx: CanvasRenderingContext2D,+ frames: AnimFrameData[],+ y: number,+ width: number,+ trackIndex: number,+ rc: TimelineRenderContext,+): void {+ if (frames.length === 0) return;+ const fps = rc.state.animClipFps;+ const defaultDur = 1 / fps;+ let time = 0;++ for (let i = 0; i < frames.length; i++) {+ const frame = frames[i];+ const dur = frame.duration ?? defaultDur;+ const x1 = rc.state.timeToX(time);+ const x2 = rc.state.timeToX(time + dur);+ const fw = x2 - x1;++ if (x2 >= 0 && x1 <= width) {+ const color = ANIM_FRAME_COLORS[i % ANIM_FRAME_COLORS.length];+ const selected = rc.isNpItemSelected('animFrames', trackIndex, i);++ ctx.fillStyle = selected ? color : color + '60';+ ctx.fillRect(x1, y + 1, fw, TRACK_HEIGHT - 2);++ ctx.strokeStyle = selected ? '#ffffff' : ANIM_FRAME_BORDER;+ ctx.lineWidth = 1;+ ctx.strokeRect(x1 + 0.5, y + 1.5, fw - 1, TRACK_HEIGHT - 3);++ if (frame.thumbnailUrl && fw > 20) {+ let cache = rc.frameImageCache;+ let img = cache?.get(frame.thumbnailUrl);+ if (!img) {+ img = new Image();+ img.src = frame.thumbnailUrl;+ if (!cache) {+ cache = new Map();+ rc.setFrameImageCache(cache);+ }+ cache.set(frame.thumbnailUrl, img);+ img.onload = () => rc.requestRedraw();+ }+ if (img.complete && img.naturalWidth > 0) {+ const imgH = TRACK_HEIGHT - 4;+ const imgW = Math.min(imgH, fw - 2);+ ctx.drawImage(img, x1 + 1, y + 2, imgW, imgH);+ }+ }++ if (fw > 30) {+ ctx.fillStyle = selected ? '#ffffff' : '#cccccc';+ ctx.font = '9px monospace';+ ctx.textAlign = 'left';+ const label = String(i).padStart(2, '0');+ const textX = frame.thumbnailUrl && fw > 20 ? x1 + TRACK_HEIGHT - 2 : x1 + 4;+ ctx.fillText(label, textX, y + TRACK_HEIGHT / 2 + 3);++ const durMs = Math.round(dur * 1000);+ const durLabel = durMs + 'ms';+ ctx.fillStyle = selected ? 'rgba(255,255,255,0.6)' : 'rgba(200,200,200,0.5)';+ ctx.textAlign = 'right';+ ctx.fillText(durLabel, x2 - 4, y + TRACK_HEIGHT / 2 + 3);+ ctx.textAlign = 'left';+ }++ if (fw > 4) {+ ctx.fillStyle = selected ? 'rgba(255,255,255,0.4)' : 'rgba(200,200,200,0.25)';+ ctx.fillRect(x2 - 3, y + 3, 2, TRACK_HEIGHT - 6);+ }+ }+ time += dur;+ }+}++function drawKeyframes(+ ctx: CanvasRenderingContext2D,+ keyframes: { time: number }[],+ y: number,+ trackIndex: number,+ channelIndex: number,+ rc: TimelineRenderContext,+): void {+ const cy = y + TRACK_HEIGHT / 2;+ const half = KEYFRAME_SIZE / 2;++ for (let ki = 0; ki < keyframes.length; ki++) {+ const kf = keyframes[ki];+ const x = rc.state.timeToX(kf.time);+ if (x < -KEYFRAME_SIZE || x > rc.canvasWidth + KEYFRAME_SIZE) continue;++ const isSelected = rc.isKeyframeSelected(trackIndex, channelIndex, ki);++ ctx.fillStyle = isSelected ? KEYFRAME_SELECTED : KEYFRAME_COLOR;+ ctx.beginPath();+ ctx.moveTo(x, cy - half);+ ctx.lineTo(x + half, cy);+ ctx.lineTo(x, cy + half);+ ctx.lineTo(x - half, cy);+ ctx.closePath();+ ctx.fill();+ }+}++function drawSpineClips(+ ctx: CanvasRenderingContext2D,+ clips: { start: number; duration: number; animation: string }[],+ y: number,+ _width: number,+ rc: TimelineRenderContext,+): void {+ const clipY = y + 3;+ const clipH = TRACK_HEIGHT - 6;++ for (const clip of clips) {+ const x1 = rc.state.timeToX(clip.start);+ const x2 = rc.state.timeToX(clip.start + clip.duration);+ const w = x2 - x1;+ if (w < 1) continue;++ ctx.fillStyle = SPINE_CLIP_COLOR;+ ctx.fillRect(x1, clipY, w, clipH);+ ctx.strokeStyle = SPINE_CLIP_BORDER;+ ctx.lineWidth = 1;+ ctx.strokeRect(x1 + 0.5, clipY + 0.5, w - 1, clipH - 1);++ ctx.fillStyle = '#cccccc';+ ctx.font = '10px monospace';+ ctx.textAlign = 'left';+ const textX = Math.max(x1 + 4, 4);+ ctx.save();+ ctx.beginPath();+ ctx.rect(x1, clipY, w, clipH);+ ctx.clip();+ ctx.fillText(clip.animation, textX, clipY + clipH / 2 + 3);+ ctx.restore();+ }+}++function drawSpriteAnimClip(+ ctx: CanvasRenderingContext2D,+ startTime: number,+ clipName: string,+ y: number,+ width: number,+ rc: TimelineRenderContext,+): void {+ const x1 = rc.state.timeToX(startTime);+ const x2 = Math.min(rc.state.timeToX(rc.state.duration), width);+ const clipY = y + 3;+ const clipH = TRACK_HEIGHT - 6;++ if (x2 > x1) {+ ctx.fillStyle = SPRITE_ANIM_COLOR;+ ctx.fillRect(x1, clipY, x2 - x1, clipH);+ ctx.strokeStyle = SPRITE_ANIM_BORDER;+ ctx.lineWidth = 1;+ ctx.strokeRect(x1 + 0.5, clipY + 0.5, x2 - x1 - 1, clipH - 1);+ }++ ctx.fillStyle = SPRITE_ANIM_BORDER;+ ctx.fillRect(x1 - 1, y + 2, 3, TRACK_HEIGHT - 4);++ if (clipName) {+ const resolvedPath = isUUID(clipName)+ ? (getAssetLibrary().getPath(clipName) ?? clipName)+ : clipName;+ const displayName = resolvedPath.includes('/')+ ? resolvedPath.slice(resolvedPath.lastIndexOf('/') + 1)+ : resolvedPath;+ ctx.fillStyle = '#cccccc';+ ctx.font = '10px monospace';+ ctx.textAlign = 'left';+ const textX = Math.max(x1 + 6, 6);+ ctx.save();+ if (x2 > x1) {+ ctx.beginPath();+ ctx.rect(x1, clipY, x2 - x1, clipH);+ ctx.clip();+ }+ ctx.fillText(displayName, textX, clipY + clipH / 2 + 3);+ ctx.restore();+ }+}++function drawAudioEvents(+ ctx: CanvasRenderingContext2D,+ events: { time: number; clip?: string }[],+ y: number,+ rc: TimelineRenderContext,+): void {+ for (const event of events) {+ const x = rc.state.timeToX(event.time);+ ctx.fillStyle = AUDIO_EVENT_COLOR;+ ctx.fillRect(x - 1, y + 2, 3, TRACK_HEIGHT - 4);++ ctx.beginPath();+ ctx.moveTo(x - 4, y + 2);+ ctx.lineTo(x + 4, y + 2);+ ctx.lineTo(x, y + 8);+ ctx.closePath();+ ctx.fill();++ if (event.clip) {+ const clipPath = isUUID(event.clip)+ ? (getAssetLibrary().getPath(event.clip) ?? event.clip)+ : event.clip;+ const label = clipPath.includes('/')+ ? clipPath.slice(clipPath.lastIndexOf('/') + 1)+ : clipPath;+ ctx.fillStyle = '#aaaaaa';+ ctx.font = '9px monospace';+ ctx.textAlign = 'left';+ ctx.fillText(label, x + 6, y + TRACK_HEIGHT / 2 + 3);+ }+ }+}++function drawActivationRanges(+ ctx: CanvasRenderingContext2D,+ ranges: { start: number; end: number }[],+ y: number,+ _width: number,+ rc: TimelineRenderContext,+): void {+ const rangeY = y + 4;+ const rangeH = TRACK_HEIGHT - 8;++ for (const range of ranges) {+ const x1 = rc.state.timeToX(range.start);+ const x2 = rc.state.timeToX(range.end);+ const w = x2 - x1;+ if (w < 1) continue;++ ctx.fillStyle = ACTIVATION_COLOR;+ ctx.fillRect(x1, rangeY, w, rangeH);+ ctx.strokeStyle = ACTIVATION_BORDER;+ ctx.lineWidth = 1;+ ctx.strokeRect(x1 + 0.5, rangeY + 0.5, w - 1, rangeH - 1);+ }+}++export function drawPlayhead(ctx: CanvasRenderingContext2D, canvasWidth: number, height: number, rc: TimelineRenderContext): void {+ const x = rc.state.timeToX(rc.state.playheadTime);+ if (x < -10 || x > canvasWidth + 10) return;++ ctx.strokeStyle = PLAYHEAD_COLOR;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(Math.round(x) + 0.5, 0);+ ctx.lineTo(Math.round(x) + 0.5, height);+ ctx.stroke();++ ctx.fillStyle = PLAYHEAD_COLOR;+ ctx.beginPath();+ ctx.moveTo(x - 5, 0);+ ctx.lineTo(x + 5, 0);+ ctx.lineTo(x, 8);+ ctx.closePath();+ ctx.fill();+}++export function drawDurationEnd(ctx: CanvasRenderingContext2D, width: number, height: number, rc: TimelineRenderContext): void {+ const x = rc.state.timeToX(rc.state.duration);+ if (x < 0) return;++ if (x < width) {+ ctx.strokeStyle = DURATION_LINE_COLOR;+ ctx.lineWidth = 1;+ ctx.setLineDash([4, 4]);+ ctx.beginPath();+ ctx.moveTo(Math.round(x) + 0.5, RULER_HEIGHT);+ ctx.lineTo(Math.round(x) + 0.5, height);+ ctx.stroke();+ ctx.setLineDash([]);+ }++ const overlayX = Math.max(x, 0);+ if (overlayX < width) {+ ctx.fillStyle = BEYOND_DURATION_COLOR;+ ctx.fillRect(overlayX, RULER_HEIGHT, width - overlayX, height - RULER_HEIGHT);+ }+}++export function drawRubberBand(+ ctx: CanvasRenderingContext2D,+ rubberBand: { startX: number; startY: number; endX: number; endY: number } | null,+): void {+ if (!rubberBand) return;+ const rb = rubberBand;+ const x = Math.min(rb.startX, rb.endX);+ const y = Math.min(rb.startY, rb.endY);+ const w = Math.abs(rb.endX - rb.startX);+ const h = Math.abs(rb.endY - rb.startY);++ ctx.fillStyle = RUBBERBAND_COLOR;+ ctx.fillRect(x, y, w, h);+ ctx.strokeStyle = RUBBERBAND_BORDER;+ ctx.lineWidth = 1;+ ctx.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1);+}diff --git a/editor/src/panels/timeline/TimelineTypes.ts b/editor/src/panels/timeline/TimelineTypes.tsnew file mode 100644index 000000000..6ab1846c2--- /dev/null+++ b/editor/src/panels/timeline/TimelineTypes.ts@@ -0,0 +1,140 @@+export interface SpineClipHit {+ trackIndex: number;+ clipIndex: number;+ zone: 'body' | 'resize';+}++export interface AudioEventHit {+ trackIndex: number;+ eventIndex: number;+}++export interface ActivationRangeHit {+ trackIndex: number;+ rangeIndex: number;+ zone: 'body' | 'left' | 'right';+}++export interface MarkerHit {+ trackIndex: number;+ markerIndex: number;+}++export interface CustomEventHit {+ trackIndex: number;+ eventIndex: number;+}++export interface SpriteAnimHit {+ trackIndex: number;+}++export interface AnimFrameHit {+ trackIndex: number;+ frameIndex: number;+ zone: 'body' | 'resize';+}++export interface TimelineAssetData {+ tracks: TimelineTrackData[];+ duration: number;+}++export interface TimelineKeyframe {+ time: number;+ value: number;+ inTangent?: number;+ outTangent?: number;+ interpolation?: string;+}++export interface TimelineChannel {+ property: string;+ keyframes: TimelineKeyframe[];+}++export interface TimelineSpineClip {+ start: number;+ duration: number;+ animation: string;+}++export interface TimelineAudioEvent {+ time: number;+ clip: string;+}++export interface TimelineCustomEvent {+ time: number;+ name: string;+ payload: Record<string, unknown>;+}++export interface TimelineActivationRange {+ start: number;+ end: number;+}++export interface TimelineMarker {+ time: number;+ name: string;+}++export interface AnimFrameData {+ texture: string;+ duration?: number;+ thumbnailUrl?: string;+}++export interface TimelineTrackData {+ type: string;+ name: string;+ childPath?: string;+ component?: string;+ channels?: TimelineChannel[];+ clips?: TimelineSpineClip[];+ events?: (TimelineAudioEvent | TimelineCustomEvent)[];+ ranges?: TimelineActivationRange[];+ markers?: TimelineMarker[];+ clip?: string;+ startTime?: number;+ animFrames?: AnimFrameData[];+}++export interface KeyframeHit {+ trackIndex: number;+ channelIndex: number;+ keyframeIndex: number;+ time: number;+}++export interface TimelinePanelHost {+ get assetData(): TimelineAssetData | null;+ executeCommand(cmd: import('../../commands/Command').Command): void;+ onAssetDataChanged(): void;+ readPropertyValue(trackIndex: number, channelIndex: number): number;+}++export interface SelectedKeyframeInfo {+ trackIndex: number;+ channelIndex: number;+ keyframeIndex: number;+ time: number;+ value: number;+}++export interface SelectionSummary {+ count: number;+ single: SelectedKeyframeInfo | null;+}++export type KeyframeSelectionCallback = (summary: SelectionSummary) => void;++export type NonPropertyHit = {+ type: string;+ hit: SpineClipHit | AudioEventHit | ActivationRangeHit | MarkerHit | CustomEventHit | SpriteAnimHit | AnimFrameHit;+};++export function kfKey(trackIndex: number, channelIndex: number, keyframeIndex: number): string {+ return `${trackIndex}:${channelIndex}:${keyframeIndex}`;+}diff --git a/src/esengine/bindings/PhysicsContext.cpp b/src/esengine/bindings/PhysicsContext.cppnew file mode 100644index 000000000..87e6c6c5e--- /dev/null+++ b/src/esengine/bindings/PhysicsContext.cpp@@ -0,0 +1,39 @@+#include "PhysicsContext.hpp"++PhysicsContext g_ctx;++std::vector<float> g_raycastBuffer;+std::vector<float> g_overlapBuffer;+std::vector<float> g_shapeCastBuffer;+float g_massDataBuffer[2] = {};++b2JointId findValidJoint(uint32_t entityId) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return b2_nullJointId;+ if (!b2Joint_IsValid(it->second)) return b2_nullJointId;+ return it->second;+}++b2BodyId findValidBody(uint32_t entityId) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return b2_nullBodyId;+ if (!b2Body_IsValid(it->second)) return b2_nullBodyId;+ return it->second;+}++uint32_t entityFromBody(b2BodyId bodyId) {+ void* ud = b2Body_GetUserData(bodyId);+ if (!ud) return 0xFFFFFFFF;+ return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(ud));+}++uint32_t entityFromShape(b2ShapeId shapeId) {+ b2BodyId bodyId = b2Shape_GetBody(shapeId);+ return entityFromBody(bodyId);+}++void pushEntityBits(std::vector<float>& buf, uint32_t entityId) {+ float bits;+ std::memcpy(&bits, &entityId, sizeof(float));+ buf.push_back(bits);+}diff --git a/src/esengine/bindings/PhysicsContext.hpp b/src/esengine/bindings/PhysicsContext.hppnew file mode 100644index 000000000..47fda22c4--- /dev/null+++ b/src/esengine/bindings/PhysicsContext.hpp@@ -0,0 +1,69 @@+#pragma once++#include <emscripten.h>++#include <box2d/box2d.h>++#include <unordered_map>+#include <vector>+#include <cstdint>+#include <cstring>++static constexpr int MAX_PHYSICS_STEPS_PER_FRAME = 8;+static constexpr int RAYCAST_STRIDE = 6;+static constexpr int MAX_RAYCAST_HITS = 64;+static constexpr int MAX_OVERLAP_HITS = 64;+static constexpr int SHAPECAST_STRIDE = 6;++struct PhysicsContext {+ b2WorldId worldId = b2_nullWorldId;+ float fixedTimestep = 1.0f / 60.0f;+ int subStepCount = 4;+ float accumulator = 0.0f;++ std::unordered_map<uint32_t, b2BodyId> entityToBody;+ std::unordered_map<uint32_t, std::vector<b2ShapeId>> entityToShapes;+ std::unordered_map<uint32_t, b2JointId> entityToJoint;+ std::vector<uint32_t> dynamicBodyEntities;++ std::vector<float> dynamicTransformBuffer;++ std::vector<float> collisionEnterBuffer;+ std::vector<float> collisionExitBuffer;+ std::vector<float> sensorEnterBuffer;+ std::vector<float> sensorExitBuffer;++ float velocityBuffer[2] = {};+ float gravityBuffer[2] = {};++ void reset() {+ entityToBody.clear();+ entityToShapes.clear();+ entityToJoint.clear();+ dynamicBodyEntities.clear();+ dynamicTransformBuffer.clear();+ collisionEnterBuffer.clear();+ collisionExitBuffer.clear();+ sensorEnterBuffer.clear();+ sensorExitBuffer.clear();+ accumulator = 0.0f;++ if (b2World_IsValid(worldId)) {+ b2DestroyWorld(worldId);+ }+ worldId = b2_nullWorldId;+ }+};++extern PhysicsContext g_ctx;++extern std::vector<float> g_raycastBuffer;+extern std::vector<float> g_overlapBuffer;+extern std::vector<float> g_shapeCastBuffer;+extern float g_massDataBuffer[2];++b2BodyId findValidBody(uint32_t entityId);+b2JointId findValidJoint(uint32_t entityId);+uint32_t entityFromBody(b2BodyId bodyId);+uint32_t entityFromShape(b2ShapeId shapeId);+void pushEntityBits(std::vector<float>& buf, uint32_t entityId);diff --git a/src/esengine/bindings/PhysicsJoints.cpp b/src/esengine/bindings/PhysicsJoints.cppnew file mode 100644index 000000000..bbbf5b7af--- /dev/null+++ b/src/esengine/bindings/PhysicsJoints.cpp@@ -0,0 +1,431 @@+#include "PhysicsContext.hpp"++#include <cmath>++extern "C" {++EMSCRIPTEN_KEEPALIVE+int physics_createRevoluteJoint(uint32_t entityIdA, uint32_t entityIdB,+ float anchorAx, float anchorAy,+ float anchorBx, float anchorBy,+ int enableMotor, float motorSpeed, float maxMotorTorque,+ int enableLimit, float lowerAngle, float upperAngle,+ int collideConnected) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ auto itA = g_ctx.entityToBody.find(entityIdA);+ auto itB = g_ctx.entityToBody.find(entityIdB);+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;++ b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef();+ jointDef.base.bodyIdA = itA->second;+ jointDef.base.bodyIdB = itB->second;+ jointDef.base.localFrameA.p = {anchorAx, anchorAy};+ jointDef.base.localFrameB.p = {anchorBx, anchorBy};+ jointDef.enableMotor = enableMotor != 0;+ jointDef.motorSpeed = motorSpeed;+ jointDef.maxMotorTorque = maxMotorTorque;+ jointDef.enableLimit = enableLimit != 0;+ jointDef.lowerAngle = lowerAngle;+ jointDef.upperAngle = upperAngle;+ jointDef.base.collideConnected = collideConnected != 0;++ b2JointId jointId = b2CreateRevoluteJoint(g_ctx.worldId, &jointDef);+ g_ctx.entityToJoint[entityIdB] = jointId;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+void physics_destroyJoint(uint32_t entityId) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;++ if (b2Joint_IsValid(it->second)) {+ b2DestroyJoint(it->second, true);+ }+ g_ctx.entityToJoint.erase(it);+}++EMSCRIPTEN_KEEPALIVE+void physics_setRevoluteMotorSpeed(uint32_t entityId, float speed) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;+ if (!b2Joint_IsValid(it->second)) return;+ b2RevoluteJoint_SetMotorSpeed(it->second, speed);+}++EMSCRIPTEN_KEEPALIVE+void physics_setRevoluteMaxMotorTorque(uint32_t entityId, float torque) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;+ if (!b2Joint_IsValid(it->second)) return;+ b2RevoluteJoint_SetMaxMotorTorque(it->second, torque);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableRevoluteMotor(uint32_t entityId, int enable) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;+ if (!b2Joint_IsValid(it->second)) return;+ b2RevoluteJoint_EnableMotor(it->second, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableRevoluteLimit(uint32_t entityId, int enable) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;+ if (!b2Joint_IsValid(it->second)) return;+ b2RevoluteJoint_EnableLimit(it->second, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setRevoluteLimits(uint32_t entityId, float lower, float upper) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return;+ if (!b2Joint_IsValid(it->second)) return;+ b2RevoluteJoint_SetLimits(it->second, lower, upper);+}++EMSCRIPTEN_KEEPALIVE+float physics_getRevoluteAngle(uint32_t entityId) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return 0;+ if (!b2Joint_IsValid(it->second)) return 0;+ return b2RevoluteJoint_GetAngle(it->second);+}++EMSCRIPTEN_KEEPALIVE+float physics_getRevoluteMotorTorque(uint32_t entityId) {+ auto it = g_ctx.entityToJoint.find(entityId);+ if (it == g_ctx.entityToJoint.end()) return 0;+ if (!b2Joint_IsValid(it->second)) return 0;+ return b2RevoluteJoint_GetMotorTorque(it->second);+}++EMSCRIPTEN_KEEPALIVE+int physics_hasJoint(uint32_t entityId) {+ return g_ctx.entityToJoint.contains(entityId) ? 1 : 0;+}++EMSCRIPTEN_KEEPALIVE+int physics_createDistanceJoint(uint32_t entityIdA, uint32_t entityIdB,+ float anchorAx, float anchorAy,+ float anchorBx, float anchorBy,+ float length, int enableSpring, float hertz, float dampingRatio,+ int enableLimit, float minLength, float maxLength,+ int enableMotor, float maxMotorForce, float motorSpeed,+ int collideConnected) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ auto itA = g_ctx.entityToBody.find(entityIdA);+ auto itB = g_ctx.entityToBody.find(entityIdB);+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;++ b2DistanceJointDef jointDef = b2DefaultDistanceJointDef();+ jointDef.base.bodyIdA = itA->second;+ jointDef.base.bodyIdB = itB->second;+ jointDef.base.localFrameA.p = {anchorAx, anchorAy};+ jointDef.base.localFrameB.p = {anchorBx, anchorBy};+ jointDef.length = length;+ jointDef.enableSpring = enableSpring != 0;+ jointDef.hertz = hertz;+ jointDef.dampingRatio = dampingRatio;+ jointDef.enableLimit = enableLimit != 0;+ jointDef.minLength = minLength;+ jointDef.maxLength = maxLength;+ jointDef.enableMotor = enableMotor != 0;+ jointDef.maxMotorForce = maxMotorForce;+ jointDef.motorSpeed = motorSpeed;+ jointDef.base.collideConnected = collideConnected != 0;++ b2JointId jointId = b2CreateDistanceJoint(g_ctx.worldId, &jointDef);+ g_ctx.entityToJoint[entityIdB] = jointId;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+int physics_createPrismaticJoint(uint32_t entityIdA, uint32_t entityIdB,+ float anchorAx, float anchorAy,+ float anchorBx, float anchorBy,+ float axisX, float axisY,+ int enableSpring, float hertz, float dampingRatio,+ int enableLimit, float lowerTranslation, float upperTranslation,+ int enableMotor, float maxMotorForce, float motorSpeed,+ int collideConnected) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ auto itA = g_ctx.entityToBody.find(entityIdA);+ auto itB = g_ctx.entityToBody.find(entityIdB);+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;++ b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef();+ jointDef.base.bodyIdA = itA->second;+ jointDef.base.bodyIdB = itB->second;+ jointDef.base.localFrameA.p = {anchorAx, anchorAy};+ jointDef.base.localFrameB.p = {anchorBx, anchorBy};++ float len = sqrtf(axisX * axisX + axisY * axisY);+ if (len > 0.0f) {+ float nx = axisX / len;+ float ny = axisY / len;+ jointDef.base.localFrameA.q = {nx, ny};+ }++ jointDef.enableSpring = enableSpring != 0;+ jointDef.hertz = hertz;+ jointDef.dampingRatio = dampingRatio;+ jointDef.enableLimit = enableLimit != 0;+ jointDef.lowerTranslation = lowerTranslation;+ jointDef.upperTranslation = upperTranslation;+ jointDef.enableMotor = enableMotor != 0;+ jointDef.maxMotorForce = maxMotorForce;+ jointDef.motorSpeed = motorSpeed;+ jointDef.base.collideConnected = collideConnected != 0;++ b2JointId jointId = b2CreatePrismaticJoint(g_ctx.worldId, &jointDef);+ g_ctx.entityToJoint[entityIdB] = jointId;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+int physics_createWeldJoint(uint32_t entityIdA, uint32_t entityIdB,+ float anchorAx, float anchorAy,+ float anchorBx, float anchorBy,+ float linearHertz, float angularHertz,+ float linearDampingRatio, float angularDampingRatio,+ int collideConnected) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ auto itA = g_ctx.entityToBody.find(entityIdA);+ auto itB = g_ctx.entityToBody.find(entityIdB);+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;++ b2WeldJointDef jointDef = b2DefaultWeldJointDef();+ jointDef.base.bodyIdA = itA->second;+ jointDef.base.bodyIdB = itB->second;+ jointDef.base.localFrameA.p = {anchorAx, anchorAy};+ jointDef.base.localFrameB.p = {anchorBx, anchorBy};+ jointDef.linearHertz = linearHertz;+ jointDef.angularHertz = angularHertz;+ jointDef.linearDampingRatio = linearDampingRatio;+ jointDef.angularDampingRatio = angularDampingRatio;+ jointDef.base.collideConnected = collideConnected != 0;++ b2JointId jointId = b2CreateWeldJoint(g_ctx.worldId, &jointDef);+ g_ctx.entityToJoint[entityIdB] = jointId;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+int physics_createWheelJoint(uint32_t entityIdA, uint32_t entityIdB,+ float anchorAx, float anchorAy,+ float anchorBx, float anchorBy,+ float axisX, float axisY,+ int enableSpring, float hertz, float dampingRatio,+ int enableLimit, float lowerTranslation, float upperTranslation,+ int enableMotor, float maxMotorTorque, float motorSpeed,+ int collideConnected) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ auto itA = g_ctx.entityToBody.find(entityIdA);+ auto itB = g_ctx.entityToBody.find(entityIdB);+ if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;+ if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;++ b2WheelJointDef jointDef = b2DefaultWheelJointDef();+ jointDef.base.bodyIdA = itA->second;+ jointDef.base.bodyIdB = itB->second;+ jointDef.base.localFrameA.p = {anchorAx, anchorAy};+ jointDef.base.localFrameB.p = {anchorBx, anchorBy};++ float len = sqrtf(axisX * axisX + axisY * axisY);+ if (len > 0.0f) {+ float nx = axisX / len;+ float ny = axisY / len;+ jointDef.base.localFrameA.q = {nx, ny};+ }++ jointDef.enableSpring = enableSpring != 0;+ jointDef.hertz = hertz;+ jointDef.dampingRatio = dampingRatio;+ jointDef.enableLimit = enableLimit != 0;+ jointDef.lowerTranslation = lowerTranslation;+ jointDef.upperTranslation = upperTranslation;+ jointDef.enableMotor = enableMotor != 0;+ jointDef.maxMotorTorque = maxMotorTorque;+ jointDef.motorSpeed = motorSpeed;+ jointDef.base.collideConnected = collideConnected != 0;++ b2JointId jointId = b2CreateWheelJoint(g_ctx.worldId, &jointDef);+ g_ctx.entityToJoint[entityIdB] = jointId;+ return 1;+}++EMSCRIPTEN_KEEPALIVE+float physics_getDistanceJointLength(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2DistanceJoint_GetLength(jid);+}++EMSCRIPTEN_KEEPALIVE+float physics_getDistanceJointCurrentLength(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2DistanceJoint_GetCurrentLength(jid);+}++EMSCRIPTEN_KEEPALIVE+void physics_setDistanceJointLength(uint32_t entityId, float length) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_SetLength(jid, length);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableDistanceJointSpring(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableSpring(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableDistanceJointLimit(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableLimit(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setDistanceJointLimits(uint32_t entityId, float minLength, float maxLength) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_SetLengthRange(jid, minLength, maxLength);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableDistanceJointMotor(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableMotor(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setDistanceJointMotorSpeed(uint32_t entityId, float speed) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_SetMotorSpeed(jid, speed);+}++EMSCRIPTEN_KEEPALIVE+void physics_setDistanceJointMaxMotorForce(uint32_t entityId, float force) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2DistanceJoint_SetMaxMotorForce(jid, force);+}++EMSCRIPTEN_KEEPALIVE+float physics_getDistanceJointMotorForce(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2DistanceJoint_GetMotorForce(jid);+}++EMSCRIPTEN_KEEPALIVE+float physics_getPrismaticJointTranslation(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2PrismaticJoint_GetTranslation(jid);+}++EMSCRIPTEN_KEEPALIVE+float physics_getPrismaticJointSpeed(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2PrismaticJoint_GetSpeed(jid);+}++EMSCRIPTEN_KEEPALIVE+void physics_enablePrismaticJointSpring(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableSpring(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_enablePrismaticJointLimit(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableLimit(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setPrismaticJointLimits(uint32_t entityId, float lower, float upper) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetLimits(jid, lower, upper);+}++EMSCRIPTEN_KEEPALIVE+void physics_enablePrismaticJointMotor(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableMotor(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setPrismaticJointMotorSpeed(uint32_t entityId, float speed) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetMotorSpeed(jid, speed);+}++EMSCRIPTEN_KEEPALIVE+void physics_setPrismaticJointMaxMotorForce(uint32_t entityId, float force) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetMaxMotorForce(jid, force);+}++EMSCRIPTEN_KEEPALIVE+float physics_getPrismaticJointMotorForce(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2PrismaticJoint_GetMotorForce(jid);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableWheelJointSpring(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_EnableSpring(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableWheelJointLimit(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_EnableLimit(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setWheelJointLimits(uint32_t entityId, float lower, float upper) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_SetLimits(jid, lower, upper);+}++EMSCRIPTEN_KEEPALIVE+void physics_enableWheelJointMotor(uint32_t entityId, int enable) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_EnableMotor(jid, enable != 0);+}++EMSCRIPTEN_KEEPALIVE+void physics_setWheelJointMotorSpeed(uint32_t entityId, float speed) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_SetMotorSpeed(jid, speed);+}++EMSCRIPTEN_KEEPALIVE+void physics_setWheelJointMaxMotorTorque(uint32_t entityId, float torque) {+ auto jid = findValidJoint(entityId);+ if (!B2_IS_NULL(jid)) b2WheelJoint_SetMaxMotorTorque(jid, torque);+}++EMSCRIPTEN_KEEPALIVE+float physics_getWheelJointMotorTorque(uint32_t entityId) {+ auto jid = findValidJoint(entityId);+ if (B2_IS_NULL(jid)) return 0;+ return b2WheelJoint_GetMotorTorque(jid);+}++} // extern "C"diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cppindex 542623103..b104beb55 100644--- a/src/esengine/bindings/PhysicsModuleEntry.cpp+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp@@ -1,121 +1,6 @@-/**- * @file PhysicsModuleEntry.cpp- * @brief Physics WASM module entry point (supports both standalone and SIDE_MODULE)- *- * Pure computation module (no GL/engine dependencies).- * Handles: Box2D world management, body creation, stepping, transform extraction.- *- * All functions exported as extern "C" + EMSCRIPTEN_KEEPALIVE for SIDE_MODULE compatibility.- */--#include <emscripten.h>--#include <box2d/box2d.h>--#include <unordered_map>-#include <vector>-#include <algorithm>-#include <cstdint>-#include <cstring>--// =============================================================================-// Physics Context-// =============================================================================--static constexpr int MAX_PHYSICS_STEPS_PER_FRAME = 8;--struct PhysicsContext {- b2WorldId worldId = b2_nullWorldId;- float fixedTimestep = 1.0f / 60.0f;- int subStepCount = 4;- float accumulator = 0.0f;-- std::unordered_map<uint32_t, b2BodyId> entityToBody;- std::unordered_map<uint32_t, std::vector<b2ShapeId>> entityToShapes;- std::unordered_map<uint32_t, b2JointId> entityToJoint;- std::vector<uint32_t> dynamicBodyEntities;-- std::vector<float> dynamicTransformBuffer;-- std::vector<float> collisionEnterBuffer;- std::vector<float> collisionExitBuffer;- std::vector<float> sensorEnterBuffer;- std::vector<float> sensorExitBuffer;-- float velocityBuffer[2] = {};- float gravityBuffer[2] = {};-- void reset() {- entityToBody.clear();- entityToShapes.clear();- entityToJoint.clear();- dynamicBodyEntities.clear();- dynamicTransformBuffer.clear();- collisionEnterBuffer.clear();- collisionExitBuffer.clear();- sensorEnterBuffer.clear();- sensorExitBuffer.clear();- accumulator = 0.0f;-- if (b2World_IsValid(worldId)) {- b2DestroyWorld(worldId);- }- worldId = b2_nullWorldId;- }-};--static PhysicsContext g_ctx;--static std::vector<float> g_raycastBuffer;-static constexpr int RAYCAST_STRIDE = 6;-static constexpr int MAX_RAYCAST_HITS = 64;--static std::vector<float> g_overlapBuffer;-static constexpr int MAX_OVERLAP_HITS = 64;--static std::vector<float> g_shapeCastBuffer;-static constexpr int SHAPECAST_STRIDE = 6;--static float g_massDataBuffer[2] = {};--static b2JointId findValidJoint(uint32_t entityId) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return b2_nullJointId;- if (!b2Joint_IsValid(it->second)) return b2_nullJointId;- return it->second;-}--static b2BodyId findValidBody(uint32_t entityId) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return b2_nullBodyId;- if (!b2Body_IsValid(it->second)) return b2_nullBodyId;- return it->second;-}--// =============================================================================-// Helper: Entity ID from body user data-// =============================================================================--static uint32_t entityFromBody(b2BodyId bodyId) {- void* ud = b2Body_GetUserData(bodyId);- if (!ud) return 0xFFFFFFFF;- return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(ud));-}--static uint32_t entityFromShape(b2ShapeId shapeId) {- b2BodyId bodyId = b2Shape_GetBody(shapeId);- return entityFromBody(bodyId);-}+#include "PhysicsContext.hpp"-static void pushEntityBits(std::vector<float>& buf, uint32_t entityId) {- float bits;- std::memcpy(&bits, &entityId, sizeof(float));- buf.push_back(bits);-}--// =============================================================================-// Exported Functions-// =============================================================================+#include <algorithm>extern "C" {@@ -207,180 +92,6 @@ int physics_hasBody(uint32_t entityId) {return g_ctx.entityToBody.contains(entityId) ? 1 : 0;}-// Shape Management--EMSCRIPTEN_KEEPALIVE-void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,- float offX, float offY, float radius,- float density, float friction, float restitution, int isSensor,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;-- b2ShapeDef shapeDef = b2DefaultShapeDef();- shapeDef.density = density;- shapeDef.material.friction = friction;- shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor != 0;- shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor != 0;- shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- b2Polygon polygon;- if (radius > 0.0f) {- float innerHalfW = halfW > radius ? halfW - radius : 0.0f;- float innerHalfH = halfH > radius ? halfH - radius : 0.0f;- polygon = b2MakeOffsetRoundedBox(innerHalfW, innerHalfH, {offX, offY}, b2MakeRot(0.0f), radius);- } else {- polygon = b2MakeOffsetBox(halfW, halfH, {offX, offY}, b2MakeRot(0.0f));- }- b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);- g_ctx.entityToShapes[entityId].push_back(shapeId);-}--EMSCRIPTEN_KEEPALIVE-void physics_addCircleShape(uint32_t entityId, float radius,- float offX, float offY,- float density, float friction, float restitution, int isSensor,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;-- b2ShapeDef shapeDef = b2DefaultShapeDef();- shapeDef.density = density;- shapeDef.material.friction = friction;- shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor != 0;- shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor != 0;- shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- b2Circle circle;- circle.center = {offX, offY};- circle.radius = radius;-- b2ShapeId shapeId = b2CreateCircleShape(it->second, &shapeDef, &circle);- g_ctx.entityToShapes[entityId].push_back(shapeId);-}--EMSCRIPTEN_KEEPALIVE-void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,- float offX, float offY,- float density, float friction, float restitution, int isSensor,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;-- b2ShapeDef shapeDef = b2DefaultShapeDef();- shapeDef.density = density;- shapeDef.material.friction = friction;- shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor != 0;- shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor != 0;- shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- b2Capsule capsule;- capsule.center1 = {offX, offY + halfHeight};- capsule.center2 = {offX, offY - halfHeight};- capsule.radius = radius;-- b2ShapeId shapeId = b2CreateCapsuleShape(it->second, &shapeDef, &capsule);- g_ctx.entityToShapes[entityId].push_back(shapeId);-}--EMSCRIPTEN_KEEPALIVE-void physics_addSegmentShape(uint32_t entityId, float x1, float y1, float x2, float y2,- float density, float friction, float restitution, int isSensor,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;-- b2ShapeDef shapeDef = b2DefaultShapeDef();- shapeDef.density = density;- shapeDef.material.friction = friction;- shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor != 0;- shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor != 0;- shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- b2Segment segment;- segment.point1 = {x1, y1};- segment.point2 = {x2, y2};-- b2ShapeId shapeId = b2CreateSegmentShape(it->second, &shapeDef, &segment);- g_ctx.entityToShapes[entityId].push_back(shapeId);-}--EMSCRIPTEN_KEEPALIVE-void physics_addPolygonShape(uint32_t entityId, uintptr_t verticesPtr, int vertexCount, float radius,- float density, float friction, float restitution, int isSensor,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;- if (vertexCount < 3 || vertexCount > B2_MAX_POLYGON_VERTICES) return;-- b2ShapeDef shapeDef = b2DefaultShapeDef();- shapeDef.density = density;- shapeDef.material.friction = friction;- shapeDef.material.restitution = restitution;- shapeDef.isSensor = isSensor != 0;- shapeDef.enableContactEvents = true;- shapeDef.enableSensorEvents = isSensor != 0;- shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- auto* floats = reinterpret_cast<float*>(verticesPtr);- b2Vec2 points[B2_MAX_POLYGON_VERTICES];- for (int i = 0; i < vertexCount; i++) {- points[i] = {floats[i * 2], floats[i * 2 + 1]};- }-- b2Hull hull = b2ComputeHull(points, vertexCount);- if (hull.count == 0) return;-- b2Polygon polygon = (radius > 0.0f)- ? b2MakePolygon(&hull, radius)- : b2MakePolygon(&hull, 0.0f);- b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);- g_ctx.entityToShapes[entityId].push_back(shapeId);-}--EMSCRIPTEN_KEEPALIVE-void physics_addChainShape(uint32_t entityId, uintptr_t pointsPtr, int pointCount, int isLoop,- float friction, float restitution,- uint32_t categoryBits, uint32_t maskBits) {- auto it = g_ctx.entityToBody.find(entityId);- if (it == g_ctx.entityToBody.end()) return;- if (pointCount < 4) return;-- auto* floats = reinterpret_cast<float*>(pointsPtr);- std::vector<b2Vec2> points(pointCount);- for (int i = 0; i < pointCount; i++) {- points[i] = {floats[i * 2], floats[i * 2 + 1]};- }-- b2SurfaceMaterial material = b2DefaultSurfaceMaterial();- material.friction = friction;- material.restitution = restitution;-- b2ChainDef chainDef = b2DefaultChainDef();- chainDef.points = points.data();- chainDef.count = pointCount;- chainDef.isLoop = isLoop != 0;- chainDef.materials = &material;- chainDef.materialCount = 1;- chainDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);- chainDef.filter.maskBits = static_cast<uint64_t>(maskBits);-- b2CreateChain(it->second, &chainDef);-}-// SimulationEMSCRIPTEN_KEEPALIVE@@ -442,7 +153,7 @@ uintptr_t physics_getDynamicBodyTransforms() {return reinterpret_cast<uintptr_t>(g_ctx.dynamicTransformBuffer.data());}-// Collision Events (flat buffer)+// Collision EventsEMSCRIPTEN_KEEPALIVEvoid physics_collectEvents() {@@ -695,352 +406,6 @@ void physics_updateBodyProperties(uint32_t entityId, int bodyType,b2Body_SetMotionLocks(it->second, locks);}-// Revolute Joint--EMSCRIPTEN_KEEPALIVE-int physics_createRevoluteJoint(uint32_t entityIdA, uint32_t entityIdB,- float anchorAx, float anchorAy,- float anchorBx, float anchorBy,- int enableMotor, float motorSpeed, float maxMotorTorque,- int enableLimit, float lowerAngle, float upperAngle,- int collideConnected) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- auto itA = g_ctx.entityToBody.find(entityIdA);- auto itB = g_ctx.entityToBody.find(entityIdB);- if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;- if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;-- b2RevoluteJointDef jointDef = b2DefaultRevoluteJointDef();- jointDef.base.bodyIdA = itA->second;- jointDef.base.bodyIdB = itB->second;- jointDef.base.localFrameA.p = {anchorAx, anchorAy};- jointDef.base.localFrameB.p = {anchorBx, anchorBy};- jointDef.enableMotor = enableMotor != 0;- jointDef.motorSpeed = motorSpeed;- jointDef.maxMotorTorque = maxMotorTorque;- jointDef.enableLimit = enableLimit != 0;- jointDef.lowerAngle = lowerAngle;- jointDef.upperAngle = upperAngle;- jointDef.base.collideConnected = collideConnected != 0;-- b2JointId jointId = b2CreateRevoluteJoint(g_ctx.worldId, &jointDef);- g_ctx.entityToJoint[entityIdB] = jointId;- return 1;-}--EMSCRIPTEN_KEEPALIVE-void physics_destroyJoint(uint32_t entityId) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;-- if (b2Joint_IsValid(it->second)) {- b2DestroyJoint(it->second, true);- }- g_ctx.entityToJoint.erase(it);-}--EMSCRIPTEN_KEEPALIVE-void physics_setRevoluteMotorSpeed(uint32_t entityId, float speed) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;- if (!b2Joint_IsValid(it->second)) return;- b2RevoluteJoint_SetMotorSpeed(it->second, speed);-}--EMSCRIPTEN_KEEPALIVE-void physics_setRevoluteMaxMotorTorque(uint32_t entityId, float torque) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;- if (!b2Joint_IsValid(it->second)) return;- b2RevoluteJoint_SetMaxMotorTorque(it->second, torque);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableRevoluteMotor(uint32_t entityId, int enable) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;- if (!b2Joint_IsValid(it->second)) return;- b2RevoluteJoint_EnableMotor(it->second, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableRevoluteLimit(uint32_t entityId, int enable) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;- if (!b2Joint_IsValid(it->second)) return;- b2RevoluteJoint_EnableLimit(it->second, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setRevoluteLimits(uint32_t entityId, float lower, float upper) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return;- if (!b2Joint_IsValid(it->second)) return;- b2RevoluteJoint_SetLimits(it->second, lower, upper);-}--EMSCRIPTEN_KEEPALIVE-float physics_getRevoluteAngle(uint32_t entityId) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return 0;- if (!b2Joint_IsValid(it->second)) return 0;- return b2RevoluteJoint_GetAngle(it->second);-}--EMSCRIPTEN_KEEPALIVE-float physics_getRevoluteMotorTorque(uint32_t entityId) {- auto it = g_ctx.entityToJoint.find(entityId);- if (it == g_ctx.entityToJoint.end()) return 0;- if (!b2Joint_IsValid(it->second)) return 0;- return b2RevoluteJoint_GetMotorTorque(it->second);-}--EMSCRIPTEN_KEEPALIVE-int physics_hasJoint(uint32_t entityId) {- return g_ctx.entityToJoint.contains(entityId) ? 1 : 0;-}--// Distance Joint--EMSCRIPTEN_KEEPALIVE-int physics_createDistanceJoint(uint32_t entityIdA, uint32_t entityIdB,- float anchorAx, float anchorAy,- float anchorBx, float anchorBy,- float length, int enableSpring, float hertz, float dampingRatio,- int enableLimit, float minLength, float maxLength,- int enableMotor, float maxMotorForce, float motorSpeed,- int collideConnected) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- auto itA = g_ctx.entityToBody.find(entityIdA);- auto itB = g_ctx.entityToBody.find(entityIdB);- if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;- if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;-- b2DistanceJointDef jointDef = b2DefaultDistanceJointDef();- jointDef.base.bodyIdA = itA->second;- jointDef.base.bodyIdB = itB->second;- jointDef.base.localFrameA.p = {anchorAx, anchorAy};- jointDef.base.localFrameB.p = {anchorBx, anchorBy};- jointDef.length = length;- jointDef.enableSpring = enableSpring != 0;- jointDef.hertz = hertz;- jointDef.dampingRatio = dampingRatio;- jointDef.enableLimit = enableLimit != 0;- jointDef.minLength = minLength;- jointDef.maxLength = maxLength;- jointDef.enableMotor = enableMotor != 0;- jointDef.maxMotorForce = maxMotorForce;- jointDef.motorSpeed = motorSpeed;- jointDef.base.collideConnected = collideConnected != 0;-- b2JointId jointId = b2CreateDistanceJoint(g_ctx.worldId, &jointDef);- g_ctx.entityToJoint[entityIdB] = jointId;- return 1;-}--// Prismatic Joint--EMSCRIPTEN_KEEPALIVE-int physics_createPrismaticJoint(uint32_t entityIdA, uint32_t entityIdB,- float anchorAx, float anchorAy,- float anchorBx, float anchorBy,- float axisX, float axisY,- int enableSpring, float hertz, float dampingRatio,- int enableLimit, float lowerTranslation, float upperTranslation,- int enableMotor, float maxMotorForce, float motorSpeed,- int collideConnected) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- auto itA = g_ctx.entityToBody.find(entityIdA);- auto itB = g_ctx.entityToBody.find(entityIdB);- if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;- if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;-- b2PrismaticJointDef jointDef = b2DefaultPrismaticJointDef();- jointDef.base.bodyIdA = itA->second;- jointDef.base.bodyIdB = itB->second;- jointDef.base.localFrameA.p = {anchorAx, anchorAy};- jointDef.base.localFrameB.p = {anchorBx, anchorBy};-- float len = sqrtf(axisX * axisX + axisY * axisY);- if (len > 0.0f) {- float nx = axisX / len;- float ny = axisY / len;- jointDef.base.localFrameA.q = {nx, ny};- }-- jointDef.enableSpring = enableSpring != 0;- jointDef.hertz = hertz;- jointDef.dampingRatio = dampingRatio;- jointDef.enableLimit = enableLimit != 0;- jointDef.lowerTranslation = lowerTranslation;- jointDef.upperTranslation = upperTranslation;- jointDef.enableMotor = enableMotor != 0;- jointDef.maxMotorForce = maxMotorForce;- jointDef.motorSpeed = motorSpeed;- jointDef.base.collideConnected = collideConnected != 0;-- b2JointId jointId = b2CreatePrismaticJoint(g_ctx.worldId, &jointDef);- g_ctx.entityToJoint[entityIdB] = jointId;- return 1;-}--// Weld Joint--EMSCRIPTEN_KEEPALIVE-int physics_createWeldJoint(uint32_t entityIdA, uint32_t entityIdB,- float anchorAx, float anchorAy,- float anchorBx, float anchorBy,- float linearHertz, float angularHertz,- float linearDampingRatio, float angularDampingRatio,- int collideConnected) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- auto itA = g_ctx.entityToBody.find(entityIdA);- auto itB = g_ctx.entityToBody.find(entityIdB);- if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;- if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;-- b2WeldJointDef jointDef = b2DefaultWeldJointDef();- jointDef.base.bodyIdA = itA->second;- jointDef.base.bodyIdB = itB->second;- jointDef.base.localFrameA.p = {anchorAx, anchorAy};- jointDef.base.localFrameB.p = {anchorBx, anchorBy};- jointDef.linearHertz = linearHertz;- jointDef.angularHertz = angularHertz;- jointDef.linearDampingRatio = linearDampingRatio;- jointDef.angularDampingRatio = angularDampingRatio;- jointDef.base.collideConnected = collideConnected != 0;-- b2JointId jointId = b2CreateWeldJoint(g_ctx.worldId, &jointDef);- g_ctx.entityToJoint[entityIdB] = jointId;- return 1;-}--// Wheel Joint--EMSCRIPTEN_KEEPALIVE-int physics_createWheelJoint(uint32_t entityIdA, uint32_t entityIdB,- float anchorAx, float anchorAy,- float anchorBx, float anchorBy,- float axisX, float axisY,- int enableSpring, float hertz, float dampingRatio,- int enableLimit, float lowerTranslation, float upperTranslation,- int enableMotor, float maxMotorTorque, float motorSpeed,- int collideConnected) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- auto itA = g_ctx.entityToBody.find(entityIdA);- auto itB = g_ctx.entityToBody.find(entityIdB);- if (itA == g_ctx.entityToBody.end() || itB == g_ctx.entityToBody.end()) return 0;- if (!b2Body_IsValid(itA->second) || !b2Body_IsValid(itB->second)) return 0;-- b2WheelJointDef jointDef = b2DefaultWheelJointDef();- jointDef.base.bodyIdA = itA->second;- jointDef.base.bodyIdB = itB->second;- jointDef.base.localFrameA.p = {anchorAx, anchorAy};- jointDef.base.localFrameB.p = {anchorBx, anchorBy};-- float len = sqrtf(axisX * axisX + axisY * axisY);- if (len > 0.0f) {- float nx = axisX / len;- float ny = axisY / len;- jointDef.base.localFrameA.q = {nx, ny};- }-- jointDef.enableSpring = enableSpring != 0;- jointDef.hertz = hertz;- jointDef.dampingRatio = dampingRatio;- jointDef.enableLimit = enableLimit != 0;- jointDef.lowerTranslation = lowerTranslation;- jointDef.upperTranslation = upperTranslation;- jointDef.enableMotor = enableMotor != 0;- jointDef.maxMotorTorque = maxMotorTorque;- jointDef.motorSpeed = motorSpeed;- jointDef.base.collideConnected = collideConnected != 0;-- b2JointId jointId = b2CreateWheelJoint(g_ctx.worldId, &jointDef);- g_ctx.entityToJoint[entityIdB] = jointId;- return 1;-}--// Raycasting--static float raycastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {- if (g_raycastBuffer.size() / RAYCAST_STRIDE >= MAX_RAYCAST_HITS) return 0.0f;-- uint32_t entityId = entityFromShape(shapeId);- if (entityId == 0xFFFFFFFF) return 1.0f;-- pushEntityBits(g_raycastBuffer, entityId);- g_raycastBuffer.push_back(point.x);- g_raycastBuffer.push_back(point.y);- g_raycastBuffer.push_back(normal.x);- g_raycastBuffer.push_back(normal.y);- g_raycastBuffer.push_back(fraction);-- return 1.0f;-}--EMSCRIPTEN_KEEPALIVE-int physics_raycast(float originX, float originY, float dirX, float dirY,- float maxDistance, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_raycastBuffer.clear();-- b2Vec2 origin = {originX, originY};- b2Vec2 translation = {dirX * maxDistance, dirY * maxDistance};-- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_CastRay(g_ctx.worldId, origin, translation, filter, raycastCallback, nullptr);-- return static_cast<int>(g_raycastBuffer.size() / RAYCAST_STRIDE);-}--EMSCRIPTEN_KEEPALIVE-uintptr_t physics_getRaycastBuffer() {- return reinterpret_cast<uintptr_t>(g_raycastBuffer.data());-}--// Overlap Query--static bool overlapCallback(b2ShapeId shapeId, void* context) {- if (g_overlapBuffer.size() >= MAX_OVERLAP_HITS) return false;-- uint32_t entityId = entityFromShape(shapeId);- if (entityId == 0xFFFFFFFF) return true;-- pushEntityBits(g_overlapBuffer, entityId);- return true;-}--EMSCRIPTEN_KEEPALIVE-int physics_overlapCircle(float centerX, float centerY, float radius, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_overlapBuffer.clear();-- b2Vec2 center = {centerX, centerY};- b2ShapeProxy proxy = b2MakeProxy(¢er, 1, radius);-- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_OverlapShape(g_ctx.worldId, &proxy, filter, overlapCallback, nullptr);-- return static_cast<int>(g_overlapBuffer.size());-}--EMSCRIPTEN_KEEPALIVE-uintptr_t physics_getOverlapBuffer() {- return reinterpret_cast<uintptr_t>(g_overlapBuffer.data());-}-// Sleep / WakeEMSCRIPTEN_KEEPALIVE@@ -1059,103 +424,6 @@ int physics_isAwake(uint32_t entityId) {return b2Body_IsAwake(it->second) ? 1 : 0;}-// Shape Cast--static float shapeCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {- if (g_shapeCastBuffer.size() / SHAPECAST_STRIDE >= MAX_RAYCAST_HITS) return 0.0f;-- uint32_t entityId = entityFromShape(shapeId);- if (entityId == 0xFFFFFFFF) return 1.0f;-- pushEntityBits(g_shapeCastBuffer, entityId);- g_shapeCastBuffer.push_back(point.x);- g_shapeCastBuffer.push_back(point.y);- g_shapeCastBuffer.push_back(normal.x);- g_shapeCastBuffer.push_back(normal.y);- g_shapeCastBuffer.push_back(fraction);-- return 1.0f;-}--EMSCRIPTEN_KEEPALIVE-int physics_shapeCastCircle(float centerX, float centerY, float radius,- float translationX, float translationY, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_shapeCastBuffer.clear();-- b2Vec2 center = {centerX, centerY};- b2ShapeProxy proxy = b2MakeProxy(¢er, 1, radius);- b2Vec2 translation = {translationX, translationY};-- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);-- return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);-}--EMSCRIPTEN_KEEPALIVE-int physics_shapeCastBox(float centerX, float centerY, float halfW, float halfH, float angle,- float translationX, float translationY, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_shapeCastBuffer.clear();-- b2Polygon box = b2MakeOffsetBox(halfW, halfH, {centerX, centerY}, b2MakeRot(angle));- b2ShapeProxy proxy = b2MakeProxy(box.vertices, box.count, box.radius);- b2Vec2 translation = {translationX, translationY};-- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);-- return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);-}--EMSCRIPTEN_KEEPALIVE-int physics_shapeCastCapsule(float center1X, float center1Y, float center2X, float center2Y,- float radius, float translationX, float translationY, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_shapeCastBuffer.clear();-- b2Vec2 centers[2] = {{center1X, center1Y}, {center2X, center2Y}};- b2ShapeProxy proxy = b2MakeProxy(centers, 2, radius);- b2Vec2 translation = {translationX, translationY};-- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);-- return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);-}--EMSCRIPTEN_KEEPALIVE-uintptr_t physics_getShapeCastBuffer() {- return reinterpret_cast<uintptr_t>(g_shapeCastBuffer.data());-}--// AABB Overlap--EMSCRIPTEN_KEEPALIVE-int physics_overlapAABB(float minX, float minY, float maxX, float maxY, uint32_t maskBits) {- if (!b2World_IsValid(g_ctx.worldId)) return 0;-- g_overlapBuffer.clear();-- b2AABB aabb = {{minX, minY}, {maxX, maxY}};- b2QueryFilter filter = b2DefaultQueryFilter();- filter.maskBits = static_cast<uint64_t>(maskBits);-- b2World_OverlapAABB(g_ctx.worldId, aabb, filter, overlapCallback, nullptr);-- return static_cast<int>(g_overlapBuffer.size());-}-// Body Mass QueriesEMSCRIPTEN_KEEPALIVE@@ -1185,173 +453,4 @@ uintptr_t physics_getBodyCenterOfMass(uint32_t entityId) {return reinterpret_cast<uintptr_t>(g_massDataBuffer);}-// Joint State Queries — Distance Joint--EMSCRIPTEN_KEEPALIVE-float physics_getDistanceJointLength(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2DistanceJoint_GetLength(jid);-}--EMSCRIPTEN_KEEPALIVE-float physics_getDistanceJointCurrentLength(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2DistanceJoint_GetCurrentLength(jid);-}--EMSCRIPTEN_KEEPALIVE-void physics_setDistanceJointLength(uint32_t entityId, float length) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_SetLength(jid, length);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableDistanceJointSpring(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableSpring(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableDistanceJointLimit(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableLimit(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setDistanceJointLimits(uint32_t entityId, float minLength, float maxLength) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_SetLengthRange(jid, minLength, maxLength);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableDistanceJointMotor(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_EnableMotor(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setDistanceJointMotorSpeed(uint32_t entityId, float speed) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_SetMotorSpeed(jid, speed);-}--EMSCRIPTEN_KEEPALIVE-void physics_setDistanceJointMaxMotorForce(uint32_t entityId, float force) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2DistanceJoint_SetMaxMotorForce(jid, force);-}--EMSCRIPTEN_KEEPALIVE-float physics_getDistanceJointMotorForce(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2DistanceJoint_GetMotorForce(jid);-}--// Joint State Queries — Prismatic Joint--EMSCRIPTEN_KEEPALIVE-float physics_getPrismaticJointTranslation(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2PrismaticJoint_GetTranslation(jid);-}--EMSCRIPTEN_KEEPALIVE-float physics_getPrismaticJointSpeed(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2PrismaticJoint_GetSpeed(jid);-}--EMSCRIPTEN_KEEPALIVE-void physics_enablePrismaticJointSpring(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableSpring(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_enablePrismaticJointLimit(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableLimit(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setPrismaticJointLimits(uint32_t entityId, float lower, float upper) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetLimits(jid, lower, upper);-}--EMSCRIPTEN_KEEPALIVE-void physics_enablePrismaticJointMotor(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_EnableMotor(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setPrismaticJointMotorSpeed(uint32_t entityId, float speed) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetMotorSpeed(jid, speed);-}--EMSCRIPTEN_KEEPALIVE-void physics_setPrismaticJointMaxMotorForce(uint32_t entityId, float force) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2PrismaticJoint_SetMaxMotorForce(jid, force);-}--EMSCRIPTEN_KEEPALIVE-float physics_getPrismaticJointMotorForce(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2PrismaticJoint_GetMotorForce(jid);-}--// Joint State Queries — Wheel Joint--EMSCRIPTEN_KEEPALIVE-void physics_enableWheelJointSpring(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_EnableSpring(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableWheelJointLimit(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_EnableLimit(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setWheelJointLimits(uint32_t entityId, float lower, float upper) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_SetLimits(jid, lower, upper);-}--EMSCRIPTEN_KEEPALIVE-void physics_enableWheelJointMotor(uint32_t entityId, int enable) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_EnableMotor(jid, enable != 0);-}--EMSCRIPTEN_KEEPALIVE-void physics_setWheelJointMotorSpeed(uint32_t entityId, float speed) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_SetMotorSpeed(jid, speed);-}--EMSCRIPTEN_KEEPALIVE-void physics_setWheelJointMaxMotorTorque(uint32_t entityId, float torque) {- auto jid = findValidJoint(entityId);- if (!B2_IS_NULL(jid)) b2WheelJoint_SetMaxMotorTorque(jid, torque);-}--EMSCRIPTEN_KEEPALIVE-float physics_getWheelJointMotorTorque(uint32_t entityId) {- auto jid = findValidJoint(entityId);- if (B2_IS_NULL(jid)) return 0;- return b2WheelJoint_GetMotorTorque(jid);-}-} // extern "C"diff --git a/src/esengine/bindings/PhysicsQueries.cpp b/src/esengine/bindings/PhysicsQueries.cppnew file mode 100644index 000000000..8edd4398d--- /dev/null+++ b/src/esengine/bindings/PhysicsQueries.cpp@@ -0,0 +1,169 @@+#include "PhysicsContext.hpp"++static float raycastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {+ if (g_raycastBuffer.size() / RAYCAST_STRIDE >= MAX_RAYCAST_HITS) return 0.0f;++ uint32_t entityId = entityFromShape(shapeId);+ if (entityId == 0xFFFFFFFF) return 1.0f;++ pushEntityBits(g_raycastBuffer, entityId);+ g_raycastBuffer.push_back(point.x);+ g_raycastBuffer.push_back(point.y);+ g_raycastBuffer.push_back(normal.x);+ g_raycastBuffer.push_back(normal.y);+ g_raycastBuffer.push_back(fraction);++ return 1.0f;+}++static bool overlapCallback(b2ShapeId shapeId, void* context) {+ if (g_overlapBuffer.size() >= MAX_OVERLAP_HITS) return false;++ uint32_t entityId = entityFromShape(shapeId);+ if (entityId == 0xFFFFFFFF) return true;++ pushEntityBits(g_overlapBuffer, entityId);+ return true;+}++static float shapeCastCallback(b2ShapeId shapeId, b2Vec2 point, b2Vec2 normal, float fraction, void* context) {+ if (g_shapeCastBuffer.size() / SHAPECAST_STRIDE >= MAX_RAYCAST_HITS) return 0.0f;++ uint32_t entityId = entityFromShape(shapeId);+ if (entityId == 0xFFFFFFFF) return 1.0f;++ pushEntityBits(g_shapeCastBuffer, entityId);+ g_shapeCastBuffer.push_back(point.x);+ g_shapeCastBuffer.push_back(point.y);+ g_shapeCastBuffer.push_back(normal.x);+ g_shapeCastBuffer.push_back(normal.y);+ g_shapeCastBuffer.push_back(fraction);++ return 1.0f;+}++extern "C" {++EMSCRIPTEN_KEEPALIVE+int physics_raycast(float originX, float originY, float dirX, float dirY,+ float maxDistance, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_raycastBuffer.clear();++ b2Vec2 origin = {originX, originY};+ b2Vec2 translation = {dirX * maxDistance, dirY * maxDistance};++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_CastRay(g_ctx.worldId, origin, translation, filter, raycastCallback, nullptr);++ return static_cast<int>(g_raycastBuffer.size() / RAYCAST_STRIDE);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getRaycastBuffer() {+ return reinterpret_cast<uintptr_t>(g_raycastBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_overlapCircle(float centerX, float centerY, float radius, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_overlapBuffer.clear();++ b2Vec2 center = {centerX, centerY};+ b2ShapeProxy proxy = b2MakeProxy(¢er, 1, radius);++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_OverlapShape(g_ctx.worldId, &proxy, filter, overlapCallback, nullptr);++ return static_cast<int>(g_overlapBuffer.size());+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getOverlapBuffer() {+ return reinterpret_cast<uintptr_t>(g_overlapBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_shapeCastCircle(float centerX, float centerY, float radius,+ float translationX, float translationY, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_shapeCastBuffer.clear();++ b2Vec2 center = {centerX, centerY};+ b2ShapeProxy proxy = b2MakeProxy(¢er, 1, radius);+ b2Vec2 translation = {translationX, translationY};++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);++ return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);+}++EMSCRIPTEN_KEEPALIVE+int physics_shapeCastBox(float centerX, float centerY, float halfW, float halfH, float angle,+ float translationX, float translationY, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_shapeCastBuffer.clear();++ b2Polygon box = b2MakeOffsetBox(halfW, halfH, {centerX, centerY}, b2MakeRot(angle));+ b2ShapeProxy proxy = b2MakeProxy(box.vertices, box.count, box.radius);+ b2Vec2 translation = {translationX, translationY};++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);++ return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);+}++EMSCRIPTEN_KEEPALIVE+int physics_shapeCastCapsule(float center1X, float center1Y, float center2X, float center2Y,+ float radius, float translationX, float translationY, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_shapeCastBuffer.clear();++ b2Vec2 centers[2] = {{center1X, center1Y}, {center2X, center2Y}};+ b2ShapeProxy proxy = b2MakeProxy(centers, 2, radius);+ b2Vec2 translation = {translationX, translationY};++ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_CastShape(g_ctx.worldId, &proxy, translation, filter, shapeCastCallback, nullptr);++ return static_cast<int>(g_shapeCastBuffer.size() / SHAPECAST_STRIDE);+}++EMSCRIPTEN_KEEPALIVE+uintptr_t physics_getShapeCastBuffer() {+ return reinterpret_cast<uintptr_t>(g_shapeCastBuffer.data());+}++EMSCRIPTEN_KEEPALIVE+int physics_overlapAABB(float minX, float minY, float maxX, float maxY, uint32_t maskBits) {+ if (!b2World_IsValid(g_ctx.worldId)) return 0;++ g_overlapBuffer.clear();++ b2AABB aabb = {{minX, minY}, {maxX, maxY}};+ b2QueryFilter filter = b2DefaultQueryFilter();+ filter.maskBits = static_cast<uint64_t>(maskBits);++ b2World_OverlapAABB(g_ctx.worldId, aabb, filter, overlapCallback, nullptr);++ return static_cast<int>(g_overlapBuffer.size());+}++} // extern "C"diff --git a/src/esengine/bindings/PhysicsShapes.cpp b/src/esengine/bindings/PhysicsShapes.cppnew file mode 100644index 000000000..2023e76af--- /dev/null+++ b/src/esengine/bindings/PhysicsShapes.cpp@@ -0,0 +1,177 @@+#include "PhysicsContext.hpp"++extern "C" {++EMSCRIPTEN_KEEPALIVE+void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,+ float offX, float offY, float radius,+ float density, float friction, float restitution, int isSensor,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;++ b2ShapeDef shapeDef = b2DefaultShapeDef();+ shapeDef.density = density;+ shapeDef.material.friction = friction;+ shapeDef.material.restitution = restitution;+ shapeDef.isSensor = isSensor != 0;+ shapeDef.enableContactEvents = true;+ shapeDef.enableSensorEvents = isSensor != 0;+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ b2Polygon polygon;+ if (radius > 0.0f) {+ float innerHalfW = halfW > radius ? halfW - radius : 0.0f;+ float innerHalfH = halfH > radius ? halfH - radius : 0.0f;+ polygon = b2MakeOffsetRoundedBox(innerHalfW, innerHalfH, {offX, offY}, b2MakeRot(0.0f), radius);+ } else {+ polygon = b2MakeOffsetBox(halfW, halfH, {offX, offY}, b2MakeRot(0.0f));+ }+ b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);+ g_ctx.entityToShapes[entityId].push_back(shapeId);+}++EMSCRIPTEN_KEEPALIVE+void physics_addCircleShape(uint32_t entityId, float radius,+ float offX, float offY,+ float density, float friction, float restitution, int isSensor,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;++ b2ShapeDef shapeDef = b2DefaultShapeDef();+ shapeDef.density = density;+ shapeDef.material.friction = friction;+ shapeDef.material.restitution = restitution;+ shapeDef.isSensor = isSensor != 0;+ shapeDef.enableContactEvents = true;+ shapeDef.enableSensorEvents = isSensor != 0;+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ b2Circle circle;+ circle.center = {offX, offY};+ circle.radius = radius;++ b2ShapeId shapeId = b2CreateCircleShape(it->second, &shapeDef, &circle);+ g_ctx.entityToShapes[entityId].push_back(shapeId);+}++EMSCRIPTEN_KEEPALIVE+void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,+ float offX, float offY,+ float density, float friction, float restitution, int isSensor,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;++ b2ShapeDef shapeDef = b2DefaultShapeDef();+ shapeDef.density = density;+ shapeDef.material.friction = friction;+ shapeDef.material.restitution = restitution;+ shapeDef.isSensor = isSensor != 0;+ shapeDef.enableContactEvents = true;+ shapeDef.enableSensorEvents = isSensor != 0;+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ b2Capsule capsule;+ capsule.center1 = {offX, offY + halfHeight};+ capsule.center2 = {offX, offY - halfHeight};+ capsule.radius = radius;++ b2ShapeId shapeId = b2CreateCapsuleShape(it->second, &shapeDef, &capsule);+ g_ctx.entityToShapes[entityId].push_back(shapeId);+}++EMSCRIPTEN_KEEPALIVE+void physics_addSegmentShape(uint32_t entityId, float x1, float y1, float x2, float y2,+ float density, float friction, float restitution, int isSensor,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;++ b2ShapeDef shapeDef = b2DefaultShapeDef();+ shapeDef.density = density;+ shapeDef.material.friction = friction;+ shapeDef.material.restitution = restitution;+ shapeDef.isSensor = isSensor != 0;+ shapeDef.enableContactEvents = true;+ shapeDef.enableSensorEvents = isSensor != 0;+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ b2Segment segment;+ segment.point1 = {x1, y1};+ segment.point2 = {x2, y2};++ b2ShapeId shapeId = b2CreateSegmentShape(it->second, &shapeDef, &segment);+ g_ctx.entityToShapes[entityId].push_back(shapeId);+}++EMSCRIPTEN_KEEPALIVE+void physics_addPolygonShape(uint32_t entityId, uintptr_t verticesPtr, int vertexCount, float radius,+ float density, float friction, float restitution, int isSensor,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;+ if (vertexCount < 3 || vertexCount > B2_MAX_POLYGON_VERTICES) return;++ b2ShapeDef shapeDef = b2DefaultShapeDef();+ shapeDef.density = density;+ shapeDef.material.friction = friction;+ shapeDef.material.restitution = restitution;+ shapeDef.isSensor = isSensor != 0;+ shapeDef.enableContactEvents = true;+ shapeDef.enableSensorEvents = isSensor != 0;+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ auto* floats = reinterpret_cast<float*>(verticesPtr);+ b2Vec2 points[B2_MAX_POLYGON_VERTICES];+ for (int i = 0; i < vertexCount; i++) {+ points[i] = {floats[i * 2], floats[i * 2 + 1]};+ }++ b2Hull hull = b2ComputeHull(points, vertexCount);+ if (hull.count == 0) return;++ b2Polygon polygon = (radius > 0.0f)+ ? b2MakePolygon(&hull, radius)+ : b2MakePolygon(&hull, 0.0f);+ b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);+ g_ctx.entityToShapes[entityId].push_back(shapeId);+}++EMSCRIPTEN_KEEPALIVE+void physics_addChainShape(uint32_t entityId, uintptr_t pointsPtr, int pointCount, int isLoop,+ float friction, float restitution,+ uint32_t categoryBits, uint32_t maskBits) {+ auto it = g_ctx.entityToBody.find(entityId);+ if (it == g_ctx.entityToBody.end()) return;+ if (pointCount < 4) return;++ auto* floats = reinterpret_cast<float*>(pointsPtr);+ std::vector<b2Vec2> points(pointCount);+ for (int i = 0; i < pointCount; i++) {+ points[i] = {floats[i * 2], floats[i * 2 + 1]};+ }++ b2SurfaceMaterial material = b2DefaultSurfaceMaterial();+ material.friction = friction;+ material.restitution = restitution;++ b2ChainDef chainDef = b2DefaultChainDef();+ chainDef.points = points.data();+ chainDef.count = pointCount;+ chainDef.isLoop = isLoop != 0;+ chainDef.materials = &material;+ chainDef.materialCount = 1;+ chainDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);+ chainDef.filter.maskBits = static_cast<uint64_t>(maskBits);++ b2CreateChain(it->second, &chainDef);+}++} // extern "C"diff --git a/src/esengine/ecs/UILayoutSystem.cpp b/src/esengine/ecs/UILayoutSystem.cppnew file mode 100644index 000000000..44245581f--- /dev/null+++ b/src/esengine/ecs/UILayoutSystem.cpp@@ -0,0 +1,602 @@+#include "UILayoutSystem.hpp"++#include "components/Transform.hpp"+#include "components/Sprite.hpp"+#include "components/Canvas.hpp"+#include "components/FlexContainer.hpp"+#include "components/FlexItem.hpp"+#include "components/LayoutGroup.hpp"+#include "components/GridLayout.hpp"+#include "components/FanLayout.hpp"++#include <yoga/Yoga.h>+#include <algorithm>+#include <cmath>+#include <vector>++namespace esengine::ecs {++LayoutResult computeAnchorLayout(+ const glm::vec2& anchorMin, const glm::vec2& anchorMax,+ const glm::vec2& offsetMin, const glm::vec2& offsetMax,+ const glm::vec2& size, const LayoutRect& parentRect,+ const glm::vec2& pivot+) {+ f32 parentW = parentRect.right - parentRect.left;+ f32 parentH = parentRect.top - parentRect.bottom;++ f32 aLeft = parentRect.left + anchorMin.x * parentW;+ f32 aRight = parentRect.left + anchorMax.x * parentW;+ f32 aBottom = parentRect.bottom + anchorMin.y * parentH;+ f32 aTop = parentRect.bottom + anchorMax.y * parentH;++ f32 myLeft, myBottom, myRight, myTop;++ if (anchorMin.x == anchorMax.x) {+ myLeft = aLeft + offsetMin.x - size.x * pivot.x;+ myRight = myLeft + size.x;+ } else {+ myLeft = aLeft + offsetMin.x;+ myRight = aRight + offsetMax.x;+ }++ if (anchorMin.y == anchorMax.y) {+ myBottom = aBottom + offsetMin.y - size.y * pivot.y;+ myTop = myBottom + size.y;+ } else {+ myBottom = aBottom + offsetMin.y;+ myTop = aTop + offsetMax.y;+ }++ f32 width = std::max(0.0f, myRight - myLeft);+ f32 height = std::max(0.0f, myTop - myBottom);+ f32 originX = myLeft + pivot.x * width;+ f32 originY = myBottom + pivot.y * height;++ return {+ originX,+ originY,+ { myLeft, myBottom, myLeft + width, myBottom + height },+ };+}++namespace {++LayoutRect getParentLayoutRect(+ Registry& registry,+ const UITree::Node& node,+ const LayoutRect& cameraRect+) {+ if (node.parent == INVALID_ENTITY) {+ return cameraRect;+ }+ auto& parentRect = registry.get<UIRect>(node.parent);+ f32 pw = parentRect.computed_size_.x;+ f32 ph = parentRect.computed_size_.y;+ return { -pw * parentRect.pivot.x, -ph * parentRect.pivot.y,+ pw * (1.0f - parentRect.pivot.x), ph * (1.0f - parentRect.pivot.y) };+}++void setLayoutPosition(Transform& t, UIRect* rect, f32 x, f32 y) {+ if (rect && rect->anim_override_) {+ if (!(rect->anim_override_ & UIRect::ANIM_POS_X)) t.position.x = x;+ if (!(rect->anim_override_ & UIRect::ANIM_POS_Y)) t.position.y = y;+ } else {+ t.position.x = x;+ t.position.y = y;+ }+}++void setLayoutRotation(Transform& t, UIRect* rect, f32 rot) {+ if (rect && (rect->anim_override_ & UIRect::ANIM_ROT_Z)) return;+ f32 halfRad = rot / 2.0f;+ t.rotation = glm::quat(std::cos(halfRad), 0.0f, 0.0f, std::sin(halfRad));+}++void writePosition(+ Registry& registry,+ const UITree::Node& node,+ f32 originX, f32 originY,+ const LayoutRect& cameraRect+) {+ auto* transform = registry.tryGet<Transform>(node.entity);+ if (!transform) return;+ setLayoutPosition(*transform, registry.tryGet<UIRect>(node.entity), originX, originY);+}++void layoutNodeAnchor(+ Registry& registry,+ UITree::Node& node,+ const LayoutRect& cameraRect+) {+ auto& rect = registry.get<UIRect>(node.entity);+ LayoutRect parentRect = getParentLayoutRect(registry, node, cameraRect);++ auto result = computeAnchorLayout(+ rect.anchorMin, rect.anchorMax,+ rect.offsetMin, rect.offsetMax,+ rect.size, parentRect, rect.pivot+ );++ f32 width = result.rect.right - result.rect.left;+ f32 height = result.rect.top - result.rect.bottom;+ rect.computed_size_.x = width;+ rect.computed_size_.y = height;++ auto* sprite = registry.tryGet<Sprite>(node.entity);+ if (sprite) {+ if (sprite->size.x != width || sprite->size.y != height) {+ sprite->size.x = width;+ sprite->size.y = height;+ }+ }++ writePosition(registry, node, result.origin_x, result.origin_y, cameraRect);+}++YGFlexDirection toYGFlexDirection(FlexDirection dir) {+ switch (dir) {+ case FlexDirection::Row: return YGFlexDirectionRow;+ case FlexDirection::Column: return YGFlexDirectionColumn;+ case FlexDirection::RowReverse: return YGFlexDirectionRowReverse;+ case FlexDirection::ColumnReverse: return YGFlexDirectionColumnReverse;+ }+ return YGFlexDirectionRow;+}++YGWrap toYGWrap(FlexWrap wrap) {+ switch (wrap) {+ case FlexWrap::NoWrap: return YGWrapNoWrap;+ case FlexWrap::Wrap: return YGWrapWrap;+ }+ return YGWrapNoWrap;+}++YGJustify toYGJustify(JustifyContent jc) {+ switch (jc) {+ case JustifyContent::Start: return YGJustifyFlexStart;+ case JustifyContent::Center: return YGJustifyCenter;+ case JustifyContent::End: return YGJustifyFlexEnd;+ case JustifyContent::SpaceBetween: return YGJustifySpaceBetween;+ case JustifyContent::SpaceAround: return YGJustifySpaceAround;+ case JustifyContent::SpaceEvenly: return YGJustifySpaceEvenly;+ }+ return YGJustifyFlexStart;+}++YGAlign toYGAlign(AlignItems ai) {+ switch (ai) {+ case AlignItems::Start: return YGAlignFlexStart;+ case AlignItems::Center: return YGAlignCenter;+ case AlignItems::End: return YGAlignFlexEnd;+ case AlignItems::Stretch: return YGAlignStretch;+ }+ return YGAlignStretch;+}++YGAlign toYGAlignContent(AlignContent ac) {+ switch (ac) {+ case AlignContent::Start: return YGAlignFlexStart;+ case AlignContent::Center: return YGAlignCenter;+ case AlignContent::End: return YGAlignFlexEnd;+ case AlignContent::Stretch: return YGAlignStretch;+ case AlignContent::SpaceBetween: return YGAlignSpaceBetween;+ case AlignContent::SpaceAround: return YGAlignSpaceAround;+ }+ return YGAlignFlexStart;+}++YGAlign toYGAlignSelf(AlignSelf as) {+ switch (as) {+ case AlignSelf::Auto: return YGAlignAuto;+ case AlignSelf::Start: return YGAlignFlexStart;+ case AlignSelf::Center: return YGAlignCenter;+ case AlignSelf::End: return YGAlignFlexEnd;+ case AlignSelf::Stretch: return YGAlignStretch;+ }+ return YGAlignAuto;+}++struct FlexChildInfo {+ i32 tree_index;+ Entity entity;+};++void resolveFlexChildren(+ Registry& registry,+ UITree& tree,+ i32 containerIndex,+ const LayoutRect& cameraRect+) {+ Entity containerEntity = tree.nodes_[containerIndex].entity;+ auto& flex = registry.get<FlexContainer>(containerEntity);+ auto& parentRect = registry.get<UIRect>(containerEntity);++ f32 parentW = parentRect.computed_size_.x;+ f32 parentH = parentRect.computed_size_.y;+ f32 pivotX = parentRect.pivot.x;+ f32 pivotY = parentRect.pivot.y;++ std::vector<FlexChildInfo> children;+ for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {+ if (tree.nodes_[j].parent != containerEntity) continue;+ if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;+ Entity childEntity = tree.nodes_[j].entity;+ if (!registry.has<UIRect>(childEntity)) continue;+ children.push_back({j, childEntity});+ }++ if (children.empty()) return;++ YGNodeRef root = YGNodeNew();+ YGNodeStyleSetFlexDirection(root, toYGFlexDirection(flex.direction));+ YGNodeStyleSetFlexWrap(root, toYGWrap(flex.wrap));+ YGNodeStyleSetJustifyContent(root, toYGJustify(flex.justifyContent));+ YGNodeStyleSetAlignItems(root, toYGAlign(flex.alignItems));+ YGNodeStyleSetWidth(root, parentW);+ YGNodeStyleSetHeight(root, parentH);+ YGNodeStyleSetPadding(root, YGEdgeLeft, flex.padding.left);+ YGNodeStyleSetPadding(root, YGEdgeTop, flex.padding.top);+ YGNodeStyleSetPadding(root, YGEdgeRight, flex.padding.right);+ YGNodeStyleSetPadding(root, YGEdgeBottom, flex.padding.bottom);+ YGNodeStyleSetAlignContent(root, toYGAlignContent(flex.alignContent));+ YGNodeStyleSetGap(root, YGGutterColumn, flex.gap.x);+ YGNodeStyleSetGap(root, YGGutterRow, flex.gap.y);++ std::vector<YGNodeRef> childNodes;+ childNodes.reserve(children.size());++ for (usize i = 0; i < children.size(); i++) {+ auto& childRect = registry.get<UIRect>(children[i].entity);+ f32 cw = childRect.computed_size_.x > 0.0f ? childRect.computed_size_.x : childRect.size.x;+ f32 ch = childRect.computed_size_.y > 0.0f ? childRect.computed_size_.y : childRect.size.y;++ YGNodeRef child = YGNodeNew();++ auto* fi = registry.tryGet<FlexItem>(children[i].entity);+ if (fi) {+ YGNodeStyleSetFlexGrow(child, fi->flexGrow);+ YGNodeStyleSetFlexShrink(child, fi->flexShrink);+ if (fi->flexBasis >= 0.0f) {+ YGNodeStyleSetFlexBasis(child, fi->flexBasis);+ } else {+ YGNodeStyleSetFlexBasisAuto(child);+ }+ YGNodeStyleSetAlignSelf(child, toYGAlignSelf(fi->alignSelf));+ YGNodeStyleSetMargin(child, YGEdgeLeft, fi->margin.left);+ YGNodeStyleSetMargin(child, YGEdgeTop, fi->margin.top);+ YGNodeStyleSetMargin(child, YGEdgeRight, fi->margin.right);+ YGNodeStyleSetMargin(child, YGEdgeBottom, fi->margin.bottom);+ if (fi->minWidth >= 0.0f) YGNodeStyleSetMinWidth(child, fi->minWidth);+ if (fi->minHeight >= 0.0f) YGNodeStyleSetMinHeight(child, fi->minHeight);+ if (fi->maxWidth >= 0.0f) YGNodeStyleSetMaxWidth(child, fi->maxWidth);+ if (fi->maxHeight >= 0.0f) YGNodeStyleSetMaxHeight(child, fi->maxHeight);+ if (fi->widthPercent >= 0.0f) {+ YGNodeStyleSetWidthPercent(child, fi->widthPercent);+ } else {+ YGNodeStyleSetWidth(child, cw);+ }+ if (fi->heightPercent >= 0.0f) {+ YGNodeStyleSetHeightPercent(child, fi->heightPercent);+ } else {+ YGNodeStyleSetHeight(child, ch);+ }+ } else {+ YGNodeStyleSetFlexGrow(child, 0.0f);+ YGNodeStyleSetFlexShrink(child, 1.0f);+ YGNodeStyleSetFlexBasisAuto(child);+ YGNodeStyleSetWidth(child, cw);+ YGNodeStyleSetHeight(child, ch);+ }++ YGNodeInsertChild(root, child, i);+ childNodes.push_back(child);+ }++ YGNodeCalculateLayout(root, parentW, parentH, YGDirectionLTR);++ for (usize i = 0; i < children.size(); i++) {+ auto& info = children[i];+ auto& childRect = registry.get<UIRect>(info.entity);++ f32 yogaLeft = YGNodeLayoutGetLeft(childNodes[i]);+ f32 yogaTop = YGNodeLayoutGetTop(childNodes[i]);+ f32 finalW = YGNodeLayoutGetWidth(childNodes[i]);+ f32 finalH = YGNodeLayoutGetHeight(childNodes[i]);++ f32 cpx = childRect.pivot.x;+ f32 cpy = childRect.pivot.y;+ f32 localX = -pivotX * parentW + yogaLeft + cpx * finalW;+ f32 localY = (1.0f - pivotY) * parentH - yogaTop - (1.0f - cpy) * finalH;++ auto* transform = registry.tryGet<Transform>(info.entity);+ if (transform) {+ setLayoutPosition(*transform, &childRect, localX, localY);+ }++ childRect.computed_size_.x = finalW;+ childRect.computed_size_.y = finalH;++ auto* sprite = registry.tryGet<Sprite>(info.entity);+ if (sprite) {+ if (sprite->size.x != finalW || sprite->size.y != finalH) {+ sprite->size.x = finalW;+ sprite->size.y = finalH;+ }+ }++ if (registry.has<FlexContainer>(info.entity) || registry.has<LayoutGroup>(info.entity)) {+ tree.nodes_[info.tree_index].flags |= LAYOUT_DIRTY;+ } else {+ tree.nodes_[info.tree_index].flags &= ~LAYOUT_DIRTY;+ }+ }++ YGNodeFreeRecursive(root);+}++void resolveLayoutGroupChildren(+ Registry& registry,+ UITree& tree,+ i32 containerIndex,+ const LayoutRect& cameraRect+) {+ Entity containerEntity = tree.nodes_[containerIndex].entity;+ auto& group = registry.get<LayoutGroup>(containerEntity);+ auto& parentRect = registry.get<UIRect>(containerEntity);++ f32 pw = parentRect.computed_size_.x;+ f32 ph = parentRect.computed_size_.y;+ f32 pivotX = parentRect.pivot.x;+ f32 pivotY = parentRect.pivot.y;++ f32 padLeft = group.padding.left;+ f32 padTop = group.padding.top;+ f32 padRight = group.padding.right;+ f32 padBottom = group.padding.bottom;++ bool isHorizontal = (group.direction == LayoutDirection::Horizontal);++ struct ChildInfo {+ i32 tree_index;+ Entity entity;+ f32 w;+ f32 h;+ };++ std::vector<ChildInfo> children;+ for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {+ if (tree.nodes_[j].parent != containerEntity) continue;+ if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;++ Entity childEntity = tree.nodes_[j].entity;+ auto* childRect = registry.tryGet<UIRect>(childEntity);+ if (!childRect || !registry.has<Transform>(childEntity)) continue;++ f32 cw = childRect->computed_size_.x > 0.0f ? childRect->computed_size_.x : childRect->size.x;+ f32 ch = childRect->computed_size_.y > 0.0f ? childRect->computed_size_.y : childRect->size.y;+ children.push_back({j, childEntity, cw, ch});+ }++ if (children.empty()) return;++ if (group.reverseOrder) {+ std::reverse(children.begin(), children.end());+ }++ f32 cursor = 0.0f;+ for (usize i = 0; i < children.size(); i++) {+ auto& child = children[i];+ auto& childRect = registry.get<UIRect>(child.entity);+ f32 cpx = childRect.pivot.x;+ f32 cpy = childRect.pivot.y;++ f32 localX, localY;++ if (isHorizontal) {+ localX = -pivotX * pw + padLeft + cursor + cpx * child.w;+ if (group.childAlignment == ChildAlignment::Start) {+ localY = (1.0f - pivotY) * ph - padTop - (1.0f - cpy) * child.h;+ } else if (group.childAlignment == ChildAlignment::End) {+ localY = -pivotY * ph + padBottom + cpy * child.h;+ } else {+ localY = (0.5f - pivotY) * ph + (padBottom - padTop) * 0.5f + (cpy - 0.5f) * child.h;+ }+ cursor += child.w;+ if (i < children.size() - 1) cursor += group.spacing;+ } else {+ if (group.childAlignment == ChildAlignment::Start) {+ localX = -pivotX * pw + padLeft + cpx * child.w;+ } else if (group.childAlignment == ChildAlignment::End) {+ localX = (1.0f - pivotX) * pw - padRight - (1.0f - cpx) * child.w;+ } else {+ localX = (0.5f - pivotX) * pw + (padLeft - padRight) * 0.5f + (cpx - 0.5f) * child.w;+ }+ localY = (1.0f - pivotY) * ph - padTop - cursor - (1.0f - cpy) * child.h;+ cursor += child.h;+ if (i < children.size() - 1) cursor += group.spacing;+ }++ auto* transform = registry.tryGet<Transform>(child.entity);+ if (transform) {+ setLayoutPosition(*transform, registry.tryGet<UIRect>(child.entity), localX, localY);+ }++ tree.nodes_[child.tree_index].flags &= ~LAYOUT_DIRTY;+ }+}++void resolveGridLayoutChildren(+ Registry& registry,+ UITree& tree,+ i32 containerIndex,+ const LayoutRect& cameraRect+) {+ (void)cameraRect;+ Entity containerEntity = tree.nodes_[containerIndex].entity;+ auto& grid = registry.get<GridLayout>(containerEntity);+ auto& parentRect = registry.get<UIRect>(containerEntity);++ f32 pw = parentRect.computed_size_.x;+ f32 ph = parentRect.computed_size_.y;+ f32 pivotX = parentRect.pivot.x;+ f32 pivotY = parentRect.pivot.y;++ i32 cols = grid.crossAxisCount;+ if (cols < 1) cols = 1;+ f32 strideX = grid.itemSize.x + grid.spacing.x;+ f32 strideY = grid.itemSize.y + grid.spacing.y;+ bool isVertical = (grid.direction == 0);++ i32 childIdx = 0;+ for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {+ if (tree.nodes_[j].parent != containerEntity) continue;+ if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;++ Entity childEntity = tree.nodes_[j].entity;+ auto* childRect = registry.tryGet<UIRect>(childEntity);+ auto* transform = registry.tryGet<Transform>(childEntity);+ if (!childRect || !transform) continue;++ i32 col = isVertical ? childIdx % cols : childIdx / cols;+ i32 row = isVertical ? childIdx / cols : childIdx % cols;++ childRect->size = grid.itemSize;+ childRect->computed_size_ = grid.itemSize;++ f32 localX = -pivotX * pw + col * strideX + childRect->pivot.x * grid.itemSize.x;+ f32 localY = (1.0f - pivotY) * ph - row * strideY - (1.0f - childRect->pivot.y) * grid.itemSize.y;++ setLayoutPosition(*transform, childRect, localX, localY);++ tree.nodes_[j].flags &= ~LAYOUT_DIRTY;+ childIdx++;+ }+}++void resolveFanLayoutChildren(+ Registry& registry,+ UITree& tree,+ i32 containerIndex,+ const LayoutRect& cameraRect+) {+ (void)cameraRect;+ Entity containerEntity = tree.nodes_[containerIndex].entity;+ auto& fan = registry.get<FanLayout>(containerEntity);++ struct ChildInfo {+ i32 tree_index;+ Entity entity;+ };++ std::vector<ChildInfo> children;+ for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {+ if (tree.nodes_[j].parent != containerEntity) continue;+ if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;++ Entity childEntity = tree.nodes_[j].entity;+ if (registry.has<Transform>(childEntity)) {+ children.push_back({j, childEntity});+ }+ }++ i32 n = static_cast<i32>(children.size());+ if (n == 0) return;++ f32 spreadAngle = std::min(fan.maxSpreadAngle, (n - 1) * fan.maxCardAngle);+ f32 dirSign = (fan.direction == 1) ? -1.0f : 1.0f;+ constexpr f32 DEG2RAD = 3.14159265358979f / 180.0f;+ bool useFixedSpacing = (fan.cardSpacing > 0.0f && n > 1);++ for (i32 i = 0; i < n; i++) {+ f32 t = (n == 1) ? 0.0f : (static_cast<f32>(i) / (n - 1) - 0.5f);+ f32 angle = spreadAngle * t * DEG2RAD;++ f32 x, y;+ if (useFixedSpacing) {+ x = (static_cast<f32>(i) - (n - 1) * 0.5f) * fan.cardSpacing;+ y = fan.radius * (1.0f - std::cos(angle)) * dirSign;+ } else {+ x = fan.radius * std::sin(angle);+ y = fan.radius * (1.0f - std::cos(angle)) * dirSign;+ }+ f32 rot = angle * fan.tiltFactor * dirSign;++ Entity childEntity = children[i].entity;+ auto& transform = registry.get<Transform>(childEntity);+ auto* childRect = registry.tryGet<UIRect>(childEntity);++ setLayoutPosition(transform, childRect, x, -y);+ setLayoutRotation(transform, childRect, rot);++ if (childRect) {+ childRect->computed_size_ = childRect->size;+ }++ tree.nodes_[children[i].tree_index].flags &= ~LAYOUT_DIRTY;+ }+}++void unifiedLayoutPass(Registry& registry, UITree& tree, const LayoutRect& cameraRect) {+ for (i32 i = 0; i < static_cast<i32>(tree.nodes_.size()); ) {+ auto& node = tree.nodes_[i];++ if (!(node.flags & (LAYOUT_DIRTY | HAS_DIRTY_CHILD))) {+ i += node.subtree_size;+ continue;+ }++ if (node.flags & LAYOUT_DIRTY) {+ bool parentManaged = node.parent != INVALID_ENTITY && (+ registry.has<FlexContainer>(node.parent) ||+ registry.has<LayoutGroup>(node.parent) ||+ registry.has<GridLayout>(node.parent) ||+ registry.has<FanLayout>(node.parent)+ );++ if (!parentManaged) {+ layoutNodeAnchor(registry, node, cameraRect);+ }++ if (registry.has<FlexContainer>(node.entity)) {+ resolveFlexChildren(registry, tree, i, cameraRect);+ } else if (registry.has<LayoutGroup>(node.entity)) {+ resolveLayoutGroupChildren(registry, tree, i, cameraRect);+ } else if (registry.has<GridLayout>(node.entity)) {+ resolveGridLayoutChildren(registry, tree, i, cameraRect);+ } else if (registry.has<FanLayout>(node.entity)) {+ resolveFanLayoutChildren(registry, tree, i, cameraRect);+ }+ }++ node.flags &= ~(LAYOUT_DIRTY | HAS_DIRTY_CHILD);+ i++;+ }+}++} // anonymous namespace++static UITree s_ui_tree;++void uiLayoutUpdate(+ Registry& registry,+ f32 camLeft, f32 camBottom, f32 camRight, f32 camTop+) {+ s_ui_tree.rebuild(registry);+ LayoutRect cameraRect{ camLeft, camBottom, camRight, camTop };+ unifiedLayoutPass(registry, s_ui_tree, cameraRect);+}++UITree& getUITree() {+ return s_ui_tree;+}++void uiTreeMarkStructureDirty() {+ s_ui_tree.structure_dirty_ = true;+}++void uiTreeMarkDirty(Entity entity) {+ s_ui_tree.markDirty(entity);+}++} // namespace esengine::ecsdiff --git a/src/esengine/ecs/UILayoutSystem.hpp b/src/esengine/ecs/UILayoutSystem.hppindex 877aa99d3..d2d338ff6 100644--- a/src/esengine/ecs/UILayoutSystem.hpp+++ b/src/esengine/ecs/UILayoutSystem.hpp@@ -2,20 +2,9 @@#include "Registry.hpp"#include "UITree.hpp"-#include "components/Transform.hpp"#include "components/UIRect.hpp"-#include "components/Sprite.hpp"-#include "components/Canvas.hpp"-#include "components/FlexContainer.hpp"-#include "components/FlexItem.hpp"-#include "components/LayoutGroup.hpp"-#include "components/GridLayout.hpp"-#include "components/FanLayout.hpp"-#include <yoga/Yoga.h>-#include <algorithm>-#include <cmath>-#include <vector>+#include <glm/glm.hpp>namespace esengine::ecs {@@ -32,583 +21,20 @@ struct LayoutResult {LayoutRect rect;};-inline LayoutResult computeAnchorLayout(+LayoutResult computeAnchorLayout(const glm::vec2& anchorMin, const glm::vec2& anchorMax,const glm::vec2& offsetMin, const glm::vec2& offsetMax,const glm::vec2& size, const LayoutRect& parentRect,const glm::vec2& pivot-) {- f32 parentW = parentRect.right - parentRect.left;- f32 parentH = parentRect.top - parentRect.bottom;+);- f32 aLeft = parentRect.left + anchorMin.x * parentW;- f32 aRight = parentRect.left + anchorMax.x * parentW;- f32 aBottom = parentRect.bottom + anchorMin.y * parentH;- f32 aTop = parentRect.bottom + anchorMax.y * parentH;-- f32 myLeft, myBottom, myRight, myTop;-- if (anchorMin.x == anchorMax.x) {- myLeft = aLeft + offsetMin.x - size.x * pivot.x;- myRight = myLeft + size.x;- } else {- myLeft = aLeft + offsetMin.x;- myRight = aRight + offsetMax.x;- }-- if (anchorMin.y == anchorMax.y) {- myBottom = aBottom + offsetMin.y - size.y * pivot.y;- myTop = myBottom + size.y;- } else {- myBottom = aBottom + offsetMin.y;- myTop = aTop + offsetMax.y;- }-- f32 width = std::max(0.0f, myRight - myLeft);- f32 height = std::max(0.0f, myTop - myBottom);- f32 originX = myLeft + pivot.x * width;- f32 originY = myBottom + pivot.y * height;-- return {- originX,- originY,- { myLeft, myBottom, myLeft + width, myBottom + height },- };-}--inline LayoutRect getParentLayoutRect(- Registry& registry,- const UITree::Node& node,- const LayoutRect& cameraRect-) {- if (node.parent == INVALID_ENTITY) {- return cameraRect;- }- auto& parentRect = registry.get<UIRect>(node.parent);- f32 pw = parentRect.computed_size_.x;- f32 ph = parentRect.computed_size_.y;- return { -pw * parentRect.pivot.x, -ph * parentRect.pivot.y,- pw * (1.0f - parentRect.pivot.x), ph * (1.0f - parentRect.pivot.y) };-}--inline void setLayoutPosition(Transform& t, UIRect* rect, f32 x, f32 y) {- if (rect && rect->anim_override_) {- if (!(rect->anim_override_ & UIRect::ANIM_POS_X)) t.position.x = x;- if (!(rect->anim_override_ & UIRect::ANIM_POS_Y)) t.position.y = y;- } else {- t.position.x = x;- t.position.y = y;- }-}--inline void setLayoutRotation(Transform& t, UIRect* rect, f32 rot) {- if (rect && (rect->anim_override_ & UIRect::ANIM_ROT_Z)) return;- f32 halfRad = rot / 2.0f;- t.rotation = glm::quat(std::cos(halfRad), 0.0f, 0.0f, std::sin(halfRad));-}--inline void writePosition(- Registry& registry,- const UITree::Node& node,- f32 originX, f32 originY,- const LayoutRect& cameraRect-) {- auto* transform = registry.tryGet<Transform>(node.entity);- if (!transform) return;- setLayoutPosition(*transform, registry.tryGet<UIRect>(node.entity), originX, originY);-}--inline void layoutNodeAnchor(- Registry& registry,- UITree::Node& node,- const LayoutRect& cameraRect-) {- auto& rect = registry.get<UIRect>(node.entity);- LayoutRect parentRect = getParentLayoutRect(registry, node, cameraRect);-- auto result = computeAnchorLayout(- rect.anchorMin, rect.anchorMax,- rect.offsetMin, rect.offsetMax,- rect.size, parentRect, rect.pivot- );-- f32 width = result.rect.right - result.rect.left;- f32 height = result.rect.top - result.rect.bottom;- rect.computed_size_.x = width;- rect.computed_size_.y = height;-- auto* sprite = registry.tryGet<Sprite>(node.entity);- if (sprite) {- if (sprite->size.x != width || sprite->size.y != height) {- sprite->size.x = width;- sprite->size.y = height;- }- }-- writePosition(registry, node, result.origin_x, result.origin_y, cameraRect);-}--inline YGFlexDirection toYGFlexDirection(FlexDirection dir) {- switch (dir) {- case FlexDirection::Row: return YGFlexDirectionRow;- case FlexDirection::Column: return YGFlexDirectionColumn;- case FlexDirection::RowReverse: return YGFlexDirectionRowReverse;- case FlexDirection::ColumnReverse: return YGFlexDirectionColumnReverse;- }- return YGFlexDirectionRow;-}--inline YGWrap toYGWrap(FlexWrap wrap) {- switch (wrap) {- case FlexWrap::NoWrap: return YGWrapNoWrap;- case FlexWrap::Wrap: return YGWrapWrap;- }- return YGWrapNoWrap;-}--inline YGJustify toYGJustify(JustifyContent jc) {- switch (jc) {- case JustifyContent::Start: return YGJustifyFlexStart;- case JustifyContent::Center: return YGJustifyCenter;- case JustifyContent::End: return YGJustifyFlexEnd;- case JustifyContent::SpaceBetween: return YGJustifySpaceBetween;- case JustifyContent::SpaceAround: return YGJustifySpaceAround;- case JustifyContent::SpaceEvenly: return YGJustifySpaceEvenly;- }- return YGJustifyFlexStart;-}--inline YGAlign toYGAlign(AlignItems ai) {- switch (ai) {- case AlignItems::Start: return YGAlignFlexStart;- case AlignItems::Center: return YGAlignCenter;- case AlignItems::End: return YGAlignFlexEnd;- case AlignItems::Stretch: return YGAlignStretch;- }- return YGAlignStretch;-}--inline YGAlign toYGAlignContent(AlignContent ac) {- switch (ac) {- case AlignContent::Start: return YGAlignFlexStart;- case AlignContent::Center: return YGAlignCenter;- case AlignContent::End: return YGAlignFlexEnd;- case AlignContent::Stretch: return YGAlignStretch;- case AlignContent::SpaceBetween: return YGAlignSpaceBetween;- case AlignContent::SpaceAround: return YGAlignSpaceAround;- }- return YGAlignFlexStart;-}--inline YGAlign toYGAlignSelf(AlignSelf as) {- switch (as) {- case AlignSelf::Auto: return YGAlignAuto;- case AlignSelf::Start: return YGAlignFlexStart;- case AlignSelf::Center: return YGAlignCenter;- case AlignSelf::End: return YGAlignFlexEnd;- case AlignSelf::Stretch: return YGAlignStretch;- }- return YGAlignAuto;-}--struct FlexChildInfo {- i32 tree_index;- Entity entity;-};--inline void resolveFlexChildren(- Registry& registry,- UITree& tree,- i32 containerIndex,- const LayoutRect& cameraRect-) {- Entity containerEntity = tree.nodes_[containerIndex].entity;- auto& flex = registry.get<FlexContainer>(containerEntity);- auto& parentRect = registry.get<UIRect>(containerEntity);-- f32 parentW = parentRect.computed_size_.x;- f32 parentH = parentRect.computed_size_.y;- f32 pivotX = parentRect.pivot.x;- f32 pivotY = parentRect.pivot.y;-- std::vector<FlexChildInfo> children;- for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {- if (tree.nodes_[j].parent != containerEntity) continue;- if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;- Entity childEntity = tree.nodes_[j].entity;- if (!registry.has<UIRect>(childEntity)) continue;- children.push_back({j, childEntity});- }-- if (children.empty()) return;-- YGNodeRef root = YGNodeNew();- YGNodeStyleSetFlexDirection(root, toYGFlexDirection(flex.direction));- YGNodeStyleSetFlexWrap(root, toYGWrap(flex.wrap));- YGNodeStyleSetJustifyContent(root, toYGJustify(flex.justifyContent));- YGNodeStyleSetAlignItems(root, toYGAlign(flex.alignItems));- YGNodeStyleSetWidth(root, parentW);- YGNodeStyleSetHeight(root, parentH);- YGNodeStyleSetPadding(root, YGEdgeLeft, flex.padding.left);- YGNodeStyleSetPadding(root, YGEdgeTop, flex.padding.top);- YGNodeStyleSetPadding(root, YGEdgeRight, flex.padding.right);- YGNodeStyleSetPadding(root, YGEdgeBottom, flex.padding.bottom);- YGNodeStyleSetAlignContent(root, toYGAlignContent(flex.alignContent));- YGNodeStyleSetGap(root, YGGutterColumn, flex.gap.x);- YGNodeStyleSetGap(root, YGGutterRow, flex.gap.y);-- std::vector<YGNodeRef> childNodes;- childNodes.reserve(children.size());-- for (usize i = 0; i < children.size(); i++) {- auto& childRect = registry.get<UIRect>(children[i].entity);- f32 cw = childRect.computed_size_.x > 0.0f ? childRect.computed_size_.x : childRect.size.x;- f32 ch = childRect.computed_size_.y > 0.0f ? childRect.computed_size_.y : childRect.size.y;-- YGNodeRef child = YGNodeNew();-- auto* fi = registry.tryGet<FlexItem>(children[i].entity);- if (fi) {- YGNodeStyleSetFlexGrow(child, fi->flexGrow);- YGNodeStyleSetFlexShrink(child, fi->flexShrink);- if (fi->flexBasis >= 0.0f) {- YGNodeStyleSetFlexBasis(child, fi->flexBasis);- } else {- YGNodeStyleSetFlexBasisAuto(child);- }- YGNodeStyleSetAlignSelf(child, toYGAlignSelf(fi->alignSelf));- YGNodeStyleSetMargin(child, YGEdgeLeft, fi->margin.left);- YGNodeStyleSetMargin(child, YGEdgeTop, fi->margin.top);- YGNodeStyleSetMargin(child, YGEdgeRight, fi->margin.right);- YGNodeStyleSetMargin(child, YGEdgeBottom, fi->margin.bottom);- if (fi->minWidth >= 0.0f) YGNodeStyleSetMinWidth(child, fi->minWidth);- if (fi->minHeight >= 0.0f) YGNodeStyleSetMinHeight(child, fi->minHeight);- if (fi->maxWidth >= 0.0f) YGNodeStyleSetMaxWidth(child, fi->maxWidth);- if (fi->maxHeight >= 0.0f) YGNodeStyleSetMaxHeight(child, fi->maxHeight);- if (fi->widthPercent >= 0.0f) {- YGNodeStyleSetWidthPercent(child, fi->widthPercent);- } else {- YGNodeStyleSetWidth(child, cw);- }- if (fi->heightPercent >= 0.0f) {- YGNodeStyleSetHeightPercent(child, fi->heightPercent);- } else {- YGNodeStyleSetHeight(child, ch);- }- } else {- YGNodeStyleSetFlexGrow(child, 0.0f);- YGNodeStyleSetFlexShrink(child, 1.0f);- YGNodeStyleSetFlexBasisAuto(child);- YGNodeStyleSetWidth(child, cw);- YGNodeStyleSetHeight(child, ch);- }-- YGNodeInsertChild(root, child, i);- childNodes.push_back(child);- }-- YGNodeCalculateLayout(root, parentW, parentH, YGDirectionLTR);-- for (usize i = 0; i < children.size(); i++) {- auto& info = children[i];- auto& childRect = registry.get<UIRect>(info.entity);-- f32 yogaLeft = YGNodeLayoutGetLeft(childNodes[i]);- f32 yogaTop = YGNodeLayoutGetTop(childNodes[i]);- f32 finalW = YGNodeLayoutGetWidth(childNodes[i]);- f32 finalH = YGNodeLayoutGetHeight(childNodes[i]);-- f32 cpx = childRect.pivot.x;- f32 cpy = childRect.pivot.y;- f32 localX = -pivotX * parentW + yogaLeft + cpx * finalW;- f32 localY = (1.0f - pivotY) * parentH - yogaTop - (1.0f - cpy) * finalH;-- auto* transform = registry.tryGet<Transform>(info.entity);- if (transform) {- setLayoutPosition(*transform, &childRect, localX, localY);- }-- childRect.computed_size_.x = finalW;- childRect.computed_size_.y = finalH;-- auto* sprite = registry.tryGet<Sprite>(info.entity);- if (sprite) {- if (sprite->size.x != finalW || sprite->size.y != finalH) {- sprite->size.x = finalW;- sprite->size.y = finalH;- }- }-- if (registry.has<FlexContainer>(info.entity) || registry.has<LayoutGroup>(info.entity)) {- tree.nodes_[info.tree_index].flags |= LAYOUT_DIRTY;- } else {- tree.nodes_[info.tree_index].flags &= ~LAYOUT_DIRTY;- }- }-- YGNodeFreeRecursive(root);-}--inline void resolveLayoutGroupChildren(- Registry& registry,- UITree& tree,- i32 containerIndex,- const LayoutRect& cameraRect-) {- Entity containerEntity = tree.nodes_[containerIndex].entity;- auto& group = registry.get<LayoutGroup>(containerEntity);- auto& parentRect = registry.get<UIRect>(containerEntity);-- f32 pw = parentRect.computed_size_.x;- f32 ph = parentRect.computed_size_.y;- f32 pivotX = parentRect.pivot.x;- f32 pivotY = parentRect.pivot.y;-- f32 padLeft = group.padding.left;- f32 padTop = group.padding.top;- f32 padRight = group.padding.right;- f32 padBottom = group.padding.bottom;-- bool isHorizontal = (group.direction == LayoutDirection::Horizontal);-- struct ChildInfo {- i32 tree_index;- Entity entity;- f32 w;- f32 h;- };-- std::vector<ChildInfo> children;- for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {- if (tree.nodes_[j].parent != containerEntity) continue;- if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;-- Entity childEntity = tree.nodes_[j].entity;- auto* childRect = registry.tryGet<UIRect>(childEntity);- if (!childRect || !registry.has<Transform>(childEntity)) continue;-- f32 cw = childRect->computed_size_.x > 0.0f ? childRect->computed_size_.x : childRect->size.x;- f32 ch = childRect->computed_size_.y > 0.0f ? childRect->computed_size_.y : childRect->size.y;- children.push_back({j, childEntity, cw, ch});- }-- if (children.empty()) return;-- if (group.reverseOrder) {- std::reverse(children.begin(), children.end());- }-- f32 cursor = 0.0f;- for (usize i = 0; i < children.size(); i++) {- auto& child = children[i];- auto& childRect = registry.get<UIRect>(child.entity);- f32 cpx = childRect.pivot.x;- f32 cpy = childRect.pivot.y;-- f32 localX, localY;-- if (isHorizontal) {- localX = -pivotX * pw + padLeft + cursor + cpx * child.w;- if (group.childAlignment == ChildAlignment::Start) {- localY = (1.0f - pivotY) * ph - padTop - (1.0f - cpy) * child.h;- } else if (group.childAlignment == ChildAlignment::End) {- localY = -pivotY * ph + padBottom + cpy * child.h;- } else {- localY = (0.5f - pivotY) * ph + (padBottom - padTop) * 0.5f + (cpy - 0.5f) * child.h;- }- cursor += child.w;- if (i < children.size() - 1) cursor += group.spacing;- } else {- if (group.childAlignment == ChildAlignment::Start) {- localX = -pivotX * pw + padLeft + cpx * child.w;- } else if (group.childAlignment == ChildAlignment::End) {- localX = (1.0f - pivotX) * pw - padRight - (1.0f - cpx) * child.w;- } else {- localX = (0.5f - pivotX) * pw + (padLeft - padRight) * 0.5f + (cpx - 0.5f) * child.w;- }- localY = (1.0f - pivotY) * ph - padTop - cursor - (1.0f - cpy) * child.h;- cursor += child.h;- if (i < children.size() - 1) cursor += group.spacing;- }-- auto* transform = registry.tryGet<Transform>(child.entity);- if (transform) {- setLayoutPosition(*transform, registry.tryGet<UIRect>(child.entity), localX, localY);- }-- tree.nodes_[child.tree_index].flags &= ~LAYOUT_DIRTY;- }-}--inline void resolveGridLayoutChildren(- Registry& registry,- UITree& tree,- i32 containerIndex,- const LayoutRect& cameraRect-) {- (void)cameraRect;- Entity containerEntity = tree.nodes_[containerIndex].entity;- auto& grid = registry.get<GridLayout>(containerEntity);- auto& parentRect = registry.get<UIRect>(containerEntity);-- f32 pw = parentRect.computed_size_.x;- f32 ph = parentRect.computed_size_.y;- f32 pivotX = parentRect.pivot.x;- f32 pivotY = parentRect.pivot.y;-- i32 cols = grid.crossAxisCount;- if (cols < 1) cols = 1;- f32 strideX = grid.itemSize.x + grid.spacing.x;- f32 strideY = grid.itemSize.y + grid.spacing.y;- bool isVertical = (grid.direction == 0);-- i32 childIdx = 0;- for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {- if (tree.nodes_[j].parent != containerEntity) continue;- if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;-- Entity childEntity = tree.nodes_[j].entity;- auto* childRect = registry.tryGet<UIRect>(childEntity);- auto* transform = registry.tryGet<Transform>(childEntity);- if (!childRect || !transform) continue;-- i32 col = isVertical ? childIdx % cols : childIdx / cols;- i32 row = isVertical ? childIdx / cols : childIdx % cols;-- childRect->size = grid.itemSize;- childRect->computed_size_ = grid.itemSize;-- f32 localX = -pivotX * pw + col * strideX + childRect->pivot.x * grid.itemSize.x;- f32 localY = (1.0f - pivotY) * ph - row * strideY - (1.0f - childRect->pivot.y) * grid.itemSize.y;-- setLayoutPosition(*transform, childRect, localX, localY);-- tree.nodes_[j].flags &= ~LAYOUT_DIRTY;- childIdx++;- }-}--inline void resolveFanLayoutChildren(- Registry& registry,- UITree& tree,- i32 containerIndex,- const LayoutRect& cameraRect-) {- (void)cameraRect;- Entity containerEntity = tree.nodes_[containerIndex].entity;- auto& fan = registry.get<FanLayout>(containerEntity);-- struct ChildInfo {- i32 tree_index;- Entity entity;- };-- std::vector<ChildInfo> children;- for (i32 j = containerIndex + 1; j < static_cast<i32>(tree.nodes_.size()); j++) {- if (tree.nodes_[j].parent != containerEntity) continue;- if (tree.nodes_[j].depth != tree.nodes_[containerIndex].depth + 1) continue;-- Entity childEntity = tree.nodes_[j].entity;- if (registry.has<Transform>(childEntity)) {- children.push_back({j, childEntity});- }- }-- i32 n = static_cast<i32>(children.size());- if (n == 0) return;-- f32 spreadAngle = std::min(fan.maxSpreadAngle, (n - 1) * fan.maxCardAngle);- f32 dirSign = (fan.direction == 1) ? -1.0f : 1.0f;- constexpr f32 DEG2RAD = 3.14159265358979f / 180.0f;- bool useFixedSpacing = (fan.cardSpacing > 0.0f && n > 1);-- for (i32 i = 0; i < n; i++) {- f32 t = (n == 1) ? 0.0f : (static_cast<f32>(i) / (n - 1) - 0.5f);- f32 angle = spreadAngle * t * DEG2RAD;-- f32 x, y;- if (useFixedSpacing) {- x = (static_cast<f32>(i) - (n - 1) * 0.5f) * fan.cardSpacing;- y = fan.radius * (1.0f - std::cos(angle)) * dirSign;- } else {- x = fan.radius * std::sin(angle);- y = fan.radius * (1.0f - std::cos(angle)) * dirSign;- }- f32 rot = angle * fan.tiltFactor * dirSign;-- Entity childEntity = children[i].entity;- auto& transform = registry.get<Transform>(childEntity);- auto* childRect = registry.tryGet<UIRect>(childEntity);-- setLayoutPosition(transform, childRect, x, -y);- setLayoutRotation(transform, childRect, rot);-- if (childRect) {- childRect->computed_size_ = childRect->size;- }-- tree.nodes_[children[i].tree_index].flags &= ~LAYOUT_DIRTY;- }-}--inline void unifiedLayoutPass(Registry& registry, UITree& tree, const LayoutRect& cameraRect) {- for (i32 i = 0; i < static_cast<i32>(tree.nodes_.size()); ) {- auto& node = tree.nodes_[i];-- if (!(node.flags & (LAYOUT_DIRTY | HAS_DIRTY_CHILD))) {- i += node.subtree_size;- continue;- }-- if (node.flags & LAYOUT_DIRTY) {- bool parentManaged = node.parent != INVALID_ENTITY && (- registry.has<FlexContainer>(node.parent) ||- registry.has<LayoutGroup>(node.parent) ||- registry.has<GridLayout>(node.parent) ||- registry.has<FanLayout>(node.parent)- );-- if (!parentManaged) {- layoutNodeAnchor(registry, node, cameraRect);- }-- if (registry.has<FlexContainer>(node.entity)) {- resolveFlexChildren(registry, tree, i, cameraRect);- } else if (registry.has<LayoutGroup>(node.entity)) {- resolveLayoutGroupChildren(registry, tree, i, cameraRect);- } else if (registry.has<GridLayout>(node.entity)) {- resolveGridLayoutChildren(registry, tree, i, cameraRect);- } else if (registry.has<FanLayout>(node.entity)) {- resolveFanLayoutChildren(registry, tree, i, cameraRect);- }- }-- node.flags &= ~(LAYOUT_DIRTY | HAS_DIRTY_CHILD);- i++;- }-}--static UITree s_ui_tree;--inline void uiLayoutUpdate(+void uiLayoutUpdate(Registry& registry,f32 camLeft, f32 camBottom, f32 camRight, f32 camTop-) {- s_ui_tree.rebuild(registry);- LayoutRect cameraRect{ camLeft, camBottom, camRight, camTop };- unifiedLayoutPass(registry, s_ui_tree, cameraRect);-}--inline UITree& getUITree() {- return s_ui_tree;-}--inline void uiTreeMarkStructureDirty() {- s_ui_tree.structure_dirty_ = true;-}+);-inline void uiTreeMarkDirty(Entity entity) {- s_ui_tree.markDirty(entity);-}+UITree& getUITree();+void uiTreeMarkStructureDirty();+void uiTreeMarkDirty(Entity entity);} // namespace esengine::ecs