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(render): what a receding field costs with and without LODGroup

esenginebcd1e0ed6f83
diff --git a/bench/lod/README.md b/bench/lod/README.md
new file mode 100644
index 000000000..814ef19a8
--- /dev/null
+++ b/bench/lod/README.md
@@ -0,0 +1,58 @@
+# LODGroup at scale — what it costs and what it buys
+
+`node bench/lod/run.mjs` drives two scenes that differ in one component. Both hold
+the same props on the same lattice under the same camera; `lod-field` gives every
+prop a `LODGroup`, `lod-field-flat` gives it none and so draws level 0 always.
+Every number below comes from the engine's own counters and scope timers, read out
+of the frames the SDK's profiler recorded — the same frame path the pixel gates use.
+
+The camera looks along the lattice, so the props recede: near ones are big on
+screen, far ones are specks. That is the shape LOD exists for, and it is also why
+the level counts are lopsided — most of a receding field is far away.
+
+## Measured 2026-09-05 (M-series Mac, WebGL2, 512x512, median of 60 frames)
+
+The counts and the triangle totals are exact and reproduce run to run; `gpuMs` is
+a measurement and moves a few percent between runs (the 10k LODGroup row read
+0.256, 0.269 and 0.285 over three).
+
+```
+props scene selections lod0 lod1 lod2 lodCulled drawn culled triangles draws collectMs gpuMs
+ 1024 LODGroup 874 10 22 458 384 490 534 4248 3 0.100 0.116
+ 1024 alwaysLOD0 0 0 0 0 0 874 150 195776 1 0.100 0.505
+10000 LODGroup 8540 102 248 4390 3800 4740 5260 42392 21 0.900 0.285
+10000 alwaysLOD0 0 0 0 0 0 8540 1460 1912960 1 0.600 3.595
+```
+
+`selections` is how many props reached LOD selection — the rest the frustum had
+already rejected, which is why the cull runs first. `culled` counts both kinds, so
+the LOD rows carry the frustum's rejections plus the ones LOD threw away.
+
+## What it says
+
+- **Triangles fall 46x at 1k and 45x at 10k.** Most of a receding field is far, and
+ far is where the 4-triangle stand-in is indistinguishable from the 224-triangle one.
+- **GPU time falls about 4x at 1k and 13x at 10k** (0.505 -> 0.116 ms, 3.5 -> 0.27 ms).
+ The gap widens with count, which is the point: this is the number that decides
+ whether a field of ten thousand props is shippable.
+- **Selection costs 0.2-0.3 ms of CPU per ten thousand props** (`render.collect`
+ 0.6-0.7 -> 0.9 ms). At a thousand it is under the timer's resolution.
+- **Instancing survives.** 1024 props at three levels reach the GPU as 3 draws, and
+ 10000 at three levels as 21 — choosing a level changes which geometry a draw names
+ and nothing else, so props sharing a level still fold into one instanced call. The
+ 21 is the depth sort interleaving two levels where their distance bands meet; it is
+ the cost of ordering opaque geometry front-to-back, not of LOD.
+- **The trade is CPU for GPU, and the exchange rate is good**: about +0.25 ms of
+ collect buys back 3.3 ms of GPU at ten thousand props.
+
+## Reproducing
+
+```
+node bench/lod/run.mjs # 1k and 10k, both scenes
+node bench/lod/run.mjs --counts 10000 # one size
+node bench/lod/run.mjs --frames 120 # a longer median
+```
+
+The lattice keeps ONE footprint across the sizes (`LAYOUTS` in `run.mjs`), so ten
+times the props is ten times as dense rather than a field ten times as wide — the
+camera frames the same world either way.
diff --git a/bench/lod/run.mjs b/bench/lod/run.mjs
new file mode 100644
index 000000000..cbf15507f
--- /dev/null
+++ b/bench/lod/run.mjs
@@ -0,0 +1,109 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bench/lod/run.mjs — what LODGroup costs and what it saves, at scale.
+ *
+ * Two scenes with the same geometry, the same camera and the same lattice:
+ * `lod-field` carries a group on every prop, `lod-field-flat` carries none and
+ * so draws level 0 always. Everything below is measured on the SAME frame path
+ * as the pixel gates, through the engine's own counters and scope timers.
+ *
+ * node bench/lod/run.mjs 1k and 10k, both scenes
+ * node bench/lod/run.mjs --counts 1000 one size
+ */
+import { spawnSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+const flag = (name, fallback) => {
+ const at = process.argv.indexOf(`--${name}`);
+ return at >= 0 && process.argv[at + 1] ? process.argv[at + 1] : fallback;
+};
+
+/** The lattice keeps ONE footprint across the sizes, so ten times the props is
+ * ten times as dense rather than a field ten times as wide. */
+const LAYOUTS = {
+ 1000: { copies: 1024, cols: 32, spacing: [120, 300] },
+ 10000: { copies: 10000, cols: 100, spacing: [38.4, 96] },
+};
+
+/** The pair that differs in one component: a group on every prop, or none at all. */
+const SCENES = ['lod-field.esscene', 'lod-field-flat.esscene'];
+
+const COUNTS = flag('counts', '1000,10000').split(',').map((s) => Number(s.trim()));
+const FRAMES = Number(flag('frames', '60'));
+const WIDTH = flag('w', '512');
+const HEIGHT = flag('h', '512');
+
+function drive(sceneId, layout) {
+ const run = spawnSync('pnpm', ['exec', 'electron', 'tools/render-host/run.mjs'], {
+ cwd: ROOT,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ ESTELLA_VERIFY_SCENE: `/scenes/${sceneId}`,
+ ESTELLA_VERIFY_W: WIDTH,
+ ESTELLA_VERIFY_H: HEIGHT,
+ ESTELLA_VERIFY_STEPS: '8',
+ ESTELLA_VERIFY_SCALE: JSON.stringify(layout),
+ ESTELLA_VERIFY_PROFILE: String(FRAMES),
+ },
+ });
+ const line = (run.stdout ?? '').split('\n').find((l) => l.startsWith('DRIVE_RESULT '));
+ if (!line) {
+ throw new Error(`${sceneId}: the host produced no result\n${run.stdout}\n${run.stderr}`);
+ }
+ const out = JSON.parse(line.slice('DRIVE_RESULT '.length));
+ const frames = out.profile?.frames ?? [];
+ if (!frames.length) throw new Error(`${sceneId}: the recorder captured no frame`);
+ return frames;
+}
+
+/** Median of a per-frame series — a mean is one stall away from a lie. */
+function median(values) {
+ const clean = values.filter((v) => typeof v === 'number');
+ if (!clean.length) return NaN;
+ const sorted = [...clean].sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+const counter = (frames, name) => median(frames.map((f) => (f.counters ?? {})[name]));
+const scope = (frames, name) => median(frames.map(
+ (f) => (f.nativeScopes ?? []).find((s) => s.name === name)?.ms));
+
+const rows = [];
+for (const count of COUNTS) {
+ const layout = LAYOUTS[count];
+ if (!layout) throw new Error(`no lattice declared for ${count} props`);
+ for (const sceneId of SCENES) {
+ const frames = drive(sceneId, layout);
+ rows.push({
+ props: layout.copies,
+ scene: sceneId === SCENES[0] ? 'LODGroup' : 'alwaysLOD0',
+ selections: counter(frames, 'render.lod.groups'),
+ lod0: counter(frames, 'render.lod.level0'),
+ lod1: counter(frames, 'render.lod.level1'),
+ lod2: counter(frames, 'render.lod.level2'),
+ lodCulled: counter(frames, 'render.lod.culled'),
+ drawn: counter(frames, 'render.meshes'),
+ culled: counter(frames, 'render.culled'),
+ triangles: counter(frames, 'render.triangles'),
+ draws: counter(frames, 'batch.draws'),
+ collectMs: scope(frames, 'render.collect'),
+ graphMs: scope(frames, 'render.graph'),
+ gpuMs: median(frames.map((f) => f.gpuMs)),
+ });
+ }
+}
+
+const cols = Object.keys(rows[0]);
+const width = Object.fromEntries(cols.map((k) => [k,
+ Math.max(k.length, ...rows.map((r) => String(fmt(r[k])).length))]));
+function fmt(v) {
+ return typeof v === 'number' && !Number.isInteger(v) ? v.toFixed(3) : String(v);
+}
+console.log(cols.map((k) => k.padStart(width[k])).join(' '));
+for (const r of rows) console.log(cols.map((k) => fmt(r[k]).padStart(width[k])).join(' '));
diff --git a/fixtures/scenes/lod-field-flat.esscene b/fixtures/scenes/lod-field-flat.esscene
new file mode 100644
index 000000000..0e0e381da
--- /dev/null
+++ b/fixtures/scenes/lod-field-flat.esscene
@@ -0,0 +1,77 @@
+{
+ "version": 4,
+ "name": "lod-field-flat",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 4800,
+ "z": 0
+ },
+ "rotation": {
+ "x": -0.7071068,
+ "y": 0,
+ "z": 0,
+ "w": 0.7071068
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 10,
+ "farPlane": 20000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Prop",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "/scenes/lod-high.esmesh",
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ }
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/fixtures/scenes/lod-field.esscene b/fixtures/scenes/lod-field.esscene
new file mode 100644
index 000000000..60da4f383
--- /dev/null
+++ b/fixtures/scenes/lod-field.esscene
@@ -0,0 +1,91 @@
+{
+ "version": 4,
+ "name": "lod-field",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 4800,
+ "z": 0
+ },
+ "rotation": {
+ "x": -0.7071068,
+ "y": 0,
+ "z": 0,
+ "w": 0.7071068
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 60,
+ "nearPlane": 10,
+ "farPlane": 20000,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Prop",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "/scenes/lod-high.esmesh",
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "LODGroup",
+ "data": {
+ "lod1": "/scenes/lod-mid.esmesh",
+ "lod2": "/scenes/lod-low.esmesh",
+ "lod3": 0,
+ "lod1Size": 0.5,
+ "lod2Size": 0.25,
+ "lod3Size": 0.0,
+ "cullSize": 0.05,
+ "hysteresis": 0.1,
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/tools/check-fixture-scenes.mjs b/tools/check-fixture-scenes.mjs
index 7000a7873..dc9f54ede 100644
--- a/tools/check-fixture-scenes.mjs
+++ b/tools/check-fixture-scenes.mjs
@@ -36,7 +36,7 @@ const UNDRIVEN = {
};
const drivers = [];
-const { files, missing } = listTrackedSources(['tools', 'desktop/scripts']);
+const { files, missing } = listTrackedSources(['tools', 'desktop/scripts', 'bench']);
if (missing.length) {
console.log(`check-fixture-scenes: no editor checkout — ${missing.join(', ')} not scanned for drivers.`);
}