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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(export): a mini-game carries the optional subsystems its project uses
esengine621db92226dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17b9c9876..e8ed1cc32 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,17 @@ published separately; it ships inside the editor.### Added+- **A WeChat mini-game now carries only the optional subsystems its project uses.**+ The engine binary was never the only thing a package paid for whether it needed it or+ not: the JavaScript bundle carried Spine, DragonBones, 2D physics, 3D physics and video+ in every build, because the runtime that starts your game named all of them. It no+ longer does — the export reads the same scan that already decides which `.wasm` side+ modules ship, and builds on an SDK entry that installs only those. *hello-world* drops+ 91KB of a 1.4MB bundle; a project that does use Spine keeps Spine and drops what it+ does not. There is more to win here and it is measured: `SpinePlugin` registers a named+ resource when its module loads, which a bundler cannot remove, and that alone is 47KB+ no package can currently shed.+- **A packaged game now says it is loading.** Between the page opening and the first framean export showed its background colour and nothing else — and on a cold start that gap isthe whole download of a 1.7MB engine binary, which reads to a player as a page that diddiff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex bd84ba4d5..847269258 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -434,7 +434,31 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {await cp(built.modulePath, path.join(absOut, 'aot', 'systems.wasm'));aotArg = `, aot: ${JSON.stringify({ module: 'aot/systems.wasm', manifest: built.manifest })}`;}+ // The same answer the scan already gives for wasm side modules, asked of their+ // JS: the lean SDK entry plus the subpaths that install what this project uses.+ // Video has no subpath, so a project with video takes the whole entry.+ const OPTIONAL_SUBPATH: Record<string, string> = {+ physics: 'esengine/physics',+ physics3d: 'esengine/physics3d',+ dragonbones: 'esengine/dragonbones',+ };+ const needed = new Set(sideModules.map((m) => m.id));+ const wantsVideo = needed.has('videodec');+ // Only when the SDK build actually produced one: a tree without it (an older+ // dist, a test fixture) must fall back to the whole entry rather than alias+ // `esengine` to a file that is not there.+ const leanEntry = profile.sdkLeanEntryFile+ && existsSync(path.join(opts.sdkDir, profile.sdkLeanEntryFile))+ ? profile.sdkLeanEntryFile : null;+ const lean = !!leanEntry && !wantsVideo;+ const installs = lean+ ? [...new Set([...needed].map((id) => (id.startsWith('spine:')+ ? 'esengine/spine'+ : OPTIONAL_SUBPATH[id] ?? '')).filter(Boolean))].sort()+ : [];+const entrySrc =+ installs.map((m) => `import ${JSON.stringify(m)};\n`).join('') +`import { ${profile.runtimeInit}${installsPlatform ? ', installMiniGamePlatform' : ''}${themeColors ? ', parseThemeOverrides' : ''} } from 'esengine';\n` +(installsPlatform ? `import __platformProfile from ${JSON.stringify(profile.runtimeProfileModule)};\n` : '') +(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +@@ -455,7 +479,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// Real-device WeChat rejects es2020 syntax (`??`, `?.`) even though the// devtools accepts it; es2017 down-levels those while keeping async/await.target: profile.esTarget,- alias: esengineAlias(opts.sdkDir, profile.sdkEntryFile),+ alias: esengineAlias(opts.sdkDir, lean ? leanEntry! : profile.sdkEntryFile),minify: opts.minify ?? false,sourcemap: false,outfile: path.join(absOut, 'game-bundle.js'),diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.tsindex 2edee0bc3..664540bf0 100644--- a/pipeline/src/export/miniGameExportProfile.ts+++ b/pipeline/src/export/miniGameExportProfile.ts@@ -115,6 +115,13 @@ export interface MiniGameExportProfile {readonly id: MiniGameVendor;/** SDK dist entry the bundle aliases `esengine` to (index.wechat.js). */readonly sdkEntryFile: string;+ /**+ * The same entry with no optional subsystems, when the vendor's SDK build has+ * one. An export that knows which subsystems its content uses takes this and+ * imports those back, so the package carries no others. Absent = always the+ * whole entry.+ */+ readonly sdkLeanEntryFile?: string;/** Runtime bootstrap fn imported from 'esengine' in the generated boot. */readonly runtimeInit: string;/** Engine glue filenames to look for in wasmDir, in preference order. */@@ -206,6 +213,7 @@ export const wechatExportProfile: MiniGameExportProfile = {id: 'wechat',// The bundle aliases `esengine` → <sdkDir>/index.wechat.js (the wechat SDK build).sdkEntryFile: 'index.wechat.js',+ sdkLeanEntryFile: 'index.wechat.lean.js',runtimeInit: 'initWeChatRuntime',// Require by the ACTUAL name in the wasm dir: the -t wechat build emits// esengine.wxgame.js; a web-aligned build, esengine.js.diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.jsindex 48d18567b..7e0589ed8 100644--- a/sdk/rolldown.config.js+++ b/sdk/rolldown.config.js@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { defineConfig } from 'rolldown';-const ENTRY_FILES = ['/index.ts', '/index.wechat.ts', '/index.minigame.ts', '/index.node.ts', '/index.native.ts'];+const ENTRY_FILES = ['/index.ts', '/index.wechat.ts', '/index.wechat.lean.ts', '/index.minigame.ts', '/index.node.ts', '/index.native.ts'];const treeshake = {moduleSideEffects: (id) => ENTRY_FILES.some(e => id.endsWith(e)),};@@ -52,6 +52,7 @@ export default defineConfig([input: {'index': 'src/index.ts','index.wechat': 'src/index.wechat.ts',+ 'index.wechat.lean': 'src/index.wechat.lean.ts','index.minigame': 'src/index.minigame.ts','index.native': 'src/index.native.ts','physics/index': 'src/physics/index.ts',diff --git a/sdk/src/core-plugins.ts b/sdk/src/core-plugins.tsindex 9943acf96..fdc41f43f 100644--- a/sdk/src/core-plugins.ts+++ b/sdk/src/core-plugins.ts@@ -32,20 +32,25 @@ export { dragPlugin, DragPlugin } from './ui/input/drag';export { focusPlugin, FocusPlugin } from './ui/input/focus';export { safeAreaPlugin, SafeAreaPlugin } from './ui/layout/safe-area';-export { Physics2DPlugin, Physics2DEvents, Physics2D, loadPhysicsModule } from './physics';+// Not from the barrel: importing `./physics` INSTALLS it (physics/index.ts), and+// core is in every package — the install would follow it there and no bundler+// could drop a subsystem the project never uses.+export { Physics2DPlugin, Physics2DEvents, Physics2D } from './physics/Physics2DPlugin';+export { loadPhysicsModule } from './physics/PhysicsModuleLoader';// The contact event names, mirrored into the main barrel: an editor palette (or// game code) must be able to spell `trigger_enter` without importing the side// module, since the wire is authored whether or not physics is loaded.-export { Physics2DEventType, type Physics2DContactEventData } from './physics';+export { Physics2DEventType, type Physics2DContactEventData } from './physics/PhysicsEventBridge';// Beside the 2D solver's and for its reason: the native host maps every// `esengine/*` import onto ONE global, so a symbol the main entry does not carry// reaches a game that imports the subpath as `undefined`.-export { Physics3DPlugin, Physics3DEvents, Physics3D } from './physics3d';-export { SpinePlugin, SpineEvents, Spine } from './spine';+export { Physics3DPlugin, Physics3D } from './physics3d/Physics3DPlugin';+export { Physics3DEvents } from './physics3d/Physics3DModule';+export { SpinePlugin, SpineEvents, Spine } from './spine/SpinePlugin';// DragonBones beside it, and in the barrel for the same reason: the native entry// collapses every `esengine*` import onto ONE global, so a game reaching// `Res(DragonBones)` through `esengine/dragonbones` finds nothing on a device// unless the resource is here too.-export { DragonBonesPlugin, dragonBonesPlugin, DragonBones } from './dragonbones';+export { DragonBonesPlugin, dragonBonesPlugin, DragonBones } from './dragonbones/DragonBonesPlugin';export { PostProcessPlugin, postProcessPlugin } from './postprocess';diff --git a/sdk/src/dragonbones/index.ts b/sdk/src/dragonbones/index.tsindex 931538dbf..480991541 100644--- a/sdk/src/dragonbones/index.ts+++ b/sdk/src/dragonbones/index.ts@@ -22,3 +22,18 @@ export {} from './loadDragonBonesScene';export type { DragonBonesAssetInfo } from './loadDragonBonesScene';export type { RuntimeAssetSource } from '../runtime/runtimeAssets';++// Importing this subpath INSTALLS DragonBones — see spine/index.ts.+import { addEntryPlugin } from '../runtime/entryPlugins';+import { setSceneOptionals } from '../runtime/sceneOptionals';+import { DragonBonesPlugin as DragonBonesPluginCtor } from './DragonBonesPlugin';+import { loadDragonBonesAssets, applyDragonBonesEntities } from './loadDragonBonesScene';++addEntryPlugin(() => new DragonBonesPluginCtor());+setSceneOptionals({+ dragonBones: {+ acquire: async (app) => (await app.getPlugin(DragonBonesPluginCtor)?.acquire()) ?? null,+ load: loadDragonBonesAssets,+ apply: applyDragonBonesEntities,+ },+});diff --git a/sdk/src/index.wechat.base.ts b/sdk/src/index.wechat.base.tsnew file mode 100644index 000000000..d7138688f--- /dev/null+++ b/sdk/src/index.wechat.base.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.wechat.base.ts+ * @brief ESEngine SDK - WeChat MiniGame entry, minus the optional subsystems+ */++import { setPlatform } from './platform';+import { wechatAdapter, initWeChatPlatform } from './platform/wechat';+import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './ecs/component';+import { ensureBuiltinAiRegistrations } from './ai/builtins';++initWeChatPlatform();+setPlatform(wechatAdapter);++// Register every engine component (COMPONENT_META) so scenes never silently drop+// a component that exists in the engine but lacks a typed const.+ensureBuiltinComponentsRegistered();+ensureBuiltinAiRegistrations();+markEngineComponentBaseline();++export * from './core';+export * from './runtime/webAppFactory';++export {+ wxReadFile,+ wxReadTextFile,+ wxFileExists,+ wxFileExistsSync,+ wxWriteFile,+ wxLoadImage,+ wxGetImagePixels,+ wxLoadImagePixels,+ type ImageLoadResult,+} from './platform/wechat';++export {+ initWeChatRuntime,+ type WeChatRuntimeConfig,+} from './runtime/wechatRuntime';++// The host as data: spread it to keep everything but the one thing you replace.+export { wechatProfile } from './platform/wechat';diff --git a/sdk/src/index.wechat.lean.ts b/sdk/src/index.wechat.lean.tsnew file mode 100644index 000000000..14a8f8005--- /dev/null+++ b/sdk/src/index.wechat.lean.ts@@ -0,0 +1,15 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.wechat.lean.ts+ * @brief ESEngine SDK - WeChat MiniGame entry with no optional subsystems+ *+ * Same engine as index.wechat, minus Spine, DragonBones, physics, 3D physics and+ * video — 259KB of a bundle, measured, in a project using none of them. A+ * package built on this imports the subpaths its own content needs+ * (`esengine/spine`, `esengine/physics`, …), which is what installs them.+ *+ * A scene that needs one nobody imported loads without it and says so, rather+ * than failing: what a lean build IS, is a build that ships less.+ */+export * from './index.wechat.base';diff --git a/sdk/src/index.wechat.ts b/sdk/src/index.wechat.tsindex 2d988c4bf..9ec684231 100644--- a/sdk/src/index.wechat.ts+++ b/sdk/src/index.wechat.ts@@ -3,44 +3,11 @@/*** @file index.wechat.ts* @brief ESEngine SDK - WeChat MiniGame entry point+ *+ * The whole entry: everything in index.wechat.base plus every optional+ * subsystem. `index.wechat.lean` is the same base with none of them, for a+ * package that imports back only what its project uses.*/--import { setPlatform } from './platform';-import { wechatAdapter, initWeChatPlatform } from './platform/wechat';-import { ensureBuiltinComponentsRegistered, markEngineComponentBaseline } from './ecs/component';-import { ensureBuiltinAiRegistrations } from './ai/builtins';--initWeChatPlatform();-setPlatform(wechatAdapter);--// Register every engine component (COMPONENT_META) so scenes never silently drop-// a component that exists in the engine but lacks a typed const.-ensureBuiltinComponentsRegistered();-ensureBuiltinAiRegistrations();-markEngineComponentBaseline();--export * from './core';-// Installs Spine + DragonBones on every app this entry builds; a lean entry-// omits this import and ships without their code.import './runtime/optionalPlugins';-export * from './runtime/webAppFactory';--export {- wxReadFile,- wxReadTextFile,- wxFileExists,- wxFileExistsSync,- wxWriteFile,- wxLoadImage,- wxGetImagePixels,- wxLoadImagePixels,- type ImageLoadResult,-} from './platform/wechat';--export {- initWeChatRuntime,- type WeChatRuntimeConfig,-} from './runtime/wechatRuntime';-// The host as data: spread it to keep everything but the one thing you replace.-export { wechatProfile } from './platform/wechat';+export * from './index.wechat.base';diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.tsindex 1a7e56667..e5858a058 100644--- a/sdk/src/physics/index.ts+++ b/sdk/src/physics/index.ts@@ -113,3 +113,16 @@ export {type SlideCast,type SlideHit,} from './CharacterController2D';++// Importing this subpath INSTALLS 2D physics — see spine/index.ts. No entry+// plugin: the scene load builds it with the world config the project declared.+import { setSceneOptionals } from '../runtime/sceneOptionals';+import { Physics2DPlugin as Physics2DPluginCtor } from './Physics2DPlugin';++setSceneOptionals({+ physics: {+ installed: (app) => !!app.getPlugin(Physics2DPluginCtor),+ install: (app, config, module) =>+ app.addPlugin(new Physics2DPluginCtor('', config, () => Promise.resolve(module))),+ },+});diff --git a/sdk/src/physics3d/index.ts b/sdk/src/physics3d/index.tsindex dae622afc..6a6165ad9 100644--- a/sdk/src/physics3d/index.ts+++ b/sdk/src/physics3d/index.ts@@ -102,3 +102,15 @@ export {type Collider3DInstance,type Collider3DComponent,} from './ColliderShape3D';++// Importing this subpath INSTALLS 3D physics — see spine/index.ts.+import { setSceneOptionals } from '../runtime/sceneOptionals';+import { Physics3DPlugin as Physics3DPluginCtor } from './Physics3DPlugin';++setSceneOptionals({+ physics3d: {+ installed: (app) => !!app.getPlugin(Physics3DPluginCtor),+ install: (app, module) =>+ app.addPlugin(new Physics3DPluginCtor('', {}, () => Promise.resolve(module))),+ },+});diff --git a/sdk/src/runtime/entryPlugins.ts b/sdk/src/runtime/entryPlugins.tsindex 5557eea37..9c51c1b83 100644--- a/sdk/src/runtime/entryPlugins.ts+++ b/sdk/src/runtime/entryPlugins.ts@@ -10,14 +10,17 @@*/import type { Plugin } from '../app/app';-let make: () => Plugin[] = () => [];+// Additive, not a single setter: each optional subsystem installs itself when+// its subpath is imported, and a setter would mean the last one imported was the+// only one installed. ESM runs a module once, so a double import adds nothing.+const makers: Array<() => Plugin> = [];-/** Called once, by `runtime/optionalPlugins`, for its side effect. */-export function setEntryPlugins(fn: () => Plugin[]): void {- make = fn;+/** Called by an optional subsystem's entry, for its side effect. */+export function addEntryPlugin(make: () => Plugin): void {+ makers.push(make);}/** Fresh instances per app: a plugin carries per-app state once built. */export function entryPlugins(): Plugin[] {- return make();+ return makers.map((make) => make());}diff --git a/sdk/src/runtime/optionalPlugins.ts b/sdk/src/runtime/optionalPlugins.tsindex 03704c099..1c9bb0709 100644--- a/sdk/src/runtime/optionalPlugins.ts+++ b/sdk/src/runtime/optionalPlugins.ts@@ -1,54 +1,22 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file optionalPlugins.ts — the entry-point side of the optional subsystems.+ * @file optionalPlugins.ts — everything optional, for an entry that wants all of it.*- * Importing this file IS the decision to ship Spine and DragonBones: it is the- * only place that reaches them from the runtime, so a build that leaves it out- * leaves their code out too. A mini-game inlines the SDK, and measured on- * examples/hello-world these two are 110KB of a package using neither.- *- * Every entry point imports it for its side effect. One that deliberately does- * not is a lean entry, and `check-entries-install-options` is what keeps the- * difference from being an accident.+ * Each subsystem installs itself when its own subpath is imported, so this file+ * is only the list. An entry importing it ships them all; a lean entry imports+ * the ones its project uses and carries no more — measured on+ * examples/hello-world, that is none of them.*/-import { SpinePlugin } from '../spine';-import { DragonBonesPlugin } from '../dragonbones';-import { loadSpineAssets, applySpineEntities } from '../spine/loadSpineScene';-import {- loadDragonBonesAssets, applyDragonBonesEntities,-} from '../dragonbones/loadDragonBonesScene';-import { setEntryPlugins } from './entryPlugins';-import { Physics2DPlugin } from '../physics/Physics2DPlugin';-import { Physics3DPlugin } from '../physics3d/Physics3DPlugin';+import '../spine';+import '../dragonbones';+import '../physics';+import '../physics3d';import { VideoPlayer } from '../video/VideoAPI';import { setSceneOptionals } from './sceneOptionals';-setEntryPlugins(() => [new SpinePlugin(), new DragonBonesPlugin()]);--// The scene-load half: the loader reaches these only when a scene actually holds-// a skeleton, so shipping them was always about bytes rather than behaviour.+// Video has no subpath of its own to be installed from, so it installs here.setSceneOptionals({- spine: {- manager: (app) => app.getPlugin(SpinePlugin)?.spineManager ?? null,- load: loadSpineAssets,- apply: applySpineEntities,- },- dragonBones: {- acquire: async (app) => (await app.getPlugin(DragonBonesPlugin)?.acquire()) ?? null,- load: loadDragonBonesAssets,- apply: applyDragonBonesEntities,- },- physics: {- installed: (app) => !!app.getPlugin(Physics2DPlugin),- install: (app, config, module) =>- app.addPlugin(new Physics2DPlugin('', config, () => Promise.resolve(module))),- },- physics3d: {- installed: (app) => !!app.getPlugin(Physics3DPlugin),- install: (app, module) =>- app.addPlugin(new Physics3DPlugin('', {}, () => Promise.resolve(module))),- },video: {setRefResolver: (app, resolve) => {if (!app.hasResource(VideoPlayer)) return false;diff --git a/sdk/src/spine/index.ts b/sdk/src/spine/index.tsindex 62c190c85..84f1fc679 100644--- a/sdk/src/spine/index.ts+++ b/sdk/src/spine/index.ts@@ -30,3 +30,20 @@ export type {// single implementation the builder runtime uses (see ./loadSpineScene).export { loadSpineSceneEntities, loadSpineAssets, applySpineEntities, spineEntityProps } from './loadSpineScene';export type { RuntimeAssetSource } from '../runtime/runtimeAssets';++// Importing this subpath INSTALLS Spine: the core runtime names no optional+// subsystem, so this is what puts it back, and a build that never imports it+// ships none of the code below.+import { addEntryPlugin } from '../runtime/entryPlugins';+import { setSceneOptionals } from '../runtime/sceneOptionals';+import { SpinePlugin as SpinePluginCtor } from './SpinePlugin';+import { loadSpineAssets, applySpineEntities } from './loadSpineScene';++addEntryPlugin(() => new SpinePluginCtor());+setSceneOptionals({+ spine: {+ manager: (app) => app.getPlugin(SpinePluginCtor)?.spineManager ?? null,+ load: loadSpineAssets,+ apply: applySpineEntities,+ },+});diff --git a/tools/check-entries-install-options.mjs b/tools/check-entries-install-options.mjsindex 21903a789..9525fc69e 100644--- a/tools/check-entries-install-options.mjs+++ b/tools/check-entries-install-options.mjs@@ -23,10 +23,16 @@ const INSTALLER = './runtime/optionalPlugins';/** Entries that deliberately ship without the optional subsystems, and why. */const LEAN = {- // (none yet — the export-side lean entry lands with the runtimeLoader half)+ 'index.wechat.lean.ts': 'ships no optional subsystem; a package imports back the'+ + ' subpaths its own content uses',+ 'index.wechat.base.ts': 'not an entry anyone builds from — the shared half of'+ + ' index.wechat and index.wechat.lean',};-const entries = readdirSync(SRC).filter((f) => /^index(\.[a-z0-9]+)?\.ts$/.test(f));+// Two dotted segments, not one: `index.wechat.lean.ts` did not match a+// single-segment pattern, so the very entry this check exists for was the one+// it never looked at — while still counting it as declared.+const entries = readdirSync(SRC).filter((f) => /^index(\.[a-z0-9]+)*\.ts$/.test(f));if (entries.length === 0) {console.error('check-entries-install-options: no sdk/src/index*.ts — the entries moved.');process.exit(1);@@ -48,6 +54,13 @@ if (missing.length > 0) {process.exit(1);}-const lean = Object.keys(LEAN).length;+// Counted over the entries that EXIST, so a stale LEAN key cannot inflate it.+const lean = entries.filter((f) => f in LEAN).length;+const stale = Object.keys(LEAN).filter((f) => !entries.includes(f));+if (stale.length > 0) {+ console.error(`check-entries-install-options: LEAN names ${stale.length} entry(ies) that are`+ + ` not there: ${stale.join(', ')}`);+ process.exit(1);+}console.log(`check-entries-install-options: ${entries.length} entry(ies) — ${entries.length - lean}`+ ` install the optional subsystems${lean > 0 ? `, ${lean} declared lean` : ''}.`);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 20189e69f..f36398a3b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,9 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(export): a mini-game carries the optional subsystems its project uses':+ { note: 'A WeChat mini-game now carries only the optional subsystems its project uses.' },+'refactor(sdk): the core runtime names no optional subsystem at all':{ internal: 'Same subsystems, same behaviour; a lean build now says when it ships without one.' },