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.

bench(aot): the loop is asked which half of its cost is the interpreter

yhh1de21d52f789
diff --git a/bench/aot-stage0/CMakeLists.txt b/bench/aot-stage0/CMakeLists.txt
new file mode 100644
index 000000000..2326a69e3
--- /dev/null
+++ b/bench/aot-stage0/CMakeLists.txt
@@ -0,0 +1,64 @@
+# SPDX-License-Identifier: Apache-2.0
+# SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+#
+# Standalone on purpose. The bench needs QuickJS and two component headers —
+# nothing else — so it configures in seconds and never waits on Dawn, the SDK
+# bundle, or the generated native bindings the host build requires. Point it at
+# the QuickJS the native build already fetched:
+#
+# cmake -S bench/aot-stage0 -B build/cmake/aot-stage0 -DCMAKE_BUILD_TYPE=Release
+# cmake --build build/cmake/aot-stage0 --config Release
+#
+cmake_minimum_required(VERSION 3.20)
+project(estella_aot_stage0 C CXX)
+
+set(CMAKE_CXX_STANDARD 20)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+# quickjs-ng uses C11 atomics; MSVC rejects them below /std:c11. Same pair
+# native/CMakeLists.txt sets, for the same reason.
+set(CMAKE_C_STANDARD 11)
+set(CMAKE_C_STANDARD_REQUIRED ON)
+
+# Variant C is the AOT ceiling, so an unoptimised build would not just be slow —
+# it would answer the Stage 0 question wrongly, in the direction that says "go".
+if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
+endif()
+
+get_filename_component(ESTELLA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE)
+
+if(NOT ESTELLA_QUICKJS_DIR)
+ set(ESTELLA_QUICKJS_DIR "${ESTELLA_ROOT}/build/native-deps/quickjs")
+endif()
+if(NOT EXISTS "${ESTELLA_QUICKJS_DIR}/quickjs.c")
+ message(FATAL_ERROR
+ "No QuickJS at ${ESTELLA_QUICKJS_DIR}. The native build fetches it — run\n"
+ " node build-tools/cli.js native --quickjs <dir>\n"
+ "or pass -DESTELLA_QUICKJS_DIR=<dir> pointing at a quickjs-ng checkout.")
+endif()
+
+# quickjs-ng core: four C files, same set the native host links.
+add_library(qjs STATIC
+ "${ESTELLA_QUICKJS_DIR}/quickjs.c"
+ "${ESTELLA_QUICKJS_DIR}/libregexp.c"
+ "${ESTELLA_QUICKJS_DIR}/libunicode.c"
+ "${ESTELLA_QUICKJS_DIR}/dtoa.c")
+target_include_directories(qjs PUBLIC "${ESTELLA_QUICKJS_DIR}")
+target_compile_definitions(qjs PRIVATE _GNU_SOURCE)
+if(MSVC)
+ target_compile_options(qjs PRIVATE /w)
+else()
+ target_compile_options(qjs PRIVATE -w)
+endif()
+
+add_executable(bench_aot_stage0 bench.cpp)
+target_link_libraries(bench_aot_stage0 PRIVATE qjs)
+target_include_directories(bench_aot_stage0 PRIVATE
+ "${ESTELLA_ROOT}/src"
+ "${ESTELLA_ROOT}/third_party/glm")
+target_compile_definitions(bench_aot_stage0 PRIVATE _CRT_SECURE_NO_WARNINGS)
+
+# variants.js is read at run time, so the binary can sit anywhere as long as it
+# is told where the file is. Bake the source path in as the default.
+target_compile_definitions(bench_aot_stage0 PRIVATE
+ BENCH_VARIANTS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/variants.js")
diff --git a/bench/aot-stage0/README.md b/bench/aot-stage0/README.md
new file mode 100644
index 000000000..2f40c476d
--- /dev/null
+++ b/bench/aot-stage0/README.md
@@ -0,0 +1,76 @@
+# Stage 0 — 编译系统循环,到底值不值
+
+`docs/REARCH_AOT.md` §10 把 Stage 0 定为 go/no-go,§11 写明它要退役的那条风险:
+**加速可能主要来自边界拷贝,而不是解释器**——而边界拷贝有个只花 5% 成本的修法(§12.B)。
+
+一个只报一个数字的 benchmark 分不开这两者。所以这个装置把同一个系统跑四遍:
+
+| 变体 | 是什么 |
+|---|---|
+| **A** | 今天的 SDK 路径 —— `fillTransform` → 系统体 → `writeTransform` |
+| **B** | 就地视图 —— 访问器直接落在组件字节上,不拷进也不回写(§12.B) |
+| **B2** | 裸下标 —— 解释执行的地板,完全没有对象层 |
+| **C** | 原生 C++ —— AOT 的天花板 |
+
+- `A → C` 是头条数字。
+- `A → B` 是**纯 SDK 改动**能买到的。
+- `B → C` 是**编译**能买到的 —— Stage 0 真正要的就是这个。
+
+---
+
+## 为什么是这个装置,不是 `bench/nojit-frame-bench.mjs`
+
+那一个存在的目的是**从 Mac 上模拟 iPhone**,所以它才需要 Bun + JSC + 关 JIT 那一整套解释。
+
+Stage 0 不需要 iOS。它需要的是:一个无 JIT 的解释器,和一个原生编译器,跑在**同一颗 CPU
+上、同一份字节上、同一个进程里**。QuickJS 正是原生宿主真正出货的解释器(它在任何平台上
+都没有 JIT),而且就链在这里。于是这个比较不再有任何需要辩解的地方。
+
+## 公平规则(每一条都重要)
+
+- 四个变体走**同一份候选实体列表**,付**同一次** sparse→dense 间接寻址,那是真查询要付的;
+- 四个变体从**同一份池快照**开始,每轮 `reset()`;
+- 算术在**全部四个**里都是 f64 运算 + f32 存储。因为那就是 JS `number` 的语义,
+ 因此也是 AOT 编译器不得不发的代码。C++ 用 float 算是**另一个程序**,不是更快的同一个;
+- 跑完对池做 FNV-1a,**四个校验和必须相同**。不同就说明它们没在做同一件事,
+ 那一轮的所有计时都不作数(装置会直接退出码 2);
+- `variants.js` 里的字段偏移由 `bench.cpp` 的 `static_assert(offsetof(...))`
+ 顶着真实 C++ 结构体校验。偏移漂了就编译不过,不会静默量出假数字。
+
+## A 是保守的
+
+真实的 `query.ts` 迭代器还要付:迭代器协议、`beginIteration/endIteration`、
+变更过滤检查、每组件一次 `getters_[i]` 间接调用、`markChanged` 是函数调用而不是一次字节写。
+这里一样都没算。**所以真实的 A 比这里量到的更慢**,A→C 是下界不是上界。
+
+---
+
+## 跑
+
+```bat
+bench\aot-stage0\build.bat :: MSVC 不在 PATH 上,脚本自己 call vcvars
+build\cmake\aot-stage0\bench_aot_stage0.exe
+```
+
+| 环境变量 | 默认 | 含义 |
+|---|---|---|
+| `BENCH_ENTITIES` | 5000 | 实体数 |
+| `BENCH_FRAMES` | 600 | 计时帧数 |
+| `BENCH_WARMUP` | 60 | 热身帧数 |
+| `BENCH_BODY` | `thin` | `thin` = 速度积分,3 个乘加;`thick` = 加限速(sqrt)与边界回绕,约 25 flops |
+| `BENCH_ORDER` | `dense` | `scattered` = 池被 churn 过,候选顺序不等于稠密顺序 |
+| `BENCH_VARIANTS` | 源码目录 | `variants.js` 的路径 |
+
+**先跑 `BENCH_BODY=thick BENCH_ORDER=scattered`。** 那是四种组合里对 AOT 最不利的一种,
+也是最像真实游戏的一种。`thin` + `dense` 是最讨好 AOT 的组合,单看它会高估。
+
+## 两个必须知道的边界
+
+1. **thin body 会高估。** 三个乘加的循环几乎全是解释器调度开销,那是 QuickJS 的最差
+ 情形、AOT 的最好情形。thick body 存在就是为了从另一侧把答案夹住。真实游戏在两者之间。
+ (thick 的限速阈值刻意设成会触发的值 —— 一个永不执行的 `sqrt` 会让 thick 退化成
+ "带死代码的 thin",第一版就踩了这个坑。)
+
+2. **这量的是系统循环,不是一帧。** 一帧里还有 C++ 的工作、渲染提交、调度本身。
+ 系统循环快 400 倍**不等于**帧快 400 倍 —— Amdahl 说了算。把这个数字翻译成帧预算,
+ 需要先量出「一帧里有多大比例是 TS 系统代码」,那是另一次测量,这里没做。
diff --git a/bench/aot-stage0/bench.cpp b/bench/aot-stage0/bench.cpp
new file mode 100644
index 000000000..a36578cf6
--- /dev/null
+++ b/bench/aot-stage0/bench.cpp
@@ -0,0 +1,470 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bench.cpp
+ * @brief Stage 0 of the AOT proposal: is compiling the system loop worth it?
+ *
+ * @details `docs/REARCH_AOT.md` §10 makes Stage 0 a go/no-go, and §11 names the
+ * risk it exists to retire: the speedup may be mostly the BOUNDARY COPY,
+ * not the interpreter — and the copy has a fix that costs 5% of a
+ * compiler (§12.B). A benchmark that reports one number cannot tell
+ * those apart, so this one runs the same system four ways:
+ *
+ * A today's SDK path — fillTransform, body, writeTransform
+ * B in-place view — accessors onto the bytes, nothing copied
+ * B2 raw indexing — the interpreted floor, no object layer
+ * C native C++ — the AOT ceiling
+ *
+ * A/C is the headline. A/B is what a pure SDK change buys. B/C is what
+ * COMPILING buys, and that is the number Stage 0 actually turns on.
+ *
+ * Why this process and not the Bun proxy in bench/README.md: that one
+ * exists to model an iPhone from a Mac. Stage 0 does not need iOS — it
+ * needs a no-JIT interpreter and a native compiler on the SAME cpu, on
+ * the SAME bytes, in the SAME process. QuickJS is the interpreter the
+ * native host actually ships (it has no JIT on ANY platform), and it is
+ * linked right here, so the comparison has nothing left to apologise for.
+ *
+ * Fairness rules, all of which matter:
+ * - every variant walks the same candidate list through the same
+ * sparse->dense indirection a real query pays;
+ * - every variant starts from an identical snapshot of the pools;
+ * - the arithmetic is f64 with an f32 store in ALL FOUR, because that
+ * is what JS `number` means and therefore what an AOT compiler would
+ * have to emit. C++ doing it in float would be a different program;
+ * - a checksum over the pool must come out identical for all four. If
+ * it does not, they are not doing the same work and no timing from
+ * the run means anything.
+ */
+#include "quickjs.h"
+
+#include "esengine/ecs/components/Transform.hpp"
+#include "esengine/ecs/components/Velocity.hpp"
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+using esengine::ecs::Transform;
+using esengine::ecs::Velocity;
+
+// The offsets variants.js hard-codes, checked against the real struct. EHT keeps
+// the SDK's generated accessors honest the same way; this keeps the bench honest.
+static_assert(offsetof(Transform, position) == 0, "variants.js T_POS");
+static_assert(offsetof(Transform, rotation) == 12, "variants.js T_ROT");
+static_assert(offsetof(Transform, scale) == 28, "variants.js T_SCL");
+static_assert(offsetof(Transform, worldPosition) == 40, "variants.js T_WPOS");
+static_assert(offsetof(Transform, worldRotation) == 52, "variants.js T_WROT");
+static_assert(offsetof(Transform, worldScale) == 68, "variants.js T_WSCL");
+static_assert(offsetof(Velocity, linear) == 0, "variants.js V_LIN");
+static_assert(offsetof(Velocity, angular) == 12, "variants.js V_ANG");
+
+namespace {
+
+// --------------------------------------------------------------------------
+// config
+// --------------------------------------------------------------------------
+int intEnv(const char* name, int def) {
+ const char* v = std::getenv(name);
+ if (!v || !*v) return def;
+ char* end = nullptr;
+ long n = std::strtol(v, &end, 10);
+ return (end && *end == 0 && n > 0) ? static_cast<int>(n) : def;
+}
+bool strEnvIs(const char* name, const char* want) {
+ const char* v = std::getenv(name);
+ return v && std::strcmp(v, want) == 0;
+}
+
+const int ENTITIES = intEnv("BENCH_ENTITIES", 5000);
+const int FRAMES = intEnv("BENCH_FRAMES", 600);
+const int WARMUP = intEnv("BENCH_WARMUP", 60);
+const double DT = 1.0 / 60.0;
+
+// --------------------------------------------------------------------------
+// world
+// --------------------------------------------------------------------------
+struct World {
+ std::vector<Transform> transforms; // the dense pool
+ std::vector<Velocity> velocities; // the dense pool
+ std::vector<uint32_t> sparse; // entity id -> dense row
+ std::vector<uint32_t> ents; // the candidate list a query walks
+ std::vector<uint8_t> changed; // world.markChanged's bit
+
+ std::vector<Transform> pristineT;
+ std::vector<Velocity> pristineV;
+
+ void reset() {
+ transforms = pristineT;
+ velocities = pristineV;
+ std::fill(changed.begin(), changed.end(), uint8_t{0});
+ }
+};
+
+// mulberry32, same generator the existing bench uses, so both build the same scene.
+struct Rand {
+ uint32_t a;
+ explicit Rand(uint32_t seed) : a(seed) {}
+ double operator()() {
+ a += 0x6D2B79F5u;
+ uint32_t t = a;
+ t = (t ^ (t >> 15)) * (1u | t);
+ t += (t ^ (t >> 7)) * (61u | t);
+ return static_cast<double>((t ^ (t >> 14))) / 4294967296.0;
+ }
+};
+
+World buildWorld(int n, bool scattered) {
+ World w;
+ w.transforms.resize(n);
+ w.velocities.resize(n);
+ w.sparse.resize(n);
+ w.ents.resize(n);
+ w.changed.assign(n, 0);
+
+ // Dense rows in entity order, or permuted. A world that has spawned and
+ // despawned does not keep its pool sorted by entity id, and walking it out of
+ // order is a different memory workload — one every variant pays equally.
+ std::vector<uint32_t> rows(n);
+ for (int i = 0; i < n; i++) rows[i] = static_cast<uint32_t>(i);
+ if (scattered) {
+ Rand shuffle(0xC0FFEEu);
+ for (int i = n - 1; i > 0; i--) {
+ int j = static_cast<int>(shuffle() * (i + 1));
+ std::swap(rows[i], rows[j]);
+ }
+ }
+
+ Rand rand(0x1234abcdu);
+ for (int e = 0; e < n; e++) {
+ w.ents[e] = static_cast<uint32_t>(e);
+ w.sparse[e] = rows[e];
+ Transform& t = w.transforms[rows[e]];
+ t.position = {static_cast<float>((rand() - 0.5) * 2000.0),
+ static_cast<float>((rand() - 0.5) * 2000.0), 0.0f};
+ Velocity& v = w.velocities[rows[e]];
+ v.linear = {static_cast<float>((rand() - 0.5) * 120.0),
+ static_cast<float>((rand() - 0.5) * 120.0), 0.0f};
+ }
+ w.pristineT = w.transforms;
+ w.pristineV = w.velocities;
+ return w;
+}
+
+// FNV-1a over the pools. Every variant must produce the same digest.
+uint64_t checksum(const World& w) {
+ uint64_t h = 1469598103934665603ull;
+ auto feed = [&h](const void* p, size_t n) {
+ const uint8_t* b = static_cast<const uint8_t*>(p);
+ for (size_t i = 0; i < n; i++) { h ^= b[i]; h *= 1099511628211ull; }
+ };
+ feed(w.transforms.data(), w.transforms.size() * sizeof(Transform));
+ feed(w.changed.data(), w.changed.size());
+ return h;
+}
+
+// --------------------------------------------------------------------------
+// variant C — native. The ceiling.
+//
+// f64 math with an f32 store, matching JS `number` semantics exactly. An AOT
+// compiler could only narrow this to f32 by PROVING the narrowing safe, which it
+// cannot do for a `number`, so this is the honest ceiling — not a faster program
+// that happens to compute something else.
+// --------------------------------------------------------------------------
+void variantC(World& w, double dt) {
+ const int n = ENTITIES;
+ const uint32_t* ents = w.ents.data();
+ const uint32_t* sparse = w.sparse.data();
+ Transform* tf = w.transforms.data();
+ const Velocity* vf = w.velocities.data();
+ uint8_t* changed = w.changed.data();
+
+ for (int i = 0; i < n; i++) {
+ const uint32_t e = ents[i];
+ const uint32_t row = sparse[e];
+ Transform& t = tf[row];
+ const Velocity& v = vf[row];
+ t.position.x = static_cast<float>(static_cast<double>(t.position.x) + static_cast<double>(v.linear.x) * dt);
+ t.position.y = static_cast<float>(static_cast<double>(t.position.y) + static_cast<double>(v.linear.y) * dt);
+ t.position.z = static_cast<float>(static_cast<double>(t.position.z) + static_cast<double>(v.linear.z) * dt);
+ changed[e] = 1;
+ }
+}
+
+// The thick body — see the header comment in variants.js. Same arithmetic, same
+// order, same branches, so it stays bit-identical to the three JS variants.
+constexpr double MAXSPEED = 50.0; // must match variants.js
+constexpr double MAXSPEED2 = MAXSPEED * MAXSPEED;
+constexpr double BOUND = 1000.0;
+constexpr double BOUND2 = BOUND * 2.0;
+
+void variantCThick(World& w, double dt) {
+ const int n = ENTITIES;
+ const uint32_t* ents = w.ents.data();
+ const uint32_t* sparse = w.sparse.data();
+ Transform* tf = w.transforms.data();
+ const Velocity* vf = w.velocities.data();
+ uint8_t* changed = w.changed.data();
+
+ for (int i = 0; i < n; i++) {
+ const uint32_t e = ents[i];
+ const uint32_t row = sparse[e];
+ Transform& t = tf[row];
+ const Velocity& v = vf[row];
+
+ double vx = v.linear.x, vy = v.linear.y, vz = v.linear.z;
+ const double sp2 = vx * vx + vy * vy + vz * vz;
+ if (sp2 > MAXSPEED2) { const double s = MAXSPEED / std::sqrt(sp2); vx *= s; vy *= s; vz *= s; }
+ double px = static_cast<double>(t.position.x) + vx * dt;
+ double py = static_cast<double>(t.position.y) + vy * dt;
+ const double pz = static_cast<double>(t.position.z) + vz * dt;
+ if (px > BOUND) px -= BOUND2; else if (px < -BOUND) px += BOUND2;
+ if (py > BOUND) py -= BOUND2; else if (py < -BOUND) py += BOUND2;
+ t.position.x = static_cast<float>(px);
+ t.position.y = static_cast<float>(py);
+ t.position.z = static_cast<float>(pz);
+
+ changed[e] = 1;
+ }
+}
+
+// --------------------------------------------------------------------------
+// stats
+// --------------------------------------------------------------------------
+struct Result {
+ const char* name;
+ const char* what;
+ double median; // ms/frame
+ double p95;
+ double mean;
+ uint64_t digest;
+};
+
+double percentile(std::vector<double>& sorted, double p) {
+ if (sorted.empty()) return 0.0;
+ size_t idx = static_cast<size_t>((p / 100.0) * sorted.size());
+ if (idx >= sorted.size()) idx = sorted.size() - 1;
+ return sorted[idx];
+}
+
+using Clock = std::chrono::steady_clock;
+double msSince(Clock::time_point t0) {
+ return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
+}
+
+// --------------------------------------------------------------------------
+// QuickJS plumbing
+// --------------------------------------------------------------------------
+std::string readFile(const char* path) {
+ FILE* f = std::fopen(path, "rb");
+ if (!f) return {};
+ std::fseek(f, 0, SEEK_END);
+ long n = std::ftell(f);
+ std::fseek(f, 0, SEEK_SET);
+ std::string s(static_cast<size_t>(n > 0 ? n : 0), '\0');
+ if (n > 0 && std::fread(s.data(), 1, static_cast<size_t>(n), f) != static_cast<size_t>(n)) s.clear();
+ std::fclose(f);
+ return s;
+}
+
+void reportException(JSContext* ctx) {
+ JSValue e = JS_GetException(ctx);
+ const char* s = JS_ToCString(ctx, e);
+ std::fprintf(stderr, "js error: %s\n", s ? s : "(unprintable)");
+ if (s) JS_FreeCString(ctx, s);
+ JS_FreeValue(ctx, e);
+}
+
+// An ArrayBuffer aliasing memory we own. free_func = nullptr, so QuickJS never
+// frees it — the same trick es_<Component>_buffer uses to hand the SDK the pool.
+JSValue aliasBuffer(JSContext* ctx, void* p, size_t bytes) {
+ return JS_NewArrayBuffer(ctx, static_cast<uint8_t*>(p), bytes, nullptr, nullptr, false);
+}
+
+} // namespace
+
+int main() {
+ const bool scattered = strEnvIs("BENCH_ORDER", "scattered");
+ const bool thick = strEnvIs("BENCH_BODY", "thick");
+
+ std::printf("================================================================\n");
+ std::printf("Estella AOT — Stage 0 loop benchmark (REARCH_AOT.md §10)\n");
+ std::printf(" interpreter : QuickJS %d.%d.%d (no JIT, on any platform)\n",
+ QJS_VERSION_MAJOR, QJS_VERSION_MINOR, QJS_VERSION_PATCH);
+ std::printf(" entities : %d\n", ENTITIES);
+ std::printf(" frames : %d (+%d warmup)\n", FRAMES, WARMUP);
+ std::printf(" pool order : %s\n", scattered ? "scattered (post-churn)" : "dense (best case)");
+ std::printf(" strides : Transform %zu B Velocity %zu B\n",
+ sizeof(Transform), sizeof(Velocity));
+ std::printf("================================================================\n");
+
+ World w = buildWorld(ENTITIES, scattered);
+
+ JSRuntime* rt = JS_NewRuntime();
+ JSContext* ctx = JS_NewContext(rt);
+ if (!rt || !ctx) { std::fprintf(stderr, "could not create the QuickJS runtime\n"); return 1; }
+
+#ifndef BENCH_VARIANTS_DEFAULT
+#define BENCH_VARIANTS_DEFAULT "variants.js"
+#endif
+ const char* srcPath = std::getenv("BENCH_VARIANTS");
+ std::string path = srcPath ? srcPath : BENCH_VARIANTS_DEFAULT;
+ std::string src = readFile(path.c_str());
+ if (src.empty()) {
+ std::fprintf(stderr, "could not read %s — set BENCH_VARIANTS to its path\n", path.c_str());
+ return 1;
+ }
+ JSValue ev = JS_Eval(ctx, src.c_str(), src.size(), path.c_str(), JS_EVAL_TYPE_GLOBAL);
+ if (JS_IsException(ev)) { reportException(ctx); return 1; }
+ JS_FreeValue(ctx, ev);
+
+ JSValue global = JS_GetGlobalObject(ctx);
+
+ // Hand JS the pools. Zero copy — the same bytes variant C walks.
+ {
+ JSValue setup = JS_GetPropertyStr(ctx, global, "setup");
+ JSValue args[8] = {
+ JS_NewInt32(ctx, ENTITIES),
+ aliasBuffer(ctx, w.ents.data(), w.ents.size() * sizeof(uint32_t)),
+ aliasBuffer(ctx, w.sparse.data(), w.sparse.size() * sizeof(uint32_t)),
+ aliasBuffer(ctx, w.transforms.data(), w.transforms.size() * sizeof(Transform)),
+ aliasBuffer(ctx, w.velocities.data(), w.velocities.size() * sizeof(Velocity)),
+ aliasBuffer(ctx, w.changed.data(), w.changed.size()),
+ JS_NewInt32(ctx, static_cast<int32_t>(sizeof(Transform))),
+ JS_NewInt32(ctx, static_cast<int32_t>(sizeof(Velocity))),
+ };
+ JSValue r = JS_Call(ctx, setup, JS_UNDEFINED, 8, args);
+ if (JS_IsException(r)) { reportException(ctx); return 1; }
+ JS_FreeValue(ctx, r);
+ for (JSValue& a : args) JS_FreeValue(ctx, a);
+ JS_FreeValue(ctx, setup);
+ }
+
+ std::vector<Result> results;
+
+ // One JS variant: reset, warm, time FRAMES calls of fn(dt).
+ auto runJs = [&](const char* name, const char* what, const char* fnName) {
+ JSValue fn = JS_GetPropertyStr(ctx, global, fnName);
+ if (!JS_IsFunction(ctx, fn)) {
+ std::fprintf(stderr, "%s is not a function in variants.js\n", fnName);
+ std::exit(1);
+ }
+ w.reset();
+ JSValue dt = JS_NewFloat64(ctx, DT);
+ for (int f = 0; f < WARMUP; f++) {
+ JSValue r = JS_Call(ctx, fn, JS_UNDEFINED, 1, &dt);
+ if (JS_IsException(r)) { reportException(ctx); std::exit(1); }
+ JS_FreeValue(ctx, r);
+ }
+ w.reset();
+ std::vector<double> samples;
+ samples.reserve(static_cast<size_t>(FRAMES));
+ for (int f = 0; f < FRAMES; f++) {
+ auto t0 = Clock::now();
+ JSValue r = JS_Call(ctx, fn, JS_UNDEFINED, 1, &dt);
+ samples.push_back(msSince(t0));
+ if (JS_IsException(r)) { reportException(ctx); std::exit(1); }
+ JS_FreeValue(ctx, r);
+ }
+ JS_FreeValue(ctx, fn);
+ uint64_t digest = checksum(w);
+ double mean = 0.0;
+ for (double s : samples) mean += s;
+ mean /= static_cast<double>(samples.size());
+ std::sort(samples.begin(), samples.end());
+ results.push_back({name, what, percentile(samples, 50), percentile(samples, 95), mean, digest});
+ };
+
+ auto runNative = [&](const char* name, const char* what) {
+ auto fn = thick ? &variantCThick : &variantC;
+ w.reset();
+ for (int f = 0; f < WARMUP; f++) fn(w, DT);
+ w.reset();
+ std::vector<double> samples;
+ samples.reserve(static_cast<size_t>(FRAMES));
+ for (int f = 0; f < FRAMES; f++) {
+ auto t0 = Clock::now();
+ fn(w, DT);
+ samples.push_back(msSince(t0));
+ }
+ uint64_t digest = checksum(w);
+ double mean = 0.0;
+ for (double s : samples) mean += s;
+ mean /= static_cast<double>(samples.size());
+ std::sort(samples.begin(), samples.end());
+ results.push_back({name, what, percentile(samples, 50), percentile(samples, 95), mean, digest});
+ };
+
+ runJs("A", "SDK today (fill + body + write-back)", thick ? "variantA_thick" : "variantA");
+ runJs("B", "in-place view (SDK fix, §12.B)", thick ? "variantB_thick" : "variantB");
+ runJs("B2", "raw indexing (interpreted floor)", thick ? "variantB2_thick" : "variantB2");
+ runNative("C", "native C++ (the AOT ceiling)");
+
+ JS_FreeValue(ctx, global);
+
+ // ----------------------------------------------------------------------
+ // report
+ // ----------------------------------------------------------------------
+ std::printf("\n variant %-38s %10s %10s\n", "what it is", "ms/frame", "p95");
+ std::printf(" ------- %-38s %10s %10s\n",
+ "--------------------------------------", "----------", "----------");
+ for (const Result& r : results) {
+ std::printf(" %-7s %-38s %10.4f %10.4f\n", r.name, r.what, r.median, r.p95);
+ }
+
+ const uint64_t want = results.front().digest;
+ bool agree = true;
+ for (const Result& r : results) if (r.digest != want) agree = false;
+ std::printf("\n checksum %016llx %s\n",
+ static_cast<unsigned long long>(want),
+ agree ? "all four variants agree"
+ : "*** MISMATCH — the variants are NOT doing the same work ***");
+ if (!agree) {
+ for (const Result& r : results) {
+ std::printf(" %-3s %016llx\n", r.name, static_cast<unsigned long long>(r.digest));
+ }
+ std::printf("\n Timings above are meaningless until this is fixed.\n");
+ JS_FreeContext(ctx);
+ JS_FreeRuntime(rt);
+ return 2;
+ }
+
+ const double A = results[0].median, B = results[1].median;
+ const double B2 = results[2].median, C = results[3].median;
+ const double total = A / C, sdkFix = A / B, viewCost = B / B2, compiled = B / C;
+
+ std::printf("\n where the speedup actually comes from\n");
+ std::printf(" ------------------------------------------------------------\n");
+ std::printf(" A -> B %6.2fx what a pure SDK change buys (§12.B)\n", sdkFix);
+ std::printf(" B -> B2 %6.2fx what the accessor layer costs\n", viewCost);
+ std::printf(" B -> C %6.2fx what COMPILING buys <-- the Stage 0 question\n", compiled);
+ std::printf(" A -> C %6.2fx total AOT ceiling\n", total);
+ std::printf(" throughput A %.2f C %.2f M entity-updates/s\n",
+ ENTITIES * (1000.0 / A) / 1e6, ENTITIES * (1000.0 / C) / 1e6);
+
+ // REARCH_AOT §10: >= 5x total, and at least half of it must NOT be the copy.
+ // "Half" in a ratio is geometric: sqrt(5) on each side.
+ const double NEED_TOTAL = 5.0;
+ const double NEED_COMPILED = 2.2360679775; // sqrt(5)
+ const bool passTotal = total >= NEED_TOTAL;
+ const bool passCompiled = compiled >= NEED_COMPILED;
+
+ std::printf("\n Stage 0 exit criteria\n");
+ std::printf(" ------------------------------------------------------------\n");
+ std::printf(" A -> C >= %.2fx %6.2fx %s\n", NEED_TOTAL, total, passTotal ? "PASS" : "FAIL");
+ std::printf(" B -> C >= %.2fx %6.2fx %s\n", NEED_COMPILED, compiled, passCompiled ? "PASS" : "FAIL");
+ std::printf("\n VERDICT: %s\n", (passTotal && passCompiled)
+ ? "GO — compiling buys more than the SDK fix alone. Proceed to Stage 1."
+ : "STOP — take REARCH_AOT.md §12 instead, starting with B. Re-read the split above.");
+ std::printf("================================================================\n");
+
+ JS_FreeContext(ctx);
+ JS_FreeRuntime(rt);
+ return 0;
+}
diff --git a/bench/aot-stage0/build.bat b/bench/aot-stage0/build.bat
new file mode 100644
index 000000000..d575a8339
--- /dev/null
+++ b/bench/aot-stage0/build.bat
@@ -0,0 +1,29 @@
+@echo off
+REM SPDX-License-Identifier: Apache-2.0
+REM Configure + build the Stage 0 AOT bench with MSVC. Run from the repo root:
+REM bench\aot-stage0\build.bat
+REM MSVC is installed here but not on PATH, so this calls vcvars itself
+REM (see the cpp-harnesses-build-locally note).
+setlocal
+set "VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
+if not exist "%VCVARS%" (
+ echo Could not find vcvars64.bat at "%VCVARS%"
+ exit /b 1
+)
+call "%VCVARS%" >nul 2>&1 || exit /b 1
+
+set "ROOT=%~dp0..\.."
+pushd "%ROOT%" || exit /b 1
+
+cmake -S bench/aot-stage0 -B build/cmake/aot-stage0 -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release || goto :fail
+cmake --build build/cmake/aot-stage0 || goto :fail
+
+popd
+echo.
+echo built: build\cmake\aot-stage0\bench_aot_stage0.exe
+exit /b 0
+
+:fail
+popd
+echo BUILD FAILED
+exit /b 1
diff --git a/bench/aot-stage0/variants.js b/bench/aot-stage0/variants.js
new file mode 100644
index 000000000..ee2e5e5f1
--- /dev/null
+++ b/bench/aot-stage0/variants.js
@@ -0,0 +1,293 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// variants.js — the JS half of the Stage 0 AOT measurement.
+//
+// Four shapes of ONE system (velocity integration over N entities), so the
+// speedup an AOT compiler could buy can be split into the two things it is
+// actually made of:
+//
+// A today's SDK path .... fillTransform -> user body -> writeTransform
+// B in-place view ....... a reused view object whose fields are accessors
+// straight onto the component bytes (REARCH_AOT §12.B)
+// B2 raw indexing ........ the interpreted floor: no object layer at all
+// C native .............. in bench.cpp, the AOT ceiling
+//
+// A -> B is what a pure SDK change buys. B -> C is what COMPILING buys.
+// The Stage 0 exit criterion needs both, which is why they are separate runs.
+//
+// A and B are transcribed from sdk/src/ecs/bridge/ptrAccessors.generated.ts —
+// same field order, same offsets, same "write every field back" behaviour. If
+// that generated file changes shape, this file is wrong and must follow it.
+//
+// All arithmetic is done the way JS does it (f64 math, f32 store), and bench.cpp
+// does the same in C++, so every variant is bit-identical and the checksums must
+// match. A checksum mismatch means the variants are not doing the same work and
+// no timing from the run means anything.
+
+'use strict';
+
+// Filled by setup(). Module-level so a per-frame call marshals one argument.
+let N = 0;
+let ents = null; // Uint32Array — the candidate list a query walks
+let sparse = null; // Uint32Array — entity id -> dense row
+let TF = null; // Float32Array over the Transform pool
+let VF = null; // Float32Array over the Velocity pool
+let changed = null; // Uint8Array — world.markChanged's bit
+let TW = 0; // Transform stride, in f32 words
+let VW = 0; // Velocity stride, in f32 words
+
+// Transform field offsets, in f32 words from the row base. Mirrors
+// fillTransform/writeTransform: position@0 rotation@12 scale@28
+// worldPosition@40 worldRotation@52 worldScale@68 (bytes).
+const T_POS = 0, T_ROT = 3, T_SCL = 7, T_WPOS = 10, T_WROT = 13, T_WSCL = 17;
+// Velocity: linear@0 angular@12 (bytes).
+const V_LIN = 0, V_ANG = 3;
+
+globalThis.setup = function (n, entsBuf, sparseBuf, tBuf, vBuf, changedBuf, tStrideBytes, vStrideBytes) {
+ N = n;
+ ents = new Uint32Array(entsBuf);
+ sparse = new Uint32Array(sparseBuf);
+ TF = new Float32Array(tBuf);
+ VF = new Float32Array(vBuf);
+ changed = new Uint8Array(changedBuf);
+ TW = tStrideBytes >> 2;
+ VW = vStrideBytes >> 2;
+};
+
+// ---------------------------------------------------------------------------
+// A — today's path.
+//
+// The `out` objects are created ONCE per query, not per entity: that is what
+// createTransformData() is for, and modelling it any other way would make the
+// baseline look worse than it is. The cost is not allocation, it is the ~90
+// property accesses and 46 typed-array accesses per entity — and above all that
+// writeTransform stores ALL TWENTY floats to change three.
+// ---------------------------------------------------------------------------
+const outT = {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 0 },
+ scale: { x: 0, y: 0, z: 0 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { x: 0, y: 0, z: 0, w: 0 },
+ worldScale: { x: 0, y: 0, z: 0 },
+};
+const outV = { linear: { x: 0, y: 0, z: 0 }, angular: { x: 0, y: 0, z: 0 } };
+
+globalThis.variantA = function (dt) {
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ const t = row * TW;
+ const v = row * VW;
+
+ // fillTransform(f32, u32, u8, ptr, out)
+ const p_ = outT.position; p_.x = TF[t + T_POS]; p_.y = TF[t + T_POS + 1]; p_.z = TF[t + T_POS + 2];
+ const r_ = outT.rotation; r_.x = TF[t + T_ROT]; r_.y = TF[t + T_ROT + 1]; r_.z = TF[t + T_ROT + 2]; r_.w = TF[t + T_ROT + 3];
+ const s_ = outT.scale; s_.x = TF[t + T_SCL]; s_.y = TF[t + T_SCL + 1]; s_.z = TF[t + T_SCL + 2];
+ const wp_ = outT.worldPosition; wp_.x = TF[t + T_WPOS]; wp_.y = TF[t + T_WPOS + 1]; wp_.z = TF[t + T_WPOS + 2];
+ const wr_ = outT.worldRotation; wr_.x = TF[t + T_WROT]; wr_.y = TF[t + T_WROT + 1]; wr_.z = TF[t + T_WROT + 2]; wr_.w = TF[t + T_WROT + 3];
+ const ws_ = outT.worldScale; ws_.x = TF[t + T_WSCL]; ws_.y = TF[t + T_WSCL + 1]; ws_.z = TF[t + T_WSCL + 2];
+
+ // fillVelocity(...)
+ const l_ = outV.linear; l_.x = VF[v + V_LIN]; l_.y = VF[v + V_LIN + 1]; l_.z = VF[v + V_LIN + 2];
+ const a_ = outV.angular; a_.x = VF[v + V_ANG]; a_.y = VF[v + V_ANG + 1]; a_.z = VF[v + V_ANG + 2];
+
+ // --- the system body the game author actually wrote ---
+ outT.position.x += outV.linear.x * dt;
+ outT.position.y += outV.linear.y * dt;
+ outT.position.z += outV.linear.z * dt;
+
+ // writeTransform(f32, u32, u8, ptr, data) — every field, readonly ones included
+ TF[t + T_POS] = outT.position.x; TF[t + T_POS + 1] = outT.position.y; TF[t + T_POS + 2] = outT.position.z;
+ TF[t + T_ROT] = outT.rotation.x; TF[t + T_ROT + 1] = outT.rotation.y; TF[t + T_ROT + 2] = outT.rotation.z; TF[t + T_ROT + 3] = outT.rotation.w;
+ TF[t + T_SCL] = outT.scale.x; TF[t + T_SCL + 1] = outT.scale.y; TF[t + T_SCL + 2] = outT.scale.z;
+ TF[t + T_WPOS] = outT.worldPosition.x; TF[t + T_WPOS + 1] = outT.worldPosition.y; TF[t + T_WPOS + 2] = outT.worldPosition.z;
+ TF[t + T_WROT] = outT.worldRotation.x; TF[t + T_WROT + 1] = outT.worldRotation.y; TF[t + T_WROT + 2] = outT.worldRotation.z; TF[t + T_WROT + 3] = outT.worldRotation.w;
+ TF[t + T_WSCL] = outT.worldScale.x; TF[t + T_WSCL + 1] = outT.worldScale.y; TF[t + T_WSCL + 2] = outT.worldScale.z;
+
+ changed[e] = 1; // world.markChanged(entity, component)
+ }
+};
+
+// ---------------------------------------------------------------------------
+// B — in-place view (REARCH_AOT §12.B).
+//
+// The game author's code is UNCHANGED: still `t.position.x += v.linear.x * dt`.
+// What changed is that `t.position` is a reused object whose x/y/z are accessors
+// onto the component bytes, so nothing is copied in and nothing is written back.
+// One object graph for the whole query, retargeted per entity by moving `base`.
+//
+// This is the honest shape of the cheap fix: the accessor CALLS are still paid,
+// which is exactly what makes it different from B2 and from C.
+// ---------------------------------------------------------------------------
+function vec3View(get, set) {
+ return {
+ get x() { return TF[get() + 0]; }, set x(n) { TF[set() + 0] = n; },
+ get y() { return TF[get() + 1]; }, set y(n) { TF[set() + 1] = n; },
+ get z() { return TF[get() + 2]; }, set z(n) { TF[set() + 2] = n; },
+ };
+}
+
+let tBase = 0, vBase = 0;
+const viewT = {
+ position: {
+ get x() { return TF[tBase + T_POS]; }, set x(n) { TF[tBase + T_POS] = n; },
+ get y() { return TF[tBase + T_POS + 1]; }, set y(n) { TF[tBase + T_POS + 1] = n; },
+ get z() { return TF[tBase + T_POS + 2]; }, set z(n) { TF[tBase + T_POS + 2] = n; },
+ },
+};
+const viewV = {
+ linear: {
+ get x() { return VF[vBase + V_LIN]; },
+ get y() { return VF[vBase + V_LIN + 1]; },
+ get z() { return VF[vBase + V_LIN + 2]; },
+ },
+};
+
+globalThis.variantB = function (dt) {
+ const t = viewT, v = viewV;
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ tBase = row * TW;
+ vBase = row * VW;
+
+ // --- byte-for-byte the same system body as variant A ---
+ t.position.x += v.linear.x * dt;
+ t.position.y += v.linear.y * dt;
+ t.position.z += v.linear.z * dt;
+
+ changed[e] = 1;
+ }
+};
+
+// ---------------------------------------------------------------------------
+// B2 — raw indexing. No object layer at all.
+//
+// Not a shippable API — a game author will not write this. It is the FLOOR for
+// interpreted JS, and it is what separates "the object layer costs this much"
+// from "the interpreter costs this much". Without it, B -> C conflates the two.
+// ---------------------------------------------------------------------------
+globalThis.variantB2 = function (dt) {
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ const t = row * TW;
+ const v = row * VW;
+ TF[t] = TF[t] + VF[v] * dt;
+ TF[t + 1] = TF[t + 1] + VF[v + 1] * dt;
+ TF[t + 2] = TF[t + 2] + VF[v + 2] * dt;
+ changed[e] = 1;
+ }
+};
+
+// vec3View is declared for symmetry with a real SDK implementation but is not on
+// the measured path; referencing it keeps a minifier or a reader from assuming
+// variant B builds its views per entity.
+globalThis.__unused_vec3View = vec3View;
+
+// ===========================================================================
+// THICK BODY
+//
+// Everything above integrates velocity in three multiply-adds. That is a real
+// system — it is the one bench/nojit-frame-bench.mjs runs — but it is also the
+// case that flatters AOT most, because almost none of the frame is arithmetic:
+// it is the interpreter's dispatch and the SDK's write-back. Reporting only that
+// number would be measuring the benchmark instead of the engine.
+//
+// So the same four variants get a second body with the arithmetic a movement
+// system actually carries: a speed clamp (with a sqrt) and a wrap into bounds.
+// ~25 flops and two branches per entity instead of three multiply-adds. The
+// honest answer for a real game is bracketed by the two.
+//
+// Written with locals and ONE store per field, in every variant, so all four
+// stay bit-identical: Math.sqrt and std::sqrt are both correctly rounded, and
+// nothing rounds to f32 until the final store.
+// ===========================================================================
+const MAXSPEED = 50.0; // velocities reach ~85, so the clamp fires for roughly half — the sqrt must be LIVE and the branch unpredictable, or "thick" is just "thin with dead code"
+const MAXSPEED2 = MAXSPEED * MAXSPEED;
+const BOUND = 1000.0;
+const BOUND2 = BOUND * 2.0;
+
+globalThis.variantA_thick = function (dt) {
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ const t = row * TW;
+ const v = row * VW;
+
+ const p_ = outT.position; p_.x = TF[t + T_POS]; p_.y = TF[t + T_POS + 1]; p_.z = TF[t + T_POS + 2];
+ const r_ = outT.rotation; r_.x = TF[t + T_ROT]; r_.y = TF[t + T_ROT + 1]; r_.z = TF[t + T_ROT + 2]; r_.w = TF[t + T_ROT + 3];
+ const s_ = outT.scale; s_.x = TF[t + T_SCL]; s_.y = TF[t + T_SCL + 1]; s_.z = TF[t + T_SCL + 2];
+ const wp_ = outT.worldPosition; wp_.x = TF[t + T_WPOS]; wp_.y = TF[t + T_WPOS + 1]; wp_.z = TF[t + T_WPOS + 2];
+ const wr_ = outT.worldRotation; wr_.x = TF[t + T_WROT]; wr_.y = TF[t + T_WROT + 1]; wr_.z = TF[t + T_WROT + 2]; wr_.w = TF[t + T_WROT + 3];
+ const ws_ = outT.worldScale; ws_.x = TF[t + T_WSCL]; ws_.y = TF[t + T_WSCL + 1]; ws_.z = TF[t + T_WSCL + 2];
+
+ const l_ = outV.linear; l_.x = VF[v + V_LIN]; l_.y = VF[v + V_LIN + 1]; l_.z = VF[v + V_LIN + 2];
+ const a_ = outV.angular; a_.x = VF[v + V_ANG]; a_.y = VF[v + V_ANG + 1]; a_.z = VF[v + V_ANG + 2];
+
+ // --- the system body ---
+ let vx = outV.linear.x, vy = outV.linear.y, vz = outV.linear.z;
+ const sp2 = vx * vx + vy * vy + vz * vz;
+ if (sp2 > MAXSPEED2) { const s = MAXSPEED / Math.sqrt(sp2); vx *= s; vy *= s; vz *= s; }
+ let px = outT.position.x + vx * dt;
+ let py = outT.position.y + vy * dt;
+ const pz = outT.position.z + vz * dt;
+ if (px > BOUND) px -= BOUND2; else if (px < -BOUND) px += BOUND2;
+ if (py > BOUND) py -= BOUND2; else if (py < -BOUND) py += BOUND2;
+ outT.position.x = px; outT.position.y = py; outT.position.z = pz;
+
+ TF[t + T_POS] = outT.position.x; TF[t + T_POS + 1] = outT.position.y; TF[t + T_POS + 2] = outT.position.z;
+ TF[t + T_ROT] = outT.rotation.x; TF[t + T_ROT + 1] = outT.rotation.y; TF[t + T_ROT + 2] = outT.rotation.z; TF[t + T_ROT + 3] = outT.rotation.w;
+ TF[t + T_SCL] = outT.scale.x; TF[t + T_SCL + 1] = outT.scale.y; TF[t + T_SCL + 2] = outT.scale.z;
+ TF[t + T_WPOS] = outT.worldPosition.x; TF[t + T_WPOS + 1] = outT.worldPosition.y; TF[t + T_WPOS + 2] = outT.worldPosition.z;
+ TF[t + T_WROT] = outT.worldRotation.x; TF[t + T_WROT + 1] = outT.worldRotation.y; TF[t + T_WROT + 2] = outT.worldRotation.z; TF[t + T_WROT + 3] = outT.worldRotation.w;
+ TF[t + T_WSCL] = outT.worldScale.x; TF[t + T_WSCL + 1] = outT.worldScale.y; TF[t + T_WSCL + 2] = outT.worldScale.z;
+
+ changed[e] = 1;
+ }
+};
+
+globalThis.variantB_thick = function (dt) {
+ const t = viewT, v = viewV;
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ tBase = row * TW;
+ vBase = row * VW;
+
+ let vx = v.linear.x, vy = v.linear.y, vz = v.linear.z;
+ const sp2 = vx * vx + vy * vy + vz * vz;
+ if (sp2 > MAXSPEED2) { const s = MAXSPEED / Math.sqrt(sp2); vx *= s; vy *= s; vz *= s; }
+ let px = t.position.x + vx * dt;
+ let py = t.position.y + vy * dt;
+ const pz = t.position.z + vz * dt;
+ if (px > BOUND) px -= BOUND2; else if (px < -BOUND) px += BOUND2;
+ if (py > BOUND) py -= BOUND2; else if (py < -BOUND) py += BOUND2;
+ t.position.x = px; t.position.y = py; t.position.z = pz;
+
+ changed[e] = 1;
+ }
+};
+
+globalThis.variantB2_thick = function (dt) {
+ for (let i = 0; i < N; i++) {
+ const e = ents[i];
+ const row = sparse[e];
+ const t = row * TW;
+ const v = row * VW;
+
+ let vx = VF[v], vy = VF[v + 1], vz = VF[v + 2];
+ const sp2 = vx * vx + vy * vy + vz * vz;
+ if (sp2 > MAXSPEED2) { const s = MAXSPEED / Math.sqrt(sp2); vx *= s; vy *= s; vz *= s; }
+ let px = TF[t] + vx * dt;
+ let py = TF[t + 1] + vy * dt;
+ const pz = TF[t + 2] + vz * dt;
+ if (px > BOUND) px -= BOUND2; else if (px < -BOUND) px += BOUND2;
+ if (py > BOUND) py -= BOUND2; else if (py < -BOUND) py += BOUND2;
+ TF[t] = px; TF[t + 1] = py; TF[t + 2] = pz;
+
+ changed[e] = 1;
+ }
+};