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.

perf(sdk): a blank mini-game package no longer carries terrain and water

yhh94fc9a55d162
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c10889d2..75df8ac83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Added
+- **A session layer for online games that do not share a tick.** `esengine/session` is the request and reply side of a game played asynchronously over a shared world. A `SessionHost` on the server authenticates each connection before it serves anything, limits frame size and message rate, pings the client, and lets a newer connection for the same player replace the older one. A `ClientSession` on the device dials, redials with backoff and jitter when the link drops, waits for the server before a request goes out, and keeps its event subscriptions across reconnects. Every request carries a key, so one that was lost on the way back and is sent again is answered from memory instead of running twice (a purchase, a departure); `serverNow()` gives the server's clock, corrected for the link's delay. `defineContract` writes every request and event once, with `s.object`, `s.int` and the other validators: the server checks each request against it, the client checks each reply, and both are typed from it; its `fingerprint` lets a server turn away a client built against another contract. `acceptWebSocket` hands a `ws` socket to a host, and `IdempotencyStore` is where a server with several processes keeps the answers in one place. `NetChannel` gained the keyed requests, a heartbeat, a rate limit, a frame size limit and `NetRequestError` (`timeout`, `closed`, `rate-limited`, `retry`, `remote`) for them. Replication is untouched.
+- **A random generator that gives the same numbers on every host.** `createRng(seed)` returns a seeded generator (`float`, `int`, `chance`, `pick`, `weighted`, `shuffle`) whose sequence is the same on a server, a browser, a mini-game and a phone, because it uses only 32-bit integer arithmetic. `fork(label)` makes a named stream that does not move when another stream draws more, and `hashSeed` turns a number, a string or a list of them into a seed. It is for rules that a server settles and a client previews, which must agree; `Math.random` cannot be seeded and is not the same anywhere.
- **Sharpen on WebGL2.** The `sharpen` effect was a compute shader, so a device with no compute stage (WebGL2, which is most of the small-game targets) left it out and showed the picture as it was. It now has a fragment pass of the same arithmetic that stands in where there is no compute stage: on WebGPU the two draw the identical picture, pixel for pixel, and a test switch in the render host (`noCompute`) checks that. Flat areas are untouched and an edge cannot overshoot past what is on either side of it.
- **Blob shadows.** A `BlobShadow` component puts a soft dark disc on the ground under an entity: no shadow map, no light, no extra pass, which is the shadow a phone can afford. It fades and shrinks as the thing leaves the ground (`fadeHeight`, `shrink`), follows the ground (`groundY`, or a height function from `setBlobShadowGround` for ground that is not flat) and is hidden by what stands in front of it. It is a disc, not the light's shadow: it does not stretch with the sun or land on a wall. The same picture on WebGL2 and WebGPU.
- **Edge Outline, a coloured line at silhouettes and creases.** A post effect (`edgeOutline`) that draws a line of `u_lineColor` where the scene's surface changes: where the distance from the camera steps (a silhouette) and where the surface's normal turns (the edge of a face, a fold), so a box on a floor is inked along its corners as well as its outline, which `depthOutline` (depth only, black only) does not do. Distance is measured in the world, so one threshold holds across a perspective view, and a plane at a grazing angle draws no line. Creases need surfaces that write their normal (lit meshes, Model and Toon materials); the same picture on WebGL2 and WebGPU.
@@ -37,6 +39,7 @@ published separately; it ships inside the editor.
### Changed
+- **A blank mini-game package no longer carries terrain and water.** The mini-game build was shipping 47KB of terrain and 37KB of water code (and its component definitions) in a project that uses neither: the SDK's shared chunks hold every entry's code together, and a bundler cannot drop a top-level `defineComponent(...)` or `new SomePlugin()` it cannot tell is pure. The chunks now keep their `/* @__PURE__ */` annotations (the minifier that removed them is set to mangle names only; consumers minify again), and terrain and water mark what only defines something. A blank WeChat package was 3,345,193 bytes and is now 3,248,459 (97KB less, 79.8% of the 4MB main-package cap down to 77.4%); a project that uses terrain or water installs them as before. A gate (`lean-bundle`) fails if a blank package carries them again.
- **A multisampled frame is not written out on a tile-based GPU.** The samples of a multisampled target, once resolved and with nothing left to draw on it, the depth of a shadow pass (the map keeps its depth in colour), and the default framebuffer's depth and stencil at the end of a frame are now said not to be needed, which a phone's GPU takes as not writing them to memory. The picture is the same on both backends; it changes nothing measurable on a desktop GPU and is most of a multisampled frame's memory traffic on a phone, which is where it was not measured.
- **A sun's shadow map leaves out the casters that shade nothing the camera sees.** A directional light with a fixed reach (`shadowExtent`) draws one map of its whole reach, so every caster in it was drawn however much of it the camera looked at. A caster's shadow is the segment its bounds sweep along the light's rays down to the lowest thing that can receive it; one whose segment stays outside the camera's view is no longer drawn into the map. The picture is the same (a mean difference under half a level on the Terrain & Water example); its shadow pass is 4.0 to 1.7 ms and 4.7 to 1.4 ms at two of its viewpoints on an RTX 3060, and unchanged where the camera sees the whole island. A cascaded sun (no `shadowExtent`) already fits its maps to the view and is as it was; a frame with a planar reflection keeps every caster.
- **The sea takes the sun's shadow as one hard edge.** The water lit itself with the sun's full soft shadow (a search for blockers and a filter of up to sixty-four taps), which a surface the sun seldom leaves and whose edge the waves hide does not need; a shader can now set `g_shadowHard` before it lights to read the shadow as the edge a source with no size throws, nine taps, and the water does. The picture is the same to the eye (a mean difference of a quarter of a level on the Terrain & Water example); the water is about 0.5 ms shorter on an RTX 3060.
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index 0a32a92d2..e64bd2ab8 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -72,7 +72,13 @@ function emitChunkManifest() {
};
}
-const minify = { compress: true, mangle: true, codegen: { removeWhitespace: true, legalComments: 'inline' } };
+// The shared chunks keep their whitespace and their pure annotations; they are inputs to a bundler that minifies them again. The minifier's `compress` and
+// whitespace passes drop `/* @__PURE__ */` (no knob keeps it, and carrying it through as a legal comment lands it after the statement instead of before),
+// and `dist/shared/` is the UNION of the entries' code: a chunk a lean entry takes one function from also holds every top-level `defineComponent(...)` and
+// `new SomePlugin()` of the modules grouped with it, which a downstream bundler can only drop if it is told they are pure. Terrain and water (84KB) rode a blank
+// mini-game package for want of that. Names are still mangled.
+const minify = { compress: false, mangle: true, codegen: false };
+const minifyBundled = { compress: true, mangle: true, codegen: { removeWhitespace: true, legalComments: 'inline' } };
export default defineConfig([
{
@@ -111,6 +117,7 @@ export default defineConfig([
'debug-channel/index': 'src/debug-channel/index.ts',
'ai/index': 'src/ai/index.ts',
'net/replication/index': 'src/net/replication/index.ts',
+ 'net/session/index': 'src/net/session/index.ts',
'gameplay/index': 'src/gameplay/index.ts',
'dragonbones/index': 'src/dragonbones/index.ts',
'douyin/index': 'src/platform/douyin/index.ts',
@@ -137,13 +144,13 @@ export default defineConfig([
},
{
input: 'src/index.ts',
- output: { file: 'dist/index.bundled.js', format: 'esm', sourcemap: true, minify },
+ output: { file: 'dist/index.bundled.js', format: 'esm', sourcemap: true, minify: minifyBundled },
plugins: [preserveViteIgnore()],
treeshake,
},
{
input: 'src/index.wechat.ts',
- output: { file: 'dist/index.wechat.cjs.js', format: 'cjs', sourcemap: true, minify },
+ output: { file: 'dist/index.wechat.cjs.js', format: 'cjs', sourcemap: true, minify: minifyBundled },
plugins: [preserveViteIgnore()],
treeshake,
},
@@ -153,7 +160,7 @@ export default defineConfig([
// global the game script uses (ESEngine.createNativeWorld(globalThis), …).
// The native (embedded-Dawn) analog of index.wechat.cjs.js.
input: 'src/index.native.ts',
- output: { file: 'dist/index.native.bundled.js', format: 'iife', name: 'ESEngine', sourcemap: false, minify },
+ output: { file: 'dist/index.native.bundled.js', format: 'iife', name: 'ESEngine', sourcemap: false, minify: minifyBundled },
plugins: [preserveViteIgnore()],
treeshake,
},
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 64f0bd1a2..a17b517cd 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -133,7 +133,7 @@ const rgb = (r: number, g: number, b: number): Color => ({ r, g, b, a: 1 });
*
* @experimental
*/
-export const Terrain: ComponentDef<TerrainData> = defineComponent<TerrainData>('Terrain', {
+export const Terrain: ComponentDef<TerrainData> = /* @__PURE__ */ defineComponent<TerrainData>('Terrain', {
extent: TerrainExtent.Area, provider: NOISE_PROVIDER, world: '', generatorVersion: 1, heightmap: 0, heightmapFormat: HeightmapFormat.Grey, splatmap: 0, splatmap2: 0, layers: [] as string[], material: 0,
sizeX: 1000, sizeZ: 1000, height: 150, cellSize: 2, detail: 1, drawDistance: 4000,
collision: true, collisionDistance: 64, collisionLayer: 0, friction: 0.6,
@@ -503,7 +503,7 @@ export class Terrains {
}
/** The resource the plugin installs. @experimental */
-export const TerrainsRes = defineResource<Terrains>(new Terrains(), 'Terrains');
+export const TerrainsRes = /* @__PURE__ */ defineResource<Terrains>(/* @__PURE__ */ new Terrains(), 'Terrains');
/** What, changed, rebuilds the ground: everything but the colours, the detail and the collision, which are read each frame. */
function signatureOf(data: TerrainData, at: { x: number; z: number }): string {
@@ -1077,4 +1077,4 @@ export class TerrainPlugin implements Plugin {
}
}
-export const terrainPlugin: Plugin = new TerrainPlugin();
+export const terrainPlugin: Plugin = /* @__PURE__ */ new TerrainPlugin();
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 70e897d38..89e1f1684 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -78,7 +78,7 @@ export interface WaterBodyData {
*
* @experimental
*/
-export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
+export const WaterBody: ComponentDef<WaterBodyData> = /* @__PURE__ */ defineComponent<WaterBodyData>('WaterBody', {
form: WaterForm.Lake, bodyId: '', sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3, bedDepth: 0,
}, {
fields: {
@@ -241,7 +241,7 @@ export class Waters {
}
/** The resource the plugin installs. @experimental */
-export const WatersRes = defineResource<Waters>(new Waters(), 'Waters');
+export const WatersRes = /* @__PURE__ */ defineResource<Waters>(/* @__PURE__ */ new Waters(), 'Waters');
/** The outline of a lake: its own boundary when it has three points or more, else the rectangle of its size. */
function outlineOf(d: WaterBodyData): Point2[] {
@@ -796,4 +796,4 @@ function implicitGrid(bodies: readonly ZoneBody[], zone: WaterZoneData): ZoneGri
return gridOver(minX - pad, minZ - pad, maxX - minX + pad * 2, maxZ - minZ + pad * 2, res);
}
-export const waterPlugin: Plugin = new WaterPlugin();
+export const waterPlugin: Plugin = /* @__PURE__ */ new WaterPlugin();
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
index 8cbb417e6..5035462fd 100644
--- a/sdk/src/water/zone.ts
+++ b/sdk/src/water/zone.ts
@@ -58,7 +58,7 @@ export interface WaterZoneData {
*
* @experimental
*/
-export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneData>('WaterZone', {
+export const WaterZone: ComponentDef<WaterZoneData> = /* @__PURE__ */ defineComponent<WaterZoneData>('WaterZone', {
sizeX: 200, sizeZ: 200, resolution: 256, material: 0,
waveLength: 14, waveSpeed: 1, waveDirection: 30, surf: 0.6, surfLength: 8,
cellSize: 1, cells: 64, rings: 5,
diff --git a/tools/check-lean-bundle.mjs b/tools/check-lean-bundle.mjs
new file mode 100644
index 000000000..c07e4d4b0
--- /dev/null
+++ b/tools/check-lean-bundle.mjs
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-lean-bundle.mjs — a blank mini-game package carries none of an optional subsystem it does not use.
+ *
+ * The lean WeChat entry is what a package that uses no terrain, no foliage, no generated world and no water is built from. It once carried 47KB of terrain and
+ * 37KB of water anyway: `dist/shared/` is the union of every entry's code, so a chunk the lean entry takes one function from also holds every top-level
+ * `defineComponent(...)` and `new SomePlugin()` of the modules grouped with it, and a bundler cannot drop a statement it cannot tell is pure. The chunks now keep
+ * their `/* @__PURE__ *\/` annotations (see sdk/rolldown.config.js) and the modules mark the statements that only define something.
+ *
+ * This bundles the built lean entry the way the mini-game export does, reads the output's source map, and says how many bytes each optional directory left
+ * behind. A directory over its ceiling is a subsystem riding along again: find the top-level statement a bundler had to keep (`node output/impure-scan.mjs` style:
+ * a call or `new` with no `/* @__PURE__ *\/`) and mark it, or take the import that reaches it out of the base.
+ *
+ * Needs the SDK built (`sdk-build`).
+ */
+import { build } from 'esbuild';
+import { createRequire } from 'node:module';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(import.meta.url);
+
+/** The most each directory may leave in a blank package, in bytes of the minified bundle. Water keeps what the post-process underwater state needs. */
+const CEILING = { terrain: 0, foliage: 0, worldgen: 0, water: 8192 };
+
+const entry = path.join(ROOT, 'sdk/dist/index.wechat.lean.js');
+if (!existsSync(entry)) {
+ console.error('check-lean-bundle: sdk/dist is not built (run sdk-build first)');
+ process.exit(1);
+}
+let SourceMapConsumer;
+try {
+ ({ SourceMapConsumer } = require('source-map-js'));
+} catch {
+ ({ SourceMapConsumer } = require(path.join(ROOT, 'node_modules/.pnpm/[email protected]/node_modules/source-map-js')));
+}
+
+const result = await build({
+ stdin: { contents: "import { initWeChatRuntime } from 'esengine'; export { initWeChatRuntime };", resolveDir: ROOT, loader: 'js' },
+ alias: { esengine: entry },
+ bundle: true, minify: true, sourcemap: 'external', outfile: path.join(ROOT, 'output/lean-check.js'), write: false,
+ target: 'es2017', format: 'cjs', platform: 'browser', logLevel: 'silent',
+});
+const code = result.outputFiles.find((f) => f.path.endsWith('.js')).text;
+const map = JSON.parse(result.outputFiles.find((f) => f.path.endsWith('.map')).text);
+const lines = code.split('\n');
+const consumer = new SourceMapConsumer(map);
+const bySource = new Map();
+let prev = null;
+const flush = (until) => {
+ if (prev) bySource.set(prev.source, (bySource.get(prev.source) ?? 0) + Math.max(0, until - prev.col));
+};
+consumer.eachMapping((m) => {
+ if (prev && prev.line === m.generatedLine) flush(m.generatedColumn);
+ else if (prev) flush(lines[prev.line - 1].length);
+ prev = { line: m.generatedLine, col: m.generatedColumn, source: m.source };
+}, null, SourceMapConsumer.GENERATED_ORDER);
+if (prev) flush(lines[prev.line - 1].length);
+
+const BS = String.fromCharCode(92);
+const byDir = new Map();
+for (const [source, bytes] of bySource) {
+ const m = /sdk\/src\/([^/]+)\//.exec(source.split(BS).join('/'));
+ if (m) byDir.set(m[1], (byDir.get(m[1]) ?? 0) + bytes);
+}
+
+let failed = false;
+for (const [dir, ceiling] of Object.entries(CEILING)) {
+ const bytes = byDir.get(dir) ?? 0;
+ if (bytes > ceiling) {
+ failed = true;
+ console.error(`check-lean-bundle: ${dir}/ left ${bytes} bytes in a blank package (ceiling ${ceiling}) — a subsystem is riding along again`);
+ }
+}
+if (failed) process.exit(1);
+console.log(`check-lean-bundle: a blank package is ${code.length} bytes; `
+ + Object.keys(CEILING).map((d) => `${d} ${byDir.get(d) ?? 0}/${CEILING[d]}`).join(', '));
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 3a167858b..d021245a4 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -87,6 +87,9 @@ export const GATES = [
// Everything below reads what this emits: the declaration snapshot, the
// editor's own type-check and the examples all resolve `esengine` from dist.
{ id: 'sdk-build', exclusive: true, run: 'pnpm --filter ./sdk build' },
+ // A blank mini-game package carries none of a subsystem it does not use: the shared chunks are the union of every entry's code, and one unmarked
+ // top-level `new SomePlugin()` is how 84KB of terrain and water rode every package.
+ { id: 'lean-bundle', run: 'node tools/check-lean-bundle.mjs' },
{ id: 'api-surface-dts', run: 'node tools/api-surface.mjs --check-dts' },
// Both read `esengine` from dist, and the editor reads the pipeline.
{ id: 'tsc-pipeline', run: 'pnpm --filter @estella/pipeline exec tsc --noEmit' },
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 8494da22e..0d8344c64 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3012,4 +3012,10 @@ export const NOTED = {
{"note":"Blob shadows."},
"feat(render): sharpen works without a compute stage":
{"note":"Sharpen on WebGL2."},
+ 'feat(math): a seeded random generator that gives the same numbers on every host':
+ {"note":"A random generator that gives the same numbers on every host."},
+ 'feat(net): a session layer for online games that do not share a tick':
+ {"note":"A session layer for online games that do not share a tick."},
+ "perf(sdk): a blank mini-game package no longer carries terrain and water":
+ {"note":"A blank mini-game package no longer carries terrain and water."},
};