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
perf(ecs): one stable sort for every component type, 239KB off the engine wasm
yhh6182c798bec3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33fd12b70..233be3d20 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,7 @@ published separately; it ships inside the editor.### Changed+- **The engine's wasm is 239KB smaller, with no change to what it does.** Reordering a component's storage (`Sprite.order` and the authored entity order reach the draw list through it) sorted inside `SparseSet<T>::reorderBy`, so each of the hundred-odd component types carried its own copy of `std::stable_sort` and its merge helpers: 275KB, 15% of the engine's code. The sort never looked at the component, so it is one function now (`SparseSetBase::stablePermutation`) and the template only moves the components along the permutation it returns. The web engine is 2,437,989 bytes, now 2,199,086 (238,903 less); the same sort and the same order: 300 random cases with ties and unranked entities came out identical to the old one, and the terrain and water example draws the same frame at the same cost. `ESTELLA_WASM_NAMES=1` keeps the name section through the optimizer, for a build made to find where the bytes are.- **A blank mini-game package no longer carries terrain, water and timelines.** 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, water and timelines mark what only defines something. A blank WeChat package was 3,345,193 bytes and is now 3,234,518 (111KB less, 79.8% of the 4MB main-package cap down to 77.1%); a project that uses terrain, water or a timeline 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.diff --git a/build-tools/tasks/wasm.js b/build-tools/tasks/wasm.jsindex fe377dd66..62cf4885e 100644--- a/build-tools/tasks/wasm.js+++ b/build-tools/tasks/wasm.js@@ -223,7 +223,9 @@ export async function optimizeWasmFiles(buildDir, outputs, optLevel = '-O2', envconst optimizedPath = `${wasmPath}.opt-${randomUUID()}.wasm`;try {const before = (await stat(wasmPath)).size;- await runCommand('wasm-opt', [optLevel, '--enable-bulk-memory', '--enable-nontrapping-float-to-int', '--enable-simd', '-o', optimizedPath, wasmPath], { silent: true, env });+ // The optimizer drops the name section unless told to keep it; a build made to find where the bytes are (a size report by subsystem) asks.+ const keepNames = process.env.ESTELLA_WASM_NAMES === '1' ? ['-g'] : [];+ await runCommand('wasm-opt', [optLevel, ...keepNames, '--enable-bulk-memory', '--enable-nontrapping-float-to-int', '--enable-simd', '-o', optimizedPath, wasmPath], { silent: true, env });const bytes = await readFile(optimizedPath);if (!WebAssembly.validate(bytes)) throw new Error('optimizer produced invalid WASM');const after = bytes.byteLength;diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hppindex 6b11540b6..4efda245b 100644--- a/src/esengine/ecs/SparseSet.hpp+++ b/src/esengine/ecs/SparseSet.hpp@@ -113,6 +113,24 @@ public:/** @brief Rank for an entity the caller did not order — sorts last, stably. */static constexpr u32 UNRANKED = 0xFFFFFFFFu;++ /**+ * @brief Which current slot belongs at each position when `dense` is put in `rank` order (stable).+ * @details Not a member of the template: the sort does not depend on the component type, and a copy of `std::stable_sort` and its+ * merge helpers for each of the hundred-odd component types was 227KB of the engine's wasm — over a tenth of its code.+ * Entities with no rank sort after the ranked ones, in their present order.+ */+ [[gnu::noinline]] static std::vector<usize> stablePermutation(const std::vector<Entity>& dense, const std::vector<u32>& rank) {+ const usize n = dense.size();+ std::vector<usize> perm(n);+ for (usize i = 0; i < n; ++i) perm[i] = i;+ const auto rankOf = [&](usize i) {+ const u32 idx = dense[i].index();+ return idx < rank.size() ? rank[idx] : UNRANKED;+ };+ std::stable_sort(perm.begin(), perm.end(), [&](usize a, usize b) { return rankOf(a) < rankOf(b); });+ return perm;+ }};// =============================================================================@@ -377,17 +395,10 @@ public:const usize n = dense_.size();if (n <= 1) return;- const auto rankOf = [&](usize i) {- const u32 idx = dense_[i].index();- return idx < rank.size() ? rank[idx] : UNRANKED;- };-- // perm[i] = which current slot belongs at position i. stable_sort keeps- // equal-ranked (and unranked) entities in their present order.- std::vector<usize> perm(n);- for (usize i = 0; i < n; ++i) perm[i] = i;- std::stable_sort(perm.begin(), perm.end(),- [&](usize a, usize b) { return rankOf(a) < rankOf(b); });+ // perm[i] = which current slot belongs at position i. The sort keeps+ // equal-ranked (and unranked) entities in their present order, and is+ // one function for every component type (see stablePermutation).+ std::vector<usize> perm = stablePermutation(dense_, rank);bool moved = false;for (usize i = 0; i < n; ++i) {diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 0d8344c64..b71b285b7 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3018,4 +3018,6 @@ export const NOTED = {{"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."},+ "perf(ecs): one stable sort for every component type, 239KB off the engine wasm":+ {"note":"The engine's wasm is 239KB smaller, with no change to what it does."},};