Skip to content

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.

feat: remove embedded WASM binaries, always use dynamic toolchain compilation

esenginea5cf7bd83584
diff --git a/desktop/src-tauri/src/compiler.rs b/desktop/src-tauri/src/compiler.rs
index af3e50c19..0f87a9640 100644
--- a/desktop/src-tauri/src/compiler.rs
+++ b/desktop/src-tauri/src/compiler.rs
@@ -54,6 +54,12 @@ pub struct CompileOptions {
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 {
@@ -62,7 +68,10 @@ impl Default for CompileOptions {
features: FeatureFlags::default(),
target: "web".to_string(),
debug: false,
- optimization: "-O2".to_string(),
+ optimization: "-Oz".to_string(),
+ enable_physics: false,
+ spine_versions: Vec::new(),
+ clean_build: false,
}
}
}
@@ -74,6 +83,13 @@ struct CompileProgress {
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,
@@ -82,6 +98,9 @@ pub struct CompileResult {
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";
@@ -479,18 +498,26 @@ pub async fn compile_wasm(
.map_err(|e| e.to_string())?
.join("build-cache");
let build_dir = build_base.join(&cache_key);
+
+ if options.clean_build && build_dir.exists() {
+ emit_progress(&app, "configure", "Cleaning build cache...", 0.05);
+ std::fs::remove_dir_all(&build_dir).map_err(|e| e.to_string())?;
+ }
+
std::fs::create_dir_all(&build_dir).map_err(|e| e.to_string())?;
// Check cache
- let wasm_output = if options.target == "playable" {
- build_dir.join("sdk/esengine.single.js")
- } else {
- build_dir.join("sdk/esengine-core.wasm")
- };
+ if !options.clean_build {
+ let wasm_output = if options.target == "playable" {
+ build_dir.join("sdk/esengine.single.js")
+ } else {
+ build_dir.join("sdk/esengine-core.wasm")
+ };
- if wasm_output.exists() {
- emit_progress(&app, "complete", "Using cached build", 1.0);
- return Ok(make_result(true, &build_dir, &cache_key, &options.target));
+ if wasm_output.exists() {
+ emit_progress(&app, "complete", "Using cached build", 1.0);
+ return Ok(make_result(true, &build_dir, &cache_key, &options));
+ }
}
let env_vars = build_env_vars(&emsdk_dir);
@@ -537,6 +564,59 @@ pub async fn compile_wasm(
)
.await?;
+ // Build spine modules
+ if options.features.spine && !options.spine_versions.is_empty() {
+ emit_progress(&app, "compile", "Compiling Spine modules...", 0.5);
+ for version in &options.spine_versions {
+ let cmake_target = match version.as_str() {
+ "3.8" => "spine_module_38",
+ "4.1" => "spine_module_41",
+ "4.2" => "spine_module",
+ _ => continue,
+ };
+ run_command_streamed(
+ &app,
+ "cmake",
+ &[
+ "--build".to_string(),
+ ".".to_string(),
+ "-j".to_string(),
+ num_cpus().to_string(),
+ "--target".to_string(),
+ cmake_target.to_string(),
+ ],
+ &build_dir,
+ &env_vars,
+ )
+ .await?;
+ }
+ }
+
+ // 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() {
+ emit_progress(&app, "compile", "Compiling Physics module...", 0.65);
+ run_command_streamed(
+ &app,
+ "cmake",
+ &[
+ "--build".to_string(),
+ ".".to_string(),
+ "-j".to_string(),
+ num_cpus().to_string(),
+ "--target".to_string(),
+ "physics_module".to_string(),
+ ],
+ &build_dir,
+ &env_vars,
+ )
+ .await?;
+ } else {
+ emit_progress(&app, "compile", "Physics module skipped (box2d not bundled)", 0.65);
+ }
+ }
+
// Optimize
if !options.debug {
emit_progress(&app, "optimize", "Optimizing WASM...", 0.8);
@@ -570,7 +650,7 @@ pub async fn compile_wasm(
emit_progress(&app, "complete", "Build complete!", 1.0);
- Ok(make_result(true, &build_dir, &cache_key, &options.target))
+ Ok(make_result(true, &build_dir, &cache_key, &options))
}
#[tauri::command]
@@ -590,8 +670,8 @@ pub fn clear_build_cache(app: AppHandle) -> Result<(), String> {
// Helpers
// =============================================================================
-fn make_result(success: bool, build_dir: &Path, cache_key: &str, target: &str) -> CompileResult {
- let (js_name, wasm_name) = if target == "playable" {
+fn make_result(success: bool, build_dir: &Path, cache_key: &str, options: &CompileOptions) -> CompileResult {
+ let (js_name, wasm_name) = if options.target == "playable" {
("sdk/esengine.single.js", None)
} else {
("sdk/esengine-core.js", Some("sdk/esengine-core.wasm"))
@@ -603,6 +683,33 @@ fn make_result(success: bool, build_dir: &Path, cache_key: &str, target: &str) -
let size_path = wasm_path.as_ref().unwrap_or(&js_path);
let wasm_size = std::fs::metadata(size_path).map(|m| m.len()).ok();
+ let mut spine_modules = Vec::new();
+ if options.features.spine {
+ for version in &options.spine_versions {
+ let tag = version.replace('.', "");
+ let sjs = build_dir.join(format!("sdk/spine{tag}.js"));
+ let swasm = build_dir.join(format!("sdk/spine{tag}.wasm"));
+ if sjs.exists() && swasm.exists() {
+ spine_modules.push(SpineModuleResult {
+ version: version.clone(),
+ js_path: sjs.to_string_lossy().to_string(),
+ wasm_path: swasm.to_string_lossy().to_string(),
+ });
+ }
+ }
+ }
+
+ let (physics_js_path, physics_wasm_path) = if options.enable_physics {
+ let pjs = build_dir.join("sdk/physics.js");
+ let pwasm = build_dir.join("sdk/physics.wasm");
+ (
+ pjs.exists().then(|| pjs.to_string_lossy().to_string()),
+ pwasm.exists().then(|| pwasm.to_string_lossy().to_string()),
+ )
+ } else {
+ (None, None)
+ };
+
CompileResult {
success,
js_path: js_path.exists().then(|| js_path.to_string_lossy().to_string()),
@@ -612,6 +719,9 @@ fn make_result(success: bool, build_dir: &Path, cache_key: &str, target: &str) -
wasm_size,
error: None,
cache_key: cache_key.to_string(),
+ spine_modules,
+ physics_js_path,
+ physics_wasm_path,
}
}
@@ -630,6 +740,8 @@ fn compute_cache_key(options: &CompileOptions) -> String {
options.target.hash(&mut hasher);
options.debug.hash(&mut hasher);
options.optimization.hash(&mut hasher);
+ options.enable_physics.hash(&mut hasher);
+ options.spine_versions.hash(&mut hasher);
format!("{:016x}", hasher.finish())
}
diff --git a/desktop/src-tauri/src/embedded_assets.rs b/desktop/src-tauri/src/embedded_assets.rs
index d65dcdc5c..960d7cafd 100644
--- a/desktop/src-tauri/src/embedded_assets.rs
+++ b/desktop/src-tauri/src/embedded_assets.rs
@@ -4,19 +4,9 @@
// WASM Modules
// =============================================================================
+// Editor runtime only — build assets are compiled dynamically via toolchain
pub const ENGINE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.js");
pub const ENGINE_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wasm");
-pub const ENGINE_SINGLE_JS: &[u8] = include_bytes!("../../public/wasm/esengine.single.js");
-pub const ENGINE_WXGAME_JS: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.js");
-pub const ENGINE_WXGAME_WASM: &[u8] = include_bytes!("../../public/wasm/esengine.wxgame.wasm");
-pub const SPINE38_JS: &[u8] = include_bytes!("../../public/wasm/spine38.js");
-pub const SPINE38_WASM: &[u8] = include_bytes!("../../public/wasm/spine38.wasm");
-pub const SPINE41_JS: &[u8] = include_bytes!("../../public/wasm/spine41.js");
-pub const SPINE41_WASM: &[u8] = include_bytes!("../../public/wasm/spine41.wasm");
-pub const SPINE42_JS: &[u8] = include_bytes!("../../public/wasm/spine42.js");
-pub const SPINE42_WASM: &[u8] = include_bytes!("../../public/wasm/spine42.wasm");
-pub const PHYSICS_JS: &[u8] = include_bytes!("../../public/wasm/physics.js");
-pub const PHYSICS_WASM: &[u8] = include_bytes!("../../public/wasm/physics.wasm");
// =============================================================================
// ESBuild
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 567ba6ace..84734a37c 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -128,11 +128,10 @@ fn open_folder(path: String) -> Result<(), String> {
#[tauri::command]
fn get_embedded_asset(name: String) -> Result<Vec<u8>, String> {
match name.as_str() {
+ // Editor runtime
"engine.js" => Ok(embedded_assets::ENGINE_JS.to_vec()),
"engine.wasm" => Ok(embedded_assets::ENGINE_WASM.to_vec()),
- "engine.single.js" => Ok(embedded_assets::ENGINE_SINGLE_JS.to_vec()),
- "engine.wxgame.js" => Ok(embedded_assets::ENGINE_WXGAME_JS.to_vec()),
- "engine.wxgame.wasm" => Ok(embedded_assets::ENGINE_WXGAME_WASM.to_vec()),
+ // SDK
"sdk.wechat.js" => Ok(embedded_assets::SDK_WECHAT_JS.to_vec()),
"sdk.esm.js" => Ok(embedded_assets::SDK_ESM_JS.to_vec()),
"sdk.esm.dts" => Ok(embedded_assets::SDK_ESM_DTS.to_vec()),
@@ -143,15 +142,13 @@ fn get_embedded_asset(name: String) -> Result<Vec<u8>, String> {
"sdk.physics.dts" => Ok(embedded_assets::SDK_PHYSICS_DTS.to_vec()),
"sdk.spine.dts" => Ok(embedded_assets::SDK_SPINE_DTS.to_vec()),
"editor.dts" => Ok(embedded_assets::EDITOR_DTS.to_vec()),
- "spine38.js" => Ok(embedded_assets::SPINE38_JS.to_vec()),
- "spine38.wasm" => Ok(embedded_assets::SPINE38_WASM.to_vec()),
- "spine41.js" => Ok(embedded_assets::SPINE41_JS.to_vec()),
- "spine41.wasm" => Ok(embedded_assets::SPINE41_WASM.to_vec()),
- "spine42.js" => Ok(embedded_assets::SPINE42_JS.to_vec()),
- "spine42.wasm" => Ok(embedded_assets::SPINE42_WASM.to_vec()),
- "physics.js" => Ok(embedded_assets::PHYSICS_JS.to_vec()),
- "physics.wasm" => Ok(embedded_assets::PHYSICS_WASM.to_vec()),
"esbuild.wasm" => Ok(embedded_assets::ESBUILD_WASM.to_vec()),
+ // Build assets removed — use toolchain compilation
+ "engine.single.js" | "engine.wxgame.js" | "engine.wxgame.wasm"
+ | "spine38.js" | "spine38.wasm" | "spine41.js" | "spine41.wasm"
+ | "spine42.js" | "spine42.wasm" | "physics.js" | "physics.wasm" => {
+ Err(format!("Asset '{}' is no longer embedded. Use toolchain compilation.", name))
+ }
_ => Err(format!("Unknown embedded asset: {}", name)),
}
}
diff --git a/desktop/src-tauri/src/preview_server.rs b/desktop/src-tauri/src/preview_server.rs
index 306ee3122..3008e05df 100644
--- a/desktop/src-tauri/src/preview_server.rs
+++ b/desktop/src-tauri/src/preview_server.rs
@@ -126,14 +126,6 @@ impl PreviewServer {
"sdk/shared/material.js.map" => serve_embedded(embedded_assets::SDK_SHARED_MATERIAL_JS_MAP, "application/json"),
"sdk/shared/SpineModuleLoader.js" => serve_embedded(embedded_assets::SDK_SHARED_SPINEMODULELOADER_JS, "application/javascript"),
"sdk/shared/SpineModuleLoader.js.map" => serve_embedded(embedded_assets::SDK_SHARED_SPINEMODULELOADER_JS_MAP, "application/json"),
- "wasm/spine38.js" => serve_embedded(embedded_assets::SPINE38_JS, "application/javascript"),
- "wasm/spine38.wasm" => serve_embedded(embedded_assets::SPINE38_WASM, "application/wasm"),
- "wasm/spine41.js" => serve_embedded(embedded_assets::SPINE41_JS, "application/javascript"),
- "wasm/spine41.wasm" => serve_embedded(embedded_assets::SPINE41_WASM, "application/wasm"),
- "wasm/spine42.js" => serve_embedded(embedded_assets::SPINE42_JS, "application/javascript"),
- "wasm/spine42.wasm" => serve_embedded(embedded_assets::SPINE42_WASM, "application/wasm"),
- "wasm/physics.js" => serve_embedded(embedded_assets::PHYSICS_JS, "application/javascript"),
- "wasm/physics.wasm" => serve_embedded(embedded_assets::PHYSICS_WASM, "application/wasm"),
_ => serve_project_file(&current_dir, path),
};
diff --git a/editor/src/asset/AssetGroup.ts b/editor/src/asset/AssetGroup.ts
index 6377713f6..44dfd9188 100644
--- a/editor/src/asset/AssetGroup.ts
+++ b/editor/src/asset/AssetGroup.ts
@@ -182,6 +182,17 @@ export class AssetGroupService {
return 'default';
}
+ getMatchedPattern(assetPath: string, groupName: string): string | null {
+ const group = this.config_.groups.find(g => g.name === groupName);
+ if (!group) return null;
+ for (const pattern of group.include) {
+ if (this.globMatch(assetPath, pattern)) {
+ return pattern;
+ }
+ }
+ return null;
+ }
+
private matchesIncludes(assetPath: string, patterns: string[]): boolean {
for (const pattern of patterns) {
if (this.globMatch(assetPath, pattern)) {
diff --git a/editor/src/builder/ArtifactBuilder.ts b/editor/src/builder/ArtifactBuilder.ts
index b34d54efc..5c34e2e72 100644
--- a/editor/src/builder/ArtifactBuilder.ts
+++ b/editor/src/builder/ArtifactBuilder.ts
@@ -563,6 +563,16 @@ export function createBuildVirtualFsPlugin(
namespace: 'esengine-sdk',
}));
+ build.onResolve({ filter: /^\./ }, (args) => {
+ if (args.namespace !== 'esengine-sdk') return undefined;
+ const baseDir = args.importer.includes('/')
+ ? args.importer.substring(0, args.importer.lastIndexOf('/'))
+ : '';
+ const resolved = baseDir ? `${baseDir}/${args.path}` : args.path;
+ const normalized = resolved.replace(/^\.\//, '').replace(/\/\.\//g, '/').replace(/[^/]+\/\.\.\//g, '');
+ return { path: normalized, namespace: 'esengine-sdk' };
+ });
+
build.onLoad({ filter: /.*/, namespace: 'esengine-sdk' }, async (args) => {
return loadSdkModule(args.path);
});
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index 57b86deef..29df148d4 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -3,7 +3,7 @@
* @brief Build service for compiling and packaging projects
*/
-import type { BuildConfig, EngineModules } from '../types/BuildTypes';
+import type { BuildConfig } from '../types/BuildTypes';
import { createDefaultEngineModules } from '../types/BuildTypes';
import type { SpineVersion } from '../types/ProjectTypes';
import type { PlatformEmitter } from './PlatformEmitter';
@@ -54,6 +54,9 @@ export interface RuntimeBuildConfig {
export interface CustomWasmPaths {
jsPath?: string;
wasmPath?: string;
+ spineModules?: Array<{ version: string; jsPath: string; wasmPath: string }>;
+ physicsJsPath?: string;
+ physicsWasmPath?: string;
}
export interface BuildContext {
@@ -73,6 +76,7 @@ export interface BuildContext {
export interface BuildOptions {
useCache?: boolean;
+ cleanBuild?: boolean;
progress?: BuildProgressReporter;
}
@@ -160,28 +164,29 @@ export class BuildService {
};
}
- if (config.engineModules && !isAllModulesEnabled(config.engineModules)) {
- progress.setPhase('compiling');
- progress.setCurrentTask('Compiling custom WASM...', 0);
- progress.log('info', 'Custom engine modules detected, compiling WASM...');
-
- const compileResult = await compileCustomWasm(config);
- if (!compileResult.success) {
- progress.fail(compileResult.error || 'WASM compilation failed');
- return {
- success: false,
- error: compileResult.error || 'WASM compilation failed',
- duration: Date.now() - startTime,
- };
- }
+ progress.setPhase('compiling');
+ progress.setCurrentTask('Compiling WASM...', 0);
+ progress.log('info', 'Compiling engine WASM via toolchain...');
- context.customWasm = {
- jsPath: compileResult.jsPath,
- wasmPath: compileResult.wasmPath,
+ const compileResult = await compileWasm(config, context, options?.cleanBuild);
+ if (!compileResult.success) {
+ progress.fail(compileResult.error || 'WASM compilation failed');
+ return {
+ success: false,
+ error: compileResult.error || 'WASM compilation failed',
+ duration: Date.now() - startTime,
};
- progress.log('info', `Custom WASM compiled (${formatSize(compileResult.wasmSize)})`);
}
+ context.customWasm = {
+ jsPath: compileResult.jsPath,
+ wasmPath: compileResult.wasmPath,
+ spineModules: compileResult.spineModules,
+ physicsJsPath: compileResult.physicsJsPath,
+ physicsWasmPath: compileResult.physicsWasmPath,
+ };
+ progress.log('info', `WASM compiled (${formatSize(compileResult.wasmSize)})`);
+
const hooks = config.hooks ?? [];
const outputPath = config.playableSettings?.outputPath
?? config.wechatSettings?.outputDir
@@ -308,27 +313,31 @@ interface CompileWasmResult {
wasmPath?: string;
wasmSize?: number;
error?: string;
+ spineModules?: Array<{ version: string; jsPath: string; wasmPath: string }>;
+ physicsJsPath?: string;
+ physicsWasmPath?: string;
}
-function isAllModulesEnabled(modules: EngineModules): boolean {
- const defaults = createDefaultEngineModules();
- return (Object.keys(defaults) as Array<keyof EngineModules>).every(
- key => modules[key] !== false
- );
-}
-
-async function compileCustomWasm(config: BuildConfig): Promise<CompileWasmResult> {
+async function compileWasm(config: BuildConfig, context: BuildContext, cleanBuild?: boolean): Promise<CompileWasmResult> {
const { invoke } = await import('@tauri-apps/api/core');
const modules = config.engineModules ?? createDefaultEngineModules();
const target = config.platform === 'wechat' ? 'wechat' : 'playable';
+ const spineVersions: string[] = [];
+ if (modules.spine && context.spineVersion) {
+ spineVersions.push(context.spineVersion);
+ }
+
const result = await invoke<{
success: boolean;
wasm_path: string | null;
js_path: string | null;
wasm_size: number | null;
error: string | null;
+ spine_modules: Array<{ version: string; js_path: string; wasm_path: string }>;
+ physics_js_path: string | null;
+ physics_wasm_path: string | null;
}>('compile_wasm', {
options: {
features: {
@@ -340,8 +349,11 @@ async function compileCustomWasm(config: BuildConfig): Promise<CompileWasmResult
spine: modules.spine,
},
target,
- debug: config.defines.includes('DEBUG'),
- optimization: '-O2',
+ debug: false,
+ optimization: '-Oz',
+ enable_physics: context.enablePhysics ?? false,
+ spine_versions: spineVersions,
+ clean_build: cleanBuild ?? false,
},
});
@@ -351,6 +363,13 @@ async function compileCustomWasm(config: BuildConfig): Promise<CompileWasmResult
wasmPath: result.wasm_path ?? undefined,
wasmSize: result.wasm_size ?? undefined,
error: result.error ?? undefined,
+ spineModules: result.spine_modules.map(m => ({
+ version: m.version,
+ jsPath: m.js_path,
+ wasmPath: m.wasm_path,
+ })),
+ physicsJsPath: result.physics_js_path ?? undefined,
+ physicsWasmPath: result.physics_wasm_path ?? undefined,
};
}
diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.ts
index 72db8e9c3..9e83e7abd 100644
--- a/editor/src/builder/BuildSettingsDialog.ts
+++ b/editor/src/builder/BuildSettingsDialog.ts
@@ -121,6 +121,9 @@ export class BuildSettingsDialog {
</button>
</div>
<div class="es-build-toolbar-right">
+ <label class="es-build-clean-toggle" title="Delete cached build and recompile from scratch">
+ <input type="checkbox" data-action="clean-build"> Clean Build
+ </label>
<button class="es-btn" data-action="build-all" title="Build All Configs">
Build All
</button>
@@ -935,7 +938,8 @@ export class BuildSettingsDialog {
case 'build':
if (config) {
- this.handleBuild(config);
+ const cleanCheckbox = this.overlay_.querySelector('[data-action="clean-build"]') as HTMLInputElement | null;
+ this.handleBuild(config, cleanCheckbox?.checked);
}
break;
@@ -1111,6 +1115,22 @@ export class BuildSettingsDialog {
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> {
@@ -1364,12 +1384,10 @@ export class BuildSettingsDialog {
}
}
- private async handleBuild(config: BuildConfig): Promise<void> {
- if (config.engineModules && Object.values(config.engineModules).some(v => v === false)) {
- if (!this.toolchainStatus_?.installed) {
- showErrorToast('Toolchain not ready. Custom engine modules require emsdk, CMake and Python.');
- return;
- }
+ 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;
@@ -1399,7 +1417,7 @@ export class BuildSettingsDialog {
});
try {
- const result = await this.options_.onBuild(config, { progress });
+ const result = await this.options_.onBuild(config, { progress, cleanBuild });
dismissToast(toastId);
diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.ts
index 093f82071..42ff3f294 100644
--- a/editor/src/builder/PlayableEmitter.ts
+++ b/editor/src/builder/PlayableEmitter.ts
@@ -47,13 +47,14 @@ export class PlayableEmitter implements PlatformEmitter {
const projectDir = getProjectDir(context.projectPath);
try {
- // 1. Load SDK
+ // 1. Load compiled SDK
progress.setCurrentTask('Loading SDK...', 0);
- const wasmSdk = context.customWasm?.jsPath
- ? await fs.readFile(context.customWasm.jsPath)
- : await this.loadSdk(fs);
+ if (!context.customWasm?.jsPath) {
+ return { success: false, error: 'WASM not compiled. Toolchain compilation is required.' };
+ }
+ const wasmSdk = await fs.readFile(context.customWasm.jsPath);
if (!wasmSdk) {
- return { success: false, error: "SDK not found. Please run 'scripts/build-web-single.bat' first." };
+ return { success: false, error: `Compiled SDK not found at: ${context.customWasm.jsPath}` };
}
progress.log('info', `SDK loaded: ${wasmSdk.length} bytes`);
@@ -75,33 +76,32 @@ export class PlayableEmitter implements PlatformEmitter {
return { success: false, error: `Startup scene not found: ${startupScene}` };
}
- // 4. Load spine modules if needed
+ // 4. Load spine modules from compiled output
progress.setCurrentTask('Loading modules...', 25);
const spineModules: Array<{ version: string; js: string; wasmBase64: string }> = [];
- const spineEnabled = context.config.engineModules?.spine !== false;
- for (const version of spineEnabled ? artifact.spineVersions : []) {
- if (version === '4.2') continue;
- if (!fs.getSpineJs) continue;
- const spineJs = await fs.getSpineJs(version);
- const spineWasm = await fs.getSpineWasm(version);
- if (spineJs && spineWasm.length > 0) {
- spineModules.push({
- version,
- js: spineJs,
- wasmBase64: arrayBufferToBase64(spineWasm),
- });
- progress.log('info', `Spine ${version} module loaded`);
+ if (context.customWasm?.spineModules) {
+ for (const mod of context.customWasm.spineModules) {
+ const spineJs = await fs.readFile(mod.jsPath);
+ const spineWasm = await fs.readBinaryFile(mod.wasmPath);
+ if (spineJs && spineWasm && spineWasm.length > 0) {
+ spineModules.push({
+ version: mod.version,
+ js: spineJs,
+ wasmBase64: arrayBufferToBase64(spineWasm),
+ });
+ progress.log('info', `Spine ${mod.version} module loaded`);
+ }
}
}
- // 5. Load physics module if needed
+ // 5. Load physics module from compiled output
let physicsJsSource = '';
let physicsWasmBase64 = '';
- if (context.enablePhysics && fs.getPhysicsJs) {
+ if (context.customWasm?.physicsJsPath && context.customWasm?.physicsWasmPath) {
progress.setCurrentTask('Loading physics module...', 27);
- const physicsJs = await fs.getPhysicsJs();
- const physicsWasm = await fs.getPhysicsWasm();
- if (physicsJs && physicsWasm.length > 0) {
+ const physicsJs = await fs.readFile(context.customWasm.physicsJsPath);
+ const physicsWasm = await fs.readBinaryFile(context.customWasm.physicsWasmPath);
+ if (physicsJs && physicsWasm && physicsWasm.length > 0) {
physicsJsSource = physicsJs;
physicsWasmBase64 = arrayBufferToBase64(physicsWasm);
progress.log('info', 'Physics module loaded');
@@ -164,19 +164,6 @@ export class PlayableEmitter implements PlatformEmitter {
// Private Methods
// =========================================================================
- private async loadSdk(fs: NativeFS): Promise<string | null> {
- try {
- if (fs.getEngineSingleJs) {
- return await fs.getEngineSingleJs();
- }
- const response = await fetch('/wasm/esengine.single.js');
- if (!response.ok) return null;
- return await response.text();
- } catch {
- return null;
- }
- }
-
private async compilePlayableScripts(
fs: NativeFS,
projectDir: string,
@@ -215,11 +202,17 @@ const __plugins = [${pluginList}];
minify: settings.minifyCode,
sdkResolver: async (path) => {
if (path === 'esengine') {
- return { contents: await fs.getSdkEsmJs(), loader: 'js' as esbuild.Loader };
+ const resp = await fetch('/sdk/esm/esengine.js');
+ return { contents: await resp.text(), loader: 'js' as esbuild.Loader };
}
if (path === 'esengine/wasm') {
return { contents: await fs.getSdkWasmJs(), loader: 'js' as esbuild.Loader };
}
+ const sdkPath = path.replace(/^\.\//, '');
+ const resp = await fetch(`/sdk/esm/${sdkPath}`);
+ if (resp.ok) {
+ return { contents: await resp.text(), loader: 'js' as esbuild.Loader };
+ }
return { contents: '', loader: 'js' as esbuild.Loader };
},
});
diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.ts
index 545667f83..0b8180c45 100644
--- a/editor/src/builder/WeChatEmitter.ts
+++ b/editor/src/builder/WeChatEmitter.ts
@@ -260,28 +260,16 @@ export class WeChatEmitter implements PlatformEmitter {
fs: NativeFS,
outputDir: string,
context: BuildContext,
- artifact: BuildArtifact,
+ _artifact: BuildArtifact,
): Promise<void> {
- let engineJs: string;
- let engineWasm: Uint8Array;
-
- if (context.customWasm?.jsPath && context.customWasm?.wasmPath) {
- const js = await fs.readFile(context.customWasm.jsPath);
- const wasm = await fs.readBinaryFile(context.customWasm.wasmPath);
- if (!js || !wasm) {
- throw new Error('Custom WASM build output not found');
- }
- engineJs = js;
- engineWasm = wasm;
- } else {
- engineJs = await fs.getEngineWxgameJs();
- engineWasm = await fs.getEngineWxgameWasm();
+ if (!context.customWasm?.jsPath || !context.customWasm?.wasmPath) {
+ throw new Error('WASM not compiled. Toolchain compilation is required.');
}
- if (!engineJs || engineJs.length === 0) {
- throw new Error(
- 'WeChat engine not found. Please run: scripts/build-wxgame.sh'
- );
+ const engineJs = await fs.readFile(context.customWasm.jsPath);
+ const engineWasm = await fs.readBinaryFile(context.customWasm.wasmPath);
+ if (!engineJs || !engineWasm) {
+ throw new Error('Compiled WASM build output not found');
}
await fs.writeFile(joinPath(outputDir, 'esengine.js'), engineJs);
@@ -292,24 +280,22 @@ export class WeChatEmitter implements PlatformEmitter {
await fs.writeFile(joinPath(outputDir, 'sdk.js'), sdkJs);
}
- const spineEnabled = context.config.engineModules?.spine !== false;
- if (spineEnabled) {
- for (const version of artifact.spineVersions) {
- if (version === '4.2') continue;
- const spineJs = await fs.getSpineJs(version);
- const spineWasm = await fs.getSpineWasm(version);
- if (spineJs && spineWasm.length > 0) {
- const tag = version.replace('.', '');
+ if (context.customWasm.spineModules) {
+ for (const mod of context.customWasm.spineModules) {
+ const spineJs = await fs.readFile(mod.jsPath);
+ const spineWasm = await fs.readBinaryFile(mod.wasmPath);
+ if (spineJs && spineWasm && spineWasm.length > 0) {
+ const tag = mod.version.replace('.', '');
await fs.writeFile(joinPath(outputDir, `spine_${tag}.js`), spineJs);
await fs.writeBinaryFile(joinPath(outputDir, `spine_${tag}.wasm`), spineWasm);
}
}
}
- if (context.enablePhysics) {
- const physicsJs = await fs.getPhysicsJs();
- const physicsWasm = await fs.getPhysicsWasm();
- if (physicsJs && physicsWasm.length > 0) {
+ if (context.customWasm.physicsJsPath && context.customWasm.physicsWasmPath) {
+ const physicsJs = await fs.readFile(context.customWasm.physicsJsPath);
+ const physicsWasm = await fs.readBinaryFile(context.customWasm.physicsWasmPath);
+ if (physicsJs && physicsWasm && physicsWasm.length > 0) {
await fs.writeFile(joinPath(outputDir, 'physics.js'), physicsJs);
await fs.writeBinaryFile(joinPath(outputDir, 'physics.wasm'), physicsWasm);
}
diff --git a/editor/src/panels/AddressablePanel.ts b/editor/src/panels/AddressablePanel.ts
index 384dbaf41..076416253 100644
--- a/editor/src/panels/AddressablePanel.ts
+++ b/editor/src/panels/AddressablePanel.ts
@@ -6,7 +6,7 @@
import type { EditorStore } from '../store/EditorStore';
import type { PanelInstance } from './PanelRegistry';
import { icons } from '../utils/icons';
-import { getAssetDatabase, type AssetEntry } from '../asset/AssetDatabase';
+import { getAssetDatabase, type AssetEntry, type AssetDatabase } from '../asset/AssetDatabase';
import type { AssetGroupService, AssetGroupDef, BundleMode } from '../asset/AssetGroup';
import { AssetDependencyAnalyzer } from '../asset/AssetDependencyAnalyzer';
import { getEditorContext } from '../context/EditorContext';
@@ -55,12 +55,15 @@ export class AddressablePanel implements PanelInstance {
private groupConfigExpanded_ = false;
private unreferencedUuids_: string[] = [];
private analyzing_ = false;
+ private dependents_: Map<string, Set<string>> = new Map();
+ private unreferencedCollapsed_ = true;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
this.store_ = store;
this.buildLayout();
this.render();
+ this.analyzeUnreferenced();
}
dispose(): void {
@@ -312,6 +315,7 @@ export class AddressablePanel implements PanelInstance {
<div class="es-addr-table-header">
<span class="es-addr-col-name${this.sortColumn_ === 'name' ? ' es-sorted' : ''}" data-col="name">Name${sortIcon('name')}</span>
<span class="es-addr-col-address${this.sortColumn_ === 'address' ? ' es-sorted' : ''}" data-col="address">Address${sortIcon('address')}</span>
+ <span class="es-addr-col-source">Source</span>
<span class="es-addr-col-labels">Labels</span>
<span class="es-addr-col-type${this.sortColumn_ === 'type' ? ' es-sorted' : ''}" data-col="type">Type${sortIcon('type')}</span>
<span class="es-addr-col-size${this.sortColumn_ === 'size' ? ' es-sorted' : ''}" data-col="size">Size${sortIcon('size')}</span>
@@ -326,10 +330,12 @@ export class AddressablePanel implements PanelInstance {
}).join('');
const size = this.formatSize(entry.fileSize);
const selected = this.selectedUuids_.has(entry.uuid);
+ const sourceHtml = this.renderSourceTags(entry.uuid, db);
return `
<div class="es-addr-table-row${selected ? ' es-selected' : ''}" data-uuid="${entry.uuid}" draggable="true">
<span class="es-addr-col-name" title="${escapeHtml(entry.path)}">${escapeHtml(name)}</span>
<span class="es-addr-col-address">${escapeHtml(entry.address || '')}</span>
+ <span class="es-addr-col-source">${sourceHtml}</span>
<span class="es-addr-col-labels">${labelsHtml}</span>
<span class="es-addr-col-type">${entry.type}</span>
<span class="es-addr-col-size">${size}</span>
@@ -535,41 +541,60 @@ export class AddressablePanel implements PanelInstance {
this.unreferencedEl_.style.display = '';
const db = getAssetDatabase();
-
- const rowsHtml = this.unreferencedUuids_.map(uuid => {
+ const chevron = this.unreferencedCollapsed_ ? icons.chevronRight(10) : icons.chevronDown(10);
+ const totalSize = this.unreferencedUuids_.reduce((sum, uuid) => {
const entry = db.getEntry(uuid);
- if (!entry) return '';
- const name = entry.path.split('/').pop() || '';
- return `
- <div class="es-addr-unreferenced-row" data-uuid="${uuid}" title="${escapeHtml(entry.path)}">
- <span class="es-addr-col-name">${escapeHtml(name)}</span>
- <span class="es-addr-col-type">${entry.type}</span>
- <span class="es-addr-col-size">${this.formatSize(entry.fileSize)}</span>
- </div>
- `;
- }).join('');
+ return sum + (entry?.fileSize ?? 0);
+ }, 0);
+
+ let listHtml = '';
+ if (!this.unreferencedCollapsed_) {
+ const rowsHtml = this.unreferencedUuids_.map(uuid => {
+ const entry = db.getEntry(uuid);
+ if (!entry) return '';
+ const name = entry.path.split('/').pop() || '';
+ return `
+ <div class="es-addr-unreferenced-row" data-uuid="${uuid}" title="${escapeHtml(entry.path)}">
+ <span class="es-addr-col-name">${escapeHtml(name)}</span>
+ <span class="es-addr-col-type">${entry.type}</span>
+ <span class="es-addr-col-size">${this.formatSize(entry.fileSize)}</span>
+ </div>
+ `;
+ }).join('');
+ listHtml = `<div class="es-addr-unreferenced-list">${rowsHtml}</div>`;
+ }
this.unreferencedEl_.innerHTML = `
- <div class="es-addr-unreferenced-header">Unreferenced Assets (${this.unreferencedUuids_.length})</div>
- <div class="es-addr-unreferenced-list">${rowsHtml}</div>
+ <div class="es-addr-unreferenced-header" data-action="toggle-unreferenced">
+ ${chevron}
+ Unreferenced Assets (${this.unreferencedUuids_.length}) — ${this.formatSize(totalSize)}
+ </div>
+ ${listHtml}
`;
- this.unreferencedEl_.querySelectorAll('.es-addr-unreferenced-row').forEach(row => {
- row.addEventListener('contextmenu', (e) => {
- e.preventDefault();
- const uuid = (row as HTMLElement).dataset.uuid;
- if (!uuid) return;
- this.showUnreferencedContextMenu(e as MouseEvent, uuid);
- });
- row.addEventListener('dblclick', () => {
- const uuid = (row as HTMLElement).dataset.uuid;
- if (!uuid) return;
- const entry = db.getEntry(uuid);
- if (entry) {
- getNavigationService().navigateToAsset(entry.path);
- }
- });
+ this.unreferencedEl_.querySelector('[data-action="toggle-unreferenced"]')?.addEventListener('click', () => {
+ this.unreferencedCollapsed_ = !this.unreferencedCollapsed_;
+ this.renderUnreferenced();
});
+
+ if (!this.unreferencedCollapsed_) {
+ this.unreferencedEl_.querySelectorAll('.es-addr-unreferenced-row').forEach(row => {
+ row.addEventListener('contextmenu', (e) => {
+ e.preventDefault();
+ const uuid = (row as HTMLElement).dataset.uuid;
+ if (!uuid) return;
+ this.showUnreferencedContextMenu(e as MouseEvent, uuid);
+ });
+ row.addEventListener('dblclick', () => {
+ const uuid = (row as HTMLElement).dataset.uuid;
+ if (!uuid) return;
+ const entry = db.getEntry(uuid);
+ if (entry) {
+ getNavigationService().navigateToAsset(entry.path);
+ }
+ });
+ });
+ }
}
// =========================================================================
@@ -641,6 +666,8 @@ export class AddressablePanel implements PanelInstance {
const analyzer = new AssetDependencyAnalyzer(fs, projectDir, db);
const graph = await analyzer.analyze(scenePaths);
this.unreferencedUuids_ = [...graph.unreferenced];
+ this.dependents_ = graph.dependents;
+ this.renderAssetTable();
this.renderUnreferenced();
this.renderStatusBar();
} catch (e) {
@@ -893,6 +920,39 @@ export class AddressablePanel implements PanelInstance {
return LABEL_COLORS[Math.abs(hash) % LABEL_COLORS.length];
}
+ private renderSourceTags(uuid: string, db: AssetDatabase): string {
+ const tags: string[] = [];
+ const entry = db.getEntry(uuid);
+
+ const deps = this.dependents_.get(uuid);
+ if (deps && deps.size > 0) {
+ for (const depUuid of deps) {
+ const depEntry = db.getEntry(depUuid);
+ if (!depEntry) continue;
+ const name = depEntry.path.split('/').pop()?.replace('.esscene', '') || depUuid;
+ if (depEntry.path.endsWith('.esscene')) {
+ tags.push(`<span class="es-addr-source-tag es-addr-source-scene" title="${escapeHtml(depEntry.path)}">${escapeHtml(name)}</span>`);
+ } else {
+ tags.push(`<span class="es-addr-source-tag es-addr-source-dep" title="${escapeHtml(depEntry.path)}">${escapeHtml(name)}</span>`);
+ }
+ }
+ }
+
+ if (entry) {
+ const gs = this.getGroupService();
+ const pattern = gs?.getMatchedPattern(entry.path, entry.group);
+ if (pattern) {
+ tags.push(`<span class="es-addr-source-tag es-addr-source-pattern" title="Include pattern: ${escapeHtml(pattern)}">${escapeHtml(pattern)}</span>`);
+ }
+ }
+
+ if (tags.length === 0) {
+ if (this.dependents_.size === 0) return '';
+ return '<span class="es-addr-source-tag es-addr-source-unused">unused</span>';
+ }
+ return tags.join('');
+ }
+
private formatSize(bytes: number): string {
if (bytes === 0) return '-';
if (bytes < 1024) return `${bytes} B`;
diff --git a/editor/src/styles/builder.css b/editor/src/styles/builder.css
index 2c54b569d..c1dc20157 100644
--- a/editor/src/styles/builder.css
+++ b/editor/src/styles/builder.css
@@ -683,6 +683,17 @@
gap: 6px;
}
+.es-build-clean-toggle {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 12px;
+ color: var(--text-secondary);
+ cursor: pointer;
+ user-select: none;
+ margin-right: 4px;
+}
+
.es-build-toolbar-left {
flex: 1;
}
@@ -1338,6 +1349,47 @@
white-space: nowrap;
}
+.es-addr-col-source {
+ flex: 1.5;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ display: flex;
+ gap: 3px;
+ align-items: center;
+}
+
+.es-addr-source-tag {
+ display: inline-block;
+ font-size: 10px;
+ padding: 1px 5px;
+ border-radius: 3px;
+ max-width: 80px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-addr-source-scene {
+ background: rgba(97, 175, 239, 0.2);
+ color: #61afef;
+}
+
+.es-addr-source-dep {
+ background: rgba(209, 154, 102, 0.2);
+ color: #d19a66;
+}
+
+.es-addr-source-pattern {
+ background: rgba(152, 195, 121, 0.2);
+ color: #98c379;
+}
+
+.es-addr-source-unused {
+ background: rgba(224, 108, 117, 0.15);
+ color: #e06c75;
+}
+
.es-addr-col-size {
width: 70px;
flex-shrink: 0;
@@ -1467,20 +1519,23 @@
.es-addr-unreferenced {
border-top: 1px solid var(--es-border);
background: var(--es-bg-secondary);
+}
+
+.es-addr-unreferenced-list {
max-height: 200px;
overflow-y: auto;
}
.es-addr-unreferenced-header {
+ display: flex;
+ align-items: center;
+ gap: 4px;
padding: 6px 12px;
font-size: 11px;
font-weight: 600;
color: var(--es-danger);
- border-bottom: 1px solid var(--es-border);
-}
-
-.es-addr-unreferenced-list {
- padding: 0;
+ cursor: pointer;
+ user-select: none;
}
.es-addr-unreferenced-row {