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: Add playable build pipeline with scene-driven architecture

esengine3440f8f9f1ad
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 3d293760a..bf8b5c450 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -4,6 +4,13 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ESEngine Preview</title>
+ <script type="importmap">
+ {
+ "imports": {
+ "esengine": "/esengine-sdk.js"
+ }
+ }
+ </script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #1a1a2e; }
@@ -37,13 +44,6 @@
<div id="error"></div>
<script type="module">
- import {
- createWebApp,
- assetPlugin,
- textPlugin,
- PreviewPlugin
- } from '/esengine-sdk.js';
-
const loading = document.getElementById('loading');
const errorDiv = document.getElementById('error');
@@ -58,70 +58,6 @@
console.error('Preview Error:', msg);
}
- async function loadPreview() {
- try {
- updateLoading('Loading WASM module...');
- const ModuleLoader = await import('/esengine.js');
- const Module = await ModuleLoader.default();
-
- let userMain = null;
- try {
- const userModule = await import('/.esengine/preview/user-scripts.js');
- if (typeof userModule.main === 'function') {
- userMain = userModule.main;
- }
- } catch (e) {
- console.log('No user main function, using default preview');
- }
-
- if (userMain) {
- await runWithUserMain(Module, userMain);
- } else {
- await runDefaultPreview(Module);
- }
-
- loading.style.display = 'none';
- } catch (err) {
- showError(err.message || String(err));
- }
- }
-
- async function runWithUserMain(Module, userMain) {
- updateLoading('Loading scene...');
-
- setupCanvas();
- window.addEventListener('resize', () => {
- setupCanvas();
- });
-
- const previewPlugin = new PreviewPlugin('/.esengine/preview/scene.json');
- const origCreate = createWebApp;
-
- const patchedCreate = (module, options) => {
- const mergedOptions = {
- ...options,
- getViewportSize: options?.getViewportSize ?? getCanvasViewportSize
- };
- const app = origCreate(module, mergedOptions);
- app.addPlugin(previewPlugin);
- return app;
- };
-
- window.esengine = window.esengine || {};
- window.esengine.createWebApp = patchedCreate;
-
- const sdkModule = await import('/esengine-sdk.js');
- Object.defineProperty(sdkModule, 'createWebApp', {
- value: patchedCreate,
- writable: true
- });
-
- await userMain(Module);
-
- // Wait for scene to be loaded
- await previewPlugin.waitForReady();
- }
-
function setupCanvas() {
const canvas = document.getElementById('canvas');
const dpr = window.devicePixelRatio || 1;
@@ -136,31 +72,42 @@
return { width: canvas.width, height: canvas.height };
}
- async function runDefaultPreview(Module) {
- updateLoading('Loading scene...');
-
- // IMPORTANT: Setup canvas BEFORE creating WebGL context
- setupCanvas();
+ async function loadPreview() {
+ try {
+ updateLoading('Loading WASM module...');
+ const ModuleLoader = await import('/esengine.js');
+ const Module = await ModuleLoader.default();
- const previewPlugin = new PreviewPlugin('/.esengine/preview/scene.json');
+ updateLoading('Loading SDK...');
+ const sdk = await import('/esengine-sdk.js');
- const app = createWebApp(Module, {
- getViewportSize: getCanvasViewportSize
- });
- app.addPlugin(assetPlugin);
- app.addPlugin(textPlugin);
- app.addPlugin(previewPlugin);
+ // Load user scripts to register custom components (but don't call main)
+ try {
+ await import('/.esengine/preview/user-scripts.js');
+ console.log('User scripts loaded (components registered)');
+ } catch (e) {
+ console.log('No user scripts found');
+ }
- // Setup resize handler AFTER app is created
- window.addEventListener('resize', () => {
+ updateLoading('Loading scene...');
setupCanvas();
- });
+ window.addEventListener('resize', () => setupCanvas());
+
+ const previewPlugin = new sdk.PreviewPlugin('/.esengine/preview/scene.json');
- // Wait for scene to be loaded before starting render loop
- await previewPlugin.waitForReady();
+ const app = sdk.createWebApp(Module, {
+ getViewportSize: getCanvasViewportSize
+ });
+ app.addPlugin(sdk.assetPlugin);
+ app.addPlugin(previewPlugin);
+
+ await previewPlugin.waitForReady();
- updateLoading('Starting renderer...');
- app.run();
+ loading.style.display = 'none';
+ app.run();
+ } catch (err) {
+ showError(err.message || String(err));
+ }
}
loadPreview();
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 35c576559..4b70c1878 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -17,6 +17,7 @@ import { saveSceneToFile, saveSceneToPath, loadSceneFromFile, loadSceneFromPath,
import { icons } from './utils/icons';
import { ScriptLoader } from './scripting';
import { PreviewService } from './preview';
+import { showBuildSettingsDialog, BuildService } from './builder';
// =============================================================================
// Types
@@ -68,6 +69,10 @@ export class Editor {
return this.projectPath_;
}
+ get currentScenePath(): string | null {
+ return this.store_.filePath;
+ }
+
setApp(app: App): void {
this.app_ = app;
this.bridge_ = new EditorBridge(app, this.store_);
@@ -118,7 +123,7 @@ export class Editor {
async openSceneFromPath(scenePath: string): Promise<void> {
const scene = await loadSceneFromPath(scenePath);
if (scene) {
- this.store_.loadScene(scene);
+ this.store_.loadScene(scene, scenePath);
console.log('Scene loaded:', scenePath);
}
}
@@ -142,7 +147,7 @@ export class Editor {
try {
await this.scriptLoader_.initialize();
- await this.scriptLoader_.compileAndExecute();
+ await this.scriptLoader_.compile();
} catch (err) {
console.error('Failed to initialize scripts:', err);
}
@@ -216,6 +221,11 @@ export class Editor {
<span class="es-menu-item-text">Save As...</span>
<span class="es-menu-item-shortcut">Ctrl+Shift+S</span>
</div>
+ <div class="es-menu-divider"></div>
+ <div class="es-menu-item" data-action="build-settings">
+ <span class="es-menu-item-text">Build Settings...</span>
+ <span class="es-menu-item-shortcut">Ctrl+Shift+B</span>
+ </div>
</div>
</div>
<div class="es-menu" data-menu="edit">
@@ -459,7 +469,29 @@ export class Editor {
case 'about':
this.showAboutDialog();
break;
+ case 'build-settings':
+ this.showBuildSettings();
+ break;
+ }
+ }
+
+ private showBuildSettings(): void {
+ if (!this.projectPath_) {
+ alert('请先打开一个项目');
+ return;
}
+
+ const buildService = new BuildService(this.projectPath_);
+ showBuildSettingsDialog({
+ projectPath: this.projectPath_,
+ onBuild: async (config) => {
+ const result = await buildService.build(config);
+ if (!result.success) {
+ throw new Error(result.error ?? 'Build failed');
+ }
+ },
+ onClose: () => {},
+ });
}
private async saveSceneAs(): Promise<void> {
@@ -570,6 +602,12 @@ export class Editor {
e.preventDefault();
this.duplicateSelected();
break;
+ case 'b':
+ if (e.shiftKey) {
+ e.preventDefault();
+ this.showBuildSettings();
+ }
+ break;
}
} else if (e.key === 'Delete') {
const selected = this.store_.selectedEntity;
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
new file mode 100644
index 000000000..7eb81cd9e
--- /dev/null
+++ b/editor/src/builder/BuildService.ts
@@ -0,0 +1,67 @@
+/**
+ * @file BuildService.ts
+ * @brief Build service for compiling and packaging projects
+ */
+
+import type { BuildConfig } from '../types/BuildTypes';
+import { PlayableBuilder } from './PlayableBuilder';
+import { WeChatBuilder } from './WeChatBuilder';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface BuildResult {
+ success: boolean;
+ outputPath?: string;
+ error?: string;
+}
+
+export interface BuildContext {
+ projectPath: string;
+ config: BuildConfig;
+}
+
+// =============================================================================
+// BuildService
+// =============================================================================
+
+export class BuildService {
+ private projectPath_: string;
+
+ constructor(projectPath: string) {
+ this.projectPath_ = projectPath;
+ }
+
+ async build(config: BuildConfig): Promise<BuildResult> {
+ console.log(`[BuildService] Starting build for config: ${config.name}`);
+ console.log(`[BuildService] Platform: ${config.platform}`);
+ console.log(`[BuildService] Scenes: ${config.scenes.join(', ')}`);
+
+ const context: BuildContext = {
+ projectPath: this.projectPath_,
+ config,
+ };
+
+ try {
+ if (config.platform === 'playable') {
+ const builder = new PlayableBuilder(context);
+ return await builder.build();
+ } else if (config.platform === 'wechat') {
+ const builder = new WeChatBuilder(context);
+ return await builder.build();
+ } else {
+ return {
+ success: false,
+ error: `Unknown platform: ${config.platform}`,
+ };
+ }
+ } catch (err) {
+ console.error('[BuildService] Build failed:', err);
+ return {
+ success: false,
+ error: String(err),
+ };
+ }
+ }
+}
diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.ts
new file mode 100644
index 000000000..40c19913d
--- /dev/null
+++ b/editor/src/builder/BuildSettingsDialog.ts
@@ -0,0 +1,659 @@
+/**
+ * @file BuildSettingsDialog.ts
+ * @brief Build settings dialog UI component
+ */
+
+import { icons } from '../utils/icons';
+import {
+ type BuildPlatform,
+ type BuildConfig,
+ type BuildSettings,
+ PLATFORMS,
+ createDefaultBuildConfig,
+ createDefaultBuildSettings,
+} from '../types/BuildTypes';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface BuildSettingsDialogOptions {
+ projectPath: string;
+ onBuild: (config: BuildConfig) => Promise<void>;
+ onClose: () => void;
+}
+
+// =============================================================================
+// Storage
+// =============================================================================
+
+const BUILD_SETTINGS_KEY = 'esengine_build_settings';
+
+function loadBuildSettings(): BuildSettings {
+ try {
+ const data = localStorage.getItem(BUILD_SETTINGS_KEY);
+ if (data) {
+ return JSON.parse(data) as BuildSettings;
+ }
+ } catch {
+ // Ignore parse errors
+ }
+ return createDefaultBuildSettings();
+}
+
+function saveBuildSettings(settings: BuildSettings): void {
+ localStorage.setItem(BUILD_SETTINGS_KEY, JSON.stringify(settings));
+}
+
+// =============================================================================
+// BuildSettingsDialog
+// =============================================================================
+
+export class BuildSettingsDialog {
+ constructor(options: BuildSettingsDialogOptions) {
+ this.options_ = options;
+ this.settings_ = loadBuildSettings();
+
+ if (!this.settings_.activeConfigId && this.settings_.configs.length > 0) {
+ this.settings_.activeConfigId = this.settings_.configs[0].id;
+ }
+
+ this.overlay_ = document.createElement('div');
+ this.overlay_.className = 'es-dialog-overlay';
+ document.body.appendChild(this.overlay_);
+
+ this.render();
+ this.setupEvents();
+ }
+
+ dispose(): void {
+ saveBuildSettings(this.settings_);
+ this.overlay_.remove();
+ }
+
+ private getActiveConfig(): BuildConfig | null {
+ return this.settings_.configs.find(c => c.id === this.settings_.activeConfigId) ?? null;
+ }
+
+ private render(): void {
+ const config = this.getActiveConfig();
+
+ this.overlay_.innerHTML = `
+ <div class="es-build-dialog">
+ <div class="es-dialog-header">
+ <span class="es-dialog-title">${icons.cog(16)} 构建设置</span>
+ <button class="es-dialog-close" data-action="close">&times;</button>
+ </div>
+ <div class="es-build-toolbar">
+ <button class="es-btn es-btn-icon" data-action="add-config" title="添加构建配置">
+ ${icons.plus(14)} 添加构建配置
+ </button>
+ </div>
+ <div class="es-build-body">
+ <div class="es-build-sidebar">
+ ${this.renderSidebar()}
+ </div>
+ <div class="es-build-detail">
+ ${config ? this.renderDetail(config) : this.renderNoConfig()}
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
+ 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">激活</span>' : ''}
+ </div>
+ </div>
+ ${configs.map(c => this.renderConfigItem(c)).join('')}
+ `;
+ }).join('');
+
+ return `
+ <div class="es-build-section-title">平台</div>
+ ${platformsHtml}
+ `;
+ }
+
+ private renderConfigItem(config: BuildConfig): string {
+ const isActive = this.settings_.activeConfigId === config.id;
+ return `
+ <div class="es-build-config-item ${isActive ? 'es-active' : ''}" data-config="${config.id}">
+ <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="删除">
+ ${icons.x(10)}
+ </button>
+ </div>
+ `;
+ }
+
+ private renderNoConfig(): string {
+ return `
+ <div class="es-build-empty">
+ <p>没有选中的构建配置</p>
+ <p>请从左侧选择一个配置或创建新配置</p>
+ </div>
+ `;
+ }
+
+ private renderDetail(config: BuildConfig): string {
+ return `
+ <div class="es-build-detail-header">
+ <div class="es-build-detail-title">
+ <h3>${config.name}</h3>
+ <span class="es-build-detail-platform">${this.getPlatformName(config.platform)}</span>
+ </div>
+ <div class="es-build-detail-actions">
+ <button class="es-btn" data-action="switch-config">切换配置</button>
+ <button class="es-btn es-btn-primary" data-action="build">
+ ${icons.play(14)} 构建
+ </button>
+ </div>
+ </div>
+ <div class="es-build-detail-content">
+ <div class="es-build-data-section">
+ <h4>构建数据</h4>
+ ${this.renderScenesSection(config)}
+ ${this.renderDefinesSection(config)}
+ </div>
+ <div class="es-build-settings-section">
+ <h4>平台设置</h4>
+ ${this.renderPlatformSettings(config)}
+ </div>
+ </div>
+ `;
+ }
+
+ private renderScenesSection(config: BuildConfig): string {
+ const isExpanded = this.expandedSections_.has('scenes');
+ const scenesHtml = config.scenes.length > 0
+ ? config.scenes.map((s, i) => `
+ <div class="es-build-scene-item">
+ <input type="checkbox" checked data-scene-index="${i}">
+ <span>${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">没有场景</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>场景列表</span>
+ </div>
+ <div class="es-build-collapse-content">
+ <div class="es-build-scene-list">
+ ${scenesHtml}
+ </div>
+ <button class="es-btn es-btn-link" data-action="add-current-scene">
+ 添加已打开的场景
+ </button>
+ </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>脚本定义</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="新定义...">
+ <button class="es-btn-icon" data-action="add-define" title="添加">
+ ${icons.plus(12)}
+ </button>
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
+ 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">启动场景</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' : ''}>
+ 开发版本
+ </label>
+ </div>
+ <div class="es-build-field">
+ <label>
+ <input type="checkbox" id="playable-minify" ${s.minifyCode ? 'checked' : ''}>
+ 压缩代码
+ </label>
+ </div>
+ <div class="es-build-field">
+ <label>
+ <input type="checkbox" id="playable-fonts" ${s.embedFonts ? 'checked' : ''}>
+ 内嵌字体
+ </label>
+ </div>
+ <div class="es-build-field">
+ <label class="es-build-label">输出路径</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>
+ `;
+ } 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">版本号</label>
+ <input type="text" class="es-input" id="wechat-version" value="${s.version}">
+ </div>
+ <div class="es-build-field">
+ <label class="es-build-label">构建模式</label>
+ <select class="es-select" id="wechat-bundle">
+ <option value="subpackage" ${s.bundleMode === 'subpackage' ? 'selected' : ''}>分包模式(推荐)</option>
+ <option value="single" ${s.bundleMode === 'single' ? 'selected' : ''}>单包模式</option>
+ <option value="singleFile" ${s.bundleMode === 'singleFile' ? 'selected' : ''}>单文件模式(可玩广告)</option>
+ </select>
+ </div>
+ <div class="es-build-field">
+ <label class="es-build-label">输出目录</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>
+ `;
+ }
+
+ const platformName = config.platform === 'playable' ? '试玩平台' : '微信小游戏';
+
+ 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}设置</span>
+ </div>
+ <div class="es-build-collapse-content">
+ ${settingsHtml}
+ </div>
+ </div>
+ `;
+ }
+
+ 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 {
+ this.overlay_.querySelector('[data-action="close"]')?.addEventListener('click', () => {
+ this.close();
+ });
+
+ this.overlay_.addEventListener('click', (e) => {
+ const target = e.target as HTMLElement;
+
+ // Platform selection
+ 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();
+ this.setupEvents();
+ return;
+ }
+
+ // Config selection
+ 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();
+ this.setupEvents();
+ }
+ return;
+ }
+
+ // Collapse toggle
+ 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);
+ } else {
+ this.expandedSections_.add(section);
+ }
+ this.render();
+ this.setupEvents();
+ }
+ return;
+ }
+
+ // Action buttons
+ const actionEl = target.closest('[data-action]') as HTMLElement;
+ if (actionEl) {
+ const action = actionEl.dataset.action;
+ this.handleAction(action, actionEl);
+ }
+ });
+
+ // Input change events
+ this.overlay_.addEventListener('change', (e) => {
+ const target = e.target as HTMLInputElement | HTMLSelectElement;
+ this.handleInputChange(target);
+ });
+
+ // Escape key
+ const keyHandler = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ this.close();
+ document.removeEventListener('keydown', keyHandler);
+ }
+ };
+ document.addEventListener('keydown', keyHandler);
+ }
+
+ private handleAction(action: string | undefined, element: HTMLElement): 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 'add-current-scene':
+ if (config) {
+ const editor = (window as any).__esengine_editor;
+ const scenePath = editor?.currentScenePath;
+ if (scenePath && !config.scenes.includes(scenePath)) {
+ config.scenes.push(scenePath);
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ }
+ break;
+
+ case 'remove-scene': {
+ const index = parseInt(element.dataset.index ?? '-1', 10);
+ if (config && index >= 0) {
+ config.scenes.splice(index, 1);
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ 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);
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ break;
+ }
+
+ case 'remove-define': {
+ const index = parseInt(element.dataset.index ?? '-1', 10);
+ if (config && index >= 0) {
+ config.defines.splice(index, 1);
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ break;
+ }
+
+ case 'build':
+ if (config) {
+ this.handleBuild(config);
+ }
+ break;
+
+ case 'switch-config':
+ // Cycle to next config of same platform
+ if (config) {
+ const platformConfigs = this.settings_.configs.filter(
+ c => c.platform === config.platform
+ );
+ const idx = platformConfigs.findIndex(c => c.id === config.id);
+ const nextIdx = (idx + 1) % platformConfigs.length;
+ this.settings_.activeConfigId = platformConfigs[nextIdx].id;
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ break;
+
+ case 'browse-startup-scene':
+ this.browseFile('playable-startup-scene', '场景文件', ['scene']);
+ break;
+
+ case 'browse-output':
+ this.browseFile('playable-output', 'HTML文件', ['html']);
+ break;
+ }
+ }
+
+ private async browseFile(inputId: string, title: string, extensions: string[]): Promise<void> {
+ const fs = (window as any).__esengine_fs;
+ if (!fs?.showOpenDialog) return;
+
+ const result = await fs.showOpenDialog({
+ title: `选择${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;
+
+ // Playable settings
+ 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;
+ }
+ }
+
+ // WeChat settings
+ 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-bundle') {
+ config.wechatSettings.bundleMode = target.value as 'subpackage' | 'single' | 'singleFile';
+ } else if (id === 'wechat-output') {
+ config.wechatSettings.outputDir = target.value;
+ }
+ }
+
+ saveBuildSettings(this.settings_);
+ }
+
+ 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">添加构建配置</span>
+ <button class="es-dialog-close" data-action="cancel">&times;</button>
+ </div>
+ <div class="es-dialog-body">
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">配置名称</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">目标平台</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">取消</button>
+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="confirm">创建</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', () => {
+ 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;
+ saveBuildSettings(this.settings_);
+
+ close();
+ this.render();
+ this.setupEvents();
+ });
+ }
+
+ 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 ?? '';
+ }
+ saveBuildSettings(this.settings_);
+ this.render();
+ this.setupEvents();
+ }
+ }
+
+ private async handleBuild(config: BuildConfig): Promise<void> {
+ const buildBtn = this.overlay_.querySelector('[data-action="build"]') as HTMLButtonElement;
+ if (buildBtn) {
+ buildBtn.disabled = true;
+ buildBtn.innerHTML = `${icons.refresh(14)} 构建中...`;
+ }
+
+ try {
+ await this.options_.onBuild(config);
+ alert('构建完成!');
+ } catch (err) {
+ alert(`构建失败: ${err}`);
+ } finally {
+ if (buildBtn) {
+ buildBtn.disabled = false;
+ buildBtn.innerHTML = `${icons.play(14)} 构建`;
+ }
+ }
+ }
+
+ // =========================================================================
+ // Member Variables
+ // =========================================================================
+
+ private overlay_!: HTMLElement;
+ private options_!: BuildSettingsDialogOptions;
+ private settings_!: BuildSettings;
+ private expandedSections_: Set<string> = new Set(['scenes', 'defines', 'platform']);
+}
+
+// =============================================================================
+// Helper Function
+// =============================================================================
+
+export function showBuildSettingsDialog(options: BuildSettingsDialogOptions): BuildSettingsDialog {
+ return new BuildSettingsDialog(options);
+}
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
new file mode 100644
index 000000000..0f4ad7337
--- /dev/null
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -0,0 +1,482 @@
+/**
+ * @file PlayableBuilder.ts
+ * @brief Builder for playable ads (single HTML file output)
+ *
+ * Build Pipeline:
+ * 1. Load pre-built esengine.single.js (WASM module loader)
+ * 2. Compile user scripts to IIFE format (with esengine bundled)
+ * 3. Read startup scene JSON
+ * 4. Collect and inline assets as base64 data URLs
+ * 5. Assemble final HTML using scene-driven template
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import type { BuildResult, BuildContext } from './BuildService';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+interface NativeFS {
+ exists(path: string): Promise<boolean>;
+ readFile(path: string): Promise<string | null>;
+ readBinaryFile(path: string): Promise<Uint8Array | null>;
+ writeFile(path: string, content: string): Promise<boolean>;
+ listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;
+ createDirectory(path: string): Promise<boolean>;
+}
+
+// =============================================================================
+// Path Utilities
+// =============================================================================
+
+function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+function getProjectDir(projectPath: string): string {
+ const normalized = normalizePath(projectPath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+function getFileExtension(path: string): string {
+ const lastDot = path.lastIndexOf('.');
+ return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';
+}
+
+function isAbsolutePath(path: string): boolean {
+ return path.startsWith('/') || /^[a-zA-Z]:/.test(path);
+}
+
+function getDir(filePath: string): string {
+ const normalized = normalizePath(filePath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+// =============================================================================
+// MIME Types
+// =============================================================================
+
+const MIME_TYPES: Record<string, string> = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp',
+ svg: 'image/svg+xml',
+};
+
+// =============================================================================
+// HTML Template (Scene-Driven)
+// =============================================================================
+
+const HTML_TEMPLATE = `<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
+<meta name="ad.size" content="width=320,height=480">
+<title>Playable</title>
+<style>
+*{margin:0;padding:0;box-sizing:border-box}
+html,body{width:100%;height:100%;overflow:hidden;background:#000}
+#canvas{display:block;width:100%;height:100%;touch-action:none}
+</style>
+</head>
+<body>
+<canvas id="canvas"></canvas>
+<script>
+{{WASM_SDK}}
+</script>
+<script>
+{{GAME_CODE}}
+</script>
+<script>
+var __STARTUP_SCENE__={{SCENE_DATA}};
+(function(){
+ var c=document.getElementById('canvas');
+ function resize(){
+ var dpr=window.devicePixelRatio||1;
+ c.width=window.innerWidth*dpr;
+ c.height=window.innerHeight*dpr;
+ }
+ window.addEventListener('resize',resize);
+ resize();
+
+ ESEngineModule({
+ canvas:c,
+ print:function(t){console.log(t)},
+ printErr:function(t){console.error(t)}
+ }).then(function(Module){
+ var es=window.esengine;
+ if(!es||!es.createWebApp){
+ console.error('esengine not found');
+ return;
+ }
+ var app=es.createWebApp(Module);
+ var assetServer=new es.AssetServer(Module);
+ es.loadSceneWithAssets(app.world,__STARTUP_SCENE__,{assetServer:assetServer}).then(function(){
+ app.run();
+ });
+ }).catch(function(e){
+ if(e!=='unwind'&&(!e.message||!e.message.includes('unwind'))){
+ console.error('Failed:',e);
+ }
+ });
+})();
+</script>
+</body>
+</html>`;
+
+// =============================================================================
+// PlayableBuilder
+// =============================================================================
+
+export class PlayableBuilder {
+ constructor(context: BuildContext) {
+ this.context_ = context;
+ this.fs_ = (window as any).__esengine_fs ?? null;
+ this.projectDir_ = getProjectDir(context.projectPath);
+ }
+
+ // =========================================================================
+ // Public Methods
+ // =========================================================================
+
+ async build(): Promise<BuildResult> {
+ if (!this.fs_) {
+ return { success: false, error: 'Native file system not available' };
+ }
+
+ const settings = this.context_.config.playableSettings;
+ if (!settings) {
+ return { success: false, error: 'Playable settings not configured' };
+ }
+
+ const startupScene = settings.startupScene || this.context_.config.scenes[0];
+ if (!startupScene) {
+ return { success: false, error: 'No startup scene configured. Add a scene to the build or set a startup scene.' };
+ }
+
+ console.log('[PlayableBuilder] Starting build...');
+
+ try {
+ // 1. Load SDK
+ const wasmSdk = await this.loadSdk();
+ if (!wasmSdk) {
+ return {
+ success: false,
+ error: "SDK not found. Please run 'scripts/build-web-single.bat' first.",
+ };
+ }
+ console.log(`[PlayableBuilder] SDK loaded: ${wasmSdk.length} bytes`);
+
+ // 2. Compile user scripts
+ const gameCode = await this.compileUserScripts();
+ console.log(`[PlayableBuilder] Scripts compiled: ${gameCode.length} bytes`);
+
+ // 3. Read startup scene
+ const scenePath = this.resolveScenePath(startupScene);
+ const sceneContent = await this.fs_.readFile(scenePath);
+ if (!sceneContent) {
+ return { success: false, error: `Startup scene not found: ${scenePath}` };
+ }
+ console.log(`[PlayableBuilder] Scene loaded: ${scenePath}`);
+
+ // 4. Collect and inline assets
+ const assets = await this.collectAssets();
+ console.log(`[PlayableBuilder] Collected ${assets.size} assets`);
+
+ const gameCodeWithAssets = this.inlineAssets(gameCode, assets);
+ const sceneDataWithAssets = this.inlineAssets(sceneContent, assets);
+
+ // 5. Assemble HTML
+ const html = this.assembleHTML(wasmSdk, gameCodeWithAssets, sceneDataWithAssets);
+ console.log(`[PlayableBuilder] HTML assembled: ${html.length} bytes`);
+
+ // 6. Write output
+ const outputPath = this.resolveOutputPath(settings.outputPath);
+ const outputDir = getDir(outputPath);
+
+ await this.fs_.createDirectory(outputDir);
+ const success = await this.fs_.writeFile(outputPath, html);
+
+ if (success) {
+ console.log(`[PlayableBuilder] Build successful: ${outputPath}`);
+ return { success: true, outputPath };
+ } else {
+ return { success: false, error: 'Failed to write output file' };
+ }
+ } catch (err) {
+ console.error('[PlayableBuilder] Build error:', err);
+ return { success: false, error: String(err) };
+ }
+ }
+
+ // =========================================================================
+ // Private Methods
+ // =========================================================================
+
+ private async loadSdk(): Promise<string | null> {
+ try {
+ const response = await fetch('/esengine.single.js');
+ if (!response.ok) return null;
+ return await response.text();
+ } catch {
+ return null;
+ }
+ }
+
+ private resolveScenePath(scenePath: string): string {
+ if (isAbsolutePath(scenePath)) {
+ return normalizePath(scenePath);
+ }
+ return joinPath(this.projectDir_, scenePath);
+ }
+
+ private resolveOutputPath(outputPath: string): string {
+ if (isAbsolutePath(outputPath)) {
+ return normalizePath(outputPath);
+ }
+ return joinPath(this.projectDir_, outputPath);
+ }
+
+ private async compileUserScripts(): Promise<string> {
+ const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+
+ if (!await this.fs_!.exists(scriptsPath)) {
+ return this.createMinimalGameCode();
+ }
+
+ const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);
+ const scripts = entries
+ .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
+ .map(e => joinPath(scriptsPath, e.name));
+
+ if (scripts.length === 0) {
+ return this.createMinimalGameCode();
+ }
+
+ // Generate entry content that:
+ // 1. Imports esengine and exposes it globally
+ // 2. Imports all user scripts (to register components)
+ const imports = scripts.map(p => `import "${p}";`).join('\n');
+ const entryContent = `
+import * as esengine from 'esengine';
+(window as any).esengine = esengine;
+${imports}
+`;
+
+ console.log('[PlayableBuilder] Compiling scripts...');
+
+ const settings = this.context_.config.playableSettings!;
+ const defines: Record<string, string> = {};
+ for (const def of this.context_.config.defines) {
+ defines[`process.env.${def}`] = 'true';
+ }
+
+ await this.initializeEsbuild();
+
+ const result = await esbuild.build({
+ stdin: {
+ contents: entryContent,
+ loader: 'ts',
+ resolveDir: scriptsPath,
+ },
+ bundle: true,
+ format: 'iife',
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ minify: settings.minifyCode,
+ define: defines,
+ plugins: [this.createVirtualFsPlugin()],
+ });
+
+ return result.outputFiles?.[0]?.text ?? this.createMinimalGameCode();
+ }
+
+ private createMinimalGameCode(): string {
+ return `
+(function(){
+ var esengine = window.esengine || {};
+ // Minimal esengine stub if no user scripts
+})();
+`;
+ }
+
+ private async initializeEsbuild(): Promise<void> {
+ try {
+ await esbuild.initialize({
+ wasmURL: 'https://cdn.jsdelivr.net/npm/[email protected]/esbuild.wasm',
+ });
+ } catch (err) {
+ if (!String(err).includes('Cannot call "initialize" more than once')) {
+ throw err;
+ }
+ }
+ }
+
+ private createVirtualFsPlugin(): esbuild.Plugin {
+ const fs = this.fs_!;
+ const projectDir = this.projectDir_;
+
+ return {
+ name: 'virtual-fs',
+ setup(build) {
+ build.onResolve({ filter: /.*/ }, async (args) => {
+ if (args.kind === 'entry-point') {
+ return { path: args.path, namespace: 'virtual' };
+ }
+
+ let resolvedPath = args.path;
+
+ if (isAbsolutePath(args.path)) {
+ resolvedPath = normalizePath(args.path);
+ } else if (args.path.startsWith('.')) {
+ const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
+ resolvedPath = joinPath(baseDir, args.path);
+ } else {
+ const pkgPath = joinPath(projectDir, 'node_modules', args.path, 'package.json');
+ const pkgContent = await fs.readFile(pkgPath);
+ if (pkgContent) {
+ try {
+ const pkg = JSON.parse(pkgContent);
+ let entry = pkg.module || pkg.main || 'index.js';
+ if (pkg.exports) {
+ const root = pkg.exports['.'];
+ if (typeof root === 'string') {
+ entry = root;
+ } else if (root?.import) {
+ entry = root.import;
+ } else if (root?.default) {
+ entry = root.default;
+ }
+ }
+ resolvedPath = joinPath(projectDir, 'node_modules', args.path, entry);
+ } catch {
+ resolvedPath = joinPath(projectDir, 'node_modules', args.path, 'index.js');
+ }
+ } else {
+ resolvedPath = joinPath(projectDir, 'node_modules', args.path);
+ }
+ }
+
+ if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {
+ if (await fs.exists(resolvedPath + '.ts')) {
+ resolvedPath += '.ts';
+ } else if (await fs.exists(resolvedPath + '.js')) {
+ resolvedPath += '.js';
+ } else if (await fs.exists(joinPath(resolvedPath, 'index.ts'))) {
+ resolvedPath = joinPath(resolvedPath, 'index.ts');
+ } else if (await fs.exists(joinPath(resolvedPath, 'index.js'))) {
+ resolvedPath = joinPath(resolvedPath, 'index.js');
+ } else {
+ resolvedPath += '.ts';
+ }
+ }
+
+ return { path: resolvedPath, namespace: 'virtual' };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {
+ const content = await fs.readFile(args.path);
+ if (content === null) {
+ return { contents: '', loader: 'ts' };
+ }
+ const loader = args.path.endsWith('.ts') ? 'ts' : 'js';
+ return { contents: content, loader };
+ });
+ },
+ };
+ }
+
+ private async collectAssets(): Promise<Map<string, string>> {
+ const assets = new Map<string, string>();
+ const texturesPath = joinPath(this.projectDir_, 'assets/textures');
+
+ if (await this.fs_!.exists(texturesPath)) {
+ await this.collectAssetsRecursive(texturesPath, '', assets);
+ }
+
+ return assets;
+ }
+
+ private async collectAssetsRecursive(
+ dirPath: string,
+ relativePath: string,
+ assets: Map<string, string>
+ ): Promise<void> {
+ const entries = await this.fs_!.listDirectoryDetailed(dirPath);
+
+ for (const entry of entries) {
+ const fullPath = joinPath(dirPath, entry.name);
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
+
+ if (entry.isDirectory) {
+ await this.collectAssetsRecursive(fullPath, entryRelativePath, assets);
+ } else {
+ const ext = getFileExtension(entry.name);
+ const mimeType = MIME_TYPES[ext];
+
+ if (mimeType) {
+ const binary = await this.fs_!.readBinaryFile(fullPath);
+ if (binary) {
+ const base64 = this.arrayBufferToBase64(binary);
+ const dataUrl = `data:${mimeType};base64,${base64}`;
+ assets.set(entryRelativePath, dataUrl);
+ }
+ }
+ }
+ }
+ }
+
+ private inlineAssets(code: string, assets: Map<string, string>): string {
+ let result = code;
+
+ for (const [relativePath, dataUrl] of assets) {
+ const pathVariants = [
+ `assets/textures/${relativePath}`,
+ `assets/${relativePath}`,
+ relativePath,
+ ];
+
+ for (const pathVariant of pathVariants) {
+ result = result.split(`'${pathVariant}'`).join(`'${dataUrl}'`);
+ result = result.split(`"${pathVariant}"`).join(`"${dataUrl}"`);
+ }
+ }
+
+ return result;
+ }
+
+ private assembleHTML(wasmSdk: string, gameCode: string, sceneData: string): string {
+ return HTML_TEMPLATE
+ .replace('{{WASM_SDK}}', wasmSdk)
+ .replace('{{GAME_CODE}}', gameCode)
+ .replace('{{SCENE_DATA}}', sceneData);
+ }
+
+ private arrayBufferToBase64(buffer: Uint8Array): string {
+ let binary = '';
+ const bytes = new Uint8Array(buffer);
+ for (let i = 0; i < bytes.byteLength; i++) {
+ binary += String.fromCharCode(bytes[i]);
+ }
+ return btoa(binary);
+ }
+
+ // =========================================================================
+ // Member Variables
+ // =========================================================================
+
+ private context_: BuildContext;
+ private fs_: NativeFS | null;
+ private projectDir_: string;
+}
diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.ts
new file mode 100644
index 000000000..3542b3ce7
--- /dev/null
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -0,0 +1,382 @@
+/**
+ * @file WeChatBuilder.ts
+ * @brief Builder for WeChat Mini Game platform
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import type { BuildResult, BuildContext } from './BuildService';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+interface NativeFS {
+ exists(path: string): Promise<boolean>;
+ readFile(path: string): Promise<string | null>;
+ readBinaryFile(path: string): Promise<Uint8Array | null>;
+ writeFile(path: string, content: string): Promise<boolean>;
+ writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;
+ copyFile(src: string, dest: string): Promise<boolean>;
+ listDirectoryDetailed(path: string): Promise<Array<{ name: string; isDirectory: boolean }>>;
+ createDirectory(path: string): Promise<boolean>;
+}
+
+// =============================================================================
+// Path Utilities
+// =============================================================================
+
+function normalizePath(path: string): string {
+ return path.replace(/\\/g, '/');
+}
+
+function joinPath(...parts: string[]): string {
+ return normalizePath(parts.join('/').replace(/\/+/g, '/'));
+}
+
+function getProjectDir(projectPath: string): string {
+ const normalized = normalizePath(projectPath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+}
+
+function getFileExtension(path: string): string {
+ const lastDot = path.lastIndexOf('.');
+ return lastDot > 0 ? path.substring(lastDot + 1).toLowerCase() : '';
+}
+
+// =============================================================================
+// WeChatBuilder
+// =============================================================================
+
+export class WeChatBuilder {
+ private context_: BuildContext;
+ private fs_: NativeFS | null;
+ private projectDir_: string;
+
+ constructor(context: BuildContext) {
+ this.context_ = context;
+ this.fs_ = (window as any).__esengine_fs ?? null;
+ this.projectDir_ = getProjectDir(context.projectPath);
+ }
+
+ async build(): Promise<BuildResult> {
+ if (!this.fs_) {
+ return { success: false, error: 'Native file system not available' };
+ }
+
+ const settings = this.context_.config.wechatSettings;
+ if (!settings) {
+ return { success: false, error: 'WeChat settings not configured' };
+ }
+
+ console.log('[WeChatBuilder] Starting build...');
+
+ try {
+ const outputDir = joinPath(this.projectDir_, settings.outputDir);
+
+ // Create output directory
+ await this.fs_.createDirectory(outputDir);
+
+ // 1. Generate project.config.json
+ await this.generateProjectConfig(outputDir, settings);
+ console.log('[WeChatBuilder] Generated project.config.json');
+
+ // 2. Generate game.json
+ await this.generateGameJson(outputDir);
+ console.log('[WeChatBuilder] Generated game.json');
+
+ // 3. Compile and generate game.js
+ await this.generateGameJs(outputDir);
+ console.log('[WeChatBuilder] Generated game.js');
+
+ // 4. Copy scenes
+ await this.copyScenes(outputDir);
+ console.log('[WeChatBuilder] Copied scenes');
+
+ // 5. Copy assets
+ await this.copyAssets(outputDir);
+ console.log('[WeChatBuilder] Copied assets');
+
+ console.log(`[WeChatBuilder] Build successful: ${outputDir}`);
+ return { success: true, outputPath: outputDir };
+ } catch (err) {
+ console.error('[WeChatBuilder] Build error:', err);
+ return { success: false, error: String(err) };
+ }
+ }
+
+ private async generateProjectConfig(
+ outputDir: string,
+ settings: NonNullable<typeof this.context_.config.wechatSettings>
+ ): Promise<void> {
+ const config = {
+ description: 'ESEngine Game',
+ packOptions: {
+ ignore: [],
+ include: [],
+ },
+ setting: {
+ urlCheck: false,
+ es6: true,
+ enhance: true,
+ compileHotReLoad: false,
+ postcss: false,
+ preloadBackgroundData: false,
+ minified: !this.context_.config.defines.includes('DEBUG'),
+ newFeature: true,
+ coverView: true,
+ nodeModules: false,
+ autoAudits: false,
+ showShadowRootInWxmlPanel: true,
+ scopeDataCheck: false,
+ uglifyFileName: false,
+ checkInvalidKey: true,
+ checkSiteMap: true,
+ uploadWithSourceMap: true,
+ compileWorklet: false,
+ babelSetting: {
+ ignore: [],
+ disablePlugins: [],
+ outputPath: '',
+ },
+ },
+ compileType: 'game',
+ libVersion: '3.0.0',
+ appid: settings.appId || 'touristappid',
+ projectname: 'ESEngineGame',
+ condition: {},
+ editorSetting: {
+ tabIndent: 'auto',
+ tabSize: 4,
+ },
+ };
+
+ await this.fs_!.writeFile(
+ joinPath(outputDir, 'project.config.json'),
+ JSON.stringify(config, null, 2)
+ );
+ }
+
+ private async generateGameJson(outputDir: string): Promise<void> {
+ const gameJson = {
+ deviceOrientation: 'portrait',
+ showStatusBar: false,
+ networkTimeout: {
+ request: 10000,
+ connectSocket: 10000,
+ uploadFile: 10000,
+ downloadFile: 10000,
+ },
+ subpackages: [],
+ };
+
+ await this.fs_!.writeFile(
+ joinPath(outputDir, 'game.json'),
+ JSON.stringify(gameJson, null, 2)
+ );
+ }
+
+ private async generateGameJs(outputDir: string): Promise<void> {
+ const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');
+
+ let userCode = '';
+ if (await this.fs_!.exists(scriptsPath)) {
+ const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);
+ const scripts = entries
+ .filter(e => !e.isDirectory && e.name.endsWith('.ts'))
+ .map(e => joinPath(scriptsPath, e.name));
+
+ if (scripts.length > 0) {
+ userCode = await this.compileScripts(scripts);
+ }
+ }
+
+ const gameJs = `
+// ESEngine WeChat Mini Game Entry
+require('./esengine/index.js');
+
+// Load scenes
+const scenes = [];
+${this.context_.config.scenes.map((s, i) => {
+ const name = s.replace(/.*\//, '').replace('.esscene', '');
+ return `scenes.push({ name: '${name}', path: 'scenes/${name}.json' });`;
+}).join('\n')}
+
+// Initialize game
+(async function() {
+ const canvas = wx.createCanvas();
+
+ // User scripts
+ ${userCode}
+
+ // Start engine
+ if (typeof ESEngine !== 'undefined' && ESEngine.init) {
+ await ESEngine.init({
+ canvas: canvas,
+ platform: 'wechat',
+ scenes: scenes,
+ });
+ }
+})();
+`;
+
+ await this.fs_!.writeFile(joinPath(outputDir, 'game.js'), gameJs);
+
+ // Create esengine directory and placeholder
+ await this.fs_!.createDirectory(joinPath(outputDir, 'esengine'));
+ await this.fs_!.writeFile(
+ joinPath(outputDir, 'esengine/index.js'),
+ '// ESEngine runtime for WeChat Mini Game\nmodule.exports = {};\n'
+ );
+ }
+
+ private async compileScripts(scripts: string[]): Promise<string> {
+ const entryContent = scripts.map(p => `import "${p}";`).join('\n');
+
+ const defines: Record<string, string> = {};
+ for (const def of this.context_.config.defines) {
+ defines[`process.env.${def}`] = 'true';
+ }
+
+ try {
+ await esbuild.initialize({
+ wasmURL: 'https://cdn.jsdelivr.net/npm/[email protected]/esbuild.wasm',
+ });
+ } catch (err) {
+ if (!String(err).includes('Cannot call "initialize" more than once')) {
+ throw err;
+ }
+ }
+
+ const result = await esbuild.build({
+ stdin: {
+ contents: entryContent,
+ loader: 'ts',
+ resolveDir: joinPath(this.projectDir_, 'assets/scripts'),
+ },
+ bundle: true,
+ format: 'iife',
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ minify: !this.context_.config.defines.includes('DEBUG'),
+ define: defines,
+ plugins: [this.createVirtualFsPlugin()],
+ });
+
+ return result.outputFiles?.[0]?.text ?? '';
+ }
+
+ private createVirtualFsPlugin(): esbuild.Plugin {
+ const fs = this.fs_!;
+ const projectDir = this.projectDir_;
+
+ const isAbsolutePath = (p: string): boolean => {
+ return p.startsWith('/') || /^[a-zA-Z]:/.test(p);
+ };
+
+ const getDir = (filePath: string): string => {
+ const normalized = normalizePath(filePath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash > 0 ? normalized.substring(0, lastSlash) : normalized;
+ };
+
+ return {
+ name: 'virtual-fs',
+ setup(build) {
+ // Mark esengine as external for WeChat (will use require)
+ build.onResolve({ filter: /^esengine$/ }, () => {
+ return { path: 'esengine', external: true };
+ });
+
+ build.onResolve({ filter: /.*/ }, (args) => {
+ if (args.kind === 'entry-point') {
+ return { path: args.path, namespace: 'virtual' };
+ }
+
+ let resolvedPath = args.path;
+
+ if (isAbsolutePath(args.path)) {
+ resolvedPath = normalizePath(args.path);
+ } else if (args.path.startsWith('.')) {
+ const baseDir = args.importer ? getDir(args.importer) : args.resolveDir;
+ resolvedPath = joinPath(baseDir, args.path);
+ } else {
+ resolvedPath = joinPath(projectDir, 'node_modules', args.path);
+ }
+
+ if (!resolvedPath.endsWith('.ts') && !resolvedPath.endsWith('.js')) {
+ resolvedPath += '.ts';
+ }
+
+ return { path: resolvedPath, namespace: 'virtual' };
+ });
+
+ build.onLoad({ filter: /.*/, namespace: 'virtual' }, async (args) => {
+ const content = await fs.readFile(args.path);
+ if (content === null) {
+ return { contents: '', loader: 'ts' };
+ }
+ const loader = args.path.endsWith('.ts') ? 'ts' : 'js';
+ return { contents: content, loader };
+ });
+ },
+ };
+ }
+
+ private async copyScenes(outputDir: string): Promise<void> {
+ const scenesDir = joinPath(outputDir, 'scenes');
+ await this.fs_!.createDirectory(scenesDir);
+
+ for (const scenePath of this.context_.config.scenes) {
+ const fullPath = scenePath.startsWith('/')
+ ? scenePath
+ : joinPath(this.projectDir_, scenePath);
+
+ const content = await this.fs_!.readFile(fullPath);
+ if (content) {
+ const name = scenePath.replace(/.*\//, '').replace('.esscene', '');
+ await this.fs_!.writeFile(joinPath(scenesDir, `${name}.json`), content);
+ }
+ }
+ }
+
+ private async copyAssets(outputDir: string): Promise<void> {
+ const srcTexturesPath = joinPath(this.projectDir_, 'assets/textures');
+ const destTexturesPath = joinPath(outputDir, 'assets/textures');
+
+ if (await this.fs_!.exists(srcTexturesPath)) {
+ await this.copyDirectoryRecursive(srcTexturesPath, destTexturesPath);
+ }
+
+ const srcAudioPath = joinPath(this.projectDir_, 'assets/audio');
+ const destAudioPath = joinPath(outputDir, 'assets/audio');
+
+ if (await this.fs_!.exists(srcAudioPath)) {
+ await this.copyDirectoryRecursive(srcAudioPath, destAudioPath);
+ }
+ }
+
+ private async copyDirectoryRecursive(srcDir: string, destDir: string): Promise<void> {
+ await this.fs_!.createDirectory(destDir);
+
+ const entries = await this.fs_!.listDirectoryDetailed(srcDir);
+
+ for (const entry of entries) {
+ const srcPath = joinPath(srcDir, entry.name);
+ const destPath = joinPath(destDir, entry.name);
+
+ if (entry.isDirectory) {
+ await this.copyDirectoryRecursive(srcPath, destPath);
+ } else {
+ const ext = getFileExtension(entry.name);
+ if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'mp3', 'wav', 'ogg'].includes(ext)) {
+ const data = await this.fs_!.readBinaryFile(srcPath);
+ if (data) {
+ await this.fs_!.writeBinaryFile(destPath, data);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.ts
new file mode 100644
index 000000000..4a4932ad2
--- /dev/null
+++ b/editor/src/builder/index.ts
@@ -0,0 +1,9 @@
+/**
+ * @file index.ts
+ * @brief Builder module exports
+ */
+
+export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';
+export { BuildService, type BuildResult, type BuildContext } from './BuildService';
+export { PlayableBuilder } from './PlayableBuilder';
+export { WeChatBuilder } from './WeChatBuilder';
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index 88b9e9d0b..72d4dbaca 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -1,12 +1,11 @@
/**
* @file ScriptLoader.ts
- * @brief Load and compile user TypeScript scripts
+ * @brief Load and compile user TypeScript scripts for preview
*/
import * as esbuild from 'esbuild-wasm/esm/browser';
import { virtualFsPlugin } from './esbuildPlugins';
import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
-import { clearScriptComponents } from '../schemas/ComponentSchemas';
// =============================================================================
// Path Utilities
@@ -39,13 +38,6 @@ function getNativeFS(): NativeFS | null {
// =============================================================================
export class ScriptLoader {
- private projectPath_: string;
- private projectDir_: string;
- private initialized_ = false;
- private lastCompiledCode_: string | null = null;
- private onCompileError_?: (errors: CompileError[]) => void;
- private onCompileSuccess_?: () => void;
-
constructor(options: ScriptLoaderOptions) {
this.projectPath_ = normalizePath(options.projectPath);
this.projectDir_ = getProjectDir(this.projectPath_);
@@ -53,8 +45,12 @@ export class ScriptLoader {
this.onCompileSuccess_ = options.onCompileSuccess;
}
+ // =========================================================================
+ // Public Methods
+ // =========================================================================
+
getCompiledCode(): string | null {
- return this.lastCompiledCode_;
+ return this.lastCompiled_;
}
async initialize(): Promise<void> {
@@ -99,7 +95,7 @@ export class ScriptLoader {
}
}
- async compileAndExecute(): Promise<boolean> {
+ async compile(): Promise<boolean> {
const fs = getNativeFS();
if (!fs) {
console.warn('ScriptLoader: NativeFS not available');
@@ -109,13 +105,12 @@ export class ScriptLoader {
const scripts = await this.discoverScripts();
if (scripts.length === 0) {
console.log('ScriptLoader: No scripts found');
+ this.lastCompiled_ = null;
return true;
}
console.log('ScriptLoader: Compiling scripts:', scripts);
- clearScriptComponents();
-
try {
const entryContent = scripts
.map(p => `import "${p}";`)
@@ -128,10 +123,11 @@ export class ScriptLoader {
resolveDir: joinPath(this.projectDir_, 'assets/scripts'),
},
bundle: true,
- format: 'iife',
+ format: 'esm',
write: false,
platform: 'browser',
target: 'es2020',
+ external: ['esengine'],
plugins: [
virtualFsPlugin({
fs,
@@ -152,15 +148,8 @@ export class ScriptLoader {
return false;
}
- const code = result.outputFiles?.[0]?.text;
- if (!code) {
- console.error('ScriptLoader: No output generated');
- return false;
- }
-
- this.lastCompiledCode_ = code;
- this.executeScript(code);
- console.log('ScriptLoader: Scripts loaded successfully');
+ this.lastCompiled_ = result.outputFiles?.[0]?.text ?? null;
+ console.log('ScriptLoader: Scripts compiled successfully');
this.onCompileSuccess_?.();
return true;
} catch (err) {
@@ -176,17 +165,18 @@ export class ScriptLoader {
}
}
- private executeScript(code: string): void {
- try {
- const fn = new Function(code);
- fn();
- } catch (err) {
- console.error('ScriptLoader: Script execution error:', err);
- throw err;
- }
- }
-
async reload(): Promise<boolean> {
- return this.compileAndExecute();
+ return this.compile();
}
+
+ // =========================================================================
+ // Member Variables
+ // =========================================================================
+
+ private projectPath_: string;
+ private projectDir_: string;
+ private initialized_ = false;
+ private lastCompiled_: string | null = null;
+ private onCompileError_?: (errors: CompileError[]) => void;
+ private onCompileSuccess_?: () => void;
}
diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.css
index 0667f1b05..a6d478712 100644
--- a/editor/src/styles/editor.css
+++ b/editor/src/styles/editor.css
@@ -2418,3 +2418,483 @@ svg {
.es-btn-locate {
flex-shrink: 0;
}
+
+/* =============================================================================
+ * Build Settings Dialog
+ * ============================================================================= */
+
+.es-build-dialog {
+ width: 90%;
+ max-width: 800px;
+ max-height: 80vh;
+ background: var(--es-bg-secondary);
+ border: 1px solid var(--es-border);
+ border-radius: 6px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.es-build-toolbar {
+ display: flex;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--es-border);
+ background: var(--es-bg-tertiary);
+}
+
+.es-build-toolbar .es-btn {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 10px;
+ font-size: 12px;
+}
+
+.es-build-body {
+ display: flex;
+ flex: 1;
+ min-height: 400px;
+ max-height: 60vh;
+ overflow: hidden;
+}
+
+.es-build-sidebar {
+ width: 200px;
+ flex-shrink: 0;
+ background: var(--es-bg-primary);
+ border-right: 1px solid var(--es-border);
+ overflow-y: auto;
+ padding: 8px 0;
+}
+
+.es-build-section-title {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--es-text-secondary);
+ text-transform: uppercase;
+ padding: 8px 12px 4px;
+ letter-spacing: 0.5px;
+}
+
+.es-build-platform {
+ padding: 8px 12px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ color: var(--es-text-primary);
+ transition: background 0.15s;
+}
+
+.es-build-platform:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-build-platform.es-active {
+ background: var(--es-bg-tertiary);
+}
+
+.es-build-platform-header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex: 1;
+}
+
+.es-build-badge {
+ font-size: 10px;
+ padding: 2px 6px;
+ background: var(--es-accent);
+ color: white;
+ border-radius: 3px;
+ margin-left: auto;
+}
+
+.es-build-config-item {
+ padding: 6px 12px 6px 32px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ cursor: pointer;
+ color: var(--es-text-secondary);
+ font-size: 12px;
+ transition: background 0.15s, color 0.15s;
+}
+
+.es-build-config-item:hover {
+ background: var(--es-bg-hover);
+ color: var(--es-text-primary);
+}
+
+.es-build-config-item.es-active {
+ background: var(--es-bg-tertiary);
+ color: var(--es-text-primary);
+}
+
+.es-build-config-item.es-active::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ width: 3px;
+ top: 0;
+ bottom: 0;
+ background: var(--es-accent);
+}
+
+.es-build-config-name {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-build-config-delete {
+ opacity: 0;
+ transition: opacity 0.15s;
+ color: var(--es-text-secondary);
+ padding: 2px;
+}
+
+.es-build-config-item:hover .es-build-config-delete {
+ opacity: 1;
+}
+
+.es-build-config-delete:hover {
+ color: var(--es-danger);
+}
+
+.es-build-detail {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ overflow-y: auto;
+ padding: 16px;
+}
+
+.es-build-detail-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding-bottom: 16px;
+ border-bottom: 1px solid var(--es-border);
+ margin-bottom: 16px;
+}
+
+.es-build-detail-title h3 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ color: var(--es-text-primary);
+}
+
+.es-build-detail-platform {
+ font-size: 12px;
+ color: var(--es-text-secondary);
+}
+
+.es-build-detail-actions {
+ display: flex;
+ gap: 8px;
+}
+
+.es-build-detail-actions .es-btn {
+ padding: 6px 12px;
+ font-size: 12px;
+}
+
+.es-build-detail-actions .es-btn-primary {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.es-build-detail-content {
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+}
+
+.es-build-data-section h4,
+.es-build-settings-section h4 {
+ margin: 0 0 12px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--es-text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.es-build-collapse {
+ border: 1px solid var(--es-border);
+ border-radius: 4px;
+ overflow: hidden;
+ margin-bottom: 8px;
+}
+
+.es-build-collapse-header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 12px;
+ background: var(--es-bg-tertiary);
+ cursor: pointer;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--es-text-primary);
+ transition: background 0.15s;
+}
+
+.es-build-collapse-header:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-build-collapse-content {
+ display: none;
+ padding: 12px;
+ background: var(--es-bg-primary);
+}
+
+.es-build-collapse.es-expanded .es-build-collapse-content {
+ display: block;
+}
+
+.es-build-scene-list {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-bottom: 8px;
+}
+
+.es-build-scene-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ background: var(--es-bg-secondary);
+ border-radius: 3px;
+ font-size: 12px;
+}
+
+.es-build-scene-item input[type="checkbox"] {
+ flex-shrink: 0;
+}
+
+.es-build-scene-item span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--es-text-primary);
+}
+
+.es-build-scene-item .es-btn-icon {
+ opacity: 0;
+ transition: opacity 0.15s;
+}
+
+.es-build-scene-item:hover .es-btn-icon {
+ opacity: 1;
+}
+
+.es-build-empty-list {
+ text-align: center;
+ color: var(--es-text-secondary);
+ font-size: 12px;
+ padding: 12px;
+}
+
+.es-build-define-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 8px;
+}
+
+.es-build-define-item {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ background: var(--es-bg-secondary);
+ border-radius: 3px;
+ font-size: 11px;
+ font-family: monospace;
+ color: var(--es-accent);
+}
+
+.es-build-define-item .es-btn-icon {
+ padding: 2px;
+ opacity: 0.6;
+}
+
+.es-build-define-item:hover .es-btn-icon {
+ opacity: 1;
+}
+
+.es-build-define-add {
+ display: flex;
+ gap: 6px;
+}
+
+.es-build-define-add .es-input {
+ flex: 1;
+ min-width: 0;
+ padding: 4px 8px;
+ font-size: 12px;
+}
+
+.es-build-field {
+ margin-bottom: 12px;
+}
+
+.es-build-field:last-child {
+ margin-bottom: 0;
+}
+
+.es-build-field label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ color: var(--es-text-primary);
+ cursor: pointer;
+}
+
+.es-build-field input[type="checkbox"] {
+ width: 14px;
+ height: 14px;
+}
+
+.es-build-label {
+ display: block;
+ margin-bottom: 4px;
+ font-size: 12px;
+ color: var(--es-text-secondary);
+}
+
+.es-build-path-row {
+ display: flex;
+ gap: 6px;
+}
+
+.es-build-path-row .es-input {
+ flex: 1;
+ min-width: 0;
+}
+
+.es-build-path-row .es-btn {
+ flex-shrink: 0;
+ padding: 6px 10px;
+}
+
+.es-build-hint {
+ margin-top: 4px;
+ font-size: 11px;
+ color: var(--es-text-tertiary);
+}
+
+.es-build-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 200px;
+ color: var(--es-text-secondary);
+ text-align: center;
+}
+
+.es-build-empty p {
+ margin: 4px 0;
+ font-size: 13px;
+}
+
+.es-build-add-dialog {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background: rgba(0, 0, 0, 0.5);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.es-build-dialog .es-input {
+ padding: 6px 10px;
+ border-radius: 3px;
+ font-size: 12px;
+}
+
+.es-build-dialog .es-select {
+ width: 100%;
+ padding: 6px 10px;
+ background: var(--es-bg-primary);
+ border: 1px solid var(--es-border);
+ border-radius: 3px;
+ color: var(--es-text-primary);
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.es-build-dialog .es-select:focus {
+ outline: none;
+ border-color: var(--es-accent);
+}
+
+.es-build-dialog .es-btn {
+ border-radius: 3px;
+}
+
+.es-build-dialog .es-btn-primary {
+ background: var(--es-accent);
+ border-color: var(--es-accent);
+ color: white;
+}
+
+.es-build-dialog .es-btn-primary:hover {
+ background: #3d9ee0;
+ border-color: #3d9ee0;
+}
+
+.es-btn-link {
+ background: none;
+ border: none;
+ color: var(--es-accent);
+ font-size: 12px;
+ cursor: pointer;
+ padding: 4px 0;
+ text-decoration: underline;
+}
+
+.es-btn-link:hover {
+ color: #3d9ee0;
+}
+
+.es-build-dialog .es-btn-icon {
+ background: transparent;
+ border: none;
+ color: var(--es-text-secondary);
+ padding: 4px;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 3px;
+}
+
+.es-build-dialog .es-btn-icon:hover {
+ background: var(--es-bg-hover);
+ color: var(--es-text-primary);
+}
+
+.es-build-define-add .es-btn-icon {
+ background: var(--es-bg-tertiary);
+ border: 1px solid var(--es-border);
+}
+
+.es-build-define-add .es-btn-icon:hover {
+ background: var(--es-bg-hover);
+}
diff --git a/editor/src/types/BuildTypes.ts b/editor/src/types/BuildTypes.ts
new file mode 100644
index 000000000..34281748b
--- /dev/null
+++ b/editor/src/types/BuildTypes.ts
@@ -0,0 +1,168 @@
+/**
+ * @file BuildTypes.ts
+ * @brief Build configuration type definitions
+ */
+
+// =============================================================================
+// Platform Types
+// =============================================================================
+
+export type BuildPlatform = 'playable' | 'wechat';
+
+export interface PlatformInfo {
+ id: BuildPlatform;
+ name: string;
+ icon: string;
+}
+
+export const PLATFORMS: PlatformInfo[] = [
+ { id: 'playable', name: '试玩平台', icon: 'play' },
+ { id: 'wechat', name: '微信小游戏', icon: 'box' },
+];
+
+// =============================================================================
+// Platform Settings
+// =============================================================================
+
+export interface PlayableSettings {
+ startupScene: string;
+ isDevelopment: boolean;
+ minifyCode: boolean;
+ embedFonts: boolean;
+ outputPath: string;
+}
+
+export interface WeChatSettings {
+ appId: string;
+ version: string;
+ bundleMode: 'subpackage' | 'single' | 'singleFile';
+ outputDir: string;
+}
+
+// =============================================================================
+// Build Configuration
+// =============================================================================
+
+export interface BuildConfig {
+ id: string;
+ name: string;
+ platform: BuildPlatform;
+ scenes: string[];
+ defines: string[];
+ playableSettings?: PlayableSettings;
+ wechatSettings?: WeChatSettings;
+}
+
+export interface BuildSettings {
+ activePlatform: BuildPlatform;
+ activeConfigId: string;
+ configs: BuildConfig[];
+}
+
+// =============================================================================
+// Default Values
+// =============================================================================
+
+export function createDefaultPlayableSettings(): PlayableSettings {
+ return {
+ startupScene: '',
+ isDevelopment: true,
+ minifyCode: false,
+ embedFonts: true,
+ outputPath: 'build/playable.html',
+ };
+}
+
+export function createDefaultWeChatSettings(): WeChatSettings {
+ return {
+ appId: '',
+ version: '1.0.0',
+ bundleMode: 'subpackage',
+ outputDir: 'build/wechat',
+ };
+}
+
+export function createDefaultBuildConfig(
+ platform: BuildPlatform,
+ name: string
+): BuildConfig {
+ const id = `${platform}-${Date.now()}`;
+ const config: BuildConfig = {
+ id,
+ name,
+ platform,
+ scenes: [],
+ defines: platform === 'playable' ? [] : ['DEBUG'],
+ };
+
+ if (platform === 'playable') {
+ config.playableSettings = createDefaultPlayableSettings();
+ } else {
+ config.wechatSettings = createDefaultWeChatSettings();
+ }
+
+ return config;
+}
+
+export function createDefaultBuildSettings(): BuildSettings {
+ return {
+ activePlatform: 'playable',
+ activeConfigId: '',
+ configs: [
+ {
+ id: 'playable-dev',
+ name: 'Playable - Development',
+ platform: 'playable',
+ scenes: [],
+ defines: ['DEBUG'],
+ playableSettings: {
+ startupScene: '',
+ isDevelopment: true,
+ minifyCode: false,
+ embedFonts: true,
+ outputPath: 'build/playable-dev.html',
+ },
+ },
+ {
+ id: 'playable-prod',
+ name: 'Playable - Production',
+ platform: 'playable',
+ scenes: [],
+ defines: [],
+ playableSettings: {
+ startupScene: '',
+ isDevelopment: false,
+ minifyCode: true,
+ embedFonts: true,
+ outputPath: 'build/playable.html',
+ },
+ },
+ {
+ id: 'wechat-dev',
+ name: 'WeChat - Development',
+ platform: 'wechat',
+ scenes: [],
+ defines: ['DEBUG'],
+ wechatSettings: {
+ appId: '',
+ version: '1.0.0',
+ bundleMode: 'subpackage',
+ outputDir: 'build/wechat-dev',
+ },
+ },
+ {
+ id: 'wechat-prod',
+ name: 'WeChat - Production',
+ platform: 'wechat',
+ scenes: [],
+ defines: [],
+ wechatSettings: {
+ appId: '',
+ version: '1.0.0',
+ bundleMode: 'subpackage',
+ outputDir: 'build/wechat',
+ },
+ },
+ ],
+ };
+}
diff --git a/editor/src/types/index.ts b/editor/src/types/index.ts
index e04600ac1..7d71e80c2 100644
--- a/editor/src/types/index.ts
+++ b/editor/src/types/index.ts
@@ -23,3 +23,17 @@ export {
parseTextureMetadata,
serializeTextureMetadata,
} from './TextureMetadata';
+
+export {
+ type BuildPlatform,
+ type PlatformInfo,
+ type PlayableSettings,
+ type WeChatSettings,
+ type BuildConfig,
+ type BuildSettings,
+ PLATFORMS,
+ createDefaultPlayableSettings,
+ createDefaultWeChatSettings,
+ createDefaultBuildConfig,
+ createDefaultBuildSettings,
+} from './BuildTypes';
diff --git a/scripts/build-web-single.bat b/scripts/build-web-single.bat
index b70f0a4e6..1a4d7851f 100644
--- a/scripts/build-web-single.bat
+++ b/scripts/build-web-single.bat
@@ -19,13 +19,12 @@ echo Single-file SDK built:
dir sdk\esengine.single.js
echo.
-echo Bundling playable HTML...
-node "%~dp0\..\tools\bundle-playable.js" --wasm sdk\esengine.single.js --game "%~dp0\..\sdk\examples\playground\build\playable\game.js" --output sdk\playable.html
+echo Copying to desktop/public...
+copy /Y sdk\esengine.single.js "%~dp0\..\desktop\public\esengine.single.js"
if errorlevel 1 goto :error
echo.
-echo Final output:
-dir sdk\playable.html
+echo SDK copied to desktop/public/esengine.single.js
goto :end
:error
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 7849d5cb0..17b6d7a46 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -7,6 +7,7 @@ import { World } from './world';
import { Schedule, SystemDef, SystemRunner } from './system';
import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';
import type { ESEngineModule, CppRegistry } from './wasm';
+import { textPlugin } from './ui/TextPlugin';
// =============================================================================
// Plugin Interface
@@ -228,5 +229,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
app.addSystemToSchedule(Schedule.Last, renderSystem);
+ app.addPlugin(textPlugin);
+
return app;
}
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 27e93ec8e..d195624ca 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -97,9 +97,12 @@ export async function loadSceneWithAssets(
const data = compData.data as Record<string, unknown>;
if (typeof data.texture === 'string' && data.texture) {
const texturePath = data.texture;
- const url = options?.assetBaseUrl
- ? `${options.assetBaseUrl}/${texturePath}`
- : `/${texturePath}`;
+ const isDataUrl = texturePath.startsWith('data:');
+ const url = isDataUrl
+ ? texturePath
+ : options?.assetBaseUrl
+ ? `${options.assetBaseUrl}/${texturePath}`
+ : `/${texturePath}`;
try {
const info = await assetServer.loadTexture(url);
data.texture = info.handle;