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: generate addressable manifest and improve build pipeline

esengine28f1dc2f91bc
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 7c3d0d4d8..47a238489 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -53,11 +53,15 @@
loading.textContent = message;
}
- function showError(msg) {
+ function showError(msg, err) {
loading.style.display = 'none';
errorDiv.style.display = 'block';
- errorDiv.textContent = msg;
- console.error('Preview Error:', msg);
+ let detail = msg;
+ if (err && err.stack) {
+ detail += '\n\n' + err.stack;
+ }
+ errorDiv.textContent = detail;
+ console.error('Preview Error:', msg, err || '');
}
function setupCanvas() {
@@ -91,11 +95,14 @@
}
async function loadPreview() {
+ let step = 'init';
try {
+ step = 'load WASM module';
updateLoading('Loading WASM module...');
const ModuleLoader = await import('/wasm/esengine.js');
const Module = await ModuleLoader.default();
+ step = 'load SDK';
updateLoading('Loading SDK...');
const sdk = await import('/sdk/index.js');
@@ -108,6 +115,7 @@
config = await configResp.json();
const spineUrl = config.spineVersion && SPINE_WASM_MAP[config.spineVersion];
if (spineUrl) {
+ step = 'load Spine ' + config.spineVersion;
updateLoading('Loading Spine ' + config.spineVersion + '...');
await loadUmdScript(spineUrl);
const { SpinePlugin } = await import('esengine/spine');
@@ -120,6 +128,7 @@
if (config.enablePhysics) {
try {
+ step = 'load Physics';
updateLoading('Loading Physics...');
await loadUmdScript('/wasm/physics.js');
physicsPlugin = new sdk.PhysicsPlugin('/wasm/physics.js', {
@@ -138,16 +147,22 @@
console.warn('User scripts load skipped:', e);
}
+ step = 'setup canvas';
updateLoading('Loading scene...');
setupCanvas();
window.addEventListener('resize', () => setupCanvas());
+ step = 'create app';
const previewPlugin = new sdk.PreviewPlugin('/.esengine/preview/scene.json', '/');
const app = sdk.createWebApp(Module, {
getViewportSize: getCanvasViewportSize
});
+
+ step = 'flushPendingSystems';
sdk.flushPendingSystems(app);
+
+ step = 'add plugins';
if (spinePlugin) {
app.addPlugin(spinePlugin);
}
@@ -156,18 +171,30 @@
}
app.addPlugin(previewPlugin);
+ step = 'waitForReady (scene load)';
await previewPlugin.waitForReady();
+
if (app.__physicsInitPromise) {
+ step = 'physics init';
await app.__physicsInitPromise;
}
+ step = 'app.run';
loading.style.display = 'none';
app.run();
} catch (err) {
- showError(err.message || String(err));
+ showError('[' + step + '] ' + (err.message || String(err)), err);
}
}
+ window.addEventListener('error', (e) => {
+ showError('[runtime error] ' + (e.message || String(e)), e.error);
+ });
+ window.addEventListener('unhandledrejection', (e) => {
+ const err = e.reason;
+ showError('[unhandled rejection] ' + (err?.message || String(err)), err);
+ });
+
loadPreview();
</script>
</body>
diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.ts
index 7c6a7b40d..2015c2bf1 100644
--- a/editor/src/builder/PlayableEmitter.ts
+++ b/editor/src/builder/PlayableEmitter.ts
@@ -11,7 +11,9 @@ 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 } from '../asset/AssetLibrary';
+import { getAssetType, toAddressableType } from '../asset/AssetTypes';
import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';
+import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';
import type { NativeFS } from '../types/NativeFS';
// =============================================================================
@@ -117,13 +119,16 @@ export class PlayableEmitter implements PlatformEmitter {
}
progress.log('info', `Collected ${assets.size} assets`);
+ // 6.5 Generate addressable manifest
+ const manifestJson = this.generateAddressableManifest(artifact);
+
// 7. Assemble HTML
progress.setCurrentTask('Assembling HTML...', 50);
const html = this.assembleHTML(
wasmSdk, gameCode, rewrittenScene, assets,
spineJsSource, spineWasmBase64,
physicsJsSource, physicsWasmBase64,
- context
+ context, manifestJson
);
progress.log('info', `HTML assembled: ${html.length} bytes`);
@@ -234,10 +239,15 @@ ${imports}
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' && isUUID(entity.prefab.prefabPath)) {
+ const path = artifact.assetLibrary.getPath(entity.prefab.prefabPath);
+ if (path) entity.prefab.prefabPath = path;
+ }
for (const comp of entity.components || []) {
if (comp.type === 'Sprite' && comp.data) {
if (typeof comp.data.texture === 'string' && isUUID(comp.data.texture)) {
@@ -308,6 +318,24 @@ ${imports}
continue;
}
+ if (relativePath.endsWith('.esprefab')) {
+ const fullPath = joinPath(projectDir, relativePath);
+ const content = await fs.readFile(fullPath);
+ if (content) {
+ const prefab = deserializePrefab(content);
+ const converted = convertPrefabAssetRefs(prefab, (value) => {
+ if (isUUID(value)) {
+ return artifact.assetLibrary.getPath(value) ?? value;
+ }
+ return value;
+ });
+ const json = JSON.stringify(converted);
+ const base64 = btoa(json);
+ assets.set(relativePath, `data:application/json;base64,${base64}`);
+ }
+ continue;
+ }
+
const ext = getFileExtension(relativePath);
const mimeType = MIME_TYPES[ext];
if (!mimeType) continue;
@@ -346,7 +374,7 @@ ${imports}
assets: Map<string, string>,
spineJs: string, spineWasmBase64: string,
physicsJs: string, physicsWasmBase64: string,
- context: BuildContext
+ context: BuildContext, manifestJson: string
): string {
const entries: string[] = [];
for (const [path, dataUrl] of assets) {
@@ -376,7 +404,91 @@ ${imports}
.replace('{{GAME_CODE}}', () => gameCode)
.replace('{{ASSETS_MAP}}', () => `{${entries.join(',')}}`)
.replace('{{SCENE_DATA}}', () => sceneData)
- .replace('{{PHYSICS_CONFIG}}', () => physicsConfig);
+ .replace('{{PHYSICS_CONFIG}}', () => physicsConfig)
+ .replace('{{MANIFEST}}', () => manifestJson);
+ }
+
+ private generateAddressableManifest(artifact: BuildArtifact): string {
+ const groupService = artifact.assetLibrary.getGroupService();
+ const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> = {};
+
+ const spineAtlasPaths = new Map<string, string>();
+ for (const relativePath of artifact.assetPaths) {
+ if (getAssetType(relativePath) === 'spine-atlas') {
+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));
+ spineAtlasPaths.set(dir, relativePath);
+ }
+ }
+
+ for (const relativePath of artifact.assetPaths) {
+ if (relativePath.endsWith('.esshader')) continue;
+
+ const editorType = getAssetType(relativePath);
+ const addressableType = toAddressableType(editorType);
+ if (!addressableType) continue;
+
+ const uuid = artifact.assetLibrary.getUuid(relativePath);
+ if (!uuid) continue;
+
+ const entry = artifact.assetLibrary.getEntry(uuid);
+ const groupName = entry?.group ?? 'default';
+
+ if (!groups[groupName]) {
+ const groupDef = groupService?.getGroup(groupName);
+ groups[groupName] = {
+ bundleMode: groupDef?.bundleMode ?? 'together',
+ labels: groupDef?.labels ?? [],
+ assets: {},
+ };
+ }
+
+ let path = relativePath;
+ const metadata: Record<string, unknown> = {};
+
+ if (artifact.packedPaths.has(relativePath)) {
+ const frame = artifact.atlasResult.frameMap.get(relativePath);
+ if (frame) {
+ path = `atlas_${frame.page}.png`;
+ metadata.atlasPage = frame.page;
+ metadata.atlasFrame = {
+ x: frame.frame.x,
+ y: frame.frame.y,
+ width: frame.frame.width,
+ height: frame.frame.height,
+ };
+ }
+ }
+
+ const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);
+ if (compiledMat) {
+ path = relativePath.replace(/\.esmaterial$/, '.json');
+ }
+
+ if (addressableType === 'spine') {
+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));
+ const atlasPath = spineAtlasPaths.get(dir);
+ if (atlasPath) {
+ metadata.atlas = atlasPath;
+ }
+ }
+
+ const asset: Record<string, unknown> = {
+ path,
+ type: addressableType,
+ size: entry?.fileSize ?? 0,
+ labels: entry ? [...entry.labels] : [],
+ };
+ if (entry?.address) {
+ asset.address = entry.address;
+ }
+ if (Object.keys(metadata).length > 0) {
+ asset.metadata = metadata;
+ }
+
+ groups[groupName].assets[uuid] = asset;
+ }
+
+ return JSON.stringify({ version: '2.0', groups });
}
private arrayBufferToBase64(buffer: Uint8Array): string {
@@ -419,6 +531,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#000}
<script>
var __PA__={{ASSETS_MAP}};
var __SCENE__={{SCENE_DATA}};
+var __MANIFEST__={{MANIFEST}};
function loadImagePixels(dataUrl){
return new Promise(function(resolve,reject){
@@ -496,7 +609,7 @@ function decodeBinary(dataUrl){
resolvePath:function(ref){return ref}
};
- await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}});
+ await es.loadRuntimeScene(app,Module,__SCENE__,provider,spineModule,physicsModule,{{PHYSICS_CONFIG}},__MANIFEST__);
var screenAspect=c.width/c.height;
es.updateCameraAspectRatio(app.world,screenAspect);
diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.ts
index c67b9934b..29150cc40 100644
--- a/editor/src/builder/WeChatEmitter.ts
+++ b/editor/src/builder/WeChatEmitter.ts
@@ -10,20 +10,13 @@ import { BuildProgressReporter } from './BuildProgress';
import { getEditorContext } from '../context/EditorContext';
import { findTsFiles, EDITOR_ONLY_DIRS } from '../scripting/ScriptLoader';
import { joinPath, getProjectDir } from '../utils/path';
-import { getAssetType } from '../asset/AssetTypes';
+import { isUUID } from '../asset/AssetLibrary';
+import { getAssetType, toAddressableType } from '../asset/AssetTypes';
import { resolveShaderPath } from '../utils/shader';
import { initializeEsbuild, createBuildVirtualFsPlugin } from './ArtifactBuilder';
+import { convertPrefabAssetRefs, deserializePrefab } from '../prefab';
import type { NativeFS } from '../types/NativeFS';
-// =============================================================================
-// Types
-// =============================================================================
-
-interface AssetManifestEntry {
- path: string;
- type: string;
-}
-
// =============================================================================
// WeChatEmitter
// =============================================================================
@@ -235,9 +228,15 @@ var SDK = require('./sdk.js');
globalThis.__esengine_sdk = SDK;
var manifest = JSON.parse(wx.getFileSystemManager().readFileSync('asset-manifest.json', 'utf-8'));
-
+var assetIndex = {};
+for (var gn in manifest.groups) {
+ var g = manifest.groups[gn];
+ for (var uuid in g.assets) {
+ assetIndex[uuid] = g.assets[uuid];
+ }
+}
function resolvePath(ref) {
- var entry = manifest[ref];
+ var entry = assetIndex[ref];
return entry ? entry.path : ref;
}
@@ -332,7 +331,7 @@ async function initPhysicsModule() {
gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
subStepCount: context.physicsSubStepCount ?? 4,
- })});
+ })}, manifest);
var screenAspect = canvas.width / canvas.height;
SDK.updateCameraAspectRatio(app.world, screenAspect);
@@ -466,6 +465,21 @@ async function initPhysicsModule() {
const destDir = destPath.substring(0, destPath.lastIndexOf('/'));
await fs.createDirectory(destDir);
+ if (relativePath.endsWith('.esprefab')) {
+ const content = await fs.readFile(srcPath);
+ if (content) {
+ const prefab = deserializePrefab(content);
+ const converted = convertPrefabAssetRefs(prefab, (value) => {
+ if (isUUID(value)) {
+ return artifact.assetLibrary.getPath(value) ?? value;
+ }
+ return value;
+ });
+ await fs.writeFile(destPath, JSON.stringify(converted, null, 2));
+ }
+ continue;
+ }
+
const data = await fs.readBinaryFile(srcPath);
if (data) {
await fs.writeBinaryFile(destPath, data);
@@ -478,40 +492,86 @@ async function initPhysicsModule() {
outputDir: string,
artifact: BuildArtifact
): Promise<void> {
- const manifest: Record<string, AssetManifestEntry> = {};
+ const groupService = artifact.assetLibrary.getGroupService();
+ const groups: Record<string, { bundleMode: string; labels: string[]; assets: Record<string, unknown> }> = {};
+
+ const spineAtlasPaths = new Map<string, string>();
+ for (const relativePath of artifact.assetPaths) {
+ if (getAssetType(relativePath) === 'spine-atlas') {
+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));
+ spineAtlasPaths.set(dir, relativePath);
+ }
+ }
for (const relativePath of artifact.assetPaths) {
if (relativePath.endsWith('.esshader')) continue;
+ const editorType = getAssetType(relativePath);
+ const addressableType = toAddressableType(editorType);
+ if (!addressableType) continue;
+
const uuid = artifact.assetLibrary.getUuid(relativePath);
if (!uuid) continue;
+ const entry = artifact.assetLibrary.getEntry(uuid);
+ const groupName = entry?.group ?? 'default';
+
+ if (!groups[groupName]) {
+ const groupDef = groupService?.getGroup(groupName);
+ groups[groupName] = {
+ bundleMode: groupDef?.bundleMode ?? 'together',
+ labels: groupDef?.labels ?? [],
+ assets: {},
+ };
+ }
+
+ let path = relativePath;
+ const metadata: Record<string, unknown> = {};
+
if (artifact.packedPaths.has(relativePath)) {
- const entry = artifact.atlasResult.frameMap.get(relativePath);
- if (entry) {
- manifest[uuid] = {
- path: `atlas_${entry.page}.png`,
- type: 'texture',
+ const frame = artifact.atlasResult.frameMap.get(relativePath);
+ if (frame) {
+ path = `atlas_${frame.page}.png`;
+ metadata.atlasPage = frame.page;
+ metadata.atlasFrame = {
+ x: frame.frame.x,
+ y: frame.frame.y,
+ width: frame.frame.width,
+ height: frame.frame.height,
};
}
- continue;
}
const compiledMat = artifact.compiledMaterials.find(m => m.relativePath === relativePath);
if (compiledMat) {
- manifest[uuid] = {
- path: relativePath.replace(/\.esmaterial$/, '.json'),
- type: 'material',
- };
- continue;
+ path = relativePath.replace(/\.esmaterial$/, '.json');
+ }
+
+ if (addressableType === 'spine') {
+ const dir = relativePath.substring(0, relativePath.lastIndexOf('/'));
+ const atlasPath = spineAtlasPaths.get(dir);
+ if (atlasPath) {
+ metadata.atlas = atlasPath;
+ }
}
- manifest[uuid] = {
- path: relativePath,
- type: getAssetType(relativePath),
+ const asset: Record<string, unknown> = {
+ path,
+ type: addressableType,
+ size: entry?.fileSize ?? 0,
+ labels: entry ? [...entry.labels] : [],
};
+ if (entry?.address) {
+ asset.address = entry.address;
+ }
+ if (Object.keys(metadata).length > 0) {
+ asset.metadata = metadata;
+ }
+
+ groups[groupName].assets[uuid] = asset;
}
+ const manifest = { version: '2.0', groups };
await fs.writeFile(
joinPath(outputDir, 'asset-manifest.json'),
JSON.stringify(manifest, null, 2)