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.

refactor: restructure build pipeline with shared utils, hooks, and scene management

esenginef70a1edafacb
diff --git a/editor/src/builder/BuildHooks.ts b/editor/src/builder/BuildHooks.ts
new file mode 100644
index 000000000..20d72913a
--- /dev/null
+++ b/editor/src/builder/BuildHooks.ts
@@ -0,0 +1,162 @@
+/**
+ * @file BuildHooks.ts
+ * @brief Build hook type definitions and executor
+ */
+
+import type { BuildHook, BuildHookPhase, CopyFilesConfig, RunCommandConfig } from '../types/BuildTypes';
+import type { NativeFS } from '../types/NativeFS';
+import { joinPath } from '../utils/path';
+import type { BuildProgressReporter } from './BuildProgress';
+
+// =============================================================================
+// Hook Execution
+// =============================================================================
+
+export async function executeHooks(
+ hooks: BuildHook[],
+ phase: BuildHookPhase,
+ projectDir: string,
+ outputPath: string,
+ fs: NativeFS,
+ progress?: BuildProgressReporter,
+): Promise<void> {
+ const phaseHooks = hooks.filter(h => h.phase === phase);
+ if (phaseHooks.length === 0) return;
+
+ progress?.log('info', `Running ${phase}-build hooks (${phaseHooks.length})`);
+
+ for (const hook of phaseHooks) {
+ switch (hook.type) {
+ case 'copy-files':
+ await executeCopyFiles(hook.config as CopyFilesConfig, projectDir, outputPath, fs, progress);
+ break;
+ case 'run-command':
+ await executeRunCommand(hook.config as RunCommandConfig, projectDir, fs, progress);
+ break;
+ }
+ }
+}
+
+async function executeCopyFiles(
+ config: CopyFilesConfig,
+ projectDir: string,
+ outputPath: string,
+ fs: NativeFS,
+ progress?: BuildProgressReporter,
+): Promise<void> {
+ const fromDir = resolveHookPath(config.from, projectDir, outputPath);
+ const toDir = resolveHookPath(config.to, projectDir, outputPath);
+
+ if (!await fs.exists(fromDir)) {
+ progress?.log('warn', `Copy hook: source not found: ${fromDir}`);
+ return;
+ }
+
+ await fs.createDirectory(toDir);
+ await copyDirectoryRecursive(fs, fromDir, toDir, config.pattern);
+ progress?.log('info', `Copied files: ${config.from} -> ${config.to}`);
+}
+
+async function copyDirectoryRecursive(
+ fs: NativeFS,
+ srcDir: string,
+ destDir: string,
+ pattern?: string,
+): Promise<void> {
+ const entries = await fs.listDirectoryDetailed(srcDir);
+
+ for (const entry of entries) {
+ const srcPath = joinPath(srcDir, entry.name);
+ const destPath = joinPath(destDir, entry.name);
+
+ if (entry.isDirectory) {
+ await fs.createDirectory(destPath);
+ await copyDirectoryRecursive(fs, srcPath, destPath, pattern);
+ } else {
+ if (pattern && !matchPattern(entry.name, pattern)) continue;
+ const data = await fs.readBinaryFile(srcPath);
+ if (data) {
+ await fs.writeBinaryFile(destPath, data);
+ }
+ }
+ }
+}
+
+function matchPattern(filename: string, pattern: string): boolean {
+ const regex = new RegExp(
+ '^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.*').replace(/\?/g, '.') + '$'
+ );
+ return regex.test(filename);
+}
+
+async function executeRunCommand(
+ config: RunCommandConfig,
+ projectDir: string,
+ fs: NativeFS,
+ progress?: BuildProgressReporter,
+): Promise<void> {
+ if (!fs.executeCommand) {
+ progress?.log('warn', 'Run-command hook: shell execution not available');
+ return;
+ }
+
+ const args = config.args ?? [];
+ progress?.log('info', `Running: ${config.command} ${args.join(' ')}`);
+
+ try {
+ const result = await fs.executeCommand(config.command, args, projectDir);
+ if (result.exitCode !== 0) {
+ progress?.log('warn', `Command exited with code ${result.exitCode}: ${result.stderr || result.stdout}`);
+ } else if (result.stdout) {
+ progress?.log('info', result.stdout.substring(0, 200));
+ }
+ } catch (err) {
+ progress?.log('error', `Command failed: ${err}`);
+ throw err;
+ }
+}
+
+function resolveHookPath(hookPath: string, projectDir: string, outputPath: string): string {
+ return hookPath
+ .replace('${projectDir}', projectDir)
+ .replace('${outputPath}', outputPath)
+ .replace('${outputDir}', outputPath.substring(0, outputPath.lastIndexOf('/')));
+}
+
+// =============================================================================
+// Hook Validation
+// =============================================================================
+
+export function validateHook(hook: BuildHook): string | null {
+ if (!hook.phase || (hook.phase !== 'pre' && hook.phase !== 'post')) {
+ return 'Invalid hook phase: must be "pre" or "post"';
+ }
+
+ if (hook.type === 'copy-files') {
+ const config = hook.config as CopyFilesConfig;
+ if (!config.from) return 'Copy hook: "from" path is required';
+ if (!config.to) return 'Copy hook: "to" path is required';
+ } else if (hook.type === 'run-command') {
+ const config = hook.config as RunCommandConfig;
+ if (!config.command) return 'Run hook: "command" is required';
+ } else {
+ return `Unknown hook type: ${hook.type}`;
+ }
+
+ return null;
+}
+
+export function createDefaultHook(type: BuildHook['type'], phase: BuildHookPhase): BuildHook {
+ if (type === 'copy-files') {
+ return {
+ phase,
+ type: 'copy-files',
+ config: { from: '${outputDir}', to: '' } as CopyFilesConfig,
+ };
+ }
+ return {
+ phase,
+ type: 'run-command',
+ config: { command: '', args: [] } as RunCommandConfig,
+ };
+}
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index f51d24816..d54bc5240 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -16,15 +16,22 @@ import { getProjectDir } from '../utils/path';
import { getSettingsValue } from '../settings/SettingsRegistry';
import { MAX_COLLISION_LAYERS } from '../settings/collisionLayers';
import { getEditorContext } from '../context/EditorContext';
+import { executeHooks } from './BuildHooks';
// =============================================================================
// Types
// =============================================================================
+export interface OutputFileEntry {
+ path: string;
+ size: number;
+}
+
export interface BuildResult {
success: boolean;
outputPath?: string;
outputSize?: number;
+ outputFiles?: OutputFileEntry[];
error?: string;
duration?: number;
cached?: boolean;
@@ -146,8 +153,21 @@ export class BuildService {
};
}
+ const hooks = config.hooks ?? [];
+ const outputPath = config.playableSettings?.outputPath
+ ?? config.wechatSettings?.outputDir
+ ?? '';
+
+ if (hooks.length > 0) {
+ await executeHooks(hooks, 'pre', projectDir, outputPath, fs, progress);
+ }
+
const result = await emitter.emit(artifact, context);
+ if (result.success && hooks.length > 0) {
+ await executeHooks(hooks, 'post', projectDir, result.outputPath ?? outputPath, fs, progress);
+ }
+
const duration = Date.now() - startTime;
result.duration = duration;
diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.ts
index beb79a2a4..de7622de9 100644
--- a/editor/src/builder/BuildSettingsDialog.ts
+++ b/editor/src/builder/BuildSettingsDialog.ts
@@ -18,9 +18,12 @@ import { showProgressToast, dismissToast, showToast } from '../ui/Toast';
import { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';
import { BuildConfigService, initBuildConfigService } from './BuildConfigService';
import { downloadConfigsAsFile, uploadConfigsFromFile } from './BuildConfigIO';
-import { BUILD_TEMPLATES, createConfigFromTemplate, type BuildTemplate } from './BuildTemplates';
+import { BUILD_TEMPLATES, createConfigFromTemplate, getAllTemplates, configToTemplate, saveUserTemplate, type BuildTemplate, type UserTemplate } from './BuildTemplates';
import { BatchBuilder } from './BatchBuilder';
import { formatSize } from './BuildProgress';
+import { discoverProjectScenes } from './SceneDiscovery';
+import { createDefaultHook } from './BuildHooks';
+import type { BuildHook, BuildHookPhase, BuildHookType, CopyFilesConfig, RunCommandConfig } from '../types/BuildTypes';
// =============================================================================
// Types
@@ -133,6 +136,8 @@ export class BuildSettingsDialog {
</div>
</div>
`;
+
+ this.setupSceneDragAndDrop();
}
private renderSidebar(): string {
@@ -197,6 +202,9 @@ export class BuildSettingsDialog {
<button class="es-btn es-btn-icon" data-action="duplicate-config" title="Duplicate">
${icons.copy(14)}
</button>
+ <button class="es-btn es-btn-icon" data-action="save-as-preset" title="Save as Preset">
+ ${icons.download(14)}
+ </button>
</div>
</div>
<div class="es-build-detail-content">
@@ -206,6 +214,63 @@ export class BuildSettingsDialog {
</div>
<div class="es-build-settings-section">
${this.renderPlatformSettings(config)}
+ ${this.renderHooksSection(config)}
+ </div>
+ </div>
+ `;
+ }
+
+ private renderHooksSection(config: BuildConfig): string {
+ const isExpanded = this.expandedSections_.has('hooks');
+ const hooks = config.hooks ?? [];
+
+ const hooksHtml = hooks.length > 0
+ ? hooks.map((h, i) => {
+ const phaseLabel = h.phase === 'pre' ? 'Pre-Build' : 'Post-Build';
+ const typeLabel = h.type === 'copy-files' ? 'Copy Files' : 'Run Command';
+ let detail = '';
+ if (h.type === 'copy-files') {
+ const c = h.config as CopyFilesConfig;
+ detail = `${c.from} → ${c.to}`;
+ } else {
+ const c = h.config as RunCommandConfig;
+ detail = `${c.command} ${(c.args ?? []).join(' ')}`.trim();
+ }
+ return `
+ <div class="es-build-hook-item">
+ <span class="es-build-badge es-build-badge-small">${phaseLabel}</span>
+ <span class="es-build-hook-type">${typeLabel}</span>
+ <span class="es-build-hook-detail" title="${detail}">${detail || '(not configured)'}</span>
+ <button class="es-btn-icon" data-action="edit-hook" data-index="${i}" title="Edit">
+ ${icons.pencil(10)}
+ </button>
+ <button class="es-btn-icon" data-action="remove-hook" data-index="${i}" title="Remove">
+ ${icons.x(10)}
+ </button>
+ </div>
+ `;
+ }).join('')
+ : '<div class="es-build-empty-list">No hooks configured</div>';
+
+ return `
+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="hooks">
+ <div class="es-build-collapse-header">
+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}
+ <span>Build Hooks</span>
+ <span class="es-build-collapse-count">${hooks.length}</span>
+ </div>
+ <div class="es-build-collapse-content">
+ <div class="es-build-hooks-list">
+ ${hooksHtml}
+ </div>
+ <div class="es-build-hook-actions">
+ <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="copy-files" data-hook-phase="post">
+ ${icons.plus(12)} Add Copy Files Hook
+ </button>
+ <button class="es-btn es-btn-link" data-action="add-hook" data-hook-type="run-command" data-hook-phase="post">
+ ${icons.plus(12)} Add Run Command Hook
+ </button>
+ </div>
</div>
</div>
`;
@@ -273,10 +338,50 @@ export class BuildSettingsDialog {
` : ''}
</div>
${latestSection}
+ ${this.renderOutputFiles(config.id)}
${historySection}
`;
}
+ private renderOutputFiles(configId: string): string {
+ const files = this.lastBuildOutputFiles_.get(configId);
+ if (!files || files.length === 0) return '';
+
+ const isExpanded = this.expandedSections_.has('output-files');
+ const sorted = [...files].sort((a, b) => b.size - a.size);
+ const totalSize = sorted.reduce((sum, f) => sum + f.size, 0);
+
+ const fileItems = sorted.slice(0, 20).map(f => {
+ const name = f.path.split('/').pop() ?? f.path;
+ const dir = f.path.substring(0, f.path.length - name.length);
+ return `
+ <div class="es-build-file-item">
+ <span class="es-build-file-icon">${icons.file(10)}</span>
+ <span class="es-build-file-path" title="${f.path}">${dir ? `<span class="es-build-file-dir">${dir}</span>` : ''}${name}</span>
+ <span class="es-build-file-size">${formatSize(f.size)}</span>
+ </div>
+ `;
+ }).join('');
+
+ const moreCount = sorted.length - 20;
+
+ return `
+ <div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="output-files">
+ <div class="es-build-collapse-header">
+ ${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}
+ <span>Output Files</span>
+ <span class="es-build-collapse-count">${files.length} files (${formatSize(totalSize)})</span>
+ </div>
+ <div class="es-build-collapse-content">
+ <div class="es-build-file-list">
+ ${fileItems}
+ ${moreCount > 0 ? `<div class="es-build-file-more">and ${moreCount} more files...</div>` : ''}
+ </div>
+ </div>
+ </div>
+ `;
+ }
+
private renderHistoryEntry(entry: BuildHistoryEntry): string {
const time = new Date(entry.timestamp).toLocaleTimeString();
return `
@@ -290,17 +395,19 @@ export class BuildSettingsDialog {
private renderScenesSection(config: BuildConfig): string {
const isExpanded = this.expandedSections_.has('scenes');
+ const firstScene = config.scenes[0];
const scenesHtml = config.scenes.length > 0
? config.scenes.map((s, i) => `
- <div class="es-build-scene-item">
- <input type="checkbox" checked data-scene-index="${i}">
- <span>${s}</span>
+ <div class="es-build-scene-item" draggable="true" data-scene-drag="${i}">
+ <span class="es-build-scene-drag-handle">${icons.grip(10)}</span>
+ ${i === 0 ? '<span class="es-build-badge es-build-badge-small">Startup</span>' : ''}
+ <span class="es-build-scene-path">${s}</span>
<button class="es-btn-icon" data-action="remove-scene" data-index="${i}">
${icons.x(10)}
</button>
</div>
`).join('')
- : '<div class="es-build-empty-list">No scenes</div>';
+ : '<div class="es-build-empty-list">No scenes added. Use buttons below to add scenes.</div>';
return `
<div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="scenes">
@@ -310,12 +417,25 @@ export class BuildSettingsDialog {
<span class="es-build-collapse-count">${config.scenes.length}</span>
</div>
<div class="es-build-collapse-content">
- <div class="es-build-scene-list">
+ <div class="es-build-scene-list" data-scene-drop-zone>
${scenesHtml}
</div>
- <button class="es-btn es-btn-link" data-action="add-current-scene">
- ${icons.plus(12)} Add Current Scene
- </button>
+ <div class="es-build-scene-actions">
+ <button class="es-btn es-btn-link" data-action="add-current-scene">
+ ${icons.plus(12)} Add Current Scene
+ </button>
+ <button class="es-btn es-btn-link" data-action="add-all-scenes">
+ ${icons.plus(12)} Add All Scenes
+ </button>
+ <button class="es-btn es-btn-link" data-action="show-scene-picker">
+ ${icons.list(12)} Scene Picker
+ </button>
+ ${config.scenes.length > 0 ? `
+ <button class="es-btn es-btn-link es-btn-danger" data-action="remove-all-scenes">
+ ${icons.trash(12)} Remove All
+ </button>
+ ` : ''}
+ </div>
</div>
</div>
`;
@@ -597,6 +717,12 @@ export class BuildSettingsDialog {
}
break;
+ case 'save-as-preset':
+ if (config) {
+ this.showSavePresetDialog(config);
+ }
+ break;
+
case 'add-current-scene':
if (config) {
const editor = getEditorInstance();
@@ -622,6 +748,26 @@ export class BuildSettingsDialog {
break;
}
+ case 'add-all-scenes':
+ if (config) {
+ await this.addAllScenes(config);
+ }
+ break;
+
+ case 'remove-all-scenes':
+ if (config) {
+ config.scenes = [];
+ await this.saveSettings();
+ this.render();
+ }
+ break;
+
+ case 'show-scene-picker':
+ if (config) {
+ await this.showScenePicker(config);
+ }
+ break;
+
case 'add-define': {
const input = this.overlay_.querySelector('#new-define') as HTMLInputElement;
const value = input?.value.trim();
@@ -643,6 +789,36 @@ export class BuildSettingsDialog {
break;
}
+ case 'add-hook': {
+ if (config) {
+ const hookType = element.dataset.hookType as BuildHookType;
+ const hookPhase = element.dataset.hookPhase as BuildHookPhase;
+ if (!config.hooks) config.hooks = [];
+ config.hooks.push(createDefaultHook(hookType, hookPhase));
+ await this.saveSettings();
+ this.render();
+ }
+ break;
+ }
+
+ case 'remove-hook': {
+ const hookIdx = parseInt(element.dataset.index ?? '-1', 10);
+ if (config && config.hooks && hookIdx >= 0) {
+ config.hooks.splice(hookIdx, 1);
+ await this.saveSettings();
+ this.render();
+ }
+ break;
+ }
+
+ case 'edit-hook': {
+ const editIdx = parseInt(element.dataset.index ?? '-1', 10);
+ if (config && config.hooks && editIdx >= 0) {
+ this.showEditHookDialog(config, editIdx);
+ }
+ break;
+ }
+
case 'build':
if (config) {
this.handleBuild(config);
@@ -808,19 +984,41 @@ export class BuildSettingsDialog {
});
}
- private showTemplatesDialog(): void {
+ private async showTemplatesDialog(): Promise<void> {
+ const fs = getEditorContext().fs;
+ const projectDir = this.getProjectDir();
+ const allTemplates = fs
+ ? await getAllTemplates(fs, projectDir)
+ : BUILD_TEMPLATES;
+
const dialog = document.createElement('div');
dialog.className = 'es-build-add-dialog';
- const templatesHtml = BUILD_TEMPLATES.map(t => `
- <div class="es-build-template-item" data-template="${t.id}">
- <div class="es-build-template-header">
- <span class="es-build-template-name">${t.name}</span>
- <span class="es-build-template-platform">${t.platform}</span>
+ const builtinHtml = allTemplates
+ .filter(t => !(t as UserTemplate).isUserDefined)
+ .map(t => `
+ <div class="es-build-template-item" data-template="${t.id}">
+ <div class="es-build-template-header">
+ <span class="es-build-template-name">${t.name}</span>
+ <span class="es-build-template-platform">${t.platform}</span>
+ </div>
+ <div class="es-build-template-desc">${t.description}</div>
</div>
- <div class="es-build-template-desc">${t.description}</div>
- </div>
- `).join('');
+ `).join('');
+
+ const userTemplates = allTemplates.filter(t => (t as UserTemplate).isUserDefined);
+ const userHtml = userTemplates.length > 0
+ ? `<div class="es-build-section-title" style="margin-top: 12px;">Custom Presets</div>` +
+ userTemplates.map(t => `
+ <div class="es-build-template-item" data-template="${t.id}">
+ <div class="es-build-template-header">
+ <span class="es-build-template-name">${t.name}</span>
+ <span class="es-build-template-platform">${t.platform}</span>
+ </div>
+ <div class="es-build-template-desc">${t.description}</div>
+ </div>
+ `).join('')
+ : '';
dialog.innerHTML = `
<div class="es-dialog" style="max-width: 400px;">
@@ -828,9 +1026,11 @@ export class BuildSettingsDialog {
<span class="es-dialog-title">Build Templates</span>
<button class="es-dialog-close" data-action="cancel">&times;</button>
</div>
- <div class="es-dialog-body">
+ <div class="es-dialog-body" style="max-height: 450px; overflow-y: auto;">
+ <div class="es-build-section-title">Built-in</div>
<div class="es-build-templates-list">
- ${templatesHtml}
+ ${builtinHtml}
+ ${userHtml}
</div>
</div>
<div class="es-dialog-footer">
@@ -848,7 +1048,7 @@ export class BuildSettingsDialog {
dialog.querySelectorAll('.es-build-template-item').forEach(item => {
item.addEventListener('click', async () => {
const templateId = (item as HTMLElement).dataset.template;
- const template = BUILD_TEMPLATES.find(t => t.id === templateId);
+ const template = allTemplates.find(t => t.id === templateId);
if (template) {
const newConfig = createConfigFromTemplate(template);
this.settings_.configs.push(newConfig);
@@ -861,6 +1061,49 @@ export class BuildSettingsDialog {
});
}
+ private showSavePresetDialog(config: BuildConfig): void {
+ const dialog = document.createElement('div');
+ dialog.className = 'es-build-add-dialog';
+ dialog.innerHTML = `
+ <div class="es-dialog" style="max-width: 360px;">
+ <div class="es-dialog-header">
+ <span class="es-dialog-title">Save as Preset</span>
+ <button class="es-dialog-close" data-action="cancel">&times;</button>
+ </div>
+ <div class="es-dialog-body">
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Preset Name</label>
+ <input type="text" class="es-dialog-input" id="preset-name" value="${config.name}" placeholder="My Preset">
+ </div>
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Description</label>
+ <input type="text" class="es-dialog-input" id="preset-desc" placeholder="Brief description...">
+ </div>
+ </div>
+ <div class="es-dialog-footer">
+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>
+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>
+ </div>
+ </div>
+ `;
+
+ this.overlay_.appendChild(dialog);
+ const close = () => dialog.remove();
+
+ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);
+ dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {
+ const name = (dialog.querySelector('#preset-name') as HTMLInputElement).value.trim() || config.name;
+ const description = (dialog.querySelector('#preset-desc') as HTMLInputElement).value.trim() || '';
+ const fs = getEditorContext().fs;
+ if (fs) {
+ const template = configToTemplate(config, name, description);
+ await saveUserTemplate(fs, this.getProjectDir(), template);
+ showToast({ type: 'success', title: 'Preset Saved', message: `Saved "${name}"`, duration: 3000 });
+ }
+ close();
+ });
+ }
+
private async handleImportConfigs(): Promise<void> {
const result = await uploadConfigsFromFile();
@@ -936,6 +1179,9 @@ export class BuildSettingsDialog {
dismissToast(toastId);
if (result.success && result.outputPath) {
+ if (result.outputFiles) {
+ this.lastBuildOutputFiles_.set(config.id, result.outputFiles);
+ }
this.history_.addEntry({
configId: config.id,
configName: config.name,
@@ -1102,6 +1348,224 @@ export class BuildSettingsDialog {
}
}
+ // =========================================================================
+ // Scene Management
+ // =========================================================================
+
+ private async addAllScenes(config: BuildConfig): Promise<void> {
+ const fs = getEditorContext().fs;
+ if (!fs) return;
+
+ const projectDir = this.getProjectDir();
+ const allScenes = await discoverProjectScenes(fs, projectDir);
+
+ let added = 0;
+ for (const scene of allScenes) {
+ if (!config.scenes.includes(scene)) {
+ config.scenes.push(scene);
+ added++;
+ }
+ }
+
+ if (added > 0) {
+ await this.saveSettings();
+ this.render();
+ showToast({ type: 'info', title: 'Scenes Added', message: `Added ${added} scene(s)`, duration: 2000 });
+ } else if (allScenes.length === 0) {
+ showToast({ type: 'warning', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });
+ } else {
+ showToast({ type: 'info', title: 'No New Scenes', message: 'All scenes already added', duration: 2000 });
+ }
+ }
+
+ private async showScenePicker(config: BuildConfig): Promise<void> {
+ const fs = getEditorContext().fs;
+ if (!fs) return;
+
+ const projectDir = this.getProjectDir();
+ const allScenes = await discoverProjectScenes(fs, projectDir);
+
+ if (allScenes.length === 0) {
+ showToast({ type: 'warning', title: 'No Scenes Found', message: 'No .esscene files found in assets/', duration: 3000 });
+ return;
+ }
+
+ const dialog = document.createElement('div');
+ dialog.className = 'es-build-add-dialog';
+
+ const scenesHtml = allScenes.map(s => {
+ const isAdded = config.scenes.includes(s);
+ return `
+ <label class="es-build-scene-picker-item ${isAdded ? 'es-active' : ''}">
+ <input type="checkbox" data-scene-path="${s}" ${isAdded ? 'checked' : ''}>
+ <span>${s}</span>
+ </label>
+ `;
+ }).join('');
+
+ dialog.innerHTML = `
+ <div class="es-dialog" style="max-width: 480px;">
+ <div class="es-dialog-header">
+ <span class="es-dialog-title">Scene Picker</span>
+ <button class="es-dialog-close" data-action="cancel">&times;</button>
+ </div>
+ <div class="es-dialog-body" style="max-height: 400px; overflow-y: auto;">
+ <div class="es-build-scene-picker-list">
+ ${scenesHtml}
+ </div>
+ </div>
+ <div class="es-dialog-footer">
+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>
+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="apply">Apply</button>
+ </div>
+ </div>
+ `;
+
+ this.overlay_.appendChild(dialog);
+
+ const close = () => dialog.remove();
+
+ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);
+ dialog.querySelector('[data-action="apply"]')?.addEventListener('click', async () => {
+ const checkboxes = dialog.querySelectorAll('input[data-scene-path]') as NodeListOf<HTMLInputElement>;
+ const selected: string[] = [];
+ checkboxes.forEach(cb => {
+ if (cb.checked) {
+ selected.push(cb.dataset.scenePath!);
+ }
+ });
+
+ const existingOrder = config.scenes.filter(s => selected.includes(s));
+ const newScenes = selected.filter(s => !existingOrder.includes(s));
+ config.scenes = [...existingOrder, ...newScenes];
+
+ await this.saveSettings();
+ close();
+ this.render();
+ });
+ }
+
+ private showEditHookDialog(config: BuildConfig, index: number): void {
+ const hook = config.hooks![index];
+ const dialog = document.createElement('div');
+ dialog.className = 'es-build-add-dialog';
+
+ const isCopy = hook.type === 'copy-files';
+ const copyConfig = isCopy ? hook.config as CopyFilesConfig : null;
+ const cmdConfig = !isCopy ? hook.config as RunCommandConfig : null;
+
+ dialog.innerHTML = `
+ <div class="es-dialog" style="max-width: 420px;">
+ <div class="es-dialog-header">
+ <span class="es-dialog-title">Edit ${isCopy ? 'Copy Files' : 'Run Command'} Hook</span>
+ <button class="es-dialog-close" data-action="cancel">&times;</button>
+ </div>
+ <div class="es-dialog-body">
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Phase</label>
+ <select class="es-dialog-input" id="hook-phase">
+ <option value="pre" ${hook.phase === 'pre' ? 'selected' : ''}>Pre-Build</option>
+ <option value="post" ${hook.phase === 'post' ? 'selected' : ''}>Post-Build</option>
+ </select>
+ </div>
+ ${isCopy ? `
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">From Path</label>
+ <input type="text" class="es-dialog-input" id="hook-from" value="${copyConfig?.from ?? ''}" placeholder="\${outputDir}">
+ </div>
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">To Path</label>
+ <input type="text" class="es-dialog-input" id="hook-to" value="${copyConfig?.to ?? ''}" placeholder="/path/to/dest">
+ </div>
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Pattern (optional)</label>
+ <input type="text" class="es-dialog-input" id="hook-pattern" value="${copyConfig?.pattern ?? ''}" placeholder="*.png">
+ </div>
+ ` : `
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Command</label>
+ <input type="text" class="es-dialog-input" id="hook-command" value="${cmdConfig?.command ?? ''}" placeholder="echo">
+ </div>
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Arguments (space-separated)</label>
+ <input type="text" class="es-dialog-input" id="hook-args" value="${(cmdConfig?.args ?? []).join(' ')}" placeholder="arg1 arg2">
+ </div>
+ `}
+ </div>
+ <div class="es-dialog-footer">
+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>
+ <button class="es-dialog-btn es-dialog-btn-primary" data-action="save">Save</button>
+ </div>
+ </div>
+ `;
+
+ this.overlay_.appendChild(dialog);
+ const close = () => dialog.remove();
+
+ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);
+ dialog.querySelector('[data-action="save"]')?.addEventListener('click', async () => {
+ const phase = (dialog.querySelector('#hook-phase') as HTMLSelectElement).value as BuildHookPhase;
+ hook.phase = phase;
+
+ if (isCopy) {
+ const from = (dialog.querySelector('#hook-from') as HTMLInputElement).value;
+ const to = (dialog.querySelector('#hook-to') as HTMLInputElement).value;
+ const pattern = (dialog.querySelector('#hook-pattern') as HTMLInputElement).value;
+ hook.config = { from, to, ...(pattern ? { pattern } : {}) } as CopyFilesConfig;
+ } else {
+ const command = (dialog.querySelector('#hook-command') as HTMLInputElement).value;
+ const argsStr = (dialog.querySelector('#hook-args') as HTMLInputElement).value.trim();
+ const args = argsStr ? argsStr.split(/\s+/) : [];
+ hook.config = { command, args } as RunCommandConfig;
+ }
+
+ await this.saveSettings();
+ close();
+ this.render();
+ });
+ }
+
+ private setupSceneDragAndDrop(): void {
+ const dropZone = this.overlay_?.querySelector('[data-scene-drop-zone]');
+ if (!dropZone) return;
+
+ const items = dropZone.querySelectorAll('[data-scene-drag]');
+ items.forEach(item => {
+ const el = item as HTMLElement;
+ el.addEventListener('dragstart', (e: DragEvent) => {
+ this.dragSourceIndex_ = parseInt(el.dataset.sceneDrag ?? '-1', 10);
+ el.classList.add('es-dragging');
+ e.dataTransfer!.effectAllowed = 'move';
+ });
+ el.addEventListener('dragend', () => {
+ el.classList.remove('es-dragging');
+ this.dragSourceIndex_ = -1;
+ });
+ el.addEventListener('dragover', (e: DragEvent) => {
+ e.preventDefault();
+ e.dataTransfer!.dropEffect = 'move';
+ el.classList.add('es-drag-over');
+ });
+ el.addEventListener('dragleave', () => {
+ el.classList.remove('es-drag-over');
+ });
+ el.addEventListener('drop', async (e: DragEvent) => {
+ e.preventDefault();
+ el.classList.remove('es-drag-over');
+ const targetIndex = parseInt(el.dataset.sceneDrag ?? '-1', 10);
+ if (this.dragSourceIndex_ >= 0 && targetIndex >= 0 && this.dragSourceIndex_ !== targetIndex) {
+ const config = this.getActiveConfig();
+ if (config) {
+ const [moved] = config.scenes.splice(this.dragSourceIndex_, 1);
+ config.scenes.splice(targetIndex, 0, moved);
+ await this.saveSettings();
+ this.render();
+ }
+ }
+ });
+ });
+ }
+
// =========================================================================
// Member Variables
// =========================================================================
@@ -1114,6 +1578,8 @@ export class BuildSettingsDialog {
private batchBuilder_!: BatchBuilder;
private expandedSections_: Set<string> = new Set(['scenes', 'defines', 'platform']);
private keyHandler_: ((e: KeyboardEvent) => void) | null = null;
+ private dragSourceIndex_ = -1;
+ private lastBuildOutputFiles_: Map<string, Array<{ path: string; size: number }>> = new Map();
}
// =============================================================================
diff --git a/editor/src/builder/BuildTemplates.ts b/editor/src/builder/BuildTemplates.ts
index 2913b4f86..7b3656c69 100644
--- a/editor/src/builder/BuildTemplates.ts
+++ b/editor/src/builder/BuildTemplates.ts
@@ -9,6 +9,8 @@ import {
PlayableSettings,
WeChatSettings,
} from '../types/BuildTypes';
+import type { NativeFS } from '../types/NativeFS';
+import { joinPath } from '../utils/path';
// =============================================================================
// Types
@@ -206,6 +208,101 @@ export function applyTemplateToConfig(
// Template Icon Mapping
// =============================================================================
+// =============================================================================
+// User Custom Presets
+// =============================================================================
+
+const USER_TEMPLATES_DIR = '.esengine/build-templates';
+
+export interface UserTemplate extends BuildTemplate {
+ isUserDefined: true;
+}
+
+export function configToTemplate(config: BuildConfig, name: string, description: string): UserTemplate {
+ const template: UserTemplate = {
+ id: `user-${Date.now()}`,
+ name,
+ description,
+ platform: config.platform,
+ icon: config.platform === 'playable' ? 'play' : 'box',
+ defines: [...config.defines],
+ isUserDefined: true,
+ };
+
+ if (config.playableSettings) {
+ const { startupScene, ...rest } = config.playableSettings;
+ template.playableSettings = rest;
+ }
+ if (config.wechatSettings) {
+ const { appId, ...rest } = config.wechatSettings;
+ template.wechatSettings = rest;
+ }
+
+ return template;
+}
+
+export async function saveUserTemplate(
+ fs: NativeFS,
+ projectDir: string,
+ template: UserTemplate,
+): Promise<void> {
+ const dir = joinPath(projectDir, USER_TEMPLATES_DIR);
+ await fs.createDirectory(dir);
+ const filePath = joinPath(dir, `${template.id}.json`);
+ await fs.writeFile(filePath, JSON.stringify(template, null, 2));
+}
+
+export async function loadUserTemplates(
+ fs: NativeFS,
+ projectDir: string,
+): Promise<UserTemplate[]> {
+ const dir = joinPath(projectDir, USER_TEMPLATES_DIR);
+ if (!await fs.exists(dir)) return [];
+
+ const entries = await fs.listDirectory(dir);
+ const templates: UserTemplate[] = [];
+
+ for (const entry of entries) {
+ if (!entry.endsWith('.json')) continue;
+ const filePath = joinPath(dir, entry);
+ const content = await fs.readFile(filePath);
+ if (content) {
+ try {
+ const parsed = JSON.parse(content) as UserTemplate;
+ parsed.isUserDefined = true;
+ templates.push(parsed);
+ } catch {
+ // skip invalid files
+ }
+ }
+ }
+
+ return templates;
+}
+
+export async function deleteUserTemplate(
+ fs: NativeFS,
+ projectDir: string,
+ templateId: string,
+): Promise<void> {
+ const filePath = joinPath(projectDir, USER_TEMPLATES_DIR, `${templateId}.json`);
+ if (await fs.exists(filePath)) {
+ await fs.writeFile(filePath, '');
+ }
+}
+
+export async function getAllTemplates(
+ fs: NativeFS,
+ projectDir: string,
+): Promise<BuildTemplate[]> {
+ const userTemplates = await loadUserTemplates(fs, projectDir);
+ return [...BUILD_TEMPLATES, ...userTemplates];
+}
+
+// =============================================================================
+// Template Icon Mapping
+// =============================================================================
+
export function getTemplateIconSvg(iconId: string): string {
const icons: Record<string, string> = {
facebook: `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>`,
diff --git a/editor/src/builder/EmitterUtils.ts b/editor/src/builder/EmitterUtils.ts
new file mode 100644
index 000000000..e69c7f3ec
--- /dev/null
+++ b/editor/src/builder/EmitterUtils.ts
@@ -0,0 +1,221 @@
+/**
+ * @file EmitterUtils.ts
+ * @brief Shared utilities for platform emitters (Playable, WeChat)
+ */
+
+import * as esbuild from 'esbuild-wasm/esm/browser';
+import type { BuildArtifact } from './PlatformEmitter';
+import type { BuildContext } from './BuildService';
+import type { NativeFS } from '../types/NativeFS';
+import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
+import { joinPath } from '../utils/path';
+import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';
+import { initializeEsbuild, createBuildVirtualFsPlugin, type SdkModuleLoader } from './ArtifactBuilder';
+import { toBuildPath } from 'esengine';
+
+// =============================================================================
+// Plugin Analysis
+// =============================================================================
+
+const COMPONENT_TO_PLUGIN: Record<string, string> = {
+ 'Text': 'textPlugin',
+ 'BitmapText': 'textPlugin',
+ 'UIRect': 'uiLayoutPlugin',
+ 'UIMask': 'uiMaskPlugin',
+ 'Interactable': 'uiInteractionPlugin',
+ 'Button': 'uiInteractionPlugin',
+ 'TextInput': 'textInputPlugin',
+ 'Image': 'imagePlugin',
+ 'Toggle': 'togglePlugin',
+ 'ToggleGroup': 'togglePlugin',
+ 'ProgressBar': 'progressBarPlugin',
+ 'Slider': 'sliderPlugin',
+ 'Draggable': 'dragPlugin',
+ 'ScrollView': 'scrollViewPlugin',
+ 'Focusable': 'focusPlugin',
+ 'SafeArea': 'safeAreaPlugin',
+ 'ListView': 'listViewPlugin',
+ 'Dropdown': 'dropdownPlugin',
+ 'LayoutGroup': 'layoutGroupPlugin',
+ 'AudioSource': 'audioPlugin',
+ 'ParticleEmitter': 'particlePlugin',
+ 'Tilemap': 'tilemapPlugin',
+ 'TilemapLayer': 'tilemapPlugin',
+ 'PostProcessVolume': 'postProcessPlugin',
+};
+
+export function analyzeUsedPlugins(artifact: BuildArtifact): string[] {
+ const plugins = new Set<string>();
+ let hasUI = false;
+
+ for (const sceneData of artifact.scenes.values()) {
+ const entities = (sceneData as any).entities as Array<{
+ components: Array<{ type: string }>;
+ }> | undefined;
+ if (!entities) continue;
+
+ for (const entity of entities) {
+ for (const comp of entity.components) {
+ const plugin = COMPONENT_TO_PLUGIN[comp.type];
+ if (plugin) {
+ plugins.add(plugin);
+ hasUI = true;
+ }
+ }
+ }
+ }
+
+ if (hasUI) {
+ plugins.add('uiRenderOrderPlugin');
+ }
+
+ return Array.from(plugins);
+}
+
+// =============================================================================
+// Defines
+// =============================================================================
+
+export function buildDefinesMap(defines: string[]): Record<string, string> {
+ const result: Record<string, string> = {
+ 'process.env.EDITOR': 'false',
+ };
+ for (const def of defines) {
+ result[`process.env.${def}`] = 'true';
+ }
+ return result;
+}
+
+// =============================================================================
+// Physics Config
+// =============================================================================
+
+export function generatePhysicsConfig(context: BuildContext): string {
+ return JSON.stringify({
+ gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
+ fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
+ subStepCount: context.physicsSubStepCount ?? 4,
+ collisionLayerMasks: context.collisionLayerMasks,
+ });
+}
+
+// =============================================================================
+// Script Compilation
+// =============================================================================
+
+export interface CompileOptions {
+ entryContent: string;
+ resolveDir: string;
+ minify: boolean;
+ sdkResolver: SdkModuleLoader;
+ preferEsmEntry?: boolean;
+}
+
+export async function compileUserScripts(
+ fs: NativeFS,
+ projectDir: string,
+ context: BuildContext,
+ options: CompileOptions,
+): Promise<string> {
+ const defines = buildDefinesMap(context.config.defines);
+
+ await initializeEsbuild();
+
+ const plugin = createBuildVirtualFsPlugin(
+ fs,
+ projectDir,
+ options.sdkResolver,
+ options.preferEsmEntry ?? true,
+ );
+
+ const result = await esbuild.build({
+ stdin: {
+ contents: options.entryContent,
+ loader: 'ts',
+ resolveDir: options.resolveDir,
+ },
+ bundle: true,
+ format: 'iife',
+ write: false,
+ platform: 'browser',
+ target: 'es2020',
+ treeShaking: true,
+ minify: options.minify,
+ define: defines,
+ plugins: [plugin],
+ });
+
+ const output = result.outputFiles?.[0]?.text;
+ if (!output) {
+ throw new Error('esbuild produced no output');
+ }
+ return output;
+}
+
+// =============================================================================
+// Scene UUID Resolution (for emitters that process scenes post-artifact)
+// =============================================================================
+
+export function resolveSceneUUIDs(sceneData: Record<string, unknown>, artifact: BuildArtifact): void {
+ const entities = sceneData.entities as Array<{
+ components: Array<{ type: string; data: Record<string, unknown> }>;
+ prefab?: { prefabPath: string };
+ }> | undefined;
+ if (!entities) return;
+
+ for (const entity of entities) {
+ if (entity.prefab && typeof entity.prefab.prefabPath === 'string') {
+ if (isUUID(entity.prefab.prefabPath)) {
+ const path = artifact.assetLibrary.getPath(entity.prefab.prefabPath);
+ if (path) entity.prefab.prefabPath = toBuildPath(path);
+ } else {
+ entity.prefab.prefabPath = toBuildPath(entity.prefab.prefabPath);
+ }
+ }
+ for (const comp of entity.components || []) {
+ const refFields = getComponentRefFields(comp.type);
+ if (!refFields || !comp.data) continue;
+ for (const field of refFields) {
+ const value = comp.data[field];
+ if (typeof value === 'string' && isUUID(value)) {
+ const path = artifact.assetLibrary.getPath(value);
+ if (path) comp.data[field] = toBuildPath(path);
+ }
+ }
+ }
+ }
+
+ const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;
+ if (textureMetadata) {
+ const resolved: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(textureMetadata)) {
+ if (isUUID(key)) {
+ const path = artifact.assetLibrary.getPath(key);
+ resolved[path ?? key] = value;
+ } else {
+ resolved[key] = value;
+ }
+ }
+ sceneData.textureMetadata = resolved;
+ }
+}
+
+// =============================================================================
+// User Script Imports
+// =============================================================================
+
+export async function collectUserScriptImports(
+ fs: NativeFS,
+ projectDir: string,
+): Promise<{ imports: string; hasSrcDir: boolean }> {
+ const scriptsPath = joinPath(projectDir, 'src');
+ const hasSrcDir = await fs.exists(scriptsPath);
+
+ let imports = '';
+ if (hasSrcDir) {
+ const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);
+ imports = scripts.map(p => `import "${p}";`).join('\n');
+ }
+
+ return { imports, hasSrcDir };
+}
diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.ts
index cb6f808e8..806d3501e 100644
--- a/editor/src/builder/PlayableEmitter.ts
+++ b/editor/src/builder/PlayableEmitter.ts
@@ -5,75 +5,21 @@
import * as esbuild from 'esbuild-wasm/esm/browser';
import type { PlatformEmitter, BuildArtifact } from './PlatformEmitter';
-import type { BuildResult, BuildContext } from './BuildService';
+import type { BuildResult, BuildContext, OutputFileEntry } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { getEditorContext } from '../context/EditorContext';
-import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
import { joinPath, getFileExtension, isAbsolutePath, getParentDir, normalizePath, getProjectDir } from '../utils/path';
-import { isUUID, getComponentRefFields } from '../asset/AssetLibrary';
-import { initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest } from './ArtifactBuilder';
+import { arrayBufferToBase64, generateAddressableManifest } from './ArtifactBuilder';
import { PLAYABLE_HTML_TEMPLATE } from './templates';
import type { NativeFS } from '../types/NativeFS';
import { getAssetMimeType, getAssetTypeEntry, toBuildPath } from 'esengine';
-
-// =============================================================================
-// Plugin Analysis
-// =============================================================================
-
-const COMPONENT_TO_PLUGIN: Record<string, string> = {
- 'Text': 'textPlugin',
- 'BitmapText': 'textPlugin',
- 'UIRect': 'uiLayoutPlugin',
- 'UIMask': 'uiMaskPlugin',
- 'Interactable': 'uiInteractionPlugin',
- 'Button': 'uiInteractionPlugin',
- 'TextInput': 'textInputPlugin',
- 'Image': 'imagePlugin',
- 'Toggle': 'togglePlugin',
- 'ToggleGroup': 'togglePlugin',
- 'ProgressBar': 'progressBarPlugin',
- 'Slider': 'sliderPlugin',
- 'Draggable': 'dragPlugin',
- 'ScrollView': 'scrollViewPlugin',
- 'Focusable': 'focusPlugin',
- 'SafeArea': 'safeAreaPlugin',
- 'ListView': 'listViewPlugin',
- 'Dropdown': 'dropdownPlugin',
- 'LayoutGroup': 'layoutGroupPlugin',
- 'AudioSource': 'audioPlugin',
- 'ParticleEmitter': 'particlePlugin',
- 'Tilemap': 'tilemapPlugin',
- 'TilemapLayer': 'tilemapPlugin',
- 'PostProcessVolume': 'postProcessPlugin',
-};
-
-function analyzeUsedPlugins(artifact: BuildArtifact): string[] {
- const plugins = new Set<string>();
- let hasUI = false;
-
- for (const sceneData of artifact.scenes.values()) {
- const entities = (sceneData as any).entities as Array<{
- components: Array<{ type: string }>;
- }> | undefined;
- if (!entities) continue;
-
- for (const entity of entities) {
- for (const comp of entity.components) {
- const plugin = COMPONENT_TO_PLUGIN[comp.type];
- if (plugin) {
- plugins.add(plugin);
- hasUI = true;
- }
- }
- }
- }
-
- if (hasUI) {
- plugins.add('uiRenderOrderPlugin');
- }
-
- return Array.from(plugins);
-}
+import {
+ analyzeUsedPlugins,
+ collectUserScriptImports,
+ compileUserScripts,
+ resolveSceneUUIDs,
+ generatePhysicsConfig,
+} from './EmitterUtils';
// =============================================================================
// PlayableEmitter
@@ -111,7 +57,7 @@ export class PlayableEmitter implements PlatformEmitter {
// 2. Compile user scripts
progress.setPhase('compiling');
progress.setCurrentTask('Compiling scripts...', 0);
- const gameCode = await this.compileUserScripts(fs, projectDir, context, artifact);
+ const gameCode = await this.compilePlayableScripts(fs, projectDir, context, artifact);
progress.log('info', `Scripts compiled: ${gameCode.length} bytes`);
// 3. Process all scenes (resolve UUIDs)
@@ -119,7 +65,7 @@ export class PlayableEmitter implements PlatformEmitter {
const allScenes: Array<{ name: string; data: string }> = [];
for (const [name, data] of artifact.scenes) {
const copy = JSON.parse(JSON.stringify(data));
- this.resolveSceneUUIDs(copy, artifact);
+ resolveSceneUUIDs(copy, artifact);
allScenes.push({ name, data: JSON.stringify(copy) });
}
if (!allScenes.some(s => s.name === startupSceneName)) {
@@ -189,11 +135,13 @@ export class PlayableEmitter implements PlatformEmitter {
const success = await fs.writeFile(outputPath, html);
if (success) {
+ const fileSize = new TextEncoder().encode(html).length;
progress.log('info', `Build successful: ${outputPath}`);
return {
success: true,
outputPath,
- outputSize: new TextEncoder().encode(html).length,
+ outputSize: fileSize,
+ outputFiles: [{ path: outputPath, size: fileSize }],
};
}
return { success: false, error: 'Failed to write output file' };
@@ -221,15 +169,13 @@ export class PlayableEmitter implements PlatformEmitter {
}
}
- private async compileUserScripts(fs: NativeFS, projectDir: string, context: BuildContext, artifact: BuildArtifact): Promise<string> {
- const scriptsPath = joinPath(projectDir, 'src');
- const hasSrcDir = await fs.exists(scriptsPath);
-
- let imports = '';
- if (hasSrcDir) {
- const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);
- imports = scripts.map(p => `import "${p}";`).join('\n');
- }
+ private async compilePlayableScripts(
+ fs: NativeFS,
+ projectDir: string,
+ context: BuildContext,
+ artifact: BuildArtifact,
+ ): Promise<string> {
+ const { imports, hasSrcDir } = await collectUserScriptImports(fs, projectDir);
const usedPlugins = analyzeUsedPlugins(artifact);
const alwaysPlugins = ['animationPlugin', 'audioPlugin', 'particlePlugin'];
@@ -250,91 +196,22 @@ const __plugins = [${pluginList}];
`;
const settings = context.config.playableSettings!;
- const defines: Record<string, string> = {
- 'process.env.EDITOR': 'false',
- };
- for (const def of context.config.defines) {
- defines[`process.env.${def}`] = 'true';
- }
-
- await initializeEsbuild();
-
- const plugin = createBuildVirtualFsPlugin(fs, projectDir, async (path) => {
- if (path === 'esengine') {
- return { contents: await fs.getSdkEsmJs(), loader: 'js' as esbuild.Loader };
- }
- if (path === 'esengine/wasm') {
- return { contents: await fs.getSdkWasmJs(), loader: 'js' as esbuild.Loader };
- }
- return { contents: '', loader: 'js' as esbuild.Loader };
- });
+ const scriptsPath = joinPath(projectDir, 'src');
- const result = await esbuild.build({
- stdin: {
- contents: entryContent,
- loader: 'ts',
- resolveDir: hasSrcDir ? scriptsPath : projectDir,
- },
- bundle: true,
- format: 'iife',
- write: false,
- platform: 'browser',
- target: 'es2020',
- treeShaking: true,
+ return compileUserScripts(fs, projectDir, context, {
+ entryContent,
+ resolveDir: hasSrcDir ? scriptsPath : projectDir,
minify: settings.minifyCode,
- define: defines,
- plugins: [plugin],
- });
-
- const output = result.outputFiles?.[0]?.text;
- if (!output) {
- throw new Error('esbuild produced no output');
- }
- return output;
- }
-
- private resolveSceneUUIDs(sceneData: Record<string, unknown>, artifact: BuildArtifact): void {
- const entities = sceneData.entities as Array<{
- components: Array<{ type: string; data: Record<string, unknown> }>;
- prefab?: { prefabPath: string };
- }> | undefined;
- if (!entities) return;
-
- for (const entity of entities) {
- if (entity.prefab && typeof entity.prefab.prefabPath === 'string') {
- if (isUUID(entity.prefab.prefabPath)) {
- const path = artifact.assetLibrary.getPath(entity.prefab.prefabPath);
- if (path) entity.prefab.prefabPath = toBuildPath(path);
- } else {
- entity.prefab.prefabPath = toBuildPath(entity.prefab.prefabPath);
+ sdkResolver: async (path) => {
+ if (path === 'esengine') {
+ return { contents: await fs.getSdkEsmJs(), loader: 'js' as esbuild.Loader };
}
- }
- for (const comp of entity.components || []) {
- const refFields = getComponentRefFields(comp.type);
- if (!refFields || !comp.data) continue;
- for (const field of refFields) {
- const value = comp.data[field];
- if (typeof value === 'string' && isUUID(value)) {
- const path = artifact.assetLibrary.getPath(value);
- if (path) comp.data[field] = toBuildPath(path);
- }
- }
- }
- }
-
- const textureMetadata = sceneData.textureMetadata as Record<string, unknown> | undefined;
- if (textureMetadata) {
- const resolved: Record<string, unknown> = {};
- for (const [key, value] of Object.entries(textureMetadata)) {
- if (isUUID(key)) {
- const path = artifact.assetLibrary.getPath(key);
- resolved[path ?? key] = value;
- } else {
- resolved[key] = value;
+ if (path === 'esengine/wasm') {
+ return { contents: await fs.getSdkWasmJs(), loader: 'js' as esbuild.Loader };
}
- }
- sceneData.textureMetadata = resolved;
- }
+ return { contents: '', loader: 'js' as esbuild.Loader };
+ },
+ });
}
private async collectInlineAssets(
@@ -460,12 +337,7 @@ const __plugins = [${pluginList}];
physicsScript = `<script>\nvar __PHYSICS_WASM_B64__="${physicsWasmBase64}";\n${physicsJs}\n</script>`;
}
- const physicsConfig = JSON.stringify({
- gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
- fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
- subStepCount: context.physicsSubStepCount ?? 4,
- collisionLayerMasks: context.collisionLayerMasks,
- });
+ const physicsConfig = generatePhysicsConfig(context);
const enableCTA = context.config.playableSettings?.enableBuiltinCTA ?? false;
const ctaUrl = JSON.stringify(context.config.playableSettings?.ctaUrl || '');
diff --git a/editor/src/builder/SceneDiscovery.ts b/editor/src/builder/SceneDiscovery.ts
new file mode 100644
index 000000000..599fbe32c
--- /dev/null
+++ b/editor/src/builder/SceneDiscovery.ts
@@ -0,0 +1,42 @@
+/**
+ * @file SceneDiscovery.ts
+ * @brief Discovers .esscene files in a project's assets directory
+ */
+
+import type { NativeFS } from '../types/NativeFS';
+import { joinPath } from '../utils/path';
+
+const SCENE_EXTENSION = '.esscene';
+
+export async function discoverProjectScenes(
+ fs: NativeFS,
+ projectDir: string,
+): Promise<string[]> {
+ const assetsDir = joinPath(projectDir, 'assets');
+ if (!await fs.exists(assetsDir)) return [];
+
+ const scenes: string[] = [];
+ await scanDirectory(fs, assetsDir, 'assets', scenes);
+ scenes.sort();
+ return scenes;
+}
+
+async function scanDirectory(
+ fs: NativeFS,
+ absDir: string,
+ relDir: string,
+ results: string[],
+): Promise<void> {
+ const entries = await fs.listDirectoryDetailed(absDir);
+
+ for (const entry of entries) {
+ const childAbs = joinPath(absDir, entry.name);
+ const childRel = `${relDir}/${entry.name}`;
+
+ if (entry.isDirectory) {
+ await scanDirectory(fs, childAbs, childRel, results);
+ } else if (entry.name.endsWith(SCENE_EXTENSION)) {
+ results.push(childRel);
+ }
+ }
+}
diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.ts
index 2156862ba..dfde811b0 100644
--- a/editor/src/builder/WeChatEmitter.ts
+++ b/editor/src/builder/WeChatEmitter.ts
@@ -5,16 +5,20 @@
import * as esbuild from 'esbuild-wasm/esm/browser';
import type { PlatformEmitter, BuildArtifact } from './PlatformEmitter';
-import type { BuildResult, BuildContext, RuntimeBuildConfig } from './BuildService';
+import type { BuildResult, BuildContext, OutputFileEntry } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { getEditorContext } from '../context/EditorContext';
-import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
import { joinPath, getProjectDir } from '../utils/path';
import { resolveShaderPath } from '../utils/shader';
-import { initializeEsbuild, createBuildVirtualFsPlugin, generateAddressableManifest } from './ArtifactBuilder';
+import { generateAddressableManifest } from './ArtifactBuilder';
import { generateWeChatGameJs } from './templates';
import type { NativeFS } from '../types/NativeFS';
import { getWeChatPackOptions, getAssetTypeEntry, toBuildPath } from 'esengine';
+import {
+ collectUserScriptImports,
+ compileUserScripts,
+ generatePhysicsConfig,
+} from './EmitterUtils';
// =============================================================================
// WeChatEmitter
@@ -105,8 +109,10 @@ export class WeChatEmitter implements PlatformEmitter {
progress.log('info', 'Generated asset-manifest.json');
progress.setCurrentTask('Finalizing...', 90);
+ const outputFiles = await this.collectOutputFiles(fs, outputDir, outputDir);
+ const totalSize = outputFiles.reduce((sum, f) => sum + f.size, 0);
progress.log('info', `Build successful: ${outputDir}`);
- return { success: true, outputPath: outputDir };
+ return { success: true, outputPath: outputDir, outputSize: totalSize, outputFiles };
} catch (err) {
console.error('[WeChatEmitter] Build error:', err);
progress.fail(String(err));
@@ -211,14 +217,20 @@ export class WeChatEmitter implements PlatformEmitter {
outputDir: string,
context: BuildContext
): Promise<void> {
- const scriptsPath = joinPath(projectDir, 'src');
+ const { imports, hasSrcDir } = await collectUserScriptImports(fs, projectDir);
let userCode = '';
- if (await fs.exists(scriptsPath)) {
- const scripts = await findTsFiles(fs, scriptsPath, EDITOR_ONLY_DIRS);
- if (scripts.length > 0) {
- userCode = await this.compileScripts(fs, projectDir, scripts, context);
- }
+ if (imports) {
+ userCode = await compileUserScripts(fs, projectDir, context, {
+ entryContent: imports,
+ resolveDir: joinPath(projectDir, 'src'),
+ minify: !context.config.defines.includes('DEBUG'),
+ sdkResolver: async () => ({
+ contents: 'module.exports = globalThis.__esengine_sdk;',
+ loader: 'js' as esbuild.Loader,
+ }),
+ preferEsmEntry: false,
+ });
}
const allSceneNames = context.config.scenes.map(
@@ -226,12 +238,7 @@ export class WeChatEmitter implements PlatformEmitter {
);
const firstSceneName = allSceneNames[0] ?? '';
- const physicsConfig = JSON.stringify({
- gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
- fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
- subStepCount: context.physicsSubStepCount ?? 4,
- collisionLayerMasks: context.collisionLayerMasks,
- });
+ const physicsConfig = generatePhysicsConfig(context);
const gameJs = generateWeChatGameJs({
userCode,
@@ -247,47 +254,6 @@ export class WeChatEmitter implements PlatformEmitter {
await this.copyWeChatSdk(fs, outputDir, context);
}
- private async compileScripts(
- fs: NativeFS,
- projectDir: string,
- scripts: string[],
- context: BuildContext
- ): Promise<string> {
- const entryContent = scripts.map(p => `import "${p}";`).join('\n');
-
- const defines: Record<string, string> = {
- 'process.env.EDITOR': 'false',
- };
- for (const def of context.config.defines) {
- defines[`process.env.${def}`] = 'true';
- }
-
- await initializeEsbuild();
-
- const plugin = createBuildVirtualFsPlugin(fs, projectDir, async () => ({
- contents: 'module.exports = globalThis.__esengine_sdk;',
- loader: 'js' as esbuild.Loader,
- }), false);
-
- const result = await esbuild.build({
- stdin: {
- contents: entryContent,
- loader: 'ts',
- resolveDir: joinPath(projectDir, 'src'),
- },
- bundle: true,
- format: 'iife',
- write: false,
- platform: 'browser',
- target: 'es2020',
- minify: !context.config.defines.includes('DEBUG'),
- define: defines,
- plugins: [plugin],
- });
-
- return result.outputFiles?.[0]?.text ?? '';
- }
-
private async copyWeChatSdk(
fs: NativeFS,
outputDir: string,
@@ -394,4 +360,29 @@ export class WeChatEmitter implements PlatformEmitter {
JSON.stringify(manifest, null, 2)
);
}
+
+ private async collectOutputFiles(
+ fs: NativeFS,
+ dir: string,
+ rootDir: string,
+ ): Promise<OutputFileEntry[]> {
+ const results: OutputFileEntry[] = [];
+ const entries = await fs.listDirectoryDetailed(dir);
+
+ for (const entry of entries) {
+ const fullPath = joinPath(dir, entry.name);
+ if (entry.isDirectory) {
+ const children = await this.collectOutputFiles(fs, fullPath, rootDir);
+ results.push(...children);
+ } else {
+ const stats = await fs.getFileStats(fullPath);
+ results.push({
+ path: fullPath.substring(rootDir.length + 1),
+ size: stats?.size ?? 0,
+ });
+ }
+ }
+
+ return results;
+ }
}
diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.ts
index 686348246..914f526f4 100644
--- a/editor/src/builder/index.ts
+++ b/editor/src/builder/index.ts
@@ -4,7 +4,7 @@
*/
export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';
-export { BuildService, type BuildResult, type BuildContext, type BuildOptions } from './BuildService';
+export { BuildService, type BuildResult, type BuildContext, type BuildOptions, type OutputFileEntry } from './BuildService';
export { buildArtifact, initializeEsbuild, createBuildVirtualFsPlugin, arrayBufferToBase64, generateAddressableManifest, type SdkModuleLoader } from './ArtifactBuilder';
export { PLAYABLE_HTML_TEMPLATE, generateWeChatGameJs, type WeChatGameJsParams } from './templates';
@@ -15,12 +15,15 @@ export { BuildConfigService, getBuildConfigService, initBuildConfigService, type
export { BuildPipeline, createTask, createPlayableTasks, type BuildTask, type TaskResult, type PipelineResult } from './BuildPipeline';
export { BuildConfigIO, downloadConfigsAsFile, uploadConfigsFromFile, type ExportedConfig, type ImportResult } from './BuildConfigIO';
export { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, getBuildStatusClass, type BuildHistoryEntry, type BuildStatus } from './BuildHistory';
-export { BUILD_TEMPLATES, getTemplates, getTemplatesByPlatform, getTemplate, createConfigFromTemplate, applyTemplateToConfig, getTemplateIconSvg, type BuildTemplate } from './BuildTemplates';
+export { BUILD_TEMPLATES, getTemplates, getTemplatesByPlatform, getTemplate, createConfigFromTemplate, applyTemplateToConfig, getTemplateIconSvg, getAllTemplates, configToTemplate, saveUserTemplate, loadUserTemplates, deleteUserTemplate, type BuildTemplate, type UserTemplate } from './BuildTemplates';
export { BatchBuilder, ParallelBatchBuilder, type BatchBuildResult, type ConfigBuildResult, type BatchBuildProgress } from './BatchBuilder';
export { AssetExportConfigService, AssetReferenceCollector, BuildAssetCollector, type FolderExportMode, type AssetExportConfig } from './AssetCollector';
export { AssetDependencyAnalyzer, collectReferencedAssets, registerRefScanner, type AssetRefScanner, type DependencyGraph } from '../asset/AssetDependencyAnalyzer';
export { type PlatformEmitter, type BuildArtifact } from './PlatformEmitter';
export { PlayableEmitter } from './PlayableEmitter';
export { WeChatEmitter } from './WeChatEmitter';
+export { discoverProjectScenes } from './SceneDiscovery';
+export { analyzeUsedPlugins, buildDefinesMap, generatePhysicsConfig, compileUserScripts, resolveSceneUUIDs, collectUserScriptImports, type CompileOptions } from './EmitterUtils';
+export { executeHooks, validateHook, createDefaultHook } from './BuildHooks';
export { TextureAtlasPacker, type AtlasFrame, type AtlasPage, type AtlasResult } from './TextureAtlas';
export { AssetDatabase, AssetDatabase as AssetLibrary, getAssetDatabase, getAssetDatabase as getAssetLibrary, resetAssetDatabase, resetAssetDatabase as resetAssetLibrary, isUUID } from '../asset/AssetDatabase';
diff --git a/editor/src/styles/builder.css b/editor/src/styles/builder.css
index 0dd1138ab..b9420d5a8 100644
--- a/editor/src/styles/builder.css
+++ b/editor/src/styles/builder.css
@@ -1533,3 +1533,174 @@
.es-addressable-window .es-addressable-panel > .es-panel-header {
display: none;
}
+
+/* =============================================================================
+ * Scene Management
+ * ============================================================================= */
+
+.es-build-scene-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 4px;
+}
+
+.es-build-scene-drag-handle {
+ cursor: grab;
+ opacity: 0.4;
+ flex-shrink: 0;
+}
+
+.es-build-scene-drag-handle:hover {
+ opacity: 0.8;
+}
+
+.es-build-scene-item[draggable="true"] {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.es-build-scene-item.es-dragging {
+ opacity: 0.4;
+}
+
+.es-build-scene-item.es-drag-over {
+ border-top: 2px solid var(--es-accent);
+}
+
+.es-build-scene-path {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-build-badge-small {
+ font-size: 9px;
+ padding: 1px 4px;
+ border-radius: 3px;
+ background: var(--es-accent);
+ color: #fff;
+ flex-shrink: 0;
+}
+
+.es-btn-danger {
+ color: var(--es-error, #e74c3c) !important;
+}
+
+/* Scene Picker */
+
+.es-build-scene-picker-list {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.es-build-scene-picker-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 8px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 12px;
+}
+
+.es-build-scene-picker-item:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-build-scene-picker-item.es-active {
+ background: var(--es-bg-tertiary);
+}
+
+/* =============================================================================
+ * Build Hooks
+ * ============================================================================= */
+
+.es-build-hooks-list {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.es-build-hook-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ background: var(--es-bg-primary);
+ border-radius: 4px;
+ font-size: 12px;
+}
+
+.es-build-hook-type {
+ font-weight: 500;
+ flex-shrink: 0;
+}
+
+.es-build-hook-detail {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0.7;
+}
+
+.es-build-hook-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 4px;
+}
+
+/* =============================================================================
+ * Output File List
+ * ============================================================================= */
+
+.es-build-file-list {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ max-height: 200px;
+ overflow-y: auto;
+}
+
+.es-build-file-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 2px 6px;
+ font-size: 11px;
+ font-family: var(--es-font-mono, monospace);
+}
+
+.es-build-file-icon {
+ flex-shrink: 0;
+ opacity: 0.5;
+}
+
+.es-build-file-path {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-build-file-dir {
+ opacity: 0.5;
+}
+
+.es-build-file-size {
+ flex-shrink: 0;
+ opacity: 0.6;
+ font-size: 10px;
+}
+
+.es-build-file-more {
+ padding: 4px 6px;
+ font-size: 11px;
+ opacity: 0.5;
+ font-style: italic;
+}
diff --git a/editor/src/types/BuildTypes.ts b/editor/src/types/BuildTypes.ts
index d4e9af1b3..d68145860 100644
--- a/editor/src/types/BuildTypes.ts
+++ b/editor/src/types/BuildTypes.ts
@@ -51,6 +51,30 @@ export interface WeChatSettings {
openDataContext?: string;
}
+// =============================================================================
+// Build Hooks
+// =============================================================================
+
+export type BuildHookPhase = 'pre' | 'post';
+export type BuildHookType = 'copy-files' | 'run-command';
+
+export interface CopyFilesConfig {
+ from: string;
+ to: string;
+ pattern?: string;
+}
+
+export interface RunCommandConfig {
+ command: string;
+ args?: string[];
+}
+
+export interface BuildHook {
+ phase: BuildHookPhase;
+ type: BuildHookType;
+ config: CopyFilesConfig | RunCommandConfig;
+}
+
// =============================================================================
// Build Configuration
// =============================================================================
@@ -62,6 +86,7 @@ export interface BuildConfig {
scenes: string[];
defines: string[];
additionalAssets?: string[];
+ hooks?: BuildHook[];
playableSettings?: PlayableSettings;
wechatSettings?: WeChatSettings;
}
diff --git a/editor/src/types/NativeFS.ts b/editor/src/types/NativeFS.ts
index 907bdac74..c58f812f7 100644
--- a/editor/src/types/NativeFS.ts
+++ b/editor/src/types/NativeFS.ts
@@ -51,4 +51,5 @@ export interface NativeFS {
getPhysicsJs(): Promise<string>;
getPhysicsWasm(): Promise<Uint8Array>;
toAssetUrl?(path: string): string;
+ executeCommand?(command: string, args: string[], cwd: string): Promise<{ exitCode: number; stdout: string; stderr: string }>;
}
diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.ts
index f8fd032b9..b30548c33 100644
--- a/editor/src/utils/icons.ts
+++ b/editor/src/utils/icons.ts
@@ -73,6 +73,7 @@ import {
Minus,
Hexagon,
Link2,
+ GripVertical,
} from 'lucide';
// =============================================================================
@@ -202,6 +203,7 @@ export const icons = {
minus: (size?: number) => renderIcon(Minus as IconNode, size),
hexagon: (size?: number) => renderIcon(Hexagon as IconNode, size),
link: (size?: number) => renderIcon(Link2 as IconNode, size),
+ grip: (size?: number) => renderIcon(GripVertical as IconNode, size),
};
export type IconName = keyof typeof icons;