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
bench(net): most of the interest win is amortised reads, not spatial locality
esengineab77624dfd5f
diff --git a/bench/replication-interest/README.md b/bench/replication-interest/README.mdindex 4730faeae..726a791da 100644--- a/bench/replication-interest/README.md+++ b/bench/replication-interest/README.md@@ -51,25 +51,69 @@ Entities visited per sample, which is the mechanism without this machine in it:| A @ 100k × 32 | 3,200,000 | 3,200,000 | 3,200,000 || B @ 100k × 32 | **32** | 3,200,000 | **32** |+## Second question: what is left, once ownership is indexed++With the owner passes gone, the radius scan is the whole cost — and it reads+each candidate's position through the builtin `Transform`, once per connection.+Two more arms separate what that costs from what the scan costs:++| | positions | walk |+|---|---|---|+| **B** | read per connection, as shipped | every candidate |+| **C0** | read once per sample, cached | every candidate |+| **C1** | read once per sample into a grid | nearby cells only |++The grid is rebuilt **every sample**, which is not a compromise — it is what+lets it support an arbitrary `position()` function. Nothing is carried between+samples, so there is no invalidation contract to get wrong. It keeps all three+of the shipped rules: a placeless entity is relevant to everyone, no positioned+anchor fails open to `'all'`, and a cell is a box while the rule is a sphere, so+the exact distance test stays.++The grid saw exactly what the full scan saw, every connection, every sample, at+all three differential points.++| population | connections | B | C0 | C1 | C0/B | C1/B |+|---|---|---|---|---|---|---|+| 10k | 8 | 115% | 19% | 16% | 0.168 | 0.143 |+| 10k | 32 | 497% | 32% | 18% | 0.064 | 0.036 |+| 100k | 8 | 1094% | 219% | 175% | 0.200 | 0.160 |+| 100k | 32 | **4623%** | 333% | **184%** | 0.072 | **0.040** |++Position reads per sample go from `connections × population` to `population`;+distance tests at 100k × 32 go from **3,200,000 to 83,267**.++**Most of the win is not the grid.** Reading each position once per sample+rather than once per connection is C0, and it alone takes 100k × 32 from 46+cores to 3.3. The grid then halves what is left. Measuring them together would+have credited spatial locality with an amortisation that has nothing to do with+space.++At 100% visible the grid still wins — 0.22 against B — because the read+amortisation survives even when locality buys nothing (C1/C0 there is 0.93).++**What an incremental index would buy is the build column, and only that.** At+100k × 32, C1 spends 1,716,864 of its 1,842,972 on rebuilding and 77,081 on+querying: the query is already 8% of a core, and the rebuild is 172%.+## What that says about the change after this one**Half the cost at 10k, two thirds at 100k, is ownership lookup — and none of itneeds a spatial index.** An index answers it in O(owned): 3.2 million visits-become 32.--So the order is settled: **ownership index first, spatial provider after.** Going-straight to a provider would remove anchors, radius and ownership in one change-and leave nobody able to say which part paid.+become 32. That shipped first, on its own, for exactly this reason.-What is left in B is the real spatial problem, and it is still the larger half —-5.8 seconds per simulated second at 100k × 32. That is what a provider has to-attack, and it is worth attacking on its own terms rather than as a side effect.+What remains is the radius scan, and a per-sample rebuilt grid takes 100k × 32+from 46 cores to 1.8 while keeping arbitrary `position()` support and matching+the full scan entity for entity. The build is 93% of what is left, so an+incremental index is worth designing — but it is now a question about+maintaining a structure, not about whether locality helps.## What this does not cover-- Position lives in a script component, not the builtin `Transform` the shipped- default reads. A builtin read crosses the wasm boundary, so arm A is- UNDERSTATED here and every ratio is conservative.+- Arms A and B were first measured with position in a script component, which+ understated them by roughly a factor of ten: the shipped default reads the+ builtin `Transform` across the wasm boundary, and that read is most of the+ cost. Everything above uses the builtin.- One anchor per connection. `radiusInterest` allows several, and the radiuspass is then `candidates × anchors` — this measures the floor of that pass.- The per-connection dirty and removal filters are timed and counted but staydiff --git a/bench/replication-interest/arm.mjs b/bench/replication-interest/arm.mjsindex 71041fd5a..a8c69dd86 100644--- a/bench/replication-interest/arm.mjs+++ b/bench/replication-interest/arm.mjs@@ -8,7 +8,9 @@import path from 'node:path';import { fileURLToPath } from 'node:url';import {- loadSdk, buildWorld, applyMovement, newStats, visibleForA, visibleForB, diffAndFilter,+ loadSdk, connectEngine, buildWorld, applyMovement, newStats,+ visibleForA, visibleForB, visibleForC0, visibleForC1,+ buildPositionCache, buildGrid, diffAndFilter,} from './workload.mjs';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');@@ -29,12 +31,13 @@ const SIM_HZ = Number(flag('simHz', '60'));const REPL_HZ = Number(flag('replHz', '20'));const WARMUP = Number(flag('warmup', '60'));const MEASURE = Number(flag('measure', '240'));-/** Arm B only: compare its visible set against arm A's, every connection, every sample. */+/** Compare this arm's visible set against arm A's, every connection, every sample. */const VERIFY = argv.includes('--verify');const REPL_EVERY = Math.round(SIM_HZ / REPL_HZ);const sdk = await loadSdk(ROOT);const app = sdk.App.new();+await connectEngine(sdk, app, ROOT);const world = app.world;const ctx = buildWorld(sdk, world, {population: ENTITIES, connections: CONNECTIONS, anchorsPerConn: ANCHORS,@@ -71,15 +74,30 @@ function sampleOnce(measuring) {const dirty = candidates.slice(0, Math.max(1, Math.round(ENTITIES * 0.01)));const removals = [];+ // Built once per sample, which is what makes an arbitrary position function+ // safe here: nothing is carried between samples to go stale.+ const shared = measuring ? stats : newStats();+ const cache = ARM === 'C0' ? buildPositionCache(world, ctx, shared) : null;+ const grid = ARM === 'C1' ? buildGrid(world, ctx, shared, RADIUS) : null;+for (let c = 0; c < CONNECTIONS; c++) {const use = measuring ? stats : newStats();- const visible = ARM === 'B'- ? visibleForB(world, ctx, c, candidates, R2, use, ctx.owned)- : visibleForA(world, ctx, c, candidates, R2, use, ctx.owned);+ const visible = ARM === 'C1'+ ? visibleForC1(ctx, c, candidates, R2, use, ctx.owned, grid, RADIUS)+ : ARM === 'C0'+ ? visibleForC0(ctx, c, candidates, R2, use, ctx.owned, cache)+ : ARM === 'B'+ ? visibleForB(world, ctx, c, candidates, R2, use, ctx.owned)+ : visibleForA(world, ctx, c, candidates, R2, use, ctx.owned);if (VERIFY) {+ // Set equality, not size: an arm that both misses one entity and+ // invents another has the same count and a different answer.const truth = visibleForA(world, ctx, c, candidates, R2, newStats());if (truth.size !== visible.size) mismatches++;- else { for (const e of truth) if (!visible.has(e)) { mismatches++; break; } }+ else {+ for (const e of truth) if (!visible.has(e)) { mismatches++; break; }+ for (const e of visible) if (!truth.has(e)) { mismatches++; break; }+ }}diffAndFilter(visible, previous.get(c), dirty, removals, use);previous.set(c, visible);diff --git a/bench/replication-interest/results.json b/bench/replication-interest/results.jsonindex cacef12ca..70c09efa5 100644--- a/bench/replication-interest/results.json+++ b/bench/replication-interest/results.json@@ -4,13 +4,13 @@"platform": "darwin 25.5.0","cpu": "Apple M4","cores": 10,- "ranAt": "2026-09-05T02:37:42.333Z"+ "ranAt": "2026-09-05T03:04:45.538Z"},"build": {- "gitHead": "7a26a773fd3002d871cccde1f1d75dd404273bde",+ "gitHead": "272dbb9ed7100693646aea57b8946566b0e9953b","workingTreeClean": false,- "sdkArtifactSha256": "335caf1aab1fbde7",- "sdkBuiltAt": "2026-09-05T02:35:04.402Z"+ "sdkArtifactSha256": "154b351d2953e6bf",+ "sdkBuiltAt": "2026-09-05T03:03:58.785Z"},"fixed": {"anchors": 1,@@ -18,86 +18,53 @@"movement": 0.01,"simHz": 60,"replHz": 20,- "warmup": 60,- "measure": 120+ "warmup": 6,+ "measure": 18},"points": [- {- "arm": "A",- "entities": 10000,- "connections": 1,- "anchors": 1,- "visible": 0.01,- "movement": 0.01,- "radius": 5.641895835477563,- "verify": false,- "simSeconds": 2,- "samples": 40,- "mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 29224.416,- "segmentUsPerSimSecond": {- "materialize": 109.3965,- "anchor": 6684.0625,- "radius": 13090.2715,- "owner": 9145.9365,- "enter": 27.7505,- "leave": 22.105,- "removeFilter": 2.581,- "dirtyFilter": 65.4385- },- "visitedPerSample": {- "candidates": 10000,- "anchor": 10000,- "radius": 10000,- "distanceTests": 10000,- "owner": 10000,- "enter": 25.3,- "leave": 25.275,- "removals": 0,- "dirty": 100- },- "visiblePerConnection": 25.3- },{"arm": "B","entities": 10000,- "connections": 1,+ "connections": 8,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 14027.248,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 1146892.5033333334,"segmentUsPerSimSecond": {- "materialize": 147.7075,- "anchor": 6.29,- "radius": 13715.832,- "owner": 6.126,- "enter": 25.23,- "leave": 18.186,- "removeFilter": 1.377,- "dirtyFilter": 64.957+ "materialize": 109.44333333333333,+ "build": 0,+ "anchor": 254.29000000000002,+ "radius": 1144889.8733333333,+ "owner": 96.39000000000001,+ "enter": 379.4466666666667,+ "leave": 335.13,+ "removeFilter": 15.683333333333334,+ "dirtyFilter": 493.3433333333333},"visitedPerSample": {"candidates": 10000,- "anchor": 1,- "radius": 10000,- "distanceTests": 10000,- "owner": 1,- "enter": 25.3,- "leave": 25.275,+ "positionReads": 0,+ "anchor": 8,+ "radius": 80000,+ "distanceTests": 80000,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 8,+ "enter": 573.6666666666666,+ "leave": 573.6666666666666,"removals": 0,- "dirty": 100+ "dirty": 800},- "visiblePerConnection": 25.3+ "visiblePerConnection": 71.70833333333333},{- "arm": "A",+ "arm": "C0","entities": 10000,"connections": 8,"anchors": 1,@@ -105,36 +72,40 @@"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 239482.3125,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 193196.39333333334,"segmentUsPerSimSecond": {- "materialize": 142.959,- "anchor": 48982.7035,- "radius": 120946.833,- "owner": 68337.5885,- "enter": 293.4625,- "leave": 217.689,- "removeFilter": 6.372,- "dirtyFilter": 347.873+ "materialize": 94.44666666666667,+ "build": 150648.47,+ "anchor": 39.33,+ "radius": 40749.59333333334,+ "owner": 305.9666666666667,+ "enter": 352.7833333333333,+ "leave": 333.90000000000003,+ "removeFilter": 10.843333333333334,+ "dirtyFilter": 478.4833333333333},"visitedPerSample": {"candidates": 10000,- "anchor": 80000,+ "positionReads": 10000,+ "anchor": 8,"radius": 80000,"distanceTests": 80000,- "owner": 80000,- "enter": 568.6,- "leave": 568.65,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 8,+ "enter": 573.6666666666666,+ "leave": 573.6666666666666,"removals": 0,"dirty": 800},- "visiblePerConnection": 71.075+ "visiblePerConnection": 71.70833333333333},{- "arm": "B",+ "arm": "C1","entities": 10000,"connections": 8,"anchors": 1,@@ -142,36 +113,40 @@"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 114669.165,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 163987.9166666667,"segmentUsPerSimSecond": {- "materialize": 217.873,- "anchor": 39.6905,- "radius": 113383.122,- "owner": 35.3335,- "enter": 282.6935,- "leave": 275.7535,- "removeFilter": 4.811,- "dirtyFilter": 294.52+ "materialize": 95.41666666666667,+ "build": 159569.72333333336,+ "anchor": 34.57,+ "radius": 2865.84,+ "owner": 21.946666666666665,+ "enter": 358.7533333333334,+ "leave": 319.86333333333334,+ "removeFilter": 12.093333333333334,+ "dirtyFilter": 482.2133333333333},"visitedPerSample": {"candidates": 10000,+ "positionReads": 10000,"anchor": 8,- "radius": 80000,- "distanceTests": 80000,+ "radius": 0,+ "distanceTests": 1839.5,+ "cells": 216,+ "spatialCandidates": 1839.5,"owner": 8,- "enter": 568.6,- "leave": 568.65,+ "enter": 573.6666666666666,+ "leave": 573.6666666666666,"removals": 0,"dirty": 800},- "visiblePerConnection": 71.075+ "visiblePerConnection": 71.70833333333333},{- "arm": "A",+ "arm": "B","entities": 10000,"connections": 32,"anchors": 1,@@ -179,36 +154,40 @@"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 945579.8535,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 4967617.916666667,"segmentUsPerSimSecond": {- "materialize": 650.7915,- "anchor": 194014.6655,- "radius": 472196.2115,- "owner": 275682.957,- "enter": 965.0975,- "leave": 737.141,- "removeFilter": 20.666,- "dirtyFilter": 850.5325+ "materialize": 115,+ "build": 0,+ "anchor": 922.0733333333334,+ "radius": 4961684.423333334,+ "owner": 208.06333333333333,+ "enter": 1401.5466666666666,+ "leave": 1172.3366666666668,+ "removeFilter": 25.443333333333335,+ "dirtyFilter": 1451.246666666667},"visitedPerSample": {"candidates": 10000,- "anchor": 320000,+ "positionReads": 0,+ "anchor": 32,"radius": 320000,"distanceTests": 320000,- "owner": 320000,- "enter": 2884.675,- "leave": 2887.7,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 32,+ "enter": 2942.8333333333335,+ "leave": 2943,"removals": 0,"dirty": 3200},- "visiblePerConnection": 90.14609375+ "visiblePerConnection": 91.96354166666667},{- "arm": "B",+ "arm": "C0","entities": 10000,"connections": 32,"anchors": 1,@@ -216,184 +195,163 @@"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 466000.3105,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 318276.39333333337,"segmentUsPerSimSecond": {- "materialize": 181.6445,- "anchor": 146.5195,- "radius": 462907.325,- "owner": 119.7275,- "enter": 859.605,- "leave": 639.336,- "removeFilter": 17.767,- "dirtyFilter": 737.395+ "materialize": 123.61333333333334,+ "build": 172926.94,+ "anchor": 133.1966666666667,+ "radius": 139903.73,+ "owner": 804.3133333333334,+ "enter": 1341.8100000000002,+ "leave": 1172.3833333333332,+ "removeFilter": 19.436666666666667,+ "dirtyFilter": 1418.36},"visitedPerSample": {"candidates": 10000,+ "positionReads": 10000,"anchor": 32,"radius": 320000,"distanceTests": 320000,+ "cells": 0,+ "spatialCandidates": 0,"owner": 32,- "enter": 2884.675,- "leave": 2887.7,+ "enter": 2942.8333333333335,+ "leave": 2943,"removals": 0,"dirty": 3200},- "visiblePerConnection": 90.14609375+ "visiblePerConnection": 91.96354166666667},{- "arm": "A",+ "arm": "C1","entities": 10000,- "connections": 128,+ "connections": 32,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 5.641895835477563,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 3786135.7485,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 180275.97666666665,"segmentUsPerSimSecond": {- "materialize": 221.8125,- "anchor": 781074.9235,- "radius": 1901248.0455,- "owner": 1090993.0055,- "enter": 4116.001,- "leave": 3218.257,- "removeFilter": 87.3265,- "dirtyFilter": 3582.117+ "materialize": 94.72666666666667,+ "build": 166073.47,+ "anchor": 96.39333333333333,+ "radius": 10010.133333333333,+ "owner": 52.39666666666667,+ "enter": 1224.5533333333333,+ "leave": 1090.68,+ "removeFilter": 19.6,+ "dirtyFilter": 1323.3166666666668},"visitedPerSample": {"candidates": 10000,- "anchor": 1280000,- "radius": 1280000,- "distanceTests": 1280000,- "owner": 1280000,- "enter": 11707.575,- "leave": 11712.375,+ "positionReads": 10000,+ "anchor": 32,+ "radius": 0,+ "distanceTests": 8354.5,+ "cells": 864,+ "spatialCandidates": 8354.5,+ "owner": 32,+ "enter": 2942.8333333333335,+ "leave": 2943,"removals": 0,- "dirty": 12800+ "dirty": 3200},- "visiblePerConnection": 91.4654296875+ "visiblePerConnection": 91.96354166666667},{"arm": "B",- "entities": 10000,- "connections": 128,- "anchors": 1,- "visible": 0.01,- "movement": 0.01,- "radius": 5.641895835477563,- "verify": false,- "simSeconds": 2,- "samples": 40,- "mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 1885122.6245,- "segmentUsPerSimSecond": {- "materialize": 379.2285,- "anchor": 653.808,- "radius": 1871585.1415,- "owner": 466.235,- "enter": 3990.219,- "leave": 3115.107,- "removeFilter": 68.8425,- "dirtyFilter": 3519.712- },- "visitedPerSample": {- "candidates": 10000,- "anchor": 128,- "radius": 1280000,- "distanceTests": 1280000,- "owner": 128,- "enter": 11707.575,- "leave": 11712.375,- "removals": 0,- "dirty": 12800- },- "visiblePerConnection": 91.4654296875- },- {- "arm": "A","entities": 100000,- "connections": 1,+ "connections": 8,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 531316.6045,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 10939771.246666666,"segmentUsPerSimSecond": {- "materialize": 2426.0405,- "anchor": 154036.188,- "radius": 188491.501,- "owner": 185446.9375,- "enter": 130.417,- "leave": 105.6885,- "removeFilter": 4.8515,- "dirtyFilter": 450.6445+ "materialize": 2462.7766666666666,+ "build": 0,+ "anchor": 753.7633333333333,+ "radius": 10925509.293333335,+ "owner": 278.73333333333335,+ "enter": 3300.1466666666665,+ "leave": 2925.1533333333336,+ "removeFilter": 20.133333333333333,+ "dirtyFilter": 3741.106666666667},"visitedPerSample": {"candidates": 100000,- "anchor": 100000,- "radius": 100000,- "distanceTests": 100000,- "owner": 100000,- "enter": 248.575,- "leave": 248.55,+ "positionReads": 0,+ "anchor": 8,+ "radius": 800000,+ "distanceTests": 800000,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 8,+ "enter": 7020.333333333333,+ "leave": 7020.666666666667,"removals": 0,- "dirty": 1000+ "dirty": 8000},- "visiblePerConnection": 248.575+ "visiblePerConnection": 877.5416666666666},{- "arm": "B",+ "arm": "C0","entities": 100000,- "connections": 1,+ "connections": 8,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 175157.48,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 2190655.8333333335,"segmentUsPerSimSecond": {- "materialize": 2380.938,- "anchor": 25.792,- "radius": 172035.417,- "owner": 33.0625,- "enter": 96.458,- "leave": 77.998,- "removeFilter": 2.187,- "dirtyFilter": 362.3955+ "materialize": 2569.86,+ "build": 1661726.3900000001,+ "anchor": 156.39666666666668,+ "radius": 503567.6533333334,+ "owner": 57.766666666666666,+ "enter": 15442.490000000002,+ "leave": 2798.76,+ "removeFilter": 8.75,+ "dirtyFilter": 3694.166666666667},"visitedPerSample": {"candidates": 100000,- "anchor": 1,- "radius": 100000,- "distanceTests": 100000,- "owner": 1,- "enter": 248.575,- "leave": 248.55,+ "positionReads": 100000,+ "anchor": 8,+ "radius": 800000,+ "distanceTests": 800000,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 8,+ "enter": 7020.333333333333,+ "leave": 7020.666666666667,"removals": 0,- "dirty": 1000+ "dirty": 8000},- "visiblePerConnection": 248.575+ "visiblePerConnection": 877.5416666666666},{- "arm": "A",+ "arm": "C1","entities": 100000,"connections": 8,"anchors": 1,@@ -401,73 +359,81 @@"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 4279556.477,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 1751896.11,"segmentUsPerSimSecond": {- "materialize": 2620.499,- "anchor": 1205966.1,- "radius": 1701799.848,- "owner": 1361254.73,- "enter": 2393.0425,- "leave": 2106.497,- "removeFilter": 22.7905,- "dirtyFilter": 2436.5+ "materialize": 2676.25,+ "build": 1696853.1966666665,+ "anchor": 60.71000000000001,+ "radius": 26192.373333333337,+ "owner": 34.303333333333335,+ "enter": 3228.2033333333334,+ "leave": 18526.803333333333,+ "removeFilter": 9.453333333333333,+ "dirtyFilter": 3829.4366666666665},"visitedPerSample": {"candidates": 100000,- "anchor": 800000,- "radius": 800000,- "distanceTests": 800000,- "owner": 800000,- "enter": 7003.9,- "leave": 7004.3,+ "positionReads": 100000,+ "anchor": 8,+ "radius": 0,+ "distanceTests": 19766.666666666668,+ "cells": 216,+ "spatialCandidates": 19766.666666666668,+ "owner": 8,+ "enter": 7020.333333333333,+ "leave": 7020.666666666667,"removals": 0,"dirty": 8000},- "visiblePerConnection": 875.4875+ "visiblePerConnection": 877.5416666666666},{"arm": "B","entities": 100000,- "connections": 8,+ "connections": 32,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 1443150.561,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 46231171.803333335,"segmentUsPerSimSecond": {- "materialize": 2574.396,- "anchor": 152.791,- "radius": 1433315.374,- "owner": 189.4245,- "enter": 2157.189,- "leave": 1887.125,- "removeFilter": 16.6885,- "dirtyFilter": 2269.165+ "materialize": 2744.5833333333335,+ "build": 0,+ "anchor": 3147.6666666666665,+ "radius": 46189352.21333334,+ "owner": 1179.73,+ "enter": 11573.193333333335,+ "leave": 9274.45,+ "removeFilter": 57.910000000000004,+ "dirtyFilter": 10929.273333333334},"visitedPerSample": {"candidates": 100000,- "anchor": 8,- "radius": 800000,- "distanceTests": 800000,- "owner": 8,- "enter": 7003.9,- "leave": 7004.3,+ "positionReads": 0,+ "anchor": 32,+ "radius": 3200000,+ "distanceTests": 3200000,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 32,+ "enter": 29563.5,+ "leave": 29564.833333333332,"removals": 0,- "dirty": 8000+ "dirty": 32000},- "visiblePerConnection": 875.4875+ "visiblePerConnection": 923.859375},{- "arm": "A",+ "arm": "C0","entities": 100000,"connections": 32,"anchors": 1,@@ -475,36 +441,40 @@"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 16995103.707,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 3333987.5,"segmentUsPerSimSecond": {- "materialize": 2604.354,- "anchor": 4617592.8325,- "radius": 6734243.512,- "owner": 5608367.383,- "enter": 10209.3545,- "leave": 8817.707,- "removeFilter": 110.0845,- "dirtyFilter": 9738.846+ "materialize": 2688.19,+ "build": 1539957.5033333334,+ "anchor": 310.11,+ "radius": 1758727.23,+ "owner": 1343.31,+ "enter": 10301.960000000001,+ "leave": 9186.673333333334,+ "removeFilter": 22.76666666666667,+ "dirtyFilter": 10439.44},"visitedPerSample": {"candidates": 100000,- "anchor": 3200000,+ "positionReads": 100000,+ "anchor": 32,"radius": 3200000,"distanceTests": 3200000,- "owner": 3200000,- "enter": 29498.15,- "leave": 29500.35,+ "cells": 0,+ "spatialCandidates": 0,+ "owner": 32,+ "enter": 29563.5,+ "leave": 29564.833333333332,"removals": 0,"dirty": 32000},- "visiblePerConnection": 921.8171875+ "visiblePerConnection": 923.859375},{- "arm": "B",+ "arm": "C1","entities": 100000,"connections": 32,"anchors": 1,@@ -512,38 +482,42 @@"movement": 0.01,"radius": 17.841241161527712,"verify": false,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 5787510.7505,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 1842971.9466666668,"segmentUsPerSimSecond": {- "materialize": 2944.686,- "anchor": 371.215,- "radius": 5753446.935,- "owner": 452.8105,- "enter": 9844.168,- "leave": 8796.4055,- "removeFilter": 77.83,- "dirtyFilter": 9738.522+ "materialize": 2781.5266666666666,+ "build": 1716863.6133333333,+ "anchor": 153.1966666666667,+ "radius": 77080.54000000001,+ "owner": 56.39666666666667,+ "enter": 10767.353333333334,+ "leave": 9459.976666666667,+ "removeFilter": 18.063333333333333,+ "dirtyFilter": 25281.53},"visitedPerSample": {"candidates": 100000,+ "positionReads": 100000,"anchor": 32,- "radius": 3200000,- "distanceTests": 3200000,+ "radius": 0,+ "distanceTests": 83266.5,+ "cells": 864,+ "spatialCandidates": 83266.5,"owner": 32,- "enter": 29498.15,- "leave": 29500.35,+ "enter": 29563.5,+ "leave": 29564.833333333332,"removals": 0,"dirty": 32000},- "visiblePerConnection": 921.8171875+ "visiblePerConnection": 923.859375}],"verifies": [{- "arm": "B",+ "arm": "C1","entities": 10000,"connections": 8,"anchors": 1,@@ -551,73 +525,81 @@"movement": 0.01,"radius": 5.641895835477563,"verify": true,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 361977.1245,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 1429582.5,"segmentUsPerSimSecond": {- "materialize": 218.0825,- "anchor": 87.8305,- "radius": 120327.145,- "owner": 44.484,- "enter": 351.9975,- "leave": 284.9925,- "removeFilter": 7.7735,- "dirtyFilter": 458.6525+ "materialize": 113.05666666666667,+ "build": 168227.22666666665,+ "anchor": 85.81333333333333,+ "radius": 3814.8633333333337,+ "owner": 22.076666666666668,+ "enter": 434.30333333333334,+ "leave": 355.4066666666667,+ "removeFilter": 25.16,+ "dirtyFilter": 493.8766666666667},"visitedPerSample": {"candidates": 10000,+ "positionReads": 10000,"anchor": 8,- "radius": 80000,- "distanceTests": 80000,+ "radius": 0,+ "distanceTests": 1839.5,+ "cells": 216,+ "spatialCandidates": 1839.5,"owner": 8,- "enter": 568.6,- "leave": 568.65,+ "enter": 573.6666666666666,+ "leave": 573.6666666666666,"removals": 0,"dirty": 800},- "visiblePerConnection": 71.075+ "visiblePerConnection": 71.70833333333333},{- "arm": "B",+ "arm": "C1","entities": 10000,- "connections": 128,+ "connections": 32,"anchors": 1,"visible": 0.01,"movement": 0.01,"radius": 5.641895835477563,"verify": true,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 18000,- "totalUsPerSimSecond": 5719760.856,+ "movedTotal": 2400,+ "totalUsPerSimSecond": 5040214.72,"segmentUsPerSimSecond": {- "materialize": 214.813,- "anchor": 1205.1725,- "radius": 1900284.463,- "owner": 501.386,- "enter": 4270.3745,- "leave": 3225.854,- "removeFilter": 96.433,- "dirtyFilter": 3650.7565+ "materialize": 115,+ "build": 156925.4166666667,+ "anchor": 319.43666666666667,+ "radius": 14791.263333333334,+ "owner": 57.93666666666667,+ "enter": 1445.1233333333332,+ "leave": 1181.55,+ "removeFilter": 22.79666666666667,+ "dirtyFilter": 1521.6299999999999},"visitedPerSample": {"candidates": 10000,- "anchor": 128,- "radius": 1280000,- "distanceTests": 1280000,- "owner": 128,- "enter": 11707.575,- "leave": 11712.375,+ "positionReads": 10000,+ "anchor": 32,+ "radius": 0,+ "distanceTests": 8354.5,+ "cells": 864,+ "spatialCandidates": 8354.5,+ "owner": 32,+ "enter": 2942.8333333333335,+ "leave": 2943,"removals": 0,- "dirty": 12800+ "dirty": 3200},- "visiblePerConnection": 91.4654296875+ "visiblePerConnection": 91.96354166666667},{- "arm": "B",+ "arm": "C1","entities": 100000,"connections": 8,"anchors": 1,@@ -625,33 +607,37 @@"movement": 0.01,"radius": 17.841241161527712,"verify": true,- "simSeconds": 2,- "samples": 40,+ "simSeconds": 0.3,+ "samples": 6,"mismatches": 0,- "movedTotal": 180000,- "totalUsPerSimSecond": 5945148.4395,+ "movedTotal": 24000,+ "totalUsPerSimSecond": 15176458.33,"segmentUsPerSimSecond": {- "materialize": 2664.0425,- "anchor": 564.2105,- "radius": 1554616.209,- "owner": 302.795,- "enter": 2384.454,- "leave": 2113.6865,- "removeFilter": 22.602,- "dirtyFilter": 2500.673+ "materialize": 2737.6400000000003,+ "build": 1789263.61,+ "anchor": 243.3366666666667,+ "radius": 36898.35666666667,+ "owner": 35.7,+ "enter": 3444.866666666667,+ "leave": 2963.5933333333332,+ "removeFilter": 33.333333333333336,+ "dirtyFilter": 3809.996666666667},"visitedPerSample": {"candidates": 100000,+ "positionReads": 100000,"anchor": 8,- "radius": 800000,- "distanceTests": 800000,+ "radius": 0,+ "distanceTests": 19766.666666666668,+ "cells": 216,+ "spatialCandidates": 19766.666666666668,"owner": 8,- "enter": 7003.9,- "leave": 7004.3,+ "enter": 7020.333333333333,+ "leave": 7020.666666666667,"removals": 0,"dirty": 8000},- "visiblePerConnection": 875.4875+ "visiblePerConnection": 877.5416666666666}],"differentialClean": truediff --git a/bench/replication-interest/run.mjs b/bench/replication-interest/run.mjsindex f6ca686f6..5c2df1c25 100644--- a/bench/replication-interest/run.mjs+++ b/bench/replication-interest/run.mjs@@ -23,21 +23,22 @@ const ROOT = path.resolve(HERE, '..', '..');const ARM = path.join(HERE, 'arm.mjs');const QUICK = process.argv.includes('--quick');-const ARMS = ['A', 'B'];+const ARMS = ['B', 'C0', 'C1'];const ARM_MEANING = {- A: 'as shipped: anchors, radius and ownership all scan every candidate',- B: 'ownership index: only the two owner passes change',+ B: 'as shipped: every connection reads every candidate\'s position',+ C0: 'positions read once per sample, cached; same full walk',+ C1: 'grid rebuilt per sample; only nearby cells are walked',};-/** 100k stops at 32 connections: arm A there is already 30 billion visits. */+/** Arm B reads a builtin position per candidate per connection, so 100k x 32 is+ * already 50 seconds of work per simulated second. Points stay few. */const POINTS = QUICK- ? [[10000, 1], [10000, 8]]- : [[10000, 1], [10000, 8], [10000, 32], [10000, 128],- [100000, 1], [100000, 8], [100000, 32]];+ ? [[10000, 8]]+ : [[10000, 8], [10000, 32], [100000, 8], [100000, 32]];const FIXED = {anchors: 1, visible: 0.01, movement: 0.01,- simHz: 60, replHz: 20, warmup: QUICK ? 12 : 60, measure: QUICK ? 30 : 120,+ simHz: 60, replHz: 20, warmup: QUICK ? 4 : 6, measure: QUICK ? 9 : 18,};-const VERIFY_POINTS = QUICK ? [[10000, 8]] : [[10000, 8], [10000, 128], [100000, 8]];+const VERIFY_POINTS = QUICK ? [[10000, 8]] : [[10000, 8], [10000, 32], [100000, 8]];const CACHE = path.join(HERE, `.sweep-${QUICK ? 'quick' : 'matrix'}.jsonl`);const buildId = () => sdkIdentity(ROOT).sdkArtifactSha256;@@ -105,7 +106,7 @@ for (const [entities, connections] of POINTS) {}const verifies = [];for (const [entities, connections] of VERIFY_POINTS) {- const { result, fresh } = measure('B', entities, connections, true);+ const { result, fresh } = measure('C1', entities, connections, true);process.stderr.write(`[${++done}/${total}] differential ${entities} ${connections} conn`+ `${fresh ? '' : ' (cached)'}\n`);verifies.push(result);@@ -123,41 +124,42 @@ for (const arm of ARMS) say(` ${arm} ${ARM_MEANING[arm]}`);say('');const clean = verifies.every((v) => v.mismatches === 0);say(clean- ? ` DIFFERENTIAL: B saw exactly what A saw, every connection, every sample (${verifies.length} point(s)).`- : ' DIFFERENTIAL: MISMATCHED — the ownership index changed what a connection sees.');+ ? ` DIFFERENTIAL: the grid saw exactly what the full scan saw, every connection,`+ + ` every sample (${verifies.length} point(s)).`+ : ' DIFFERENTIAL: MISMATCHED — the grid changed what a connection sees.');say('');say(' us per simulated second, and the share of one core');-say(' pop conn arm total 1 core anchor radius owner B/A');+say(' pop conn arm total 1 core build radius vs B');for (const [entities, connections] of POINTS) {- const a = at('A', entities, connections);+ const b = at('B', entities, connections);for (const arm of ARMS) {const p = at(arm, entities, connections);const s = p.segmentUsPerSimSecond;- const ratio = arm === 'B' ? (p.totalUsPerSimSecond / a.totalUsPerSimSecond).toFixed(2) : '—';- say(` ${pad(entities, 7)} ${pad(connections, 5)} ${arm} ${pad(round(p.totalUsPerSimSecond), 11)}`+ const ratio = arm === 'B' ? '—' : (p.totalUsPerSimSecond / b.totalUsPerSimSecond).toFixed(3);+ say(` ${pad(entities, 7)} ${pad(connections, 5)} ${pad(arm, 2)} ${pad(round(p.totalUsPerSimSecond), 11)}`+ ` ${pad(`${(p.totalUsPerSimSecond / 1e4).toFixed(0)}%`, 7)}`- + ` ${pad(round(s.anchor), 8)} ${pad(round(s.radius), 9)} ${pad(round(s.owner), 9)} ${pad(ratio, 6)}`);+ + ` ${pad(round(s.build), 8)} ${pad(round(s.radius), 9)} ${pad(ratio, 6)}`);}}say('');-say(' entities visited per sample (the mechanism, without this machine in it)');-say(' pop conn arm anchor radius owner distance');+say(' visits per sample (the mechanism, without this machine in it)');+say(' pop conn arm posReads cells spatialCand distTests');for (const [entities, connections] of POINTS) {for (const arm of ARMS) {const v = at(arm, entities, connections).visitedPerSample;- say(` ${pad(entities, 7)} ${pad(connections, 5)} ${arm} ${pad(round(v.anchor), 10)}`- + ` ${pad(round(v.radius), 10)} ${pad(round(v.owner), 10)} ${pad(round(v.distanceTests), 10)}`);+ say(` ${pad(entities, 7)} ${pad(connections, 5)} ${pad(arm, 2)} ${pad(round(v.positionReads), 10)}`+ + ` ${pad(round(v.cells), 10)} ${pad(round(v.spatialCandidates), 12)} ${pad(round(v.distanceTests), 11)}`);}}say('');-say('--- WHAT THIS DECOMPOSES ---');-say(' anchor finding the entities this connection owns, to place its view');-say(' radius testing every candidate against those anchors');-say(' owner the server putting owned entities back, not trusting the policy');+say('--- WHAT THIS SEPARATES ---');+say(' C0/B reading each position ONCE per sample instead of once per connection');+say(' C1/C0 spatial locality on top of that');+say(' build the price of rebuilding, paid every sample whatever moved');say('');-say(' anchor and owner are the same question asked twice, both O(population).');-say(' B answers it from an index and changes nothing else — so B/A is the price');-say(' of NOT having one, and what is left in B is the spatial problem alone.');+say(' Rebuilding is what lets this support an arbitrary position() function:');+say(' nothing is carried between samples, so there is no invalidation to get');+say(' wrong. What an incremental index would buy is the build column alone.');const out = path.join(HERE, QUICK ? 'results.quick.json' : 'results.json');writeFileSync(out, `${JSON.stringify({diff --git a/bench/replication-interest/workload.mjs b/bench/replication-interest/workload.mjsindex 73898eae0..b80f34b85 100644--- a/bench/replication-interest/workload.mjs+++ b/bench/replication-interest/workload.mjs@@ -8,10 +8,9 @@* in one timer: a visited count says what the mechanism does, where a wall time* says what this machine did today.*- * Position lives in a script component rather than the builtin `Transform` the- * shipped default reads. That understates arm A — a builtin read crosses the- * wasm boundary — so every ratio here is conservative about how much the full- * scans cost.+ * Position is read from the builtin `Transform`, as the shipped default does:+ * every read crosses the wasm boundary, and how much of the cost is that+ * crossing rather than the scan itself is one of the things being separated.*/import { pathToFileURL } from 'node:url';import { readdirSync, statSync } from 'node:fs';@@ -40,9 +39,17 @@ export async function loadSdk(root) {return import(pathToFileURL(entry).href);}+/** The engine module, so `Transform` is the real builtin the default reads. */+export async function connectEngine(sdk, app, root) {+ const dir = process.env.ESENGINE_WASM_DIR ?? path.join(root, 'build', 'wasm', 'web');+ const factory = (await import(pathToFileURL(path.join(dir, 'esengine.js')).href)).default;+ const module = await factory({ locateFile: (f) => path.join(dir, f) });+ app.connectCpp(new module.Registry(), module, { strict: false });+}+export function defineComponents(sdk) {return {- Pos: sdk.defineComponent('IPos', { x: 0, y: 0, z: 0 }, { replicatedFields: ['x', 'y', 'z'] }),+ Pos: sdk.Transform,Owned: sdk.defineComponent('IOwned', { owner: -1 }, { replicatedFields: ['owner'] }),};}@@ -51,11 +58,12 @@ export function defineComponents(sdk) {export function newStats() {return {ns: {- materialize: 0n, anchor: 0n, radius: 0n, owner: 0n,+ materialize: 0n, build: 0n, anchor: 0n, radius: 0n, owner: 0n,enter: 0n, leave: 0n, removeFilter: 0n, dirtyFilter: 0n,},visited: {- candidates: 0, anchor: 0, radius: 0, distanceTests: 0, owner: 0,+ candidates: 0, positionReads: 0, anchor: 0, radius: 0, distanceTests: 0,+ cells: 0, spatialCandidates: 0, owner: 0,enter: 0, leave: 0, removals: 0, dirty: 0,},visibleTotal: 0,@@ -73,7 +81,7 @@ export function buildWorld(sdk, world, { population, connections, anchorsPerConnconst entities = new Array(population);for (let i = 0; i < population; i++) {const e = world.spawn();- world.insert(e, Pos, { x: i % side, y: Math.floor(i / side), z: 0 });+ world.insert(e, Pos, { position: { x: i % side, y: Math.floor(i / side), z: 0 } });world.insert(e, Owned, { owner: -1 });entities[i] = e;}@@ -102,15 +110,15 @@ export function applyMovement(world, ctx, tick, count) {let idx = (tick * 7919) % n;for (let k = 0; k < Math.min(count, n); k++) {const e = entities[idx];- const p = world.get(e, Pos);- world.update(e, Pos, (d) => { d.x = p.x + ((tick + k) % 3) - 1; });+ world.update(e, Pos, (d) => { d.position.x += ((tick + k) % 3) - 1; });moved++;idx = (idx + 7919) % n;}return moved;}-const positionOf = (world, Pos, e) => world.tryGet(e, Pos);+/** What `defaultPosition` does: a builtin read, then the position field. */+const positionOf = (world, Pos, e) => world.tryGet(e, Pos)?.position ?? null;/*** Arm A: exactly what ships. Anchors are found by scanning the whole candidate@@ -178,7 +186,140 @@ export function visibleForB(world, ctx, connId, candidates, r2, stats, ownedIndereturn visible;}-/** The radius pass both arms share: every candidate against every anchor. */++/**+ * Every position, read once per sample instead of once per connection. The+ * ceiling for amortising the read alone: the radius pass still walks every+ * candidate, it just no longer crosses the wasm boundary to do it.+ */+export function buildPositionCache(world, ctx, stats) {+ const t = process.hrtime.bigint();+ const cache = new Map();+ for (const e of ctx.entities) {+ stats.visited.positionReads++;+ cache.set(e, positionOf(world, ctx.Pos, e));+ }+ stats.ns.build += process.hrtime.bigint() - t;+ return cache;+}++const cellKey = (x, y, z, size) =>+ `${Math.floor(x / size)},${Math.floor(y / size)},${Math.floor(z / size)}`;++/**+ * A uniform grid, rebuilt every sample. Rebuilding is what lets it support an+ * ARBITRARY position function: nothing is carried between samples, so there is+ * no invalidation to get wrong. `placeless` keeps the shipped rule that an+ * entity with no position is relevant to everyone.+ */+export function buildGrid(world, ctx, stats, cellSize) {+ const t = process.hrtime.bigint();+ const cells = new Map();+ const placeless = new Set();+ const cache = new Map();+ for (const e of ctx.entities) {+ stats.visited.positionReads++;+ const p = positionOf(world, ctx.Pos, e);+ cache.set(e, p);+ if (!p) { placeless.add(e); continue; }+ const key = cellKey(p.x, p.y, p.z ?? 0, cellSize);+ let bucket = cells.get(key);+ if (!bucket) { bucket = []; cells.set(key, bucket); }+ bucket.push(e);+ }+ stats.ns.build += process.hrtime.bigint() - t;+ return { cells, placeless, cache, cellSize };+}++/** Arm C0: cached coordinates, same full walk. */+export function visibleForC0(ctx, connId, candidates, r2, stats, ownedIndex, cache) {+ let t = process.hrtime.bigint();+ const anchors = [];+ for (const e of ownedIndex.get(connId) ?? []) {+ stats.visited.anchor++;+ const p = cache.get(e);+ if (p) anchors.push(p);+ }+ stats.ns.anchor += process.hrtime.bigint() - t;+ if (anchors.length === 0) return new Set(candidates);++ t = process.hrtime.bigint();+ const visible = new Set();+ for (const e of candidates) {+ stats.visited.radius++;+ const p = cache.get(e);+ if (!p) { visible.add(e); continue; }+ for (const a of anchors) {+ stats.visited.distanceTests++;+ if (within(p, a, r2)) { visible.add(e); break; }+ }+ }+ stats.ns.radius += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ for (const e of ownedIndex.get(connId) ?? []) { stats.visited.owner++; visible.add(e); }+ stats.ns.owner += process.hrtime.bigint() - t;+ return visible;+}++/**+ * Arm C1: the grid answers which candidates are near enough to test. The exact+ * distance test stays — a cell is a box and the rule is a sphere, so being in a+ * neighbouring cell is not being in range.+ */+export function visibleForC1(ctx, connId, candidates, r2, stats, ownedIndex, grid, radius) {+ let t = process.hrtime.bigint();+ const anchors = [];+ for (const e of ownedIndex.get(connId) ?? []) {+ stats.visited.anchor++;+ const p = grid.cache.get(e);+ if (p) anchors.push(p);+ }+ stats.ns.anchor += process.hrtime.bigint() - t;+ // The shipped fail-open: no positioned anchor means no view to filter by.+ if (anchors.length === 0) return new Set(candidates);++ t = process.hrtime.bigint();+ const visible = new Set();+ const size = grid.cellSize;+ for (const a of anchors) {+ const cx = Math.floor(a.x / size);+ const cy = Math.floor(a.y / size);+ const cz = Math.floor((a.z ?? 0) / size);+ const reach = Math.ceil(radius / size);+ for (let dx = -reach; dx <= reach; dx++) {+ for (let dy = -reach; dy <= reach; dy++) {+ for (let dz = -reach; dz <= reach; dz++) {+ stats.visited.cells++;+ const bucket = grid.cells.get(`${cx + dx},${cy + dy},${cz + dz}`);+ if (!bucket) continue;+ for (const e of bucket) {+ stats.visited.spatialCandidates++;+ if (visible.has(e)) continue;+ stats.visited.distanceTests++;+ if (within(grid.cache.get(e), a, r2)) visible.add(e);+ }+ }+ }+ }+ }+ for (const e of grid.placeless) visible.add(e);+ stats.ns.radius += process.hrtime.bigint() - t;++ t = process.hrtime.bigint();+ for (const e of ownedIndex.get(connId) ?? []) { stats.visited.owner++; visible.add(e); }+ stats.ns.owner += process.hrtime.bigint() - t;+ return visible;+}++function within(p, a, r2) {+ const dx = p.x - a.x;+ const dy = p.y - a.y;+ const dz = (p.z ?? 0) - (a.z ?? 0);+ return dx * dx + dy * dy + dz * dz <= r2;+}++/** The radius pass arms A and B share: every candidate against every anchor. */function radiusScan(world, ctx, candidates, anchors, r2, stats) {const { Pos } = ctx;const visible = new Set();