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.

fix(export): a shipped build gets the project's physics world and its mixer

yhh0e43db297abc
diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.ts
index cc8c5c32e..8b98afa34 100644
--- a/desktop/electron/exportMiniGame.ts
+++ b/desktop/electron/exportMiniGame.ts
@@ -115,9 +115,14 @@ async function scanSideModules(
absOut: string,
wasmDir: string,
errors: string[],
+ physicsEnabled: boolean,
): Promise<Array<{ id: string; file: string }>> {
const ids = new Set<string>();
- if (sceneDatas.some((s) => s && sceneUsesPhysics(s as Parameters<typeof sceneUsesPhysics>[0]))) ids.add('physics');
+ // The project's own declaration counts as a use: a game that spawns bodies from
+ // script has none in the scene, and shipping the enable flag without the binary
+ // would fail at the first spawn instead of at build time.
+ if (physicsEnabled
+ || sceneDatas.some((s) => s && sceneUsesPhysics(s as Parameters<typeof sceneUsesPhysics>[0]))) ids.add('physics');
if (sceneDatas.some((s) => s && sceneUsesVideo(s as Parameters<typeof sceneUsesVideo>[0]))) ids.add('videodec');
if (sceneDatas.some((s) => s && sceneUsesDragonBones(s as Parameters<typeof sceneUsesDragonBones>[0]))) ids.add('dragonbones');
// Any staged .esv also needs the decoder: script-driven playback
@@ -273,7 +278,10 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// the generated entry requires exactly those — the export-time half of
// the runtime's self-gating. A dynamically switched scene must find its
// modules present, so the union over ALL shipped scenes counts.
- const engineSideModules = await scanSideModules(profile, [...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors);
+ const engineSideModules = await scanSideModules(
+ profile, [...sceneRawByName.values()], cookEntries, absOut, opts.wasmDir, errors,
+ opts.runtime?.physicsEnabled ?? false,
+ );
// …plus the ones the PROJECT supplies. They are not scanned for: a project put
// them in `.esengine/modules/` in order to use them, and unlike physics or
// spine there is no component in the scene the engine could recognize as the
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index 31b2251dd..9164b537a 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -123,9 +123,13 @@ async function collectSideModules(
cookDir: string,
wasmDir: string,
errors: string[],
+ physicsEnabled: boolean,
): Promise<Record<string, { glueBase64: string; wasmBase64: string }>> {
const ids = new Set<string>();
- if (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0])) ids.add('physics');
+ // A declared physics project counts as a use even with no bodies in the scene:
+ // it spawns them from script, and the flag is worthless without the binary.
+ if (physicsEnabled
+ || (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0]))) ids.add('physics');
if (sceneData && sceneUsesDragonBones(sceneData as Parameters<typeof sceneUsesDragonBones>[0])) ids.add('dragonbones');
// Spine: the skeleton carries the version. Skeleton + atlas share the authored
// meta type `spine`, so we discriminate by extension (as the runtime does via
@@ -297,7 +301,10 @@ export async function exportPlayable(opts: {
// A needed module missing from wasmDir is a HARD error — better a failed
// export than a playable that silently ships without physics.
progress({ phase: 'Embedding modules' });
- const sideModules = await collectSideModules(scenes[0]?.data, manifestEntries, cookDir, opts.wasmDir, errors);
+ const sideModules = await collectSideModules(
+ scenes[0]?.data, manifestEntries, cookDir, opts.wasmDir, errors,
+ opts.runtime?.physicsEnabled ?? false,
+ );
// 6. Assemble the single HTML, then drop the temp cook dir.
progress({ phase: 'Assembling HTML' });
diff --git a/desktop/src/project/runtimeConfig.ts b/desktop/src/project/runtimeConfig.ts
index 118337065..4e53b4074 100644
--- a/desktop/src/project/runtimeConfig.ts
+++ b/desktop/src/project/runtimeConfig.ts
@@ -135,6 +135,7 @@ export function runtimeConfigOf(
export type PackagedRuntimeFields = Pick<
PackagedGameConfig,
'ySortLayers' | 'depthLayers' | 'colorSpace' | 'screenFit' | 'uiTheme' | 'uiThemeColors'
+ | 'physicsEnabled' | 'physicsConfig' | 'audioConfig'
>;
/**
@@ -154,8 +155,23 @@ export function packagedRuntimeFields(rc: RuntimeProjectConfig): PackagedRuntime
...(rc.screenFit.scaleMode >= 0 ? { screenFit: rc.screenFit } : {}),
...(rc.uiTheme === 'light' ? { uiTheme: rc.uiTheme } : {}),
...(Object.keys(rc.uiThemeColors).length > 0 ? { uiThemeColors: rc.uiThemeColors } : {}),
+ // Physics and the mixer ride along only when the project actually declared
+ // something: a build whose settings are all defaults keeps the config it has
+ // always had, byte for byte, and the runtime falls back to the same values
+ // this would have spelled out.
+ ...(rc.physicsEnabled ? { physicsEnabled: true } : {}),
+ ...(isDefaultPhysics(rc.physicsConfig) ? {} : { physicsConfig: rc.physicsConfig }),
+ ...(rc.audioConfig.buses?.length ? { audioConfig: rc.audioConfig } : {}),
};
}
+/** Whether the world config is exactly what a runtime would default to anyway. */
+function isDefaultPhysics(config: PhysicsPluginConfig): boolean {
+ return JSON.stringify(config) === JSON.stringify(DEFAULT_PHYSICS_CONFIG);
+}
+
/** The effective settings of a project with nothing declared — every default. */
export const DEFAULT_RUNTIME_CONFIG: RuntimeProjectConfig = runtimeConfigOf({});
+
+/** The physics world an undeclared project runs, for "is this worth shipping". */
+const DEFAULT_PHYSICS_CONFIG: PhysicsPluginConfig = DEFAULT_RUNTIME_CONFIG.physicsConfig;
diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.ts
index 81c722415..c4964d945 100644
--- a/desktop/tests/export-playable.test.ts
+++ b/desktop/tests/export-playable.test.ts
@@ -44,7 +44,9 @@ beforeAll(() => {
// Stub SDK dist exporting what the real host + scripts import (bundles for real).
mkdirSync(path.join(root, '_sdk'), { recursive: true });
writeFileSync(path.join(root, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\nexport function parseThemeOverrides(){}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
// Stub web wasm runtime (glue text + wasm) — playable inlines these, no separate build.
mkdirSync(path.join(root, '_wasm'), { recursive: true });
writeFileSync(path.join(root, '_wasm', 'esengine.js'), `export default function(){}/*WEB_GLUE*/\n`);
@@ -257,7 +259,9 @@ describe('exportGame (playable) — side-module embedding', () => {
writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(PSCN, 'scene'));
mkdirSync(path.join(r, '_sdk'), { recursive: true });
writeFileSync(path.join(r, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
mkdirSync(path.join(r, '_wasm'), { recursive: true });
writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
@@ -273,6 +277,31 @@ describe('exportGame (playable) — side-module embedding', () => {
sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',
});
+ // A game that spawns its bodies from script has none in the scene, so the scan
+ // sees nothing — and the package used to ship without physics.wasm while the
+ // config told the runtime to install physics. Both halves or neither.
+ it('inlines physics for a declared physics project whose scene has no bodies', async () => {
+ const { r, o } = setupRoot(true);
+ try {
+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [] }] }));
+ const res = await exportGame({
+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,
+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',
+ runtime: runtimeConfigOf({ features: { physics: { enabled: true, gravity: { x: 0, y: -20 } } } }),
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('"physics"');
+ expect(html).toContain(Buffer.from('PHYSWASM').toString('base64'));
+ // ...and the runtime is told to install it, plus the world it declared.
+ expect(html).toMatch(/"physicsEnabled":true/);
+ expect(html).toMatch(/"y":-20/);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+
it('inlines physics into __SIDE_MODULES__ when the scene uses physics', async () => {
const { r, o } = setupRoot(true);
try {
@@ -331,7 +360,9 @@ describe('exportGame (playable) — spine embedding', () => {
writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(SSCN, 'scene'));
mkdirSync(path.join(r, '_sdk'), { recursive: true });
writeFileSync(path.join(r, '_sdk', 'index.js'),
- `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}\n`);
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
mkdirSync(path.join(r, '_wasm'), { recursive: true });
writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
diff --git a/desktop/tests/runtime-config.test.ts b/desktop/tests/runtime-config.test.ts
index 38ff8b414..d62eafea0 100644
--- a/desktop/tests/runtime-config.test.ts
+++ b/desktop/tests/runtime-config.test.ts
@@ -94,6 +94,32 @@ describe('packagedRuntimeFields', () => {
});
});
+ // Physics and the mixer used to reach Play and no shipped build at all, so a
+ // game verified in Play could ship with different gravity and a silent mixer.
+ it('carries physics and the mixer, which used to reach Play and no build', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ features: {
+ physics: { enabled: true, gravity: { x: 0, y: -20 }, collisionLayerMasks: [0xfffe] },
+ audio: { buses: [{ name: 'sfx', volume: 0.5 }] },
+ },
+ }));
+ expect(fields.physicsEnabled).toBe(true);
+ expect(fields.physicsConfig?.gravity).toEqual({ x: 0, y: -20 });
+ expect(fields.physicsConfig?.collisionLayerMasks?.[0]).toBe(0xfffe);
+ expect(fields.audioConfig?.buses?.[0]).toEqual({ name: 'sfx', volume: 0.5 });
+ });
+
+ // ...but only when declared: a default world would otherwise be spelled out in
+ // every existing build's config, and a runtime falls back to the same values.
+ it('omits a physics world and a mixer that are just the defaults', () => {
+ const declaredButDefault = packagedRuntimeFields(runtimeConfigOf({
+ features: { physics: { gravity: { x: 0, y: -9.81 } }, audio: {} },
+ }));
+ expect(declaredButDefault.physicsConfig).toBeUndefined();
+ expect(declaredButDefault.audioConfig).toBeUndefined();
+ expect(declaredButDefault.physicsEnabled).toBeUndefined();
+ });
+
// The editor's live project state is not a manifest object, but it has the two
// fields this reads — that structural match is what lets one derivation serve
// the renderer and the main process.
diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjs
index 64570f89b..ff345ed09 100644
--- a/tools/check-project-settings.mjs
+++ b/tools/check-project-settings.mjs
@@ -43,17 +43,9 @@ const STORE = 'desktop/src/project/ProjectStore.ts';
const DECLARED_GAPS = {
physicsEnabled: {
editor: 'edit mode does not simulate — bodies are authored, not stepped',
- packaged: 'game.config.json has no physics field yet; a shipped build installs '
- + 'physics only when a scene uses it, so a project that spawns bodies from '
- + 'script still needs this carried (tracked follow-up)',
},
physicsConfig: {
editor: 'edit mode does not simulate — see physicsEnabled',
- packaged: 'same follow-up as physicsEnabled: gravity/solver reach Play and not a build',
- },
- audioConfig: {
- packaged: 'the mixer state reaches Play and not a shipped build yet (same '
- + 'follow-up: PackagedGameConfig has no audio field)',
},
colorSpace: {
editor: 'boot-fixed — shaders compile against it, so the settings page asks '