test(m4): finish audit, measurement and archive (#76)

- client/e2e/audit.test.mjs: independent player-browser traffic audit (own
  frame catalogue and banned-key list, never leakcheck.nim), with a
  -d:leakfault/otherVision negative control.
- client/e2e/fogbench.test.mjs + tools/fogbench.nim: 50 tokens on a
  16384 px map (server move path and headless SwiftShader cadence);
  results/m4-fog-bench.md records both honestly (SW is not the phone gate).
- Archive prototype-* under docs/archive/prototypes (Q24); DESIGN 13 M4
  done, TESTING 13 M4 accept result, HANDOFF-M4 close-out.
- mutation.sh c1/c2 patch the post-#65 tile-gate line again (they had
  silently become sed no-ops).
This commit is contained in:
2026-11-21 15:43:08 +01:00
parent fd711de152
commit fcd90529b6
142 changed files with 1111 additions and 242 deletions
+3 -3
View File
@@ -84,13 +84,13 @@ All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN.
## B. HANDOFF traceability (old DESIGN §12)
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries). Every
Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries). Every
row is resolved; the current rules are in the sections each row names.
<!-- BEGIN old section 12 verbatim -->
## 12. HANDOFF items -> decisions / open questions
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries).
Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries).
| # | Item | Decision / open | Milestone |
|---|---|---|---|
@@ -148,7 +148,7 @@ Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries).
[FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is
at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to
~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual
phone run; fallback 64 px (per-scene config). Evidence: `prototype-tile-leak/README.md`. Applied
phone run; fallback 64 px (per-scene config). Evidence: `docs/archive/prototypes/tile-leak/README.md`. Applied
in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6).
5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start?
**RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is
+31 -24
View File
@@ -19,15 +19,16 @@ Legend:
- **[PROPOSED]** design choice made in this doc; the owner may overturn it.
Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
- `docs/archive/prototypes/pixi-perf/` (client perf; README holds all tables)
- `docs/archive/prototypes/server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
`results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08
- `docs/archive/prototypes/tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08
phone run; `results/phone-20261108T113701.jsonl`)
- `docs/prototype.md` is only the original brief for the perf prototype.
- No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` exist per AGENTS.md (Q24,
FIXED). `prototype-*` dirs stay in-tree until the M4 client port, then are archived (Q24, FIXED).
Nothing here is FFF-specific beyond the seam in section 9.
FIXED). `prototype-*` trees are archived at `docs/archive/prototypes/` from the M4 finish (#76;
Q24, FIXED): frozen history, never built or maintained, with the maintained code in `/server` and
`/client`. Nothing here is FFF-specific beyond the seam in section 9.
---
@@ -107,7 +108,7 @@ entitled to.
the official pixijs-skills (already in `.agents/skills/pixijs*`).
- Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former
pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags
0.4.6-0.4.8 exist]. `prototype-server-vision/servervision.nimble` still pins the commit until
0.4.6-0.4.8 exist]. `docs/archive/prototypes/server-vision/servervision.nimble` still pins the commit until
ported; `db_connector/db_sqlite`, WAL. No Nim in the browser.
- nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join`, `/tiles/`;
internal location for tile bytes.
@@ -157,7 +158,7 @@ entitled to.
- **Single egress rule [PROPOSED]:** all bytes to a player leave through one egress module that
takes a recipient and a typed per-recipient view. Raw world state (walls, hidden entities, other
players' explored grids) has no code path into that module. The prototype enforces this by
discipline in `sync()` (`prototype-server-vision/src/server.nim`); the real build should enforce
discipline in `sync()` (`docs/archive/prototypes/server-vision/src/server.nim`); the real build should enforce
it by types (distinct `PlayerView` and `GmView` structures, no `JsonNode` of world state passed
around).
- Client-side fog is cosmetic. Security never depends on the client hiding anything (section 7).
@@ -420,7 +421,7 @@ server clamps nothing silently (clamping would leak the hit distance, T8).
### 4.3 Locking and threading
- mummy: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock`
and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED
reading, `prototype-server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
reading, `docs/archive/prototypes/server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
- **One global lock** around intent handling and outbox enqueue; network sends happen outside it
(flush, see 4.2). [MEASURED] order, loss and final-view consistency over 3 x 60 s runs, and the
latency figures: TESTING §4.3.
@@ -691,7 +692,7 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
## 5. Vision and explored
### 5.1 Algorithm (ported from `prototype-server-vision/src/geometry.nim`)
### 5.1 Algorithm (ported from `docs/archive/prototypes/server-vision/src/geometry.nim`)
- **Visibility polygon** from token centre: cast rays to every blocking wall endpoint (for a thick
wall, every corner of its body quad, 5.10) at angle -eps, 0, +eps (`RayEps` = 1e-4 rad), plus an
inscribed 64-gon of radius R as range limit; sort by angle; each ray returns nearest hit among
@@ -1900,7 +1901,7 @@ they are not fed until resync, and nginx closes dead peers (M5).
### 7.1 Layers (bottom to top, one Pixi stage under a world container with pan/zoom)
1. **Map tiles**: sprites per tile, loaded lazily for tiles the server allows.
2. **Grid**: one `TilingSprite` over a small cell texture, toggleable [MEASURED technique,
`prototype-pixi-perf/README.md` Techniques].
`docs/archive/prototypes/pixi-perf/README.md` Techniques].
3. **Entities/tokens**: pooled containers, shared `GraphicsContext` per colour, `BitmapText` labels.
4. **Fog (players)**: explored dim layer + vision cut-out (7.3).
5. **GM overlay (GM only)**: walls/doors Graphics, wall editor handles; hidden from players by never
@@ -1911,7 +1912,7 @@ they are not fed until resync, and nginx closes dead peers (M5).
The module layout and the append-only extension rules (one reducer slice file, one render module
file per feature; no shared registry edit) are written in `client/README.md` [T4, #67].
### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `prototype-pixi-perf/README.md`]
### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `docs/archive/prototypes/pixi-perf/README.md`]
- Verdict: Pixi v8 renders a VTT scene at 60 fps on Radeon 780M (WebGL and WebGPU) and Galaxy Note
10 (WebGL) up to 1000 tokens (Note 10 js ~14 ms, 2000 tokens -> 32-36 fps, CPU-bound; laptop js
9-12 ms at 2000). Only per-frame token JS scales; a table needs tens of tokens.
@@ -2144,7 +2145,7 @@ copy/export stable).
- **Connection (runtime)**: id, player, `known` map, last vision ver, counter.
Prototype entity (for mapping): `Tok{id,name,kind,pos,gmOnly}` + `tokenRadius` global in scene
(`prototype-server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius
(`docs/archive/prototypes/server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius
20, cell 32, 60 walls, 8 tokens).
---
@@ -2256,7 +2257,7 @@ See TESTING §10.4 (Node 26 black-box harnesses, built-ins only, `devbox run tes
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss),
`X-Content-Type-Options`, `Referrer-Policy`.
- No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space).
- Prototype nginx config (`prototype-server-vision/nginx/nginx.conf`) is the functional reference;
- Prototype nginx config (`docs/archive/prototypes/server-vision/nginx/nginx.conf`) is the functional reference;
its `listen` has no address (binds all) and its temp/log paths are dev-only.
- Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into
`<state>/tiles/<scene>/v<art_version>/` and registers/updates the scene (prototype:
@@ -2327,18 +2328,24 @@ columns with today's defaults) lands complete now, so the later build needs no m
green on a clean checkout with the nine groups: leak+fault, tiles, probing, protocol, auth,
characters and names, restart, persistence, logs. Gate mechanics and the measured result: TESTING
§13. Out of M3 accept: concurrency (M5), the 127.0.0.1 bind check (M6).
- **M4 - Client v1.** Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText),
character and encountered lists, reveal controls, fog textures, the wall editor (four presets,
switches, marker, label, one-way arrow and flips), token drag with prediction/rollback, DOM
overlay, reconnect backoff, reducer tests; then archive `prototype-*` (Q24). Thickness and height
controls are not in M4 (build order above; 5.7, 5.10).
- Accept: headless e2e (fog pixel checks, player traffic audit clean, reconnect restores); manual
run on laptop and Note 10 at 60 fps with 50 tokens on a 16384 px tiled map (test target
PROPOSED, Q2), fog active.
- **M4 - Client v1.** Done (2026-11-21, #76). Vite + TS + Pixi v8 client: layers, tiles, grid,
tokens (BitmapText), character and encountered lists, reveal controls, fog textures, the wall
editor (four presets, switches, marker, label, one-way arrow and flips), token drag with
prediction/rollback, DOM overlay, reconnect backoff, reducer tests; `prototype-*` archived under
`docs/archive/prototypes/` (Q24). Thickness and height controls are not in M4 (build order above;
5.7, 5.10).
- Accept: headless e2e (fog pixel checks, player traffic audit clean, reconnect restores) - met by
`devbox run e2e` including `client/e2e/audit.test.mjs`; the manual run on laptop and Note 10 at
60 fps with 50 tokens on a 16384 px tiled map (test target PROPOSED, Q2) with fog active is
#77, the one `ready-for-human` step, and remains open by design.
- Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test (mobile emulation, real server
path): viewport fills in < 1 s at zoom 1; (b) one manual run on the owner's 5-year-old Android
phone. If either fails: `tile_size` 64 px (per-scene config, no code change). Harness detail and
the prototype-run caveat: TESTING §13.
path): viewport fills in < 1 s at zoom 1 - met in `client/e2e/map.test.mjs`; (b) one manual run
on the owner's 5-year-old Android phone - #77. If either fails: `tile_size` 64 px (per-scene
config, no code change). Harness detail and the prototype-run caveat: TESTING §13.
- Finish evidence (#76): `results/m4-fog-bench.md` (50 tokens / 16384 px: server move path
0.119 ms; headless SwiftShader cadence recorded, explicitly not a phone number),
`results/bench.log`, `results/mutation.log`, `results/nimble-test.log`, and the
`devbox run test | client-test | e2e` logs (regenerated, not committed).
- **M5 - Robustness and observability.** SIGTERM handler, bounded metrics and SLOW lines, per-client
bounded outbox with coalescing and Ping/Pong lag tracking (4.3), verify `/ws` goes through nginx
and which timeout closes a dead peer, healthz lock check. Accept: concurrency 60 s x3 with p99 <=
+43
View File
@@ -0,0 +1,43 @@
# Handoff: end of M4
**Current at 2026-11-21**, M4 finish (#76). M1-M4 are done; M5 is next. This is the close-out note
for the M4 run: what exists, what is proven, what is deliberately still open.
## State
- **Server:** `proto` 2, 29 intents / 16 server messages, one scene, thin walls with the 5.8
switches, doors/secret/locked, windows, one-way, player markers, characters/names, per-player
explored + vision, lock-free tile gate and session cache (#64, #65). `devbox run test` is the
server gate.
- **Client:** `/client` (Vite + TS + PixiJS v8, plain DOM overlay). Sign-in, name prompt, badge,
reconnect + full resync, tiles/grid/pan/zoom, three-state fog + markers, tokens/labels/statuses,
both lists, drag with prediction/rollback, GM wall editor, roster/keys/tokens panel, characters/
reveals/who-sees-it. Gates: `devbox run client-test`, `devbox run e2e`.
- **M4 accept:** `devbox run e2e` proves join, fog pixels, drag/rollback, reconnect and the
independent player-traffic audit; `results/m4-fog-bench.md` records 50 tokens on a 16384 px map
(server move path 0.12-0.14 ms; headless SwiftShader cadence recorded as a floor, not a phone
number). Thickness/height controls are **not** in M4 (ADR-0012); walls round 2 is #37/#45/#50/
#41/#44.
- **Archived:** the three `prototype-*` trees now live under `docs/archive/prototypes/` (frozen,
not built). One maintained client (`/client`), one server (`/server`).
## Still open
- **#77** - the human real-phone playtest: Note 10 + laptop, 16384 px map, 50 tokens, fog active,
LAN TLS/h2. Its comment is the checklist with commands, numbers to record and pass thresholds.
`#63` and `#62` close only after #77.
- **M5** - concurrency, bounded outbox/coalescing, lag tracking, SIGTERM, metrics, nginx dead-peer
timeout, stats outside the lock. `#34` heartbeat is M5.
- **Deferred:** `db_connector` -> thin sqlite3 binding (build item 13); per-token polygon cache and
incremental wall-edit refresh (items 3/4) are **not** needed by the M4 measurement.
## Notes for the next session
- `AGENTS.md` points at the issue tracker and the domain docs. Use the Gitea issues, not the docs,
for work state.
- Gates are sequential and real: `devbox run test`, `devbox run client-test`, `devbox run e2e`,
`devbox run mutation`, `devbox run bench`, and (for fog numbers) `devbox run fogbench`.
- `results/*.log` are evidence and committed; `results/node-test.log`, `results/e2e.log`,
`results/client-test.log` are gitignored scratch and regenerated.
- Browser e2e: `client/e2e/` owns `playwright-core`; `tools/` stays built-ins-only (TESTING §10.4).
The e2e stack is the real server through the TLS/HTTP2 test nginx, never a fixture.
+29 -10
View File
@@ -18,10 +18,10 @@ independent of the code under test where possible, and every check needs a negat
it can fail.
Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
- `docs/archive/prototypes/pixi-perf/` (client perf; README holds all tables)
- `docs/archive/prototypes/server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
`results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run)
- `docs/archive/prototypes/tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run)
How to run: `devbox run test` = Nim in-process tests first, then the Node black-box harnesses;
`devbox run mutation` = the mutation suite. Run everything from the repo root through `devbox run`.
@@ -46,11 +46,11 @@ built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built `lib
**Rule:** DESIGN §3.3.
- Direct hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README
- Direct hits on `/_tiles/` give 404 [MEASURED: `docs/archive/prototypes/server-vision/results/smoke.log`, README
"Phase 2a"].
- A tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak
test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`].
- The residual 32 px edge leak's sizing evidence: `prototype-tile-leak/README.md` (desktop numbers;
- The residual 32 px edge leak's sizing evidence: `docs/archive/prototypes/tile-leak/README.md` (desktop numbers;
phone run 2026-11-08). M4's tile-size gates are in §13 below.
- `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect
unchanged; nginx adds nothing of its own there (the test vhost records this, §11.1).
@@ -552,7 +552,7 @@ from the prototype, what was missing, what the M3 build added, and the tools it
state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the
dead `/ws` socket within its configured timeout.
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype
already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness,
already drives devbox chromium, `docs/archive/prototypes/pixi-perf/bench.mjs`; SwiftShader is fine for correctness,
not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area
map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect
restores view; drag moves token and rollback works. The harness is `client/e2e/` (the client package
@@ -571,13 +571,20 @@ from the prototype, what was missing, what the M3 build added, and the tools it
real Vite build (`client/e2e/run.sh` runs `npm run build` first):
`performance.getEntriesByType('navigation')[0].nextHopProtocol` is `h2` over TLS. The vhost group
keeps a local stub dist because `devbox run test` must not depend on the client's npm install.
- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player
browser and run the leak checker's (a)(e) assertions over them.
- **Independent traffic audit in e2e**: `client/e2e/audit.test.mjs` records every WS frame and every
HTTP response the *player browser* receives and judges them with its own catalogue and banned-key
list (never importing `tools/leakcheck.nim`): only the 13 player frame types; no wall geometry or
GM-only column at any depth; vision polygons only for the player's own tokens; no other player's
id or out-of-sight token id; explored cells only inside a historical own-vision bbox and never near
the other player; tiles only on `/tiles/`, only 200/403, every 200 covering an explored cell, and
`/_tiles/` unreachable (direct fetch 404). It runs in `devbox run e2e` beside the fog, drag and
reconnect files. A negative control runs the same rules against a `-d:leakfault` build with
`LEAK_FAULT=otherVision`, so the rule that rejects a foreign vision polygon is proven able to fail.
### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from
`prototype-server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`,
`docs/archive/prototypes/server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`,
`lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required
for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the
server cannot share its protocol bugs; zero deps; already measured. The harness lives in
@@ -594,7 +601,8 @@ from the prototype, what was missing, what the M3 build added, and the tools it
keeps holding.
- `devbox run test` = Nim tests first, then Node harnesses. `devbox run client-test` = the client's
Vitest seam (pure reducer, protocol client, envelope); `devbox run e2e` = the built client through
the real server and vhost. The finish gate runs all three.
the real server and vhost; `devbox run fogbench` = the 50-token 16384 px server measurement
(`results/m4-fog-bench.log`). The finish gate (#76) runs all of them plus `mutation` and `bench`.
- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`;
`tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the
acceptance checklist cannot silently go stale. Harnesses that are not an accept group (`smoke`,
@@ -657,6 +665,17 @@ from the prototype, what was missing, what the M3 build added, and the tools it
registered test ran and passed. The restart group takes its baseline from the as-built state on the
first server instance, before any restart, not from a state that has already been through one
(#36).
- **M4 accept result.** Measured 2026-11-21 at the finish commit (#76): `devbox run test` exit 0
(Nim suite all pass, 419 OK checks; 159 Node harness tests with the group evidence step),
`devbox run client-test` 164, `devbox run e2e` 27/27 (join, fog pixel probes, drag + rollback,
reconnect, the independent traffic audit and the 50-token measurement), `devbox run mutation`
control + 80 mutations each failing at least its expected test, `devbox run bench` PASS and
`devbox run fogbench` PASS. Evidence: `results/nimble-test.log`, `results/mutation.log`,
`results/bench.log`, `results/m4-fog-bench.md` (+ `.log`); the e2e/client logs are regenerated
per run and not committed. The manual Note 10 + laptop 60 fps run is **#77** and is the only
open M4 accept item. Mutation housekeeping found here: `c1`/`c2` still patched the pre-#65
tile-gate expression and had silently become `sed` no-ops; both now patch
`cy * sc.cols + cx in explored` and fail the tile gate group again.
- **M4 gate harness.** (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU
and network throttle) against the real server path (nginx HTTP/2 + caching); (b) one manual run on
the owner's 5-year-old Android phone. The 2026-11-08 prototype phone run is evidence, not the gate
+13
View File
@@ -0,0 +1,13 @@
# Archived prototypes (M4 close-out, #76)
These three trees are the pre-M4 prototypes. They are **frozen history**: not built, not tested and
not maintained. The one maintained client is `/client`; the server is `/server`.
| Tree | What it proved | Where its numbers now live |
|---|---|---|
| [`pixi-perf/`](pixi-perf/) | PixiJS v8 can draw a VTT-sized scene on modest hardware; 2048-16384 px maps, 50-2000 tokens, fog and labels | `docs/DESIGN.md` §7.2, `results/m4-fog-bench.md` |
| [`server-vision/`](server-vision/) | The visibility polygon, scanline cells, explored, the leak transcripts and the move rules that `server/` ports at M1-M3 | `results/bench.log`, `docs/TESTING.md` §10 |
| [`tile-leak/`](tile-leak/) | Tile size vs the fog edge leak; the 2026-11-08 phone run (evidence, not a gate) | `docs/TESTING.md` §13 M4 gate harness |
They were moved here from the repo root in the M4 finish commit; `git log --follow <path>` shows
their last live revision. Do not revive them for a fix: change `/client` or `/server`.
@@ -0,0 +1,3 @@
node_modules
dist
.devbox
+248
View File
@@ -0,0 +1,248 @@
# Pixi v8 VTT perf prototype (THROWAWAY)
Question: can PixiJS v8 (8.22) render a VTT-sized scene smoothly on modest hardware? Measurement tool, not the product.
## Run
All commands through devbox (NixOS, nothing global):
```sh
devbox run -- npm install
devbox run -- npm run dev # http://localhost:5173
devbox run -- npm run dev -- --host # reachable from LAN
devbox run -- npm run build # tsc + vite build
```
URL params (joined with `&`, e.g. `?renderer=webgpu&res=1&bench=1`): `?renderer=webgl|webgpu` (prefer, not force: Pixi falls back to WebGL silently if WebGPU is unavailable, so check the overlay / benchmark header for `requested X → fallback`), `?res=1` (canvas resolution, default min(dpr,2)),
`?bench=1` (auto-run benchmark on load), `?benchMs=5000&warmMs=700`.
Use the dev server (port 5173), not the stale 4173 preview build.
WebGPU on Linux Chrome (what actually worked): set these at `chrome://flags`, then relaunch Chrome:
`#enable-vulkan`, `#enable-unsafe-webgpu`, `#ignore-gpu-blocklist`.
CLI flags (`--enable-unsafe-webgpu --enable-features=Vulkan`) were overridden by the NixOS wrapper / an already-running Chrome process. Confirm WebGPU is enabled at `chrome://gpu`.
Controls (top right): map size, tile size override (auto = GPU max texture), local map image, grid on/off + cell size, token count,
chaos, HP churn, culling, tool (move / pen), +200 random strokes, Run benchmark (markdown table in the textarea; copy button).
Mouse: wheel = zoom, drag = pan / drag a token, pen tool: LMB draws, RMB/MMB pans. Touch: 1 finger = drag token / pan / draw, 2 fingers = pinch zoom + pan.
## Test on mobile
`devbox run -- npm run dev -- --host`, open `http://<LAN-IP>:5173` on the phone/tablet (same network; open the firewall for 5173 on NixOS if needed:
`networking.firewall.allowedTCPPorts`). Then use the on-screen overlay and the benchmark button.
Done: Galaxy Note 10 (SM-N970F), WebGL, Chrome 156 Android. See benchmark (D) below. Not done: other phones, tablets, iOS.
## Headless benchmark (software GL, NOT representative)
`bench.mjs` drives chromium (from devbox) via playwright-core with SwiftShader (software GL). Only useful as a harness smoke test; real numbers come from the in-page button on real hardware (see Benchmark below).
```sh
devbox run -- npm run build && devbox run -- npx vite preview --port 4173 &
devbox run -- bash -c 'CHROMIUM=$(which chromium) node bench.mjs http://localhost:4173/'
```
## Benchmark
Scenario for all runs = view fitted to whole map (so small maps show all tokens on screen, large maps show only a fraction), chaos on, grid on, cull on, 5 s each after 700 ms warmup.
fps is capped at 60 (vsync / rAF), so **fps is not a headroom metric on real GPUs: use `js ms` (JS time per frame measured after Pixi's render call) as headroom**. Frame budget is 16.7 ms.
### Software GL (headless Chromium 155, SwiftShader, 1280x720, res 1, WebGL2, maxTex 8192) — NOT REPRESENTATIVE
**CAVEAT: CPU-emulated GPU. Absolute numbers and the shape are artifacts of SwiftShader. Kept only as the first harness run; superseded by the real-hardware runs (A)-(D) below.**
With software GL the driver blocks inside draw calls, so `js ms` is inflated at high token counts.
| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |
|---|---|---|---|---|---|---|---|---|---|
| 2048 | single | 50 | 0 | 59.8 | 16.7 | 29.9 | 30.3 | 0.9 | 299 |
| 2048 | single | 200 | 0 | 48.4 | 20.6 | 41.2 | 43.1 | 1.7 | 242 |
| 2048 | single | 500 | 0 | 31.0 | 32.3 | 36.3 | 38.0 | 4.2 | 154 |
| 2048 | single | 1000 | 0 | 20.1 | 49.9 | 54.6 | 54.6 | 7.8 | 100 |
| 2048 | single | 2000 | 0 | 11.5 | 86.9 | 94.2 | 94.2 | 85.7 | 59 |
| 4096 | single | 50 | 0 | 60.0 | 16.7 | 27.1 | 33.6 | 0.7 | 300 |
| 4096 | single | 200 | 0 | 56.5 | 17.7 | 33.3 | 34.5 | 1.7 | 282 |
| 4096 | single | 500 | 0 | 43.2 | 23.2 | 49.3 | 51.3 | 3.9 | 216 |
| 4096 | single | 1000 | 0 | 30.1 | 33.2 | 38.0 | 39.2 | 7.0 | 150 |
| 4096 | single | 2000 | 0 | 18.8 | 53.2 | 58.5 | 58.5 | 52.3 | 96 |
| 8192 | single | 50 | 0 | 60.1 | 16.6 | 26.1 | 29.3 | 0.7 | 300 |
| 8192 | single | 200 | 0 | 58.4 | 17.1 | 32.9 | 40.8 | 1.7 | 291 |
| 8192 | single | 500 | 0 | 48.0 | 20.8 | 40.2 | 41.0 | 3.9 | 240 |
| 8192 | single | 1000 | 0 | 36.4 | 27.5 | 33.2 | 39.8 | 7.3 | 182 |
| 8192 | single | 2000 | 0 | 23.4 | 42.8 | 48.5 | 49.1 | 42.2 | 118 |
| 16384 | 4 tiles | 50 | 0 | 59.7 | 16.8 | 28.0 | 33.0 | 0.7 | 298 |
| 16384 | 4 tiles | 200 | 0 | 58.1 | 17.2 | 32.2 | 34.2 | 2.2 | 290 |
| 16384 | 4 tiles | 500 | 0 | 48.1 | 20.8 | 38.3 | 40.6 | 4.8 | 240 |
| 16384 | 4 tiles | 1000 | 0 | 37.8 | 26.5 | 44.9 | 52.2 | 8.2 | 189 |
| 16384 | 4 tiles | 2000 | 0 | 25.4 | 39.3 | 45.4 | 46.0 | 38.7 | 129 |
| 4096 | single | 50 | 200 | 38.2 | 26.1 | 49.1 | 49.7 | 0.7 | 191 |
| 4096 | single | 500 | 200 | 28.2 | 35.4 | 45.5 | 111.9 | 4.7 | 141 |
### (A) Laptop, WebGL run 1 — Linux Chrome 155, AMD Radeon 780M
Renderer: webgl, GPU: ANGLE (AMD, AMD Radeon 780M Graphics (radeonsi phoenix ACO), OpenGL 4.6), maxTex 16384, res 1.203125, viewport 1877x1058, 5000ms/scenario (+700ms warmup), chaos on, grid on, cull on
UA: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36
| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |
|---|---|---|---|---|---|---|---|---|---|
| 2048 | single | 50 | 0 | 60.0 | 16.7 | 18.3 | 19.1 | 0.4 | 300 |
| 2048 | single | 200 | 0 | 60.0 | 16.7 | 18.3 | 18.4 | 1.5 | 299 |
| 2048 | single | 500 | 0 | 60.0 | 16.7 | 18.1 | 18.3 | 2.9 | 300 |
| 2048 | single | 1000 | 0 | 60.0 | 16.7 | 18.0 | 18.1 | 5.3 | 300 |
| 2048 | single | 2000 | 0 | 60.0 | 16.7 | 17.9 | 18.4 | 9.7 | 300 |
| 4096 | single | 50 | 0 | 60.0 | 16.7 | 18.9 | 19.4 | 0.4 | 300 |
| 4096 | single | 200 | 0 | 60.0 | 16.7 | 18.3 | 19.5 | 1.6 | 300 |
| 4096 | single | 500 | 0 | 60.0 | 16.7 | 18.6 | 19.6 | 3.1 | 300 |
| 4096 | single | 1000 | 0 | 60.0 | 16.7 | 18.3 | 19.3 | 5.3 | 300 |
| 4096 | single | 2000 | 0 | 60.0 | 16.7 | 17.7 | 17.8 | 10.1 | 300 |
| 8192 | single | 50 | 0 | 60.0 | 16.7 | 18.2 | 18.4 | 0.5 | 299 |
| 8192 | single | 200 | 0 | 60.0 | 16.7 | 18.8 | 23.0 | 1.9 | 300 |
| 8192 | single | 500 | 0 | 60.0 | 16.7 | 18.1 | 18.4 | 3.7 | 300 |
| 8192 | single | 1000 | 0 | 60.0 | 16.7 | 18.3 | 18.5 | 6.1 | 300 |
| 8192 | single | 2000 | 0 | 60.0 | 16.7 | 17.8 | 17.9 | 10.5 | 300 |
| 16384 | single | 50 | 0 | 60.0 | 16.7 | 18.5 | 18.8 | 0.4 | 299 |
| 16384 | single | 200 | 0 | 60.0 | 16.7 | 18.3 | 18.4 | 1.5 | 300 |
| 16384 | single | 500 | 0 | 60.0 | 16.7 | 18.4 | 19.8 | 4.3 | 300 |
| 16384 | single | 1000 | 0 | 60.0 | 16.7 | 18.6 | 20.6 | 6.4 | 300 |
| 16384 | single | 2000 | 0 | 60.0 | 16.7 | 17.7 | 18.0 | 11.8 | 300 |
| 4096 | single | 50 | 200 | 60.0 | 16.7 | 19.0 | 19.5 | 0.7 | 300 |
| 4096 | single | 500 | 200 | 60.0 | 16.7 | 18.1 | 18.1 | 3.6 | 300 |
### (B) Laptop, WebGL run 2 — same header as (A)
Note: this run was launched as a WebGPU request (`?renderer=webgpu`) and fell back to WebGL, so the results are WebGL. Header same as (A).
Renderer: webgl, GPU: ANGLE (AMD, AMD Radeon 780M Graphics (radeonsi phoenix ACO), OpenGL 4.6), maxTex 16384, res 1.203125, viewport 1877x1058, 5000ms/scenario (+700ms warmup), chaos on, grid on, cull on
UA: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36
| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |
|---|---|---|---|---|---|---|---|---|---|
| 2048 | single | 50 | 0 | 60.0 | 16.7 | 18.3 | 18.5 | 0.5 | 300 |
| 2048 | single | 200 | 0 | 60.0 | 16.7 | 18.3 | 19.0 | 1.7 | 300 |
| 2048 | single | 500 | 0 | 60.0 | 16.7 | 18.1 | 18.9 | 3.0 | 300 |
| 2048 | single | 1000 | 0 | 60.0 | 16.7 | 18.4 | 18.6 | 5.5 | 300 |
| 2048 | single | 2000 | 0 | 60.0 | 16.7 | 17.8 | 18.2 | 11.0 | 300 |
| 4096 | single | 50 | 0 | 60.0 | 16.7 | 18.1 | 18.3 | 0.6 | 299 |
| 4096 | single | 200 | 0 | 60.0 | 16.7 | 18.3 | 19.0 | 1.8 | 300 |
| 4096 | single | 500 | 0 | 60.0 | 16.7 | 18.2 | 18.5 | 3.3 | 300 |
| 4096 | single | 1000 | 0 | 60.0 | 16.7 | 18.2 | 18.5 | 5.6 | 300 |
| 4096 | single | 2000 | 0 | 60.0 | 16.7 | 17.7 | 18.1 | 11.3 | 300 |
| 8192 | single | 50 | 0 | 60.0 | 16.7 | 18.6 | 19.1 | 0.7 | 300 |
| 8192 | single | 200 | 0 | 60.0 | 16.7 | 18.7 | 19.3 | 2.4 | 300 |
| 8192 | single | 500 | 0 | 60.0 | 16.7 | 18.1 | 18.2 | 4.0 | 300 |
| 8192 | single | 1000 | 0 | 60.0 | 16.7 | 18.0 | 18.5 | 6.4 | 300 |
| 8192 | single | 2000 | 0 | 60.0 | 16.7 | 17.7 | 18.4 | 11.6 | 300 |
| 16384 | single | 50 | 0 | 60.0 | 16.7 | 18.2 | 18.8 | 0.5 | 299 |
| 16384 | single | 200 | 0 | 60.0 | 16.7 | 18.1 | 24.1 | 2.1 | 299 |
| 16384 | single | 500 | 0 | 60.0 | 16.7 | 18.0 | 18.5 | 4.5 | 300 |
| 16384 | single | 1000 | 0 | 60.0 | 16.7 | 17.8 | 18.3 | 6.7 | 300 |
| 16384 | single | 2000 | 0 | 60.0 | 16.7 | 18.1 | 18.6 | 11.7 | 300 |
| 4096 | single | 50 | 200 | 59.8 | 16.7 | 19.6 | 32.4 | 0.6 | 298 |
| 4096 | single | 500 | 200 | 60.0 | 16.7 | 18.4 | 18.4 | 3.6 | 300 |
### (C) Laptop, WebGPU — Linux Chrome 155, AMD Radeon 780M
Renderer: webgpu (requested webgpu, honored), GPU: ?, maxTex 8192, res 1.203125, viewport 1877x1058, 5000ms/scenario (+700ms warmup), chaos on, grid on, cull on
UA: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36
| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |
|---|---|---|---|---|---|---|---|---|---|
| 2048 | single | 50 | 0 | 59.9 | 16.7 | 17.5 | 17.7 | 0.4 | 299 |
| 2048 | single | 200 | 0 | 59.9 | 16.7 | 17.7 | 18.3 | 1.6 | 299 |
| 2048 | single | 500 | 0 | 59.9 | 16.7 | 17.6 | 17.7 | 3.8 | 299 |
| 2048 | single | 1000 | 0 | 59.9 | 16.7 | 17.2 | 17.5 | 4.5 | 299 |
| 2048 | single | 2000 | 0 | 59.9 | 16.7 | 17.2 | 17.3 | 8.8 | 300 |
| 4096 | single | 50 | 0 | 59.9 | 16.7 | 17.6 | 20.2 | 0.4 | 299 |
| 4096 | single | 200 | 0 | 59.9 | 16.7 | 17.6 | 17.7 | 1.7 | 299 |
| 4096 | single | 500 | 0 | 59.9 | 16.7 | 17.5 | 17.6 | 3.7 | 299 |
| 4096 | single | 1000 | 0 | 59.9 | 16.7 | 17.0 | 17.7 | 4.5 | 299 |
| 4096 | single | 2000 | 0 | 59.9 | 16.7 | 17.7 | 17.7 | 9.0 | 300 |
| 8192 | single | 50 | 0 | 59.9 | 16.7 | 17.7 | 24.9 | 0.4 | 299 |
| 8192 | single | 200 | 0 | 59.9 | 16.7 | 17.7 | 20.4 | 1.6 | 299 |
| 8192 | single | 500 | 0 | 59.9 | 16.7 | 17.6 | 18.1 | 3.6 | 299 |
| 8192 | single | 1000 | 0 | 59.9 | 16.7 | 17.0 | 17.1 | 4.6 | 299 |
| 8192 | single | 2000 | 0 | 59.9 | 16.7 | 17.6 | 17.7 | 8.8 | 300 |
| 16384 | 4 tiles | 50 | 0 | 59.9 | 16.7 | 17.5 | 17.5 | 0.4 | 299 |
| 16384 | 4 tiles | 200 | 0 | 59.9 | 16.7 | 17.7 | 17.7 | 1.6 | 299 |
| 16384 | 4 tiles | 500 | 0 | 59.9 | 16.7 | 17.2 | 17.3 | 3.4 | 299 |
| 16384 | 4 tiles | 1000 | 0 | 59.9 | 16.7 | 17.3 | 18.5 | 4.9 | 299 |
| 16384 | 4 tiles | 2000 | 0 | 59.9 | 16.7 | 17.6 | 17.7 | 10.0 | 300 |
| 4096 | single | 50 | 200 | 59.9 | 16.7 | 17.7 | 17.7 | 0.9 | 299 |
| 4096 | single | 500 | 200 | 59.9 | 16.7 | 17.4 | 17.5 | 4.0 | 299 |
### (D) Samsung Galaxy Note 10 (SM-N970F, Exynos 9825 / Mali-G76), WebGL — Chrome 156 Android
Renderer: webgl, GPU: ANGLE (ARM, Mali-G76, OpenGL ES 3.2), maxTex 4096, res 2, viewport 411x730, 5000ms/scenario (+700ms warmup), chaos on, grid on, cull on
UA: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Mobile Safari/537.36
| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |
|---|---|---|---|---|---|---|---|---|---|
| 2048 | single | 50 | 0 | 60.0 | 16.7 | 20.8 | 24.0 | 3.1 | 300 |
| 2048 | single | 200 | 0 | 60.0 | 16.7 | 19.8 | 20.6 | 4.5 | 300 |
| 2048 | single | 500 | 0 | 60.0 | 16.7 | 19.7 | 21.7 | 9.1 | 300 |
| 2048 | single | 1000 | 0 | 59.8 | 16.7 | 22.1 | 28.9 | 14.1 | 300 |
| 2048 | single | 2000 | 0 | 36.0 | 27.8 | 31.5 | 40.0 | 26.8 | 180 |
| 4096 | single | 50 | 0 | 59.8 | 16.7 | 19.8 | 30.1 | 2.8 | 299 |
| 4096 | single | 200 | 0 | 59.8 | 16.7 | 19.1 | 45.5 | 5.1 | 299 |
| 4096 | single | 500 | 0 | 60.0 | 16.7 | 18.8 | 20.3 | 9.0 | 300 |
| 4096 | single | 1000 | 0 | 60.0 | 16.7 | 19.3 | 21.0 | 13.8 | 300 |
| 4096 | single | 2000 | 0 | 34.6 | 28.9 | 30.4 | 30.8 | 28.1 | 173 |
| 8192 | 4 tiles | 50 | 0 | 60.0 | 16.7 | 18.5 | 19.2 | 3.0 | 300 |
| 8192 | 4 tiles | 200 | 0 | 60.0 | 16.7 | 18.9 | 20.4 | 4.5 | 300 |
| 8192 | 4 tiles | 500 | 0 | 60.0 | 16.7 | 19.3 | 28.8 | 9.1 | 300 |
| 8192 | 4 tiles | 1000 | 0 | 60.0 | 16.7 | 20.0 | 22.6 | 14.2 | 300 |
| 8192 | 4 tiles | 2000 | 0 | 35.1 | 28.5 | 30.7 | 32.7 | 27.7 | 176 |
| 16384 | 16 tiles | 50 | 0 | 60.0 | 16.7 | 20.1 | 23.6 | 3.0 | 300 |
| 16384 | 16 tiles | 200 | 0 | 60.0 | 16.7 | 18.7 | 19.8 | 4.9 | 300 |
| 16384 | 16 tiles | 500 | 0 | 60.0 | 16.7 | 21.0 | 25.7 | 9.8 | 300 |
| 16384 | 16 tiles | 1000 | 0 | 59.3 | 16.9 | 24.2 | 80.2 | 14.5 | 297 |
| 16384 | 16 tiles | 2000 | 0 | 32.3 | 30.9 | 32.6 | 33.4 | 30.1 | 162 |
| 4096 | single | 50 | 200 | 60.0 | 16.7 | 18.5 | 20.8 | 3.0 | 300 |
| 4096 | single | 500 | 200 | 60.0 | 16.7 | 19.4 | 24.0 | 9.5 | 300 |
## Techniques used (v8)
- **Map larger than max texture**: max texture read from the backend (`gl.getParameter(MAX_TEXTURE_SIZE)` / `device.limits.maxTextureDimension2D`);
if map > that (or > the "tile size" override) it is sliced into square tiles, each its own canvas -> `Texture.from(canvas)` -> `Sprite` at an integer position.
Overlay says SINGLE vs TILED. Here 16384 on a maxTex 8192 device = 2x2 tiles of 8192.
- **Culling**: manual `Culler.shared.cull(world, screen, false)` each frame (not the plugin, so it can be toggled); map tiles and stroke sprites are `cullable`
with bounds; tokens use a fixed `cullArea` rectangle (no per-frame bounds calc) and `cullableChildren = false`.
- **Token labels under HP churn**: `BitmapText` with a pre-installed `BitmapFont` (`BitmapFont.install`), not `Text`: changing `.text` only rebuilds quads, no canvas raster or GPU upload.
Circle bodies: one shared `GraphicsContext` per colour (6), tessellated once, reused by all tokens. Tokens are pooled (removed/added, never destroyed).
- **Grid**: one `TilingSprite` over a small cell texture (1 quad regardless of map size) rather than thousands of `Graphics` lines.
- **Stroke baking**: live stroke = `Graphics` chunks of <=48 points (only the last chunk is re-tessellated per move, older chunks frozen). On pointer up the chunks are rendered once with
`renderer.textureGenerator.generateTexture({target, frame, resolution, antialias})` into a `Sprite` and the Graphics are destroyed.
Bake resolution follows zoom (1..2), capped so no side exceeds 4096 px.
- **Input**: DOM pointer events on the canvas with a hand-rolled pan/zoom/pinch (pixi-viewport 6.0.3 declares `pixi.js >=8` peer, but token drag + pen + pinch needed custom handling anyway).
Pixi's federated event features are disabled; token hit test is an O(N) scan on press only.
## Findings (real hardware)
Supersedes the SwiftShader-based findings of the earlier headless run.
**Verdict: PixiJS v8 renders a VTT-sized scene smoothly on the laptop (Radeon 780M, both WebGL and WebGPU) and on a 2019 phone (Note 10, WebGL).** Only per-frame JS for token updates under chaos scales in a way that matters.
- **200 baked strokes: refuted as a cost.** The SwiftShader result (4096/50 tokens 60 -> 38 fps) is a **SwiftShader artifact**, not a real-GPU effect. On real devices the strokes cost no fps; js ms rises by at most ~0.5 ms on the laptop, and the phone 4096/500 with strokes is 9.5 ms vs 9.0 ms without. Hypothesis about un-mipmapped stroke textures is moot for now.
- **Map size: ~free.** The tiled path was verified on real GPUs with no measurable cost:
laptop WebGPU maxTex 8192 -> 16384 map = 4 tiles; phone maxTex 4096 -> 8192 = 4 tiles, 16384 = 16 tiles.
Hypothesis: the WebGPU maxTex of 8192 (vs WebGL 16384 on the same GPU) is Pixi requesting default device limits, not the adapter max.
- **Baked strokes at 200: no measurable cost on any real device** (see above).
- **Only scaling cost = per-frame JS for token updates under chaos (all tokens moving).**
- Laptop 2000 tokens: js 9.7–11.8 ms (WebGL, runs A/B), 8.8–10.0 ms (WebGPU, run C). Both well under budget.
- Phone: 60 fps (59–60) up to 1000 tokens at ~14 ms js; 2000 tokens -> 32–36 fps, js 27–30 ms -> CPU-bound.
- Phone is ~2.5x slower than laptop on the same JS work.
- **Phone fixed overhead:** js ~3 ms even at 50 tokens vs 0.4 ms on laptop. Hypothesis: overlay / culling per-frame cost. Keep small in the real app.
- **Isolated spikes, not patterns:** phone worst 80 ms at 16384/1000 tokens; laptop worst 32 ms at 4096/50/200 strokes (run B). Likely GC or texture upload one-offs; not reproduced across runs.
- **fps column is vsync-capped at 60.** Use js ms as the headroom metric; fps only drops once js exceeds budget.
Real-VTT risks:
- Update only moved tokens; never all tokens per frame. Chaos at 2000 moves everything and is the worst case.
- If mass movement is ever needed on mobile, switch to `ParticleContainer` (next step, not tested).
- A single 16384 texture is ~1 GB VRAM (16384² × 4 B) on GPUs whose maxTex allows it. Consider capping texture size or forcing tiles, even where the device could take a single texture.
- BitmapText rasterises at one font size: labels blur when zoomed in. The installed glyph set is Latin/digits only; non-Latin names need `Text`/HTMLText or a bigger atlas.
- Per-stroke textures: 200 strokes = 200 GPU textures. Thousands of strokes need atlasing/merging and texture GC planning. Very long strokes are baked at a 4096 px cap and look soft.
- Tokens are one Container + 2 children each: 2000 tokens = 6000 scene nodes touched per frame in chaos mode.
- WebGPU header shows `GPU: ?` (adapter info not read). Cosmetic.
Untested:
- HP churn timing (the Run-benchmark runs churn OFF; toggle is manual).
- iOS / Safari.
- WebGPU on mobile.
- Tablets beyond the Note 10.
@@ -0,0 +1,16 @@
// Headless benchmark runner: `devbox run -- npm run bench -- "http://localhost:5173/?benchMs=5000&renderer=webgl"`
// needs the dev/preview server running. Chromium from devbox ($CHROMIUM or `chromium` on PATH). SOFTWARE GL => not representative.
import { chromium } from 'playwright-core';
const url = process.argv[2] ?? 'http://localhost:5173/';
const b = await chromium.launch({
executablePath: process.env.CHROMIUM ?? 'chromium',
args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--enable-unsafe-webgpu', '--no-sandbox'],
});
const p = await b.newPage({ viewport: { width: 1280, height: 720 } });
p.on('console', (m) => console.error('[page]', m.text()));
p.on('pageerror', (e) => console.error('[pageerror]', e.message));
await p.goto(url);
await p.waitForFunction('window.__ready', null, { timeout: 60000 });
if (process.env.SHOT) await p.screenshot({ path: process.env.SHOT });
console.log(await p.evaluate('window.__app.runBench()'));
await b.close();
@@ -0,0 +1,17 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": [
"nodejs@latest",
"chromium@latest"
],
"shell": {
"init_hook": [
"echo 'Welcome to devbox!' > /dev/null"
],
"scripts": {
"test": [
"echo \"Error: no test specified\" && exit 1"
]
}
}
}
@@ -0,0 +1,84 @@
{
"lockfile_version": "1",
"packages": {
"chromium@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#chromium",
"source": "devbox-search",
"version": "155.0.8059.39",
"systems": {
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/a1w34yg08mvma03xps5dsy8vw5hrdy9w-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/5hpd396v5byrfp1vnw7zmpfscqd3b1zv-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"nodejs@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
}
}
}
@@ -0,0 +1,23 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Pixi v8 VTT perf prototype (throwaway)</title>
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #111; font: 12px monospace; color: #eee; }
canvas { display: block; touch-action: none; }
.panel { position: fixed; background: rgba(0,0,0,.75); padding: 6px 8px; border-radius: 4px; }
#stats { top: 4px; left: 4px; white-space: pre; pointer-events: none; }
#ctl { top: 4px; right: 4px; max-width: 280px; display: flex; flex-direction: column; gap: 4px; max-height: 96vh; overflow: auto; }
#ctl label { display: flex; justify-content: space-between; gap: 6px; align-items: center; }
#out { width: 100%; height: 120px; font: 10px monospace; }
button, select, input { font: inherit; }
</style>
</head>
<body>
<div id="stats" class="panel"></div>
<div id="ctl" class="panel"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
{
"name": "prototype-pixi-perf",
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"bench": "node bench.mjs"
},
"type": "module",
"dependencies": {
"pixi.js": "^8.22.0"
},
"devDependencies": {
"playwright-core": "^1.64.1",
"typescript": "^7.0.2",
"vite": "^8.3.5"
},
"private": true
}
@@ -0,0 +1,469 @@
// THROWAWAY perf prototype. Pixi v8. See ../README.md.
import {
Application, BitmapFont, BitmapText, Container, Culler, Graphics, GraphicsContext,
Rectangle, Sprite, Texture, TilingSprite, UPDATE_PRIORITY,
} from 'pixi.js';
// ---------- state ----------
const S = {
map: 4096, tile: 0 /* 0 = auto (maxTex) */, n: 200, cell: 64,
grid: true, chaos: false, churn: false, cull: true, tool: 'move' as 'move' | 'pen',
};
const q = new URLSearchParams(location.search);
const BENCH_MS = Number(q.get('benchMs') ?? 5000);
const WARM_MS = Number(q.get('warmMs') ?? 700);
const TOKEN_R = 24;
const TOKEN_MAX = 2000;
let customBitmap: ImageBitmap | null = null;
let mapInfo = '';
let mapBuildMs = 0;
let maxTex = 0;
let benchStatus = '';
// ---------- app ----------
const app = new Application();
const pref = q.get('renderer'); // webgl | webgpu
await app.init({
resizeTo: window,
background: 0x1a1a1a,
antialias: false,
resolution: Number(q.get('res') ?? Math.min(devicePixelRatio, 2)),
autoDensity: true,
preference: pref === 'webgl' || pref === 'webgpu' ? pref : undefined,
// DOM pointer events are used instead of Pixi's federated events (see README): no hit-testing per move.
eventFeatures: { move: false, globalMove: false, click: false, wheel: false },
});
document.body.prepend(app.canvas);
const rendererName = app.renderer.name;
// Pixi `preference` is only a hint; label requested vs actual so a silent WebGL fallback is visible.
const req = pref === 'webgl' || pref === 'webgpu' ? pref : undefined;
const rendererLabel = !req ? rendererName
: req === rendererName ? `${rendererName} (requested ${req}, honored)`
: `${rendererName} (requested ${req} → fallback)`;
{
const r = app.renderer as any;
maxTex = rendererName === 'webgpu'
? r.gpu.device.limits.maxTextureDimension2D
: r.gl.getParameter(WebGL2RenderingContext.MAX_TEXTURE_SIZE);
}
let gpuName = '?';
try {
const gl = (app.renderer as any).gl as WebGL2RenderingContext | undefined;
const ext = gl?.getExtension('WEBGL_debug_renderer_info');
if (gl && ext) gpuName = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
} catch { /* ignore */ }
const world = new Container();
const mapLayer = new Container();
const strokeLayer = new Container();
const liveLayer = new Container();
const tokenLayer = new Container();
world.addChild(mapLayer, strokeLayer, tokenLayer, liveLayer);
app.stage.addChild(world);
let grid: TilingSprite | null = null;
// ---------- map (tiling over max texture size) ----------
function hash(x: number, y: number) {
let h = (x * 374761393 + y * 668265263) | 0;
h = (h ^ (h >>> 13)) * 1274126177;
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function drawProc(ctx: CanvasRenderingContext2D, ox: number, oy: number, w: number, h: number) {
const C = 128; // world-space cell, deterministic so tiles line up
for (let cy = Math.floor(oy / C); cy * C < oy + h; cy++) {
for (let cx = Math.floor(ox / C); cx * C < ox + w; cx++) {
const r = hash(cx, cy);
ctx.fillStyle = `hsl(${90 + r * 60}, ${25 + r * 25}%, ${22 + hash(cy, cx) * 18}%)`;
ctx.fillRect(cx * C - ox, cy * C - oy, C, C);
if (r > 0.7) {
ctx.fillStyle = 'rgba(40,90,160,.6)';
ctx.beginPath();
ctx.arc(cx * C - ox + C / 2, cy * C - oy + C / 2, 20 + r * 40, 0, 7);
ctx.fill();
}
}
}
ctx.strokeStyle = 'rgba(0,0,0,.5)';
ctx.lineWidth = 3;
for (let x = Math.ceil(ox / 1024) * 1024; x < ox + w; x += 1024) { ctx.beginPath(); ctx.moveTo(x - ox, 0); ctx.lineTo(x - ox, h); ctx.stroke(); }
for (let y = Math.ceil(oy / 1024) * 1024; y < oy + h; y += 1024) { ctx.beginPath(); ctx.moveTo(0, y - oy); ctx.lineTo(w, y - oy); ctx.stroke(); }
}
function buildMap() {
const t0 = performance.now();
for (const c of mapLayer.removeChildren()) (c as Sprite).destroy({ texture: true, textureSource: true });
const size = S.map;
const tile = Math.min(size, S.tile || maxTex, maxTex);
const nt = Math.ceil(size / tile);
try {
for (let ty = 0; ty < nt; ty++) {
for (let tx = 0; tx < nt; tx++) {
const ox = tx * tile, oy = ty * tile;
const w = Math.min(tile, size - ox), h = Math.min(tile, size - oy);
const cv = document.createElement('canvas');
cv.width = w; cv.height = h;
const ctx = cv.getContext('2d')!;
if (customBitmap) {
const k = customBitmap.width / size, kh = customBitmap.height / size;
ctx.drawImage(customBitmap, ox * k, oy * kh, w * k, h * kh, 0, 0, w, h);
} else drawProc(ctx, ox, oy, w, h);
const spr = new Sprite(Texture.from(cv));
spr.position.set(ox, oy);
spr.cullable = true; // culled by the Culler each frame (tiles outside view are skipped)
mapLayer.addChild(spr);
}
}
mapInfo = nt === 1
? `${size}px: SINGLE texture (maxTex ${maxTex})`
: `${size}px: TILED ${nt}x${nt} of ${tile}px (maxTex ${maxTex})`;
} catch (e) {
mapInfo = `${size}px: BUILD FAILED ${e}`;
}
if (grid) { grid.width = grid.height = size; }
mapBuildMs = performance.now() - t0;
}
// ---------- grid (one TilingSprite, 1 quad) ----------
function buildGrid() {
const c = S.cell;
const cv = document.createElement('canvas');
cv.width = cv.height = c;
const ctx = cv.getContext('2d')!;
ctx.strokeStyle = 'rgba(255,255,255,.35)';
ctx.lineWidth = 2;
ctx.strokeRect(0, 0, c, c);
const tex = Texture.from(cv);
if (!grid) { grid = new TilingSprite({ texture: tex, width: S.map, height: S.map }); mapLayer.parent!.addChildAt(grid, 1); }
else { const old = grid.texture; grid.texture = tex; old.destroy(true); }
grid.width = grid.height = S.map;
grid.visible = S.grid;
}
// ---------- tokens ----------
BitmapFont.install({
name: 'tok',
style: { fontFamily: 'Arial', fontSize: 16, fill: 0xffffff, stroke: { color: 0x000000, width: 3 } },
chars: [['a', 'z'], ['A', 'Z'], ['0', '9'], ' /-'],
});
// one shared GraphicsContext per colour: tessellated once, reused by every token
const bodyCtx = [0xc0392b, 0x2980b9, 0x27ae60, 0x8e44ad, 0xd35400, 0x16a085].map(
(c) => new GraphicsContext().circle(0, 0, TOKEN_R).fill(c).stroke({ width: 3, color: 0xffffff }),
);
type Tok = { c: Container; label: BitmapText; x: number; y: number; vx: number; vy: number; hp: number; name: string };
const toks: Tok[] = [];
const label = (t: Tok) => `${t.name} ${t.hp}/99`;
function makeTok(i: number): Tok {
const c = new Container();
const body = new Graphics(bodyCtx[i % bodyCtx.length]);
const t: Tok = {
c, label: null as any, name: 'T' + i, hp: (hash(i, 7) * 99) | 0,
x: hash(i, 1) * S.map, y: hash(i, 2) * S.map,
vx: (hash(i, 3) - 0.5) * 400, vy: (hash(i, 4) - 0.5) * 400,
};
const l = new BitmapText({ text: label(t), style: { fontFamily: 'tok', fontSize: 16 } });
l.anchor.set(0.5, 0);
l.y = TOKEN_R + 2;
t.label = l;
c.addChild(body, l);
c.cullable = true;
c.cullArea = new Rectangle(-45, -TOKEN_R - 2, 90, TOKEN_R * 2 + 28); // fixed cull rect: no per-frame bounds calc
c.cullableChildren = false;
c.position.set(t.x, t.y);
return t;
}
function setTokens() {
while (toks.length < S.n) toks.push(makeTok(toks.length));
tokenLayer.removeChildren(); // pooled, never destroyed
for (let i = 0; i < S.n; i++) {
const t = toks[i];
t.x = Math.min(t.x, S.map); t.y = Math.min(t.y, S.map);
t.c.position.set(t.x, t.y);
tokenLayer.addChild(t.c);
}
}
// ---------- strokes: live Graphics chunks -> baked to one Sprite texture ----------
const PEN_W = 4;
let live: { pts: number[]; start: number; cur: Graphics; color: number } | null = null;
function drawChunk(g: Graphics, pts: number[], from: number, color: number) {
g.clear().moveTo(pts[from], pts[from + 1]);
for (let i = from + 2; i < pts.length; i += 2) g.lineTo(pts[i], pts[i + 1]);
if (pts.length - from === 2) g.lineTo(pts[from] + 0.01, pts[from + 1]);
g.stroke({ width: PEN_W, color, cap: 'round', join: 'round' });
}
function startStroke(x: number, y: number) {
const color = (Math.random() * 0xffffff) | 0 | 0x303030;
const cur = new Graphics();
liveLayer.addChild(cur);
live = { pts: [x, y], start: 0, cur, color };
drawChunk(cur, live.pts, 0, color);
}
function addPoint(x: number, y: number) {
if (!live) return;
const L = live;
L.pts.push(x, y);
// only the last <=48 points get re-tessellated; older chunks stay frozen => O(1) per move
if (L.pts.length - L.start > 96) {
L.start = L.pts.length - 2;
L.cur = new Graphics();
liveLayer.addChild(L.cur);
}
drawChunk(L.cur, L.pts, L.start, L.color);
}
function bake(target: Container) {
const b = target.getLocalBounds().rectangle;
const pad = PEN_W;
const frame = new Rectangle(Math.floor(b.x - pad), Math.floor(b.y - pad), Math.ceil(b.width + 2 * pad), Math.ceil(b.height + 2 * pad));
// resolution follows zoom (sharp when zoomed in) but caps the texture at 4096px per side
const res = Math.min(Math.max(1, Math.min(2, world.scale.x)), 4096 / Math.max(frame.width, frame.height));
const texture = app.renderer.textureGenerator.generateTexture({ target, frame, resolution: res, antialias: true });
const spr = new Sprite(texture);
spr.scale.set(1 / res);
spr.position.set(frame.x, frame.y);
spr.cullable = true;
strokeLayer.addChild(spr);
}
function endStroke() {
if (!live) return;
live = null;
bake(liveLayer);
for (const c of liveLayer.removeChildren()) c.destroy();
}
function randomStrokes(count: number) {
for (let k = 0; k < count; k++) {
const g = new Graphics();
let x = Math.random() * S.map, y = Math.random() * S.map, a = Math.random() * 6.28;
const pts = [x, y];
for (let i = 0; i < 60; i++) { a += (Math.random() - 0.5) * 0.9; x += Math.cos(a) * 14; y += Math.sin(a) * 14; pts.push(x, y); }
drawChunk(g, pts, 0, (Math.random() * 0xffffff) | 0 | 0x303030);
bake(g);
g.destroy();
}
}
function clearStrokes() {
for (const c of strokeLayer.removeChildren()) (c as Sprite).destroy({ texture: true, textureSource: true });
}
// ---------- pan / zoom / drag / draw (DOM pointer events) ----------
function zoomAt(px: number, py: number, k: number) {
const s0 = world.scale.x, s1 = Math.min(8, Math.max(0.02, s0 * k));
world.position.set(px - (px - world.x) * (s1 / s0), py - (py - world.y) * (s1 / s0));
world.scale.set(s1);
}
function fit() {
const s = (Math.min(innerWidth, innerHeight) / S.map) * 0.9;
world.scale.set(s);
world.position.set((innerWidth - S.map * s) / 2, (innerHeight - S.map * s) / 2);
}
const cv = app.canvas;
cv.addEventListener('contextmenu', (e) => e.preventDefault());
cv.addEventListener('wheel', (e) => { e.preventDefault(); zoomAt(e.offsetX, e.offsetY, Math.exp(-e.deltaY * 0.0015)); }, { passive: false });
const ptrs = new Map<number, { x: number; y: number }>();
let mode: 'none' | 'pan' | 'drag' | 'draw' | 'pinch' = 'none';
let dragTok: Tok | null = null;
let pinch = { d: 1, cx: 0, cy: 0 };
const toWorld = (x: number, y: number) => [(x - world.x) / world.scale.x, (y - world.y) / world.scale.x];
function pinchState() {
const [a, b] = [...ptrs.values()];
return { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2 };
}
cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId);
ptrs.set(e.pointerId, { x: e.offsetX, y: e.offsetY });
if (ptrs.size >= 2) { endStroke(); dragTok = null; mode = 'pinch'; pinch = pinchState(); return; }
if (S.tool === 'pen' && e.button === 0) { mode = 'draw'; startStroke(...(toWorld(e.offsetX, e.offsetY) as [number, number])); return; }
const [wx, wy] = toWorld(e.offsetX, e.offsetY);
dragTok = null;
if (e.button === 0) {
for (let i = S.n - 1; i >= 0; i--) { // O(N) only on press, not per move
const t = toks[i];
if ((t.x - wx) ** 2 + (t.y - wy) ** 2 < TOKEN_R * TOKEN_R) { dragTok = t; break; }
}
}
mode = dragTok ? 'drag' : 'pan';
});
cv.addEventListener('pointermove', (e) => {
const p = ptrs.get(e.pointerId);
if (!p) return;
const dx = e.offsetX - p.x, dy = e.offsetY - p.y;
p.x = e.offsetX; p.y = e.offsetY;
if (mode === 'pan') world.position.set(world.x + dx, world.y + dy);
else if (mode === 'drag' && dragTok) {
dragTok.x += dx / world.scale.x; dragTok.y += dy / world.scale.x;
dragTok.c.position.set(dragTok.x, dragTok.y);
} else if (mode === 'draw') {
const rect = cv.getBoundingClientRect();
for (const ce of e.getCoalescedEvents?.() ?? [e]) {
const [wx, wy] = toWorld(ce.clientX - rect.left, ce.clientY - rect.top);
addPoint(wx, wy);
}
} else if (mode === 'pinch' && ptrs.size >= 2) {
const n = pinchState();
world.position.set(world.x + (n.cx - pinch.cx), world.y + (n.cy - pinch.cy));
zoomAt(n.cx, n.cy, n.d / pinch.d);
pinch = n;
}
});
function up(e: PointerEvent) {
if (!ptrs.delete(e.pointerId)) return;
if (mode === 'draw') endStroke();
dragTok = null;
mode = ptrs.size === 1 && mode === 'pinch' ? 'pan' : 'none';
}
cv.addEventListener('pointerup', up);
cv.addEventListener('pointercancel', up);
// ---------- per-frame loop + frame stats ----------
type Sample = { t: number; dt: number; cpu: number };
let samples: Sample[] = [];
let lastT = performance.now();
let frameStart = 0;
let benchSink: Sample[] | null = null;
function setCull(on: boolean) {
if (!on) for (const l of [mapLayer, strokeLayer, tokenLayer]) for (const c of l.children) c.renderable = true;
}
app.ticker.add(() => {
const now = performance.now();
frameStart = now;
const dt = now - lastT;
lastT = now;
samples.push({ t: now, dt, cpu: 0 });
while (samples[0].t < now - 2000) samples.shift();
const sec = Math.min(dt, 100) / 1000;
if (S.chaos) {
for (let i = 0; i < S.n; i++) {
const t = toks[i];
t.x += t.vx * sec; t.y += t.vy * sec;
if (t.x < 0 || t.x > S.map) t.vx = -t.vx;
if (t.y < 0 || t.y > S.map) t.vy = -t.vy;
t.c.position.set(t.x, t.y);
}
}
if (S.churn) {
for (let i = 0; i < S.n; i++) { const t = toks[i]; t.hp = (t.hp + 1 + ((Math.random() * 7) | 0)) % 100; t.label.text = label(t); }
}
if (S.cull) Culler.shared.cull(world, app.screen, false);
}, undefined, UPDATE_PRIORITY.HIGH);
// runs after Pixi's render (LOW) => JS time spent per frame incl. render submission (not GPU time)
app.ticker.add(() => {
const s = samples[samples.length - 1];
s.cpu = performance.now() - frameStart;
benchSink?.push(s);
}, undefined, UPDATE_PRIORITY.UTILITY);
function stats() {
const n = samples.length || 1;
const avg = samples.reduce((a, s) => a + s.dt, 0) / n;
const worst = samples.reduce((a, s) => Math.max(a, s.dt), 0);
const cpu = samples.reduce((a, s) => a + s.cpu, 0) / n;
return { avg, worst, cpu, fps: 1000 / avg };
}
const stat = document.getElementById('stats')!;
setInterval(() => {
const s = stats();
stat.textContent =
`FPS ${s.fps.toFixed(1)} frame avg ${s.avg.toFixed(1)}ms worst(2s) ${s.worst.toFixed(1)}ms js ${s.cpu.toFixed(1)}ms\n` +
`renderer: ${rendererLabel} res ${app.renderer.resolution} maxTex ${maxTex}\n` +
`map: ${mapInfo} (built ${mapBuildMs.toFixed(0)}ms${customBitmap ? ', custom image' : ', procedural'})\n` +
`tokens ${S.n} strokes ${strokeLayer.children.length} grid ${S.grid ? S.cell + 'px' : 'off'} chaos ${S.chaos} churn ${S.churn} cull ${S.cull} tool ${S.tool}\n` +
`zoom ${world.scale.x.toFixed(2)}${benchStatus ? '\n' + benchStatus : ''}`;
}, 250);
// ---------- benchmark ----------
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const nextFrames = (n: number) => new Promise<void>((r) => { let k = 0; const f = () => { if (++k >= n) { app.ticker.remove(f); r(); } }; app.ticker.add(f); });
async function runBench(out: HTMLTextAreaElement) {
const maps = [2048, 4096, 8192, 16384], counts = [50, 200, 500, 1000, 2000];
const sc: { map: number; n: number; strokes: number }[] = [];
for (const m of maps) for (const n of counts) sc.push({ map: m, n, strokes: 0 });
sc.push({ map: 4096, n: 50, strokes: 200 }, { map: 4096, n: 500, strokes: 200 });
const saved = { ...S };
S.chaos = true; S.churn = false; S.cull = true; S.grid = true;
const rows: string[] = [];
let strokes = strokeLayer.children.length;
for (let i = 0; i < sc.length; i++) {
const c = sc[i];
benchStatus = `BENCH ${i + 1}/${sc.length}: map ${c.map} tokens ${c.n} strokes ${c.strokes}`;
if (S.map !== c.map) { S.map = c.map; buildMap(); fit(); }
if (strokes !== c.strokes) { clearStrokes(); randomStrokes(c.strokes); strokes = c.strokes; }
S.n = c.n; setTokens();
const path = mapLayer.children.length === 1 ? 'single' : `${mapLayer.children.length} tiles`;
await sleep(WARM_MS);
await nextFrames(3); // first frames include GPU texture upload; never measure them
const sink: Sample[] = [];
benchSink = sink;
await sleep(BENCH_MS);
benchSink = null;
console.log(`scenario ${i}`, c.map, c.n, c.strokes, path, mapInfo, 'frames', sink.length);
if (!sink.length) await nextFrames(2); // unreachable in practice
const dts = sink.length ? sink.map((s) => s.dt) : [NaN];
const avg = dts.reduce((a, b) => a + b, 0) / dts.length;
const sorted = [...dts].sort((a, b) => a - b);
const p99 = sorted[Math.floor(sorted.length * 0.99)];
const cpu = sink.reduce((a, s) => a + s.cpu, 0) / sink.length;
rows.push(`| ${c.map} | ${path} | ${c.n} | ${c.strokes} | ${(1000 / avg).toFixed(1)} | ${avg.toFixed(1)} | ${p99.toFixed(1)} | ${Math.max(...dts).toFixed(1)} | ${cpu.toFixed(1)} | ${dts.length} |`);
}
Object.assign(S, saved);
buildMap(); setTokens(); clearStrokes(); buildGrid(); fit(); refreshUI();
benchStatus = '';
const md =
`Renderer: ${rendererLabel}, GPU: ${gpuName}, maxTex ${maxTex}, res ${app.renderer.resolution}, viewport ${innerWidth}x${innerHeight}, ${BENCH_MS}ms/scenario (+${WARM_MS}ms warmup), chaos on, grid on, cull on\n` +
`UA: ${navigator.userAgent}\n\n` +
`| map | map path | tokens | strokes | fps | avg ms | p99 ms | worst ms | js ms | frames |\n|---|---|---|---|---|---|---|---|---|---|\n` +
rows.join('\n');
out.value = md;
(window as any).__bench = md;
return md;
}
// ---------- controls ----------
const ctl = document.getElementById('ctl')!;
const refreshers: (() => void)[] = [];
const refreshUI = () => refreshers.forEach((f) => f());
function select(name: string, opts: (string | number)[], get: () => string | number, set: (v: string) => void) {
const l = document.createElement('label'); l.append(name);
const s = document.createElement('select');
for (const o of opts) s.add(new Option(String(o), String(o)));
s.onchange = () => set(s.value);
refreshers.push(() => (s.value = String(get())));
l.append(s); ctl.append(l); refreshers.at(-1)!();
}
function check(name: string, get: () => boolean, set: (v: boolean) => void) {
const l = document.createElement('label'); l.append(name);
const c = document.createElement('input'); c.type = 'checkbox';
c.onchange = () => set(c.checked);
refreshers.push(() => (c.checked = get()));
l.append(c); ctl.append(l); refreshers.at(-1)!();
}
function button(name: string, fn: () => void) {
const b = document.createElement('button'); b.textContent = name; b.onclick = fn; ctl.append(b);
}
select('map size', [2048, 4096, 8192, 16384], () => S.map, (v) => { S.map = +v; buildMap(); buildGrid(); setTokens(); fit(); });
select('tile size', ['auto', 2048, 4096], () => S.tile || 'auto', (v) => { S.tile = v === 'auto' ? 0 : +v; buildMap(); });
const file = document.createElement('input'); file.type = 'file'; file.accept = 'image/*';
file.onchange = async () => { if (file.files?.[0]) { customBitmap = await createImageBitmap(file.files[0]); buildMap(); } };
ctl.append('map image:', file);
check('grid', () => S.grid, (v) => { S.grid = v; grid!.visible = v; });
select('grid cell px', [16, 32, 50, 64, 100, 128, 256], () => S.cell, (v) => { S.cell = +v; buildGrid(); });
select('tokens', [50, 200, 500, 1000, 2000], () => S.n, (v) => { S.n = +v; setTokens(); });
check('chaos (move all every frame)', () => S.chaos, (v) => (S.chaos = v));
check('HP churn (text every frame)', () => S.churn, (v) => (S.churn = v));
check('culling', () => S.cull, (v) => { S.cull = v; setCull(v); });
select('tool (RMB/MMB/2 fingers = pan)', ['move', 'pen'], () => S.tool, (v) => (S.tool = v as 'move' | 'pen'));
button('+200 random strokes', () => randomStrokes(200));
button('clear strokes', clearStrokes);
button('fit view', fit);
const out = document.createElement('textarea'); out.id = 'out'; out.readOnly = true;
button('Run benchmark', () => { void runBench(out); });
button('copy results', () => navigator.clipboard?.writeText(out.value));
ctl.append(out);
// ---------- init ----------
buildMap();
buildGrid();
setTokens();
fit();
refreshUI();
(window as any).__ready = true;
(window as any).__app = { S, world, strokeLayer, stats, runBench: () => runBench(out), randomStrokes, setTokens, buildMap, buildGrid, fit };
if (q.get('bench')) void runBench(out);
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["vite/client"]
},
"include": ["src"]
}
@@ -0,0 +1,9 @@
.devbox/
nimbledeps/
data/tiles/
nimble.paths
tests/t[a-z]*
!tests/*.nim
server
run/
results/*-15s*
@@ -0,0 +1,33 @@
# Handoff: server-authoritative vision prototype -> real VTT
Each item verified against code at the commit named in README. Pointers = where to look.
## Port as-is
- Vision/geometry: `src/geometry.nim` (visibilityPolygon, cellsTouched, inside, moveBlocked) + `tests/tgeometry.nim` (corner tests, run `nimble test`; mutation check `devbox run mutation`, `tools/mutation.sh`). Leak harness (`tools/leak.mjs`, `tools/leakcheck.nim`, `tools/faulttest.sh`) is the acceptance test for any port.
- Limits: token exactly on a wall cannot move off it (`moveBlocked`, inclusive `segsCross`, `geometry.nim:59-85`); vision is O(rays x walls) per token, bbox cull only (`geometry.nim` visibilityPolygon); cellsTouched ~12x the polygon cost (`results/bench.log`).
- Test gap: "shared endpoint: no leak at the vertex" (`tests/tgeometry.nim:29`) still passes with the horizontal arm removed (verified); shared-vertex coverage is only indirect via `hasVertex`. Port a test that fails if either arm is missing.
## Caveats
- All timings are single machine, loopback, power-save CPU; no real network, no client render. Not production numbers (`results/bench.log`, `results/concurrency-final*.log`).
- Boundary epsilon (`RayEps` 1e-4 rad, `geometry.nim:12`; inclusive tests): a token exactly on a vision boundary is ambiguous. Leak checker uses a 0.5 px neighbourhood (`tools/leakcheck.nim:17-20`).
## Leaks / security
- Tile leak: a revealed tile exposes all 256 px, not just explored cells; door changes never affect tiles (static art). `src/server.nim` tile handler, `data/tiles/`.
- Invite links = permanent bearer secrets, cookie `sid` IS the secret, no expiry/rotation (`server.nim` ~L270-290, L346). Needs expiry/rotation + HTTPS. `nginx/nginx.conf` `listen NGX_PORT` has no address => binds 0.0.0.0.
- Move collision checks only the centre path (a->b) and the destination circle (`moveBlocked`, `server.nim:194`), not the swept circle: corner clipping possible.
- Leak test explored/tile checks use the server's own `cellsTouched` (self-consistency, not an independent oracle); see README.
## Protocol / scale
- Full vision polygon (~3 KB) resent on every player move (`bytes/delivery`, `results/concurrency-final1-server.log`) -> send deltas or coarser polygons.
- Explored grid sent whole on connect, one SQLite row per cell (`server.nim` persistCells/loadState) -> bitmap/RLE + per-tile summaries.
## Ops / robustness
- No SIGTERM handler: only `setControlCHook` (SIGINT) prints stats (`server.nim:359`); shutdown = hard kill. Durability rests on WAL commit before ack (`results/final-restart.log`).
- `PRAGMA synchronous=NORMAL` (`server.nim:331`): process kill loses nothing, OS crash/power loss may drop last commits (never corrupts). Tail (~20 ms server worst) unchanged by it: `results/spike/investigation.md`. Real project must choose NORMAL vs FULL deliberately (NORMAL cut avg commit 0.60 -> 0.17 ms, bought no tail).
- Timing instrumentation in `server.nim` (`tm` samples L52, appended per mutation L178; `printStats` L69-80 copies+sorts all samples, called at L174 inside `finish` under the global `lk`) is prototype-only: DO NOT PORT. Real build needs bounded metrics (histogram/ring buffer) computed outside the lock.
- 583 ms intent->ack spike: not reproduced (base worst 73.1/21.8/18.1 ms, fixed 21.3/20.8/21.0), cause undetermined (host-wide stall or node harness pause; original run was ~3.5x slower on average). Server tail >50 ms = SQLite COMMIT stall + lock_wait queued behind it. `results/spike/investigation.md`.
- mummy: send queue is one unbounded server-wide deque, no backpressure for slow clients; `WebSocket` keyed in `conns` by its raw bytes (no hash/==) (`server.nim` Conn/conns, README "mummy suitability").
## Client
- Fog masks are Graphics that grow unbounded (`client/src/main.ts` ~L98, shortcut comment) -> bake to RenderTexture. One Pixi `Text` per token (`main.ts:55`) is heavy -> BitmapText.
- Browser rendering never verified (no browser in build env): only reducer (`client/src/state.test.ts`, `results/client-tests.log`) and HTTP/WS paths are tested.
@@ -0,0 +1,32 @@
# Notes (feeds README Findings)
## Geometry edge-case log
- BROKE: `cellsTouched` returned nothing for a polygon wholly inside one cell (no edge crosses the cell, no cell corner inside poly). FIX: also hit if a polygon vertex lies in the cell.
- Test bug (not code): "shared endpoint" case asserted a point hugging a wall the token stands on line with was hidden; it is legitimately visible. Removed. RESTORED with the correct expectation (token on the arm line: point 5 px below visible, 5 px above hidden); weak corner-case tests (box corner, collinear, T-junction, token at endpoint, free-standing wall, behind-viewer fan) got visible+hidden probes, no geometry bug found.
- Design choices that avoided bugs (all pass first run): rays to each endpoint at -eps/0/+eps (1e-4 rad); ray/segment u-range inclusive with 1e-9 tolerance so no cracks at shared vertices / T-junctions; parallel (collinear) rays skipped since neighbouring +-eps rays cover them; token on an endpoint: that endpoint skipped for ray generation and hits at t<=1e-9 ignored.
- Moves: inclusive intersection (touching = blocked) so no squeezing through shared vertices. Limit: token standing exactly on a wall can't move off it; server must keep tokens off walls.
- Vision circle = inscribed 64-gon (max error r*(1-cos(pi/64)) ~ 0.12% of r).
## Layout
- Hand-authored (no RNG): reproducible by construction. 6 rooms, 7 corridors, 1 pillar (R1), T-junction (partition at x=3000 in R3 ends mid south wall), collinear split (R3 north wall at x=3200), long thin corridor (R2-R5, 1024x64), doors: R2 west (closed), R5 north (open).
## Phase 2a (server)
- Port 8080 was taken on dev box (docker puma): `PORT=8088 devbox run server|nginx` (sed into run/nginx.conf; server prints invite origin from PORT). Default 8080.
- Verified: WS path tricks rejected (webby 400 on %2f/%00); `/_tiles/` 404 when hit directly.
- Non-owned move => `error` (not moveAck: server pos of an unseen token would leak).
- `by` = "gm"|"A"|"B" (conn role name).
- Smoke: `devbox run smoke` (isolated via tools/withserver.sh: server+nginx on 19000/18088, run/test/invites.txt written by server).
## Phase 3
- BUG (client): reconnect did not reset state (stale tokens/explored/sprites); server already resends hello+state on every connect. FIX: reducer resets on `hello`, main.ts clears sprites/masks/doors/pending (tiles kept). Reducer test added.
- BUG (client): door click `if (d)` would ignore door id 0. FIX: `!== null`.
- Leak scenario bugs were scenario bugs (diagonal steps through walls), not server bugs; server answered `ok:false` as designed.
- Leak checker B-string check initially flagged legit `remove{id:"B"}`; exempted token/remove.
- Perf finding: cellsTouched (~0.46 ms) is ~12x the visibility polygon (~0.04 ms) (results/bench.log); per-move vision_ms is dominated by explored-cell computation.
## Post-phase-3 manual-test bug
- BUG (server, geometry.nim): `visibilityPolygon` sorted circle-segment angles in [0,2pi) together with wall-endpoint atan2 angles in (-pi,pi] -> fan vertices out of angular order -> bow-tie polygon, even-odd `inside`/`cellsTouched` dropped regions (tokens in plain LOS not shown, explored/tiles missing). Position dependent. FIX: wrap circle angles with atan2(sin,cos).
- Why tests missed it: leakcheck recomputed its oracle with the same `visibilityPolygon` (only checked "nothing extra leaks", never "everything visible shows"), and only subject A was checked. Now: independent clear-LOS (segment test) oracle, `SUBJECT=A|B`, geometry regression test.
## Token radius bug
- BUG (server): move validation treated tokens as points; client drew radius 20, so tokens stopped half inside walls/pillar/doors. FIX: `moveBlocked(..., r)` also requires dest circle clear (point-segment dist >= r); `tokenRadius` in scene.json + `hello`. 64 px corridors/doorways leave 12 px slack each side of the centreline. Leak scenario steps adjusted to stop >= r from the closed door/wall.
@@ -0,0 +1,123 @@
# Server-authoritative vision prototype (throwaway)
Question: can the server alone decide what each player sees (tokens, fog, map tiles) so a modified client learns nothing hidden? Stack: Nim + mummy (WS/HTTP), SQLite, nginx (static + `X-Accel-Redirect` tiles), Vite + TS + Pixi v8 client.
## Run (everything through devbox)
```
devbox run gen # data/scene.json + data/tiles/*.png (deterministic, hand-authored layout)
devbox run client # npm install, reducer test, tsc + vite build -> client/dist
PORT=8088 devbox run server # :9000 backend, prints invite links, writes run/invites.txt
PORT=8088 devbox run nginx # public port; separate terminal
```
`PORT` (default 8080) is only the public nginx port and the origin printed in invite links. On the dev box 8080 is taken by unrelated docker, hence 8088 in all examples.
Open the 3 invite links (gm, A, B) each in a **separate browser or profile**. The link sets cookie `sid=<secret>` (HttpOnly, SameSite=Strict) and redirects to `/`; the WS and tile requests authenticate by that cookie. One cookie jar = one identity, so two links in the same profile overwrite each other. Same cookie in two tabs = same player (shared vision, both connections synced).
Browser rendering was NOT verified (no browser in the build environment): only HTTP/WS behaviour is scripted-tested (served `/`, JS bundle 200, join -> cookie, WS through nginx, tiles).
## Tests
| cmd | what |
|---|---|
| `devbox run test` | regen map + `nimble test` (geometry), smoke, leaktest, faulttest, restart, concurrency (DUR=15; its log `results/concurrency-15s*` is gitignored) |
| `devbox run clienttest` | client reducer tests (`client/src/state.test.ts` via `npm run check`, incl. reconnect reset) -> `results/client-tests.log`; `devbox run client` also runs them |
| `devbox run smoke` | fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks |
| `devbox run leaktest` | runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays the transcript. Output per subject: `results/leak-A.log`, `results/leak-B.log` (committed), transcripts `results/leak-{A,B}.jsonl` (1.1-1.3 MB each, 2.4 MB total, committed) |
| `devbox run faulttest` | deliberate leaks: builds the server with `-d:leakfault` (hook absent from the normal build, asserted by grepping the clean binary for `LEAK_FAULT`), injects 8 faults one at a time (`LEAK_FAULT=`): hidden token sent (`hidden`), wall data to player (`walls`), unexplored tile 200 (`tile`), visible token withheld (`withhold`), B's vision / explored / ownership sent to A (`other-vision`, `other-explored`, `other-owner`), missing `remove` (`noremove`). Passes only if the checker fails each with exactly the expected failure-class set (classes: HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE, plus collateral OWN_VIEW / EXPLORED) and the clean build still passes. Details in `results/faults.log` (committed), summary `results/final-faulttest.log` |
| `devbox run restart` | isolated server, moves A/B/monsters, toggles doors, A explores a new area; stops with SIGTERM then (second round of changes) SIGKILL, restarts on the same DB; asserts invite secrets, token positions, doors, vision, explored grids per role and the full hello+state a reconnecting client receives are identical (gseq excluded: in-memory). Note: the server has no SIGTERM handler, so SIGTERM is as abrupt as SIGKILL; durability rests on the SQLite WAL commit before ack (`synchronous=NORMAL`: survives process kill, may lose the last commits on OS crash/power loss; see `results/spike/investigation.md`) |
| `devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token; logs `results/concurrency-<TAG>.log` + `...-server.log` (server STATS; TAG defaults to `<DUR>s`; final runs use `TAG=final1..3`) |
| `devbox run mutation` | geometry mutation check on a temp copy (`tools/mutation.sh`): (a) no ±RayEps rays, (b) upper segment end exclusive, (c) lower end exclusive; control must pass, each mutation must fail a corner test. Logs `results/mutation-{a,b,c}.log` |
| `devbox run bench` | vision microbench, log `results/bench.log` |
Other saved outputs: `results/nimble-test.log` (`nimble test`), `results/mutation-summary.log`, `results/final-{leaktest,faulttest,restart}.log`, `results/smoke.log`, `results/final-rc.txt` (exit code of every final-run step), `results/spike/` (historical 583 ms investigation, earlier commits, see its `investigation.md`).
Tests are isolated: `tools/withserver.sh` uses `run/test/` (own DB, invites, nginx conf/logs) and ports 18088 (nginx) / 19000 (server), overridable via `TEST_PORT`/`TEST_BACKEND_PORT`; the live session on 8088/9000 and `run/` are never touched. Server stats print on stop into `run/test/server.log`.
### Leak test asserts
Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored is recomputed with `geometry.nim`, never from A's own messages. Per gseq:
- (a) A receives only hello/vision/explored/token/remove/moveAck; no wall-like keys (walls, door, open, a, b, segments...) anywhere.
- (b) every token A is sent is inside the independently computed polygon (0.5 px boundary tolerance); every token inside it IS in A's view (completeness); view positions == truth; A's `vision` polygon equals the recomputed one (1e-6); A's explored set == recomputed set.
- (c) `remove` arrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes.
- (d) 256 tiles requested per sweep (A: 39 sweeps = 9984 requests, B: 29 = 7424; incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403.
- (e) A never gets B-bound info: no B string outside token/remove, no `by:B` on others' tokens, hello tokens == ["A"], no error msgs.
**Caveat (self-consistency, not an independent oracle):** the explored-set check in (b) and the tile 200/403 check in (d) recompute the expected values with the server's own `geometry.nim` (`visibilityPolygon` + `cellsTouched`). They prove the server sends/gates exactly what its own geometry says and that nothing else leaks, not that `cellsTouched` is geometrically right. Only the token-visibility checks (clear-LOS segment oracle + polygon containment) are independent of the explored-cell computation.
Negative control: automated, `devbox run faulttest` (above).
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Result (`results/leak-A.log`): PASS (218 gseq groups, 467 A msgs, 4 other tokens seen, 4 removes, tiles 1709 x 200 / 8275 x 403, 2142 explored cells, 0 failures). Fault test: 8/8 faults caught with the exact class set + clean build passes (`results/final-faulttest.log`).
Result (`results/leak-B.log`): PASS (218 gseq groups, 217 B msgs, 3 other tokens seen, 3 removes, tiles 686 x 200 / 6738 x 403, 1114 explored cells, 0 failures).
### Concurrency result (60 s x3, all PASS; `results/concurrency-final{1,2,3}.log`, server side `...-server.log`)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Load ~223 intents/s (final1: A 28, B 28, 6 monsters 167/s) + door toggles every 1-3 s. final1: 13748 mutations (10286 monster + 3400 player moves + 62 doors, `results/concurrency-final1-server.log`, = final gseq), no crash, 0 errors, gseq never went backwards at any client, every intent acked (sent == acks for all 3 clients; nacks = blocked random-walk moves, final1: GM 13, A 26, B 0), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot (the script asserts this; PASS line).
| run | intent->ack avg | p99 | worst | source |
|---|---|---|---|---|
| final1 | 1.40 ms | 4.58 ms | 20.31 ms | `concurrency-final1.log` |
| final2 | 1.50 ms | 4.98 ms | 21.73 ms | `concurrency-final2.log` |
| final3 | 1.43 ms | 4.75 ms | 24.72 ms | `concurrency-final3.log` |
No `SLOW` (>50 ms) line in any final run. The 583 ms outlier seen once in an earlier, differently-built run did not reproduce and has no known cause (`results/spike/investigation.md`).
### Other final-run results (all PASS; exit codes in `results/final-rc.txt`)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
All results in `results/` were produced at code commit `18c9884` (last code/test-script commit; later commits are docs/results only).
| step | result | file |
|---|---|---|
| `nimble test` | 33 checks OK | `results/nimble-test.log` |
| `devbox run mutation` | control passes; a, b, c each fail >= 1 corner test (1, 2, 2) | `results/mutation-summary.log`, `results/mutation-{a,b,c}.log` |
| faulttest | 8/8 faults caught, clean build passes | `results/final-faulttest.log`, `results/faults.log` |
| restart | PASS | `results/final-restart.log` |
| smoke | PASS | `results/smoke.log` |
| client tests | 4/4 pass | `results/client-tests.log` |
## Measurements (laptop, release build, localhost)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Sources: C = `results/concurrency-final1.log`, S = `results/concurrency-final1-server.log` (server STATS), B = `results/bench.log`.
| metric | avg | p95 | worst | source |
|---|---|---|---|---|
| vision recompute per player move (server, incl. cellsTouched + diff) | 1.18 ms | - | 4.55 ms | S `vision_ms move-player` |
| vision recompute per monster move | 0.000 ms (no vision) | - | 0.024 ms | S `vision_ms move-monster` |
| door toggle (2 roles) | 0.20 ms | - | 0.30 ms | S `vision_ms door` |
| server total per mutation (lock wait + vision + sqlite + send) | 0.70 ms | - (p99 3.71) | 19.63 ms | S `timing_ms total` |
| bench: 1 visibility polygon | 0.038 ms | - | 0.18 ms | B |
| bench: 6 polygons | 0.205 ms | - | 0.29 ms | B |
| bench: 1 poly + cellsTouched | 0.451 ms | - | 0.98 ms | B |
| bench: 6 polys + cellsTouched | 2.95 ms | - | 3.73 ms | B |
| latency intent -> ack (sender, via nginx) | 1.40 ms | 2.99 ms | 20.31 ms | C |
| latency intent -> arrival at other clients | 2.04 ms | 3.66 ms | 18.94 ms | C |
Bytes per delivery (only recipients that got something; S `bytes/delivery`):
| mutation | recipient | avg B |
|---|---|---|
| monster move | GM | 243.5 |
| monster move | player who sees it | 145.5 (B) - 146.0 (A) |
| player move | the mover (ack + token + new `vision` + `explored` diff) | 3359 (B) - 3653 (A) (worst 4.9 KB) |
| player move | GM | 144.6 |
| door toggle | GM | 44.8 |
"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.205 ms polys, 2.95 ms with cell marking; B). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players.
## Findings
**Worked**
- Server-only filtering is simple under one global lock: validate -> mutate -> recompute -> persist -> per-connection diff -> send. Players never receive walls/doors/other tokens; leak test finds nothing.
- Per-connection `known` map gives correct enter/leave (`token`/`remove`) and a fresh connection gets full state; clients reset on `hello`.
- Token radius `tokenRadius` (20 px, data/scene.json via tools/genmap.mjs) is server-authoritative and sent in `hello` (client falls back to 20 if absent). A move is accepted only if the centre path crosses no blocking wall AND the destination circle is >= r from every blocking wall (open doors ignored). Only the destination is checked, so a token already overlapping a wall (closed door, legacy DB) can leave. Vision origin stays the token centre.
- Tile gating via nginx `internal` + `X-Accel-Redirect` after Nim checks explored cells; `/_tiles/` unreachable directly.
- Moves: inclusive segment test blocks squeezing through shared vertices; non-owned/malformed moves get `error` (not an ack, an ack would echo the position of an unseen token).
**Edge cases that broke (see NOTES.md)**: `cellsTouched` missed polygons wholly inside one cell (fix: vertex-in-cell test); client did not reset on reconnect (fix: reset on `hello`); door id 0 falsy check; leak scenario steps crossing walls diagonally (scenario bug, server correctly refused).
**mummy suitability**
- Send is thread-safe by construction: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, 13748 mutations, ~36k messages (C: 24054 + 6093 + 6035 recv, final1): no crash, no reorder, no loss, consistent final views.
- Caveats: `WebSocket` has no `==`/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1.18 ms/player move, S). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows).
- Pinned to an exact commit (no tags upstream).
**Worries for a real VTT**
- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~12x costlier than the polygon itself (0.451 vs 0.038 ms, B) and dominates.
- Explored grid: 128x128 cells here; explored set sent whole on connect, kept in memory + one SQLite row per cell. Larger maps need run-length/bitmap + per-tile summaries.
- Full `vision` polygon resent on each player move (most of the ~3.4-3.7 KB per mover delivery); needs deltas or lower-res polygons.
- Cookie = the secret (bearer, no rotation/expiry); invite links in logs/URLs are credentials. HTTPS needed beyond localhost.
- Tiles do not update when a door changes (static art; only fog changes); a revealed tile stays visible forever and leaks the whole tile (256 px), not just the explored cells; tile granularity vs exploredCell is a leak/size tradeoff.
- Polygon boundary epsilon: ray nudges (1e-4 rad) and inclusive tolerances; tokens right on the boundary are ambiguous (tests use a 0.5 px tolerance). A token standing exactly on a wall cannot move off it; server must keep tokens off walls.
- Fog masks are Graphics that grow unbounded (explored rects re-tessellated); needs baking to a RenderTexture. Pixi `Text` per token is heavy vs `BitmapText` at scale.
- Browser rendering (fog masks, drag, reconnect visuals) is unverified: only the reducer and HTTP/WS paths were tested.
- Timing trusts a single machine/loopback; latencies exclude real network and client render.
@@ -0,0 +1,2 @@
node_modules/
dist/
@@ -0,0 +1,6 @@
<!doctype html>
<meta charset="utf-8"><title>servervision</title>
<style>html,body{margin:0;height:100%;overflow:hidden;background:#000}
#bar{position:fixed;top:0;left:0;right:0;padding:2px 8px;font:12px monospace;color:#0f0;background:#000a;z-index:1;pointer-events:none}</style>
<div id="bar"></div>
<script type="module" src="/src/main.ts"></script>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
{
"name": "servervision-client",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"check": "node --test src/state.test.ts"
},
"dependencies": { "pixi.js": "^8.0.0" },
"devDependencies": { "typescript": "^5.6.0", "vite": "^6.0.0", "@types/node": "^22.0.0" }
}
@@ -0,0 +1,174 @@
import { Application, Container, Graphics, Sprite, Text, Texture } from 'pixi.js';
import { apply, newState, tilesOfCells, type Tok, type V2 } from './state.ts';
const s = newState();
const bar = document.getElementById('bar')!;
let conn = 'connecting';
// identity from hello.tokens: a player owns only the token whose id is their slot ("A"/"B")
const who = () => (s.role === 'player' ? `player ${s.owned[0] ?? '?'}` : s.role ?? '?');
const status = () => (bar.textContent = `${who()} conn=${conn} gseq=${s.gseq}${s.lastError ? ' err=' + s.lastError : ''}`);
const app = new Application();
await app.init({ resizeTo: window, background: 0x000000, antialias: true });
document.body.appendChild(app.canvas);
const world = new Container();
const tilesL = new Container();
const doorsG = new Graphics();
const tokensL = new Container();
// Fog: dim = everywhere except current vision; black = everywhere except explored. Inverse stencil masks.
const dim = new Graphics();
const black = new Graphics();
const visionM = new Graphics();
const exploredM = new Graphics();
dim.addChild(visionM); dim.setMask({ mask: visionM, inverse: true });
black.addChild(exploredM); black.setMask({ mask: exploredM, inverse: true });
world.addChild(tilesL, dim, black, doorsG, tokensL);
app.stage.addChild(world);
// ---- tiles ----
const tileState = new Map<string, 'loading' | 'ok' | 'fail'>();
function loadTile(key: string) {
if (tileState.has(key) && tileState.get(key) !== 'fail') return;
tileState.set(key, 'loading');
fetch(`/tiles/${key}.png`)
.then((r) => (r.ok ? r.blob() : Promise.reject(r.status))) // 403 = not available (yet)
.then((b) => createImageBitmap(b))
.then((bmp) => {
const [x, y] = key.split('_').map(Number);
const sp = new Sprite(Texture.from(bmp));
sp.position.set(x * s.tileSize, y * s.tileSize);
tilesL.addChild(sp);
tileState.set(key, 'ok');
})
.catch(() => tileState.set(key, 'fail'));
}
// ---- tokens ----
const sprites = new Map<string, Container>();
const dragging = new Map<string, true>();
function drawToken(t: Tok) {
let c = sprites.get(t.id);
if (!c) {
c = new Container();
const g = new Graphics().circle(0, 0, s.tokenR).fill(t.mine ? 0x3a9d3a : 0xb03030).stroke({ width: 3, color: 0xffffff });
const l = new Text({ text: t.name, style: { fontSize: 14, fill: 0xffffff, stroke: { color: 0, width: 3 } } });
l.anchor.set(0.5, 0); l.y = s.tokenR + 2;
c.addChild(g, l);
tokensL.addChild(c); sprites.set(t.id, c);
}
if (!dragging.has(t.id)) c.position.set(t.pos[0], t.pos[1]); // incoming pos ignored while locally dragging
}
const canDrag = (t: Tok) => s.role === 'gm' || t.mine;
// ---- ws ----
let ws: WebSocket;
const send = (o: object) => ws.readyState === 1 && ws.send(JSON.stringify(o));
let reqId = 0;
const pending = new Map<number, string>();
function onMsg(m: any) {
if (m.t === 'moveAck') {
const id = pending.get(m.reqId); pending.delete(m.reqId);
if (!m.ok && id && !dragging.has(id)) { // snap to server pos
const t = s.tokens.get(id), c = sprites.get(id);
if (t) t.pos = m.pos;
c?.position.set(m.pos[0], m.pos[1]);
}
s.gseq = m.gseq;
return;
}
const fresh = apply(s, m);
switch (m.t) {
case 'hello':
for (const c of sprites.values()) c.destroy({ children: true });
sprites.clear(); pending.clear(); visionM.clear(); exploredM.clear(); doorsG.clear(); // tiles kept: explored only grows
fit();
if (s.role === 'gm') { dim.visible = black.visible = false; const n = Math.ceil(s.w / s.tileSize), k = Math.ceil(s.h / s.tileSize); for (let y = 0; y < k; y++) for (let x = 0; x < n; x++) loadTile(x + '_' + y); }
else { for (const g of [dim, black]) g.clear().rect(0, 0, s.w, s.h).fill(0x000000); dim.alpha = 0.6; }
break;
case 'walls': case 'door': drawDoors(); break;
case 'vision':
visionM.clear();
for (const p of s.polys) visionM.poly(p.flat()).fill(0xffffff);
break;
case 'explored':
if (fresh!.length) {
for (const [cx, cy] of fresh!) exploredM.rect(cx * s.cell, cy * s.cell, s.cell, s.cell);
exploredM.fill(0xffffff); // shortcut: Graphics grows unbounded, re-tessellates; bake to RenderTexture when cells >~50k
// retry failed/unrequested tiles under newly explored cells
for (const k of tilesOfCells(fresh!, s)) loadTile(k);
}
break;
case 'token': drawToken(s.tokens.get(m.id)!); break;
case 'remove': sprites.get(m.id)?.destroy({ children: true }); sprites.delete(m.id); break;
}
}
function connect() {
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
ws.onopen = () => { conn = 'open'; status(); };
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // state reset on hello; server resends everything
ws.onmessage = (e) => { onMsg(JSON.parse(e.data)); status(); };
}
// ---- walls (GM only) ----
function drawDoors() {
doorsG.clear();
for (const w of s.walls.values()) {
doorsG.moveTo(...w.a).lineTo(...w.b).stroke({ width: w.door ? 6 : 3, color: w.door ? (w.open ? 0x40ff40 : 0xff4040) : 0xffff00 });
}
}
function pickDoor(p: V2): string | null {
const tol = 10 / world.scale.x;
for (const w of s.walls.values()) {
if (!w.door) continue;
const [ax, ay] = w.a, [bx, by] = w.b, dx = bx - ax, dy = by - ay;
const u = Math.max(0, Math.min(1, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy || 1)));
if (Math.hypot(p[0] - (ax + u * dx), p[1] - (ay + u * dy)) < tol) return w.id;
}
return null;
}
// ---- camera + input ----
function fit() { const k = Math.min(innerWidth / s.w, innerHeight / s.h); world.scale.set(k); world.position.set(0, 0); }
const toWorld = (e: PointerEvent | WheelEvent): V2 => [(e.clientX - world.x) / world.scale.x, (e.clientY - world.y) / world.scale.x];
let pan: { x: number; y: number } | null = null;
let drag: { id: string; dx: number; dy: number; last: number } | null = null;
const moveTok = (id: string, pos: V2) => { const r = ++reqId; pending.set(r, id); send({ t: 'move', reqId: r, id, pos }); };
const cv = app.canvas;
cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId);
const p = toWorld(e);
for (const [id, c] of [...sprites].reverse()) { // O(N) hit test on press
const t = s.tokens.get(id)!;
if (canDrag(t) && Math.hypot(p[0] - c.x, p[1] - c.y) <= s.tokenR) { drag = { id, dx: c.x - p[0], dy: c.y - p[1], last: 0 }; dragging.set(id, true); return; }
}
if (s.role === 'gm') { const d = pickDoor(p); if (d !== null) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
pan = { x: e.clientX - world.x, y: e.clientY - world.y };
});
cv.addEventListener('pointermove', (e) => {
if (drag) {
const p = toWorld(e), pos: V2 = [p[0] + drag.dx, p[1] + drag.dy];
sprites.get(drag.id)!.position.set(pos[0], pos[1]); // optimistic
const now = performance.now();
if (now - drag.last >= 50) { drag.last = now; moveTok(drag.id, pos); }
} else if (pan) world.position.set(e.clientX - pan.x, e.clientY - pan.y);
});
const up = () => {
if (drag) {
const c = sprites.get(drag.id)!, pos: V2 = [c.x, c.y];
moveTok(drag.id, pos); // final
const t = s.tokens.get(drag.id); if (t) t.pos = pos;
dragging.delete(drag.id); drag = null;
}
pan = null;
};
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('wheel', (e) => {
e.preventDefault();
const p = toWorld(e), k = Math.max(0.05, Math.min(8, world.scale.x * Math.exp(-e.deltaY * 0.001)));
world.scale.set(k); world.position.set(e.clientX - p[0] * k, e.clientY - p[1] * k);
}, { passive: false });
status();
connect();
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { apply, newState, tilesOfCells } from './state.ts';
test('protocol reducer: fake server script', () => {
const s = newState();
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
assert.equal(s.role, 'player');
assert.equal(s.walls.size, 0); // players never get walls
assert.deepEqual(apply(s, { t: 'explored', gseq: 2, cells: [[0, 0], [1, 0]] }), [[0, 0], [1, 0]]);
assert.deepEqual(apply(s, { t: 'explored', gseq: 3, cells: [[1, 0], [2, 0]] }), [[2, 0]]); // diff accumulates
assert.equal(s.explored.size, 3);
apply(s, { t: 'vision', gseq: 4, polys: [[[0, 0], [1, 0], [1, 1]]] });
apply(s, { t: 'vision', gseq: 5, polys: [] });
assert.equal(s.polys.length, 0); // full replacement
apply(s, { t: 'token', gseq: 6, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
apply(s, { t: 'token', gseq: 7, id: 'a', name: 'A', kind: 'pc', pos: [7, 8], mine: true });
assert.deepEqual(s.tokens.get('a')!.pos, [7, 8]);
apply(s, { t: 'remove', gseq: 8, id: 'a' });
assert.equal(s.tokens.size, 0);
assert.equal(s.gseq, 8);
});
test('gm walls + door', () => {
const s = newState();
apply(s, { t: 'walls', gseq: 1, walls: [{ id: 'd1', a: [0, 0], b: [10, 0], door: true, open: false }] });
apply(s, { t: 'door', gseq: 2, id: 'd1', open: true });
assert.equal(s.walls.get('d1')!.open, true);
});
test('tilesOfCells', () => {
const g = { w: 4096, h: 4096, tileSize: 512, cell: 64 };
assert.deepEqual([...tilesOfCells([[0, 0], [7, 7]], g)], ['0_0']);
assert.deepEqual([...tilesOfCells([[8, 0]], g)], ['1_0']);
assert.deepEqual([...tilesOfCells([[0, 0]], { ...g, cell: 1024 })].length, 4); // cell spans 2x2 tiles
});
test('hello resets state (reconnect)', () => {
const s = newState();
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
apply(s, { t: 'token', gseq: 2, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
apply(s, { t: 'explored', gseq: 3, cells: [[0, 0]] });
apply(s, { t: 'hello', gseq: 9, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
assert.equal(s.tokens.size, 0);
assert.equal(s.explored.size, 0);
assert.equal(s.gseq, 9);
});
@@ -0,0 +1,71 @@
// Pure protocol state + reducer (no Pixi) so it can be checked without a server.
export type V2 = [number, number];
export type Tok = { id: string; name: string; kind: string; pos: V2; mine: boolean };
export type Wall = { id: string; a: V2; b: V2; door: boolean; open: boolean };
export type Msg = { t: string; gseq: number; [k: string]: any };
export type State = {
role: 'gm' | 'player' | null;
owned: string[];
w: number; h: number; tileSize: number; cell: number; tokenR: number;
walls: Map<string, Wall>;
polys: V2[][];
explored: Set<string>;
tokens: Map<string, Tok>;
gseq: number;
lastError: string;
};
export const newState = (): State => ({
role: null, owned: [], w: 0, h: 0, tileSize: 512, cell: 32, tokenR: 20,
walls: new Map(), polys: [], explored: new Set(), tokens: new Map(), gseq: 0, lastError: '',
});
// Returns newly-added explored cells (only for t=explored), else undefined.
export function apply(s: State, m: Msg): V2[] | undefined {
s.gseq = m.gseq;
switch (m.t) {
case 'hello': // server resends full state after hello: start clean (reconnect)
Object.assign(s, newState(), { gseq: m.gseq });
s.role = m.role; s.owned = m.tokens; s.w = m.world.w; s.h = m.world.h;
s.tileSize = m.tileSize; s.cell = m.exploredCell; s.tokenR = m.tokenRadius ?? s.tokenR; // ?? : older server omits it
break;
case 'walls':
s.walls = new Map((m.walls as Wall[]).map((w) => [w.id, w]));
break;
case 'door': {
const w = s.walls.get(m.id);
if (w) w.open = m.open;
break;
}
case 'vision': s.polys = m.polys; break;
case 'explored': {
const fresh: V2[] = [];
for (const c of m.cells as V2[]) {
const k = c[0] + ',' + c[1];
if (!s.explored.has(k)) { s.explored.add(k); fresh.push(c); }
}
return fresh;
}
case 'token':
s.tokens.set(m.id, { id: m.id, name: m.name, kind: m.kind, pos: m.pos, mine: !!m.mine });
break;
case 'remove': s.tokens.delete(m.id); break;
case 'error': s.lastError = m.msg; break;
// moveAck handled by the view (needs pending/drag state)
}
return undefined;
}
// Tile keys "x_y" overlapped by the given explored cells.
export function tilesOfCells(cells: V2[], s: Pick<State, 'w' | 'h' | 'tileSize' | 'cell'>): Set<string> {
const out = new Set<string>();
const maxX = Math.ceil(s.w / s.tileSize) - 1, maxY = Math.ceil(s.h / s.tileSize) - 1;
for (const [cx, cy] of cells) {
const x0 = Math.floor((cx * s.cell) / s.tileSize), x1 = Math.floor(((cx + 1) * s.cell - 1) / s.tileSize);
const y0 = Math.floor((cy * s.cell) / s.tileSize), y1 = Math.floor(((cy + 1) * s.cell - 1) / s.tileSize);
for (let y = Math.max(0, y0); y <= Math.min(maxY, y1); y++)
for (let x = Math.max(0, x0); x <= Math.min(maxX, x1); x++) out.add(x + '_' + y);
}
return out;
}
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler",
"lib": ["ES2022", "DOM"], "strict": true, "noEmit": true, "skipLibCheck": true,
"allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "types": ["node"]
},
"include": ["src"]
}
@@ -0,0 +1 @@
export default { base: './', build: { target: 'es2022' } };
@@ -0,0 +1,954 @@
{
"world": {
"w": 4096,
"h": 4096
},
"tileSize": 256,
"visionRadius": 400,
"tokenRadius": 20,
"exploredCell": 32,
"walls": [
{
"id": 0,
"a": [
256,
256
],
"b": [
1024,
256
],
"door": false,
"open": false
},
{
"id": 1,
"a": [
256,
1024
],
"b": [
608,
1024
],
"door": false,
"open": false
},
{
"id": 2,
"a": [
672,
1024
],
"b": [
1024,
1024
],
"door": false,
"open": false
},
{
"id": 3,
"a": [
256,
256
],
"b": [
256,
1024
],
"door": false,
"open": false
},
{
"id": 4,
"a": [
1024,
256
],
"b": [
1024,
608
],
"door": false,
"open": false
},
{
"id": 5,
"a": [
1024,
672
],
"b": [
1024,
1024
],
"door": false,
"open": false
},
{
"id": 6,
"a": [
1536,
256
],
"b": [
2304,
256
],
"door": false,
"open": false
},
{
"id": 7,
"a": [
1536,
1024
],
"b": [
1888,
1024
],
"door": false,
"open": false
},
{
"id": 8,
"a": [
1952,
1024
],
"b": [
2304,
1024
],
"door": false,
"open": false
},
{
"id": 9,
"a": [
1536,
256
],
"b": [
1536,
608
],
"door": false,
"open": false
},
{
"id": 10,
"a": [
1536,
608
],
"b": [
1536,
672
],
"door": true,
"open": false
},
{
"id": 11,
"a": [
1536,
672
],
"b": [
1536,
1024
],
"door": false,
"open": false
},
{
"id": 12,
"a": [
2304,
256
],
"b": [
2304,
608
],
"door": false,
"open": false
},
{
"id": 13,
"a": [
2304,
672
],
"b": [
2304,
1024
],
"door": false,
"open": false
},
{
"id": 14,
"a": [
2816,
256
],
"b": [
3200,
256
],
"door": false,
"open": false
},
{
"id": 15,
"a": [
2816,
1024
],
"b": [
3168,
1024
],
"door": false,
"open": false
},
{
"id": 16,
"a": [
3232,
1024
],
"b": [
3584,
1024
],
"door": false,
"open": false
},
{
"id": 17,
"a": [
2816,
256
],
"b": [
2816,
608
],
"door": false,
"open": false
},
{
"id": 18,
"a": [
2816,
672
],
"b": [
2816,
1024
],
"door": false,
"open": false
},
{
"id": 19,
"a": [
3584,
256
],
"b": [
3584,
1024
],
"door": false,
"open": false
},
{
"id": 20,
"a": [
256,
2048
],
"b": [
608,
2048
],
"door": false,
"open": false
},
{
"id": 21,
"a": [
672,
2048
],
"b": [
1024,
2048
],
"door": false,
"open": false
},
{
"id": 22,
"a": [
256,
2816
],
"b": [
1024,
2816
],
"door": false,
"open": false
},
{
"id": 23,
"a": [
256,
2048
],
"b": [
256,
2816
],
"door": false,
"open": false
},
{
"id": 24,
"a": [
1024,
2048
],
"b": [
1024,
2400
],
"door": false,
"open": false
},
{
"id": 25,
"a": [
1024,
2464
],
"b": [
1024,
2816
],
"door": false,
"open": false
},
{
"id": 26,
"a": [
1536,
2048
],
"b": [
1888,
2048
],
"door": false,
"open": false
},
{
"id": 27,
"a": [
1888,
2048
],
"b": [
1952,
2048
],
"door": true,
"open": true
},
{
"id": 28,
"a": [
1952,
2048
],
"b": [
2304,
2048
],
"door": false,
"open": false
},
{
"id": 29,
"a": [
1536,
2816
],
"b": [
2304,
2816
],
"door": false,
"open": false
},
{
"id": 30,
"a": [
1536,
2048
],
"b": [
1536,
2400
],
"door": false,
"open": false
},
{
"id": 31,
"a": [
1536,
2464
],
"b": [
1536,
2816
],
"door": false,
"open": false
},
{
"id": 32,
"a": [
2304,
2048
],
"b": [
2304,
2400
],
"door": false,
"open": false
},
{
"id": 33,
"a": [
2304,
2464
],
"b": [
2304,
2816
],
"door": false,
"open": false
},
{
"id": 34,
"a": [
2816,
2048
],
"b": [
3168,
2048
],
"door": false,
"open": false
},
{
"id": 35,
"a": [
3232,
2048
],
"b": [
3584,
2048
],
"door": false,
"open": false
},
{
"id": 36,
"a": [
2816,
2816
],
"b": [
3584,
2816
],
"door": false,
"open": false
},
{
"id": 37,
"a": [
2816,
2048
],
"b": [
2816,
2400
],
"door": false,
"open": false
},
{
"id": 38,
"a": [
2816,
2464
],
"b": [
2816,
2816
],
"door": false,
"open": false
},
{
"id": 39,
"a": [
3584,
2048
],
"b": [
3584,
2816
],
"door": false,
"open": false
},
{
"id": 40,
"a": [
3200,
256
],
"b": [
3584,
256
],
"door": false,
"open": false
},
{
"id": 41,
"a": [
1024,
608
],
"b": [
1536,
608
],
"door": false,
"open": false
},
{
"id": 42,
"a": [
1024,
672
],
"b": [
1536,
672
],
"door": false,
"open": false
},
{
"id": 43,
"a": [
2304,
608
],
"b": [
2816,
608
],
"door": false,
"open": false
},
{
"id": 44,
"a": [
2304,
672
],
"b": [
2816,
672
],
"door": false,
"open": false
},
{
"id": 45,
"a": [
1024,
2400
],
"b": [
1536,
2400
],
"door": false,
"open": false
},
{
"id": 46,
"a": [
1024,
2464
],
"b": [
1536,
2464
],
"door": false,
"open": false
},
{
"id": 47,
"a": [
2304,
2400
],
"b": [
2816,
2400
],
"door": false,
"open": false
},
{
"id": 48,
"a": [
2304,
2464
],
"b": [
2816,
2464
],
"door": false,
"open": false
},
{
"id": 49,
"a": [
1888,
1024
],
"b": [
1888,
2048
],
"door": false,
"open": false
},
{
"id": 50,
"a": [
1952,
1024
],
"b": [
1952,
2048
],
"door": false,
"open": false
},
{
"id": 51,
"a": [
3168,
1024
],
"b": [
3168,
2048
],
"door": false,
"open": false
},
{
"id": 52,
"a": [
3232,
1024
],
"b": [
3232,
2048
],
"door": false,
"open": false
},
{
"id": 53,
"a": [
608,
1024
],
"b": [
608,
2048
],
"door": false,
"open": false
},
{
"id": 54,
"a": [
672,
1024
],
"b": [
672,
2048
],
"door": false,
"open": false
},
{
"id": 55,
"a": [
600,
600
],
"b": [
680,
600
],
"door": false,
"open": false
},
{
"id": 56,
"a": [
600,
680
],
"b": [
680,
680
],
"door": false,
"open": false
},
{
"id": 57,
"a": [
600,
600
],
"b": [
600,
680
],
"door": false,
"open": false
},
{
"id": 58,
"a": [
680,
600
],
"b": [
680,
680
],
"door": false,
"open": false
},
{
"id": 59,
"a": [
3000,
700
],
"b": [
3000,
1024
],
"door": false,
"open": false
}
],
"floors": [
[
256,
256,
1024,
1024
],
[
1536,
256,
2304,
1024
],
[
2816,
256,
3584,
1024
],
[
256,
2048,
1024,
2816
],
[
1536,
2048,
2304,
2816
],
[
2816,
2048,
3584,
2816
],
[
1024,
608,
1536,
672
],
[
2304,
608,
2816,
672
],
[
1024,
2400,
1536,
2464
],
[
2304,
2400,
2816,
2464
],
[
1888,
1024,
1952,
2048
],
[
3168,
1024,
3232,
2048
],
[
608,
1024,
672,
2048
]
],
"tokens": [
{
"id": "A",
"kind": "player",
"name": "Player A",
"pos": [
400,
400
],
"gmOnly": false
},
{
"id": "B",
"kind": "player",
"name": "Player B",
"pos": [
400,
2200
],
"gmOnly": false
},
{
"id": "M1",
"kind": "monster",
"name": "Monster 1",
"pos": [
900,
900
],
"gmOnly": true
},
{
"id": "M2",
"kind": "monster",
"name": "Monster 2",
"pos": [
1920,
640
],
"gmOnly": true
},
{
"id": "M3",
"kind": "monster",
"name": "Monster 3",
"pos": [
3400,
500
],
"gmOnly": true
},
{
"id": "M4",
"kind": "monster",
"name": "Monster 4",
"pos": [
900,
2700
],
"gmOnly": true
},
{
"id": "M5",
"kind": "monster",
"name": "Monster 5",
"pos": [
1920,
2400
],
"gmOnly": true
},
{
"id": "M6",
"kind": "monster",
"name": "Monster 6",
"pos": [
3200,
2400
],
"gmOnly": true
}
]
}
@@ -0,0 +1,73 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": {
"nim": "2",
"nimble": "latest",
"nginx": "latest",
"nodejs": "latest",
"sqlite": {
"version": "latest",
"outputs": [
"out",
"bin"
]
}
},
"shell": {
"init_hook": [],
"scripts": {
"gen": [
"node tools/genmap.mjs"
],
"client": [
"cd client && npm install --silent && npm run check && npm run build"
],
"test": [
"node tools/genmap.mjs",
"nimble test",
"devbox run smoke",
"devbox run leaktest",
"devbox run faulttest",
"devbox run restart",
"DUR=15 devbox run concurrency"
],
"server": [
"nimble build -d:release -y",
"mkdir -p run",
"./server"
],
"nginx": [
"mkdir -p run/temp client/dist",
"sed \"s/NGX_PORT/${PORT:-8080}/;s/NGX_BACKEND/${BACKEND_PORT:-9000}/\" nginx/nginx.conf > run/nginx.conf",
"nginx -p \"$PWD/\" -c run/nginx.conf -e run/error.log"
],
"leaktest": [
"tools/leaktest.sh"
],
"concurrency": [
"mkdir -p results; D=${DUR:-60}; N=${TAG:-${D}s}; tools/withserver.sh node tools/concurrency.mjs > results/concurrency-$N.log 2>&1; rc=$?; cat results/concurrency-$N.log; grep STATS run/test/server.log | awk '{k=$0; sub(/ n=.*/, \"\", k); a[k]=$0} END{for (k in a) print a[k]}' | sort > results/concurrency-$N-server.log; { grep SLOW run/test/server.log >> results/concurrency-$N-server.log || true; }; exit $rc"
],
"faulttest": [
"tools/faulttest.sh"
],
"restart": [
"NOSERVE=1 tools/withserver.sh node tools/restart.mjs"
],
"smoke": [
"tools/withserver.sh node tools/smoke.mjs"
],
"mutation": [
"tools/mutation.sh"
],
"clienttest": [
"mkdir -p results; (cd client && npm run check) > results/client-tests.log 2>&1; rc=$?; cat results/client-tests.log; exit $rc"
],
"bench": [
"mkdir -p results; nim c -d:release --hints:off -r -o:run/bench tools/bench.nim | tee results/bench.log"
]
}
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
}
}
@@ -0,0 +1,437 @@
{
"lockfile_version": "1",
"packages": {
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
"source": "devbox-search",
"version": "2.2.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"nimble@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
"source": "devbox-search",
"version": "0.24.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
}
}
},
"nodejs@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
},
"sqlite@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite",
"source": "devbox-search",
"version": "3.53.3",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/wlwc2gz7r5884rdmfjnqjk38lwv94qsy-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/p6bsmbp6a5dz55isxvfr7941wbfjmjvf-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/0k4r9hnfbnyngn5f3j31siddfs0iglwl-sqlite-3.53.3"
},
{
"name": "dev",
"path": "/nix/store/r9cljv2bvqi3ci3n6m0z0wi3ldpvlyzq-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/9q84sy842rw7k4z4jdsb4hkbiapr7pm0-sqlite-3.53.3-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/q39crs8z0dafx19dv0l2y4jxc8ahvy03-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/74r7ps7mmjw10fl23xsgcp7ss09jrkjr-sqlite-3.53.3-dev"
},
{
"name": "doc",
"path": "/nix/store/g4f5y9laa7l7lbriv8x05clyi9x7w14z-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/2lyx0wc6ccabpdwpviksww3x5xhsmnvk-sqlite-3.53.3"
}
],
"store_path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/is1ld1bxvwqqjwv89kl6vcnlpypbkg5r-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/l778wamidjdrjyahinx63c7n50fwh0il-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/9x0m6s73sg89fv5awb95vsac2mbns8n0-sqlite-3.53.3"
},
{
"name": "debug",
"path": "/nix/store/1vbdchnss15n90chl72l80z16shxjp7l-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/xrcjl59yi7zswbv0vzm8cmvw4vplsbgj-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin"
}
}
}
}
}
@@ -0,0 +1,99 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/avif avif;
image/png png;
image/svg+xml svg svgz;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/webp webp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
font/woff woff;
font/woff2 woff2;
application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.oasis.opendocument.graphics odg;
application/vnd.oasis.opendocument.presentation odp;
application/vnd.oasis.opendocument.spreadsheet ods;
application/vnd.oasis.opendocument.text odt;
application/vnd.openxmlformats-officedocument.presentationml.presentation
pptx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx;
application/vnd.openxmlformats-officedocument.wordprocessingml.document
docx;
application/vnd.wap.wmlc wmlc;
application/wasm wasm;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}
@@ -0,0 +1,33 @@
# run via `devbox run nginx`; prefix = project root, all temp/log paths in run/
daemon off;
pid run/nginx.pid;
error_log run/error.log warn;
events {}
http {
access_log run/access.log;
client_body_temp_path run/temp/client_body;
proxy_temp_path run/temp/proxy;
fastcgi_temp_path run/temp/fastcgi;
uwsgi_temp_path run/temp/uwsgi;
scgi_temp_path run/temp/scgi;
server_tokens off;
include ../nginx/mime.types; # relative to the generated run/nginx.conf
map $http_upgrade $conn_up { default upgrade; '' close; }
server {
listen NGX_PORT; # sed-substituted from $PORT (default 8080); NGX_BACKEND from $BACKEND_PORT (default 9000)
server_name localhost;
root client/dist;
index index.html;
location /join/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
location /tiles/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
location /ws {
proxy_pass http://127.0.0.1:NGX_BACKEND;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $conn_up;
proxy_read_timeout 1h;
}
# only reachable via X-Accel-Redirect from Nim after its access check
location /_tiles/ { internal; alias data/tiles/; add_header Cache-Control "private, no-cache"; }
}
}
@@ -0,0 +1,3 @@
--path:"src"
--threads:on
--mm:orc
@@ -0,0 +1,5 @@
1 poly (jittered start positions): n=2000 avg=0.038ms worst=0.180ms
6 polys (one 6-token party): n=500 avg=0.205ms worst=0.291ms
1 poly + cellsTouched: n=2000 avg=0.451ms worst=0.980ms
6 polys + cellsTouched: n=300 avg=2.947ms worst=3.727ms
(sink 2063860)
@@ -0,0 +1,16 @@
> check
> node --test src/state.test.ts
✔ protocol reducer: fake server script (1.456001ms)
✔ gm walls + door (0.181201ms)
✔ tilesOfCells (0.268275ms)
✔ hello resets state (reconnect) (0.211899ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.877698
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=62 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=843 avg=146.0 worst=154.
STATS bytes/delivery move-monster B: n=754 avg=145.5 worst=154.
STATS bytes/delivery move-monster gm: n=10286 avg=243.5 worst=252.
STATS bytes/delivery move-player A: n=1689 avg=3652.8 worst=4887.
STATS bytes/delivery move-player B: n=1711 avg=3358.9 worst=4433.
STATS bytes/delivery move-player gm: n=3400 avg=144.6 worst=149.
STATS timing_ms lock_wait: n=13748 avg=0.119 p50=0.000 p99=2.181 worst=16.860
STATS timing_ms send: n=13748 avg=0.061 p50=0.040 p99=0.187 worst=0.335
STATS timing_ms sqlite: n=13748 avg=0.167 p50=0.139 p99=0.307 worst=17.568
STATS timing_ms total: n=13748 avg=0.701 p50=0.286 p99=3.714 worst=19.634
STATS timing_ms vision: n=13748 avg=0.293 p50=0.000 p99=2.491 worst=4.549
STATS vision_ms door: n=62 avg=0.204 worst=0.297
STATS vision_ms move-monster: n=10286 avg=0.000 worst=0.024
STATS vision_ms move-player: n=3400 avg=1.181 worst=4.549
@@ -0,0 +1,6 @@
gm: sent 10299 moves (167/s), acks 10299 (nack 13), recv 24054 msgs 2935 KiB, final gseq 13748, tokens in view 8
A: sent 1715 moves (28/s), acks 1715 (nack 26), recv 6093 msgs 6153 KiB, final gseq 13745, tokens in view 2
B: sent 1711 moves (28/s), acks 1711 (nack 0), recv 6035 msgs 5725 KiB, final gseq 13742, tokens in view 1
latency intent->ack (sender): n=13725 avg=1.40ms p95=2.99ms p99=4.58ms worst=20.31ms
latency intent->arrival at other clients: n=4926 avg=2.04ms p95=3.66ms p99=5.17ms worst=18.94ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=58 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=1393 avg=149.0 worst=154.
STATS bytes/delivery move-monster B: n=850 avg=147.4 worst=154.
STATS bytes/delivery move-monster gm: n=10222 avg=243.6 worst=252.
STATS bytes/delivery move-player A: n=1699 avg=3903.2 worst=4949.
STATS bytes/delivery move-player B: n=1716 avg=3341.6 worst=4514.
STATS bytes/delivery move-player gm: n=3414 avg=144.6 worst=148.
STATS timing_ms lock_wait: n=13695 avg=0.146 p50=0.000 p99=2.640 worst=19.868
STATS timing_ms send: n=13695 avg=0.064 p50=0.041 p99=0.199 worst=0.486
STATS timing_ms sqlite: n=13695 avg=0.169 p50=0.142 p99=0.301 worst=19.760
STATS timing_ms total: n=13695 avg=0.789 p50=0.293 p99=4.092 worst=21.321
STATS timing_ms vision: n=13695 avg=0.347 p50=0.000 p99=3.059 worst=4.930
STATS vision_ms door: n=58 avg=0.224 worst=0.328
STATS vision_ms move-monster: n=10222 avg=0.000 worst=0.022
STATS vision_ms move-player: n=3415 avg=1.387 worst=4.930
@@ -0,0 +1,6 @@
gm: sent 10271 moves (166/s), acks 10271 (nack 49), recv 23971 msgs 2926 KiB, final gseq 13695, tokens in view 8
A: sent 1709 moves (28/s), acks 1709 (nack 10), recv 6617 msgs 6685 KiB, final gseq 13693, tokens in view 2
B: sent 1716 moves (28/s), acks 1716 (nack 0), recv 6148 msgs 5728 KiB, final gseq 13690, tokens in view 2
latency intent->ack (sender): n=13696 avg=1.50ms p95=3.39ms p99=4.98ms worst=21.73ms
latency intent->arrival at other clients: n=5610 avg=2.10ms p95=4.11ms p99=5.47ms worst=21.78ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=64 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=912 avg=146.8 worst=154.
STATS bytes/delivery move-monster B: n=739 avg=143.6 worst=154.
STATS bytes/delivery move-monster gm: n=10278 avg=243.4 worst=252.
STATS bytes/delivery move-player A: n=1709 avg=3639.5 worst=4978.
STATS bytes/delivery move-player B: n=1707 avg=3280.8 worst=4489.
STATS bytes/delivery move-player gm: n=3413 avg=144.7 worst=149.
STATS timing_ms lock_wait: n=13758 avg=0.128 p50=0.000 p99=2.341 worst=21.024
STATS timing_ms send: n=13758 avg=0.061 p50=0.039 p99=0.184 worst=0.336
STATS timing_ms sqlite: n=13758 avg=0.170 p50=0.141 p99=0.297 worst=23.209
STATS timing_ms total: n=13758 avg=0.719 p50=0.288 p99=3.874 worst=24.258
STATS timing_ms vision: n=13758 avg=0.297 p50=0.000 p99=2.874 worst=4.548
STATS vision_ms door: n=64 avg=0.209 worst=0.288
STATS vision_ms move-monster: n=10278 avg=0.000 worst=0.026
STATS vision_ms move-player: n=3416 avg=1.191 worst=4.548
@@ -0,0 +1,6 @@
gm: sent 10302 moves (163/s), acks 10302 (nack 24), recv 24064 msgs 2936 KiB, final gseq 13758, tokens in view 8
A: sent 1724 moves (27/s), acks 1724 (nack 15), recv 6214 msgs 6212 KiB, final gseq 13748, tokens in view 1
B: sent 1707 moves (27/s), acks 1707 (nack 0), recv 6065 msgs 5578 KiB, final gseq 13756, tokens in view 2
latency intent->ack (sender): n=13733 avg=1.43ms p95=3.15ms p99=4.75ms worst=24.72ms
latency intent->arrival at other clients: n=4987 avg=2.04ms p95=3.90ms p99=5.41ms worst=24.80ms
concurrency: PASS
@@ -0,0 +1,148 @@
== fault hidden
FAIL [HIDDEN_TOKEN] LEAK token M5 outside A vision at g=0
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=0
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=1
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=2
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=3
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=4
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=5
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=6
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=7
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=8
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=9
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=10
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=11
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=12
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=13
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=14
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=15
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=16
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=17
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=18
FAILCLASS HIDDEN_TOKEN 144
leakcheck: 218 gseq groups, subject msgs 466, tokens seen 4 others, removes 3, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 144
== fault walls
FAIL [WALLDATA] A got forbidden type walls
FAILCLASS WALLDATA 1
leakcheck: 218 gseq groups, subject msgs 468, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 1
== fault tile
FAIL [TILE] tile 3_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 4_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 5_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 6_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 7_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 8_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 9_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 10_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 11_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 12_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 13_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 14_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 15_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 4_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 5_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 6_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 7_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 8_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 9_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 10_1 g=0 (start) status 200 expected 403
FAILCLASS TILE 8275
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:9984 403:0 other:0), explored cells 2142, failures 8275
== fault withhold
FAIL [WITHHELD] view mismatch M1 want=true at g=21
FAIL [WITHHELD] view mismatch M1 want=true at g=22
FAIL [WITHHELD] view mismatch M1 want=true at g=23
FAIL [WITHHELD] view mismatch M1 want=true at g=24
FAIL [WITHHELD] view mismatch M1 want=true at g=25
FAIL [WITHHELD] view mismatch M1 want=true at g=26
FAIL [WITHHELD] view mismatch M1 want=true at g=27
FAIL [WITHHELD] view mismatch M1 want=true at g=28
FAIL [WITHHELD] view mismatch M1 want=true at g=29
FAIL [WITHHELD] view mismatch M1 want=true at g=30
FAIL [WITHHELD] view mismatch M1 want=true at g=31
FAIL [WITHHELD] view mismatch M1 want=true at g=32
FAIL [WITHHELD] view mismatch M1 want=true at g=33
FAIL [WITHHELD] view mismatch M1 want=true at g=34
FAIL [WITHHELD] view mismatch M1 want=true at g=35
FAIL [WITHHELD] view mismatch M1 want=true at g=36
FAIL [WITHHELD] view mismatch M1 want=true at g=37
FAIL [WITHHELD] view mismatch M1 want=true at g=38
FAIL [WITHHELD] scenario never showed subject token M1
FAILCLASS WITHHELD 19
leakcheck: 218 gseq groups, subject msgs 465, tokens seen 3 others, removes 3, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 19
== fault other-vision
FAIL [OTHER_PLAYER] vision carries B's polygon at g=0
FAIL [OWN_VIEW] vision shape at g=0
FAIL [OTHER_PLAYER] vision carries B's polygon at g=1
FAIL [OWN_VIEW] vision shape at g=1
FAIL [OTHER_PLAYER] vision carries B's polygon at g=2
FAIL [OWN_VIEW] vision shape at g=2
FAIL [OTHER_PLAYER] vision carries B's polygon at g=3
FAIL [OWN_VIEW] vision shape at g=3
FAIL [OTHER_PLAYER] vision carries B's polygon at g=4
FAIL [OWN_VIEW] vision shape at g=4
FAIL [OTHER_PLAYER] vision carries B's polygon at g=5
FAIL [OWN_VIEW] vision shape at g=5
FAIL [OTHER_PLAYER] vision carries B's polygon at g=6
FAIL [OWN_VIEW] vision shape at g=6
FAIL [OTHER_PLAYER] vision carries B's polygon at g=7
FAIL [OWN_VIEW] vision shape at g=7
FAIL [OTHER_PLAYER] vision carries B's polygon at g=8
FAIL [OWN_VIEW] vision shape at g=8
FAIL [OTHER_PLAYER] vision carries B's polygon at g=9
FAIL [OWN_VIEW] vision shape at g=9
FAILCLASS OTHER_PLAYER 218
FAILCLASS OWN_VIEW 218
leakcheck: 218 gseq groups, subject msgs 574, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 436
== fault other-explored
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [7,65]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [24,68]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [14,81]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [7,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,79]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [8,68]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [21,75]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [18,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [15,69]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [15,66]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [10,73]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [8,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [18,74]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,75]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [21,66]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [16,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [23,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [10,77]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [12,77]
FAILCLASS OTHER_PLAYER 786
FAILCLASS EXPLORED 218
leakcheck: 218 gseq groups, subject msgs 505, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 1004
== fault other-owner
FAIL [OTHER_PLAYER] B mentioned in {"role":"player","tokens":["A","B"],"world":{"w":4096,"h":4096},"tileSize":256,"exploredCell":32,"tokenRadius":20,"t":"hello","gseq":0}
FAIL [OTHER_PLAYER] hello tokens ["A","B"]
FAILCLASS OTHER_PLAYER 2
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 2
== fault noremove
FAIL [NO_REMOVE] view mismatch M1 want=false at g=39
FAIL [NO_REMOVE] view mismatch M1 want=false at g=40
FAIL [NO_REMOVE] view mismatch M1 want=false at g=41
FAIL [NO_REMOVE] view mismatch M1 want=false at g=42
FAIL [NO_REMOVE] view mismatch M1 want=false at g=43
FAIL [NO_REMOVE] view mismatch M1 want=false at g=44
FAIL [NO_REMOVE] view mismatch M1 want=false at g=45
FAIL [NO_REMOVE] view mismatch M1 want=false at g=46
FAIL [NO_REMOVE] view mismatch M1 want=false at g=47
FAIL [NO_REMOVE] view mismatch M1 want=false at g=48
FAIL [NO_REMOVE] view mismatch M1 want=false at g=49
FAIL [NO_REMOVE] view mismatch M1 want=false at g=50
FAIL [NO_REMOVE] view mismatch M1 want=false at g=51
FAIL [NO_REMOVE] view mismatch M1 want=false at g=52
FAIL [NO_REMOVE] view mismatch M1 want=false at g=53
FAIL [NO_REMOVE] view mismatch M1 want=false at g=54
FAIL [NO_REMOVE] view mismatch M1 want=false at g=55
FAIL [NO_REMOVE] view mismatch M1 want=false at g=56
FAIL [NO_REMOVE] view mismatch M1 want=false at g=57
FAIL [NO_REMOVE] view mismatch M1 want=false at g=58
FAILCLASS NO_REMOVE 356
leakcheck: 218 gseq groups, subject msgs 463, tokens seen 4 others, removes 0, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 356
@@ -0,0 +1,11 @@
Info: Running script "faulttest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS run/test/server-clean has no fault hook
PASS fault hidden caught as: HIDDEN_TOKEN
PASS fault walls caught as: WALLDATA
PASS fault tile caught as: TILE
PASS fault withhold caught as: WITHHELD
PASS fault other-vision caught as: OTHER_PLAYER OWN_VIEW
PASS fault other-explored caught as: EXPLORED OTHER_PLAYER
PASS fault other-owner caught as: OTHER_PLAYER
PASS fault noremove caught as: NO_REMOVE
PASS clean build passes
@@ -0,0 +1,7 @@
Info: Running script "leaktest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
== SUBJECT=A
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
== SUBJECT=B
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,12 @@
nimble-test 0
mutation 0
leaktest 0
faulttest 0
restart 0
smoke 0
bench 0
client-tests 0
concurrency-final1 0
concurrency-final2 0
concurrency-final3 0
DONE
@@ -0,0 +1,28 @@
Info: Running script "restart" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS move A -> 400,800
PASS move A -> 800,800
PASS move A -> 800,640
PASS move A -> 1000,640
PASS move A -> 1510,640
PASS move B -> 700,2300
PASS move M1 -> 900,640
PASS move M2 -> 2200,300
PASS move A -> 1700,640
PASS cycle1: invite secrets identical
PASS cycle1: gm state identical after SIGTERM restart
PASS cycle1: A state identical after SIGTERM restart
PASS cycle1: B state identical after SIGTERM restart
PASS A explored new area (292 -> 1145)
PASS cycle1: token positions are the moved ones
PASS cycle1: door states are the toggled ones
PASS cycle1: doors differ from initial (test is not vacuous)
PASS move A -> 1900,640
PASS move B -> 1000,2300
PASS move M1 -> 1200,640
PASS cycle2: invite secrets identical
PASS cycle2: gm state identical after SIGKILL restart
PASS cycle2: A state identical after SIGKILL restart
PASS cycle2: B state identical after SIGKILL restart
PASS cycle2: A explored more before kill -9
PASS cycle2: B explored more before kill -9
restart: PASS
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,57 @@
# mutation a: remove the +-RayEps rays
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 50,51d49
# < angles.add ang - RayEps
# < angles.add ang + RayEps
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
[OK] '<' apex: ray through the shared tip must not leak
[OK] every segment endpoint is a polygon vertex (lower and upper end inclusive)
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(65, 14): Check failed: sees(w, (0.0, 7.4), (100.0, -6.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(69, 14): Check failed: sees(m, (0.0, -7.4), (100.0, 6.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(73, 14): Check failed: sees(b, (0.0, -24.0), (200.0, 130.0))
[FAILED] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] rays nudged past a corner: area just beyond a wall end is visible
@@ -0,0 +1,63 @@
# mutation b: upper segment end exclusive
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 27c27
# < if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
# ---
# > if t > Eps and u >= -Eps and u < 1 - Eps: t else: Inf
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(45, 59): Check failed: visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(46, 12): Check failed: not sees(w, (0.0, 0.0), (150.0, 0.0))
sees(w, (0.0, 0.0), (150.0, 0.0)) was true
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(47, 12): Check failed: not sees(w, (0.0, 0.0), (300.0, 0.0))
sees(w, (0.0, 0.0), (300.0, 0.0)) was true
[FAILED] '<' apex: ray through the shared tip must not leak
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(55, 24): Check failed: poly.hasVertex((80.0, 10.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(58, 22): Check failed: pr.hasVertex((50.0, -30.0))
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
[OK] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] '<' apex: ray through the shared tip must not leak
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
@@ -0,0 +1,63 @@
# mutation c: lower segment end exclusive
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 27c27
# < if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
# ---
# > if t > Eps and u > Eps and u <= 1 + Eps: t else: Inf
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(45, 59): Check failed: visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(46, 12): Check failed: not sees(w, (0.0, 0.0), (150.0, 0.0))
sees(w, (0.0, 0.0), (150.0, 0.0)) was true
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(47, 12): Check failed: not sees(w, (0.0, 0.0), (300.0, 0.0))
sees(w, (0.0, 0.0), (300.0, 0.0)) was true
[FAILED] '<' apex: ray through the shared tip must not leak
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(54, 24): Check failed: poly.hasVertex((50.0, -30.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(59, 22): Check failed: pr.hasVertex((80.0, 10.0))
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
[OK] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] '<' apex: ray through the shared tip must not leak
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
@@ -0,0 +1,5 @@
Info: Running script "mutation" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
control: exit=0 newfailed=0
a: exit=1 newfailed=1
b: exit=1 newfailed=2
c: exit=1 newfailed=2
@@ -0,0 +1,45 @@
Info: Running script "nimble" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
Info: Ensuring packages are installed.
Info: Using the environment variable: NIMBLE_DIR='/home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/.devbox/nimble'
Info: using /nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12/bin/nim for compilation
Compiling /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/tests/tgeometry (from package servervision) using c backend
Nim Output [Suite] visibility
... [OK] open space is a circle
... [OK] wall blocks
... [OK] shared endpoint: no leak at the vertex
... [OK] '<' apex: ray through the shared tip must not leak
... [OK] every segment endpoint is a polygon vertex (lower and upper end inclusive)
... [OK] rays nudged past a corner: area just beyond a wall end is visible
... [OK] shared endpoint: closed corner of box has no crack
... [OK] collinear walls act as one
... [OK] collinear walls with a gap let light through
... [OK] T-junction: no leak and correct shadow
... [OK] pillar mid-room casts a shadow, sides visible
... [OK] closed door blocks, open door passes
... [OK] token exactly at wall endpoint
... [OK] token at endpoint of free-standing wall sees along it
... [OK] long thin corridor
... [OK] wall endpoints behind the viewer: fan stays angularly ordered
... [OK] radius clips
... [Suite] moves
... [OK] crossing blocked, parallel ok
... [OK] grazing an endpoint is blocked
... [OK] no leak through shared vertex
... [OK] diagonal squeeze through corner vertex of L
... [OK] moving along a collinear wall is blocked
... [OK] doors
... [OK] zero-length move
... [Suite] cells
... [OK] square polygon
... [OK] tiny polygon inside one cell
... [OK] polygon spanning a cell with no vertex in it
... [OK] big polygon includes fully covered interior cells
... [Suite] seed
... [OK] every token in seed sees itself and is not walled in
... [Suite] token clearance (r=20)
... [OK] near pillar: circle overlapping blocked, clear ok
... [OK] near closed door blocks, open door passes
... [OK] 64px corridor and doorway passable on centerline
... [OK] legacy overlap can escape, not stay overlapped
Success: Execution finished
Success: All tests passed
@@ -0,0 +1,20 @@
Info: Running script "smoke" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS join A: 302 + HttpOnly SameSite cookie
PASS bad secret 403
PASS ws without cookie refused
PASS ws bad cookie refused
player A msgs: hello,vision,explored,token
PASS hello first, player owns A
PASS no walls/door to player
PASS vision + explored sent
PASS only own token visible
PASS explored tile 200, 767 bytes
PASS unexplored tile 403
PASS tile without cookie 403
PASS /_tiles not reachable directly
PASS path trick rejected
PASS GM gets any tile
PASS steal/door/garbage -> 3 errors
PASS move through wall rejected
PASS legal move acked
PASS GM: walls, all 8 tokens, no explored
@@ -0,0 +1,18 @@
STATS bytes/delivery door gm: n=56 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=900 avg=147.5 worst=153.
STATS bytes/delivery move-monster B: n=544 avg=146.5 worst=154.
STATS bytes/delivery move-monster gm: n=10370 avg=243.2 worst=252.
STATS bytes/delivery move-player A: n=1691 avg=3746.9 worst=4959.
STATS bytes/delivery move-player B: n=1714 avg=2950.4 worst=4376.
STATS bytes/delivery move-player gm: n=3404 avg=144.7 worst=149.
STATS timing_ms lock_wait: n=13831 avg=0.162 p50=0.000 p99=2.567 worst=71.704
STATS timing_ms send: n=13831 avg=0.060 p50=0.040 p99=0.177 worst=0.467
STATS timing_ms sqlite: n=13831 avg=0.616 p50=0.604 p99=1.224 worst=62.928
STATS timing_ms total: n=13831 avg=1.143 p50=0.762 p99=4.450 worst=72.870
STATS timing_ms vision: n=13831 avg=0.242 p50=0.000 p99=2.875 worst=4.230
STATS vision_ms door: n=56 avg=0.207 worst=0.346
STATS vision_ms move-monster: n=10370 avg=0.000 worst=0.050
STATS vision_ms move-player: n=3405 avg=0.981 worst=4.230
SLOW gseq=136 move-player total=63.8 lock_wait=0.0 vision=0.7 sqlite=62.9 send=0.1 other=0.1
SLOW gseq=138 move-monster total=56.6 lock_wait=55.9 vision=0.0 sqlite=0.6 send=0.0 other=0.0
SLOW gseq=152 move-player total=72.9 lock_wait=71.7 vision=0.4 sqlite=0.7 send=0.1 other=0.0
@@ -0,0 +1,6 @@
gm: sent 10391 moves (169/s), acks 10391 (nack 21), recv 24222 msgs 2953 KiB, final gseq 13831, tokens in view 8
A: sent 1704 moves (28/s), acks 1704 (nack 13), recv 6125 msgs 6324 KiB, final gseq 13826, tokens in view 2
B: sent 1714 moves (28/s), acks 1714 (nack 0), recv 5792 msgs 5022 KiB, final gseq 13829, tokens in view 1
latency intent->ack (sender): n=13809 avg=1.84ms p95=3.53ms p99=5.17ms worst=73.08ms
latency intent->arrival at other clients: n=4809 avg=2.43ms p95=4.54ms p99=5.92ms worst=73.22ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=60 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=907 avg=147.0 worst=155.
STATS bytes/delivery move-monster B: n=862 avg=146.8 worst=154.
STATS bytes/delivery move-monster gm: n=10257 avg=242.7 worst=252.
STATS bytes/delivery move-player A: n=1724 avg=3812.4 worst=4998.
STATS bytes/delivery move-player B: n=1710 avg=3252.1 worst=4567.
STATS bytes/delivery move-player gm: n=3432 avg=144.5 worst=149.
STATS timing_ms lock_wait: n=13751 avg=0.177 p50=0.000 p99=3.061 worst=11.928
STATS timing_ms send: n=13751 avg=0.060 p50=0.040 p99=0.185 worst=0.570
STATS timing_ms sqlite: n=13751 avg=0.592 p50=0.591 p99=1.168 worst=21.248
STATS timing_ms total: n=13751 avg=1.207 p50=0.753 p99=4.874 worst=21.348
STATS timing_ms vision: n=13751 avg=0.317 p50=0.000 p99=3.258 worst=4.943
STATS vision_ms door: n=60 avg=0.202 worst=0.315
STATS vision_ms move-monster: n=10257 avg=0.000 worst=0.017
STATS vision_ms move-player: n=3434 avg=1.267 worst=4.943
@@ -0,0 +1,6 @@
gm: sent 10338 moves (165/s), acks 10338 (nack 81), recv 24090 msgs 2931 KiB, final gseq 13751, tokens in view 8
A: sent 1728 moves (28/s), acks 1728 (nack 4), recv 6241 msgs 6554 KiB, final gseq 13748, tokens in view 2
B: sent 1710 moves (27/s), acks 1710 (nack 0), recv 6158 msgs 5560 KiB, final gseq 13749, tokens in view 2
latency intent->ack (sender): n=13776 avg=1.84ms p95=4.03ms p99=5.48ms worst=21.83ms
latency intent->arrival at other clients: n=5145 avg=2.43ms p95=4.84ms p99=6.26ms worst=15.69ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=56 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=901 avg=148.9 worst=155.
STATS bytes/delivery move-monster B: n=1125 avg=146.8 worst=154.
STATS bytes/delivery move-monster gm: n=10370 avg=243.1 worst=252.
STATS bytes/delivery move-player A: n=1721 avg=3563.7 worst=4934.
STATS bytes/delivery move-player B: n=1737 avg=3242.3 worst=4524.
STATS bytes/delivery move-player gm: n=3456 avg=144.9 worst=149.
STATS timing_ms lock_wait: n=13884 avg=0.144 p50=0.000 p99=2.448 worst=13.060
STATS timing_ms send: n=13884 avg=0.061 p50=0.042 p99=0.179 worst=0.334
STATS timing_ms sqlite: n=13884 avg=0.609 p50=0.604 p99=1.192 worst=9.628
STATS timing_ms total: n=13884 avg=1.133 p50=0.758 p99=3.934 worst=14.178
STATS timing_ms vision: n=13884 avg=0.256 p50=0.000 p99=2.257 worst=3.514
STATS vision_ms door: n=56 avg=0.229 worst=0.699
STATS vision_ms move-monster: n=10370 avg=0.000 worst=0.069
STATS vision_ms move-player: n=3458 avg=1.023 worst=3.514
@@ -0,0 +1,6 @@
gm: sent 10385 moves (167/s), acks 10385 (nack 15), recv 24270 msgs 2960 KiB, final gseq 13884, tokens in view 8
A: sent 1723 moves (28/s), acks 1723 (nack 2), recv 6173 msgs 6126 KiB, final gseq 13881, tokens in view 2
B: sent 1737 moves (28/s), acks 1737 (nack 0), recv 6513 msgs 5666 KiB, final gseq 13874, tokens in view 1
latency intent->ack (sender): n=13845 avg=1.78ms p95=3.46ms p99=4.51ms worst=18.14ms
latency intent->arrival at other clients: n=5425 avg=2.26ms p95=3.98ms p99=4.97ms worst=14.13ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=58 avg=44.9 worst=46.
STATS bytes/delivery move-monster A: n=754 avg=146.4 worst=154.
STATS bytes/delivery move-monster B: n=400 avg=137.6 worst=155.
STATS bytes/delivery move-monster gm: n=10266 avg=242.8 worst=252.
STATS bytes/delivery move-player A: n=1707 avg=3854.9 worst=5028.
STATS bytes/delivery move-player B: n=1710 avg=3394.4 worst=4724.
STATS bytes/delivery move-player gm: n=3409 avg=144.5 worst=149.
STATS timing_ms lock_wait: n=13741 avg=0.148 p50=0.000 p99=2.687 worst=16.594
STATS timing_ms send: n=13741 avg=0.063 p50=0.040 p99=0.199 worst=0.394
STATS timing_ms sqlite: n=13741 avg=0.167 p50=0.137 p99=0.314 worst=17.739
STATS timing_ms total: n=13741 avg=0.792 p50=0.288 p99=4.203 worst=21.053
STATS timing_ms vision: n=13741 avg=0.351 p50=0.000 p99=3.172 worst=6.325
STATS vision_ms door: n=58 avg=0.236 worst=0.344
STATS vision_ms move-monster: n=10266 avg=0.000 worst=0.081
STATS vision_ms move-player: n=3417 avg=1.405 worst=6.325
@@ -0,0 +1,6 @@
gm: sent 10281 moves (164/s), acks 10281 (nack 15), recv 24018 msgs 2925 KiB, final gseq 13741, tokens in view 8
A: sent 1715 moves (27/s), acks 1715 (nack 8), recv 6041 msgs 6540 KiB, final gseq 13738, tokens in view 1
B: sent 1710 moves (27/s), acks 1710 (nack 0), recv 5687 msgs 5727 KiB, final gseq 13737, tokens in view 1
latency intent->ack (sender): n=13706 avg=1.51ms p95=3.48ms p99=5.09ms worst=21.33ms
latency intent->arrival at other clients: n=4490 avg=2.33ms p95=4.37ms p99=5.79ms worst=21.36ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=66 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=649 avg=146.1 worst=153.
STATS bytes/delivery move-monster B: n=1210 avg=147.0 worst=154.
STATS bytes/delivery move-monster gm: n=10238 avg=242.6 worst=252.
STATS bytes/delivery move-player A: n=1691 avg=3626.7 worst=4956.
STATS bytes/delivery move-player B: n=1703 avg=3336.6 worst=4459.
STATS bytes/delivery move-player gm: n=3394 avg=144.9 worst=149.
STATS timing_ms lock_wait: n=13698 avg=0.123 p50=0.000 p99=2.178 worst=18.542
STATS timing_ms send: n=13698 avg=0.062 p50=0.040 p99=0.185 worst=0.480
STATS timing_ms sqlite: n=13698 avg=0.170 p50=0.138 p99=0.315 worst=18.178
STATS timing_ms total: n=13698 avg=0.715 p50=0.287 p99=3.432 worst=20.612
STATS timing_ms vision: n=13698 avg=0.295 p50=0.000 p99=2.385 worst=4.037
STATS vision_ms door: n=66 avg=0.222 worst=0.345
STATS vision_ms move-monster: n=10238 avg=0.000 worst=0.029
STATS vision_ms move-player: n=3394 avg=1.187 worst=4.037
@@ -0,0 +1,6 @@
gm: sent 10281 moves (166/s), acks 10281 (nack 43), recv 23979 msgs 2918 KiB, final gseq 13698, tokens in view 8
A: sent 1714 moves (28/s), acks 1714 (nack 23), recv 5871 msgs 6089 KiB, final gseq 13693, tokens in view 2
B: sent 1703 moves (28/s), acks 1703 (nack 0), recv 6444 msgs 5728 KiB, final gseq 13694, tokens in view 2
latency intent->ack (sender): n=13698 avg=1.43ms p95=3.04ms p99=4.28ms worst=20.83ms
latency intent->arrival at other clients: n=5194 avg=2.03ms p95=3.61ms p99=4.93ms worst=20.95ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=64 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=384 avg=142.5 worst=154.
STATS bytes/delivery move-monster B: n=1018 avg=148.1 worst=154.
STATS bytes/delivery move-monster gm: n=10300 avg=243.1 worst=252.
STATS bytes/delivery move-player A: n=1708 avg=3746.7 worst=4879.
STATS bytes/delivery move-player B: n=1725 avg=3242.8 worst=4766.
STATS bytes/delivery move-player gm: n=3429 avg=144.6 worst=149.
STATS timing_ms lock_wait: n=13797 avg=0.126 p50=0.000 p99=2.384 worst=18.662
STATS timing_ms send: n=13797 avg=0.061 p50=0.039 p99=0.185 worst=0.369
STATS timing_ms sqlite: n=13797 avg=0.169 p50=0.136 p99=0.312 worst=18.797
STATS timing_ms total: n=13797 avg=0.724 p50=0.282 p99=3.789 worst=19.906
STATS timing_ms vision: n=13797 avg=0.305 p50=0.000 p99=2.841 worst=4.198
STATS vision_ms door: n=64 avg=0.217 worst=0.304
STATS vision_ms move-monster: n=10300 avg=0.000 worst=0.039
STATS vision_ms move-player: n=3433 avg=1.221 worst=4.198
@@ -0,0 +1,6 @@
gm: sent 10311 moves (166/s), acks 10311 (nack 11), recv 24109 msgs 2939 KiB, final gseq 13797, tokens in view 8
A: sent 1715 moves (28/s), acks 1715 (nack 7), recv 5671 msgs 6309 KiB, final gseq 13793, tokens in view 2
B: sent 1725 moves (28/s), acks 1725 (nack 0), recv 6322 msgs 5615 KiB, final gseq 13792, tokens in view 2
latency intent->ack (sender): n=13751 avg=1.43ms p95=3.20ms p99=4.49ms worst=20.95ms
latency intent->arrival at other clients: n=4774 avg=2.10ms p95=3.91ms p99=4.78ms worst=21.13ms
concurrency: PASS
@@ -0,0 +1,34 @@
# 583 ms spike investigation (results/spike/original-60s.log: worst intent->ack 583.13 ms, avg 6.33 ms)
HISTORICAL: measured 2026-11-07 on AMD Ryzen 7 7840U, 60.6 GiB, NixOS 26.05, power-save (capped), at commits b202eb6 (baseline) and a337cec (fixed). Not the final-run data (see README).
Setup: DUR=60, isolated stack (run/test, :18088/:19000), CPU powersave governor untouched, runs strictly sequential.
Server now logs per mutation: lock_wait / vision / sqlite / send / total, `SLOW` line when total > `SLOW_MS` (default 50), percentiles in `STATS timing_ms` (end of run + every 5000 mutations).
Client p99 added to `tools/concurrency.mjs`. Logs: `results/spike/base{1,2,3}[-server].log` (baseline), `results/spike/fixed{1,2,3}[-server].log` (after fix).
## Runs (client intent->ack, ms | server total per mutation, ms)
| run | avg | p99 | worst | srv avg | srv p99 | srv worst | srv sqlite avg / worst | srv lock_wait worst |
|---|---|---|---|---|---|---|---|---|
| original (no timing) | 6.33 | n/a | 583.13 | - | - | - | - | - |
| base 1 | 1.84 | 5.17 | 73.08 | 1.143 | 4.450 | 72.870 | 0.616 / 62.928 | 71.704 |
| base 2 | 1.84 | 5.48 | 21.83 | 1.207 | 4.874 | 21.348 | 0.592 / 21.248 | 11.928 |
| base 3 | 1.78 | 4.51 | 18.14 | 1.133 | 3.934 | 14.178 | 0.609 / 9.628 | 13.060 |
| fixed 1 | 1.51 | 5.09 | 21.33 | 0.792 | 4.203 | 21.053 | 0.167 / 17.739 | 16.594 |
| fixed 2 | 1.43 | 4.28 | 20.83 | 0.715 | 3.432 | 20.612 | 0.170 / 18.178 | 18.542 |
| fixed 3 | 1.43 | 4.49 | 20.95 | 0.724 | 3.789 | 19.906 | 0.169 / 18.797 | 18.662 |
(base runs' sqlite worst: run 2 file shows 21.2, run 3 file 9.6; table taken per file.)
## Slowest mutations (baseline; three exceeded 50 ms, all in base run 1 (gseq 136, 138, 152), `SLOW` lines in `spike/base1-server.log`; none in base 2/3 or fixed runs)
- run1 gseq=136 move-player total=63.8: sqlite=62.9 (COMMIT), vision 0.7, send 0.1, lock_wait 0.
- run1 gseq=138 move-monster total=56.6: lock_wait=55.9 (queued behind gseq=136's commit).
- run1 gseq=152 move-player total=72.9: lock_wait=71.7 (queued behind another stalled holder), rest < 1.
- run2/3 worst 21 / 14 ms: also sqlite commit (21.2 / 9.6), others queue behind it as lock_wait (12 / 13).
Vision (worst 4-5 ms) and send enqueue (worst < 0.6 ms) never matter. The global lock turns every stalled COMMIT into lock_wait for the mutations queued behind it.
## Verdict
- 583 ms does NOT reproduce: worst 73 / 22 / 18 ms over 3 runs, avg 1.8 ms vs 6.33 ms in the original run (original run was ~3.5x slower on average too, i.e. the whole run was degraded, not one event; the original server had no timing, so its breakdown is unrecoverable). Most likely host-wide (power cap / scheduler / disk) or node harness stall at that time; client-side not excluded: the 583.13 (ack) and 583.22 (other clients) worst are the same event seen from the same node process, which fits either a server/nginx stall or a node event-loop/GC pause. Not proven either way.
- What the breakdown does show: server-side tail (>10 ms) is the SQLite COMMIT (fsync, synchronous=FULL in WAL) + lock queueing behind it. Compute (vision) and send are not the tail.
- Fix: `PRAGMA synchronous=NORMAL` (WAL), 1 line in `src/server.nim`. Effect (before -> after, mean of 3 runs): sqlite avg 0.60 -> 0.17 ms, p50 0.60 -> 0.14 ms, server total avg 1.16 -> 0.74 ms, client avg 1.82 -> 1.46 ms. Tail is NOT fixed: server worst stays ~20 ms (sqlite worst ~18 ms still, now likely WAL auto-checkpoint / OS scheduling rather than per-commit fsync), client p99 ~4.6-5.1 ms unchanged within noise. The 73 ms outlier of base run 1 did not recur in fixed runs, but n=3, not evidence.
- Tradeoff: with synchronous=NORMAL in WAL, a commit is not fsynced; process crash/SIGKILL loses nothing (restart test passes), OS crash / power loss may drop the last few committed mutations (never corrupts). Ack-before-durable on power loss. Not done: moving persist out of the lock (would break gseq order == send order / ack-after-commit).
- After the change leaktest, faulttest, restart re-run: all PASS (`results/spike/postfix-{leaktest,faulttest,restart}.log`; leak-A/B logs byte-identical to committed).
@@ -0,0 +1,10 @@
STATS bytes/delivery door gm: n=60 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=747 avg=145.0 worst=153.
STATS bytes/delivery move-monster B: n=814 avg=147.5 worst=154.
STATS bytes/delivery move-monster gm: n=10300 avg=243.0 worst=252.
STATS bytes/delivery move-player A: n=1711 avg=3678.6 worst=4927.
STATS bytes/delivery move-player B: n=1710 avg=3180.6 worst=4851.
STATS bytes/delivery move-player gm: n=3417 avg=144.7 worst=149.
STATS vision_ms door: n=60 avg=0.192 worst=0.492
STATS vision_ms move-monster: n=10300 avg=0.000 worst=0.025
STATS vision_ms move-player: n=3421 avg=1.159 worst=14.023
@@ -0,0 +1,6 @@
gm: sent 10364 moves (167/s), acks 10364 (nack 64), recv 24144 msgs 2940 KiB, final gseq 13781, tokens in view 8
A: sent 1728 moves (28/s), acks 1728 (nack 17), recv 6039 msgs 6259 KiB, final gseq 13777, tokens in view 2
B: sent 1710 moves (28/s), acks 1710 (nack 0), recv 6079 msgs 5434 KiB, final gseq 13772, tokens in view 1
latency intent->ack (sender): n=13802 avg=6.33ms p95=11.58ms worst=583.13ms
latency intent->arrival at other clients: n=4917 avg=7.22ms p95=12.89ms worst=583.22ms
concurrency: PASS
@@ -0,0 +1,11 @@
Info: Running script "faulttest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS run/test/server-clean has no fault hook
PASS fault hidden caught as: HIDDEN_TOKEN
PASS fault walls caught as: WALLDATA
PASS fault tile caught as: TILE
PASS fault withhold caught as: WITHHELD
PASS fault other-vision caught as: OTHER_PLAYER OWN_VIEW
PASS fault other-explored caught as: EXPLORED OTHER_PLAYER
PASS fault other-owner caught as: OTHER_PLAYER
PASS fault noremove caught as: NO_REMOVE
PASS clean build passes
@@ -0,0 +1,7 @@
Info: Running script "leaktest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
== SUBJECT=A
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
== SUBJECT=B
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,28 @@
Info: Running script "restart" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS move A -> 400,800
PASS move A -> 800,800
PASS move A -> 800,640
PASS move A -> 1000,640
PASS move A -> 1510,640
PASS move B -> 700,2300
PASS move M1 -> 900,640
PASS move M2 -> 2200,300
PASS move A -> 1700,640
PASS cycle1: invite secrets identical
PASS cycle1: gm state identical after SIGTERM restart
PASS cycle1: A state identical after SIGTERM restart
PASS cycle1: B state identical after SIGTERM restart
PASS A explored new area (292 -> 1145)
PASS cycle1: token positions are the moved ones
PASS cycle1: door states are the toggled ones
PASS cycle1: doors differ from initial (test is not vacuous)
PASS move A -> 1900,640
PASS move B -> 1000,2300
PASS move M1 -> 1200,640
PASS cycle2: invite secrets identical
PASS cycle2: gm state identical after SIGKILL restart
PASS cycle2: A state identical after SIGKILL restart
PASS cycle2: B state identical after SIGKILL restart
PASS cycle2: A explored more before kill -9
PASS cycle2: B explored more before kill -9
restart: PASS
@@ -0,0 +1,11 @@
version = "0.1.0"
author = "proto"
description = "Throwaway: server-authoritative vision prototype"
license = "MIT"
srcDir = "src"
bin = @["server"]
requires "nim >= 2.0"
# no tags upstream: pin exact commit
requires "mummy#01deb1ff694988635c7bf0f24f6088a0bdf6db5d"
requires "db_connector"
@@ -0,0 +1,116 @@
## 2D vision geometry. Pure, no deps.
import std/[math, algorithm]
type
Vec* = tuple[x, y: float]
Wall* = object
a*, b*: Vec
door*, open*: bool
const
Eps = 1e-9 # geometric tolerance (px)
RayEps = 1e-4 # angular nudge past endpoints (rad)
proc blocks*(w: Wall): bool = not (w.door and w.open)
proc cross(a, b: Vec): float = a.x * b.y - a.y * b.x
proc `-`(a, b: Vec): Vec = (a.x - b.x, a.y - b.y)
proc rayHit(o, d: Vec, a, b: Vec): float =
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
let e = b - a
let den = cross(d, e)
if abs(den) < 1e-12: return Inf # parallel/collinear: grazing, other rays cover it
let ao = a - o
let t = cross(ao, e) / den
let u = cross(ao, d) / den
if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
proc visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float,
circleSegs = 64): seq[Vec] =
## CCW polygon of what `o` sees, bounded by an inscribed circleSegs-gon of `radius`.
var segs: seq[(Vec, Vec)]
var angles: seq[float]
for i in 0 ..< circleSegs:
let a0 = 2 * PI * i.float / circleSegs.float
let a1 = 2 * PI * (i + 1).float / circleSegs.float
segs.add(((o.x + radius * cos a0, o.y + radius * sin a0),
(o.x + radius * cos a1, o.y + radius * sin a1)))
angles.add arctan2(sin a0, cos a0) # same (-pi,pi] range as the wall angles, else the sort scrambles the fan
for w in walls:
if not w.blocks: continue
# shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid
if max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or
max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue
segs.add((w.a, w.b))
for p in [w.a, w.b]:
if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue # token on endpoint
let ang = arctan2(p.y - o.y, p.x - o.x)
angles.add ang
angles.add ang - RayEps
angles.add ang + RayEps
angles.sort
for ang in angles:
let d: Vec = (cos ang, sin ang)
var best = Inf
for s in segs: best = min(best, rayHit(o, d, s[0], s[1]))
if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best))
proc segsCross(p, q, a, b: Vec): bool =
## inclusive segment intersection (touching and collinear overlap count)
proc orient(a, b, c: Vec): int =
let v = cross(b - a, c - a)
if v > Eps: 1 elif v < -Eps: -1 else: 0
proc onSeg(a, b, c: Vec): bool = # c collinear with ab: within bbox?
c.x >= min(a.x, b.x) - Eps and c.x <= max(a.x, b.x) + Eps and
c.y >= min(a.y, b.y) - Eps and c.y <= max(a.y, b.y) + Eps
let o1 = orient(p, q, a); let o2 = orient(p, q, b)
let o3 = orient(a, b, p); let o4 = orient(a, b, q)
if o1 != o2 and o3 != o4: return true
(o1 == 0 and onSeg(p, q, a)) or (o2 == 0 and onSeg(p, q, b)) or
(o3 == 0 and onSeg(a, b, p)) or (o4 == 0 and onSeg(a, b, q))
proc segDist(p, a, b: Vec): float =
let e = b - a
let l2 = e.x * e.x + e.y * e.y
let t = if l2 < Eps: 0.0 else: clamp(((p.x - a.x) * e.x + (p.y - a.y) * e.y) / l2, 0.0, 1.0)
hypot(p.x - a.x - t * e.x, p.y - a.y - t * e.y)
proc moveBlocked*(walls: openArray[Wall], a, b: Vec, r = 0.0): bool =
## true if travelling a->b touches any blocking wall (touching counts: no leaking through shared vertices)
## or the token circle (radius r) at b overlaps one. Only b is checked for clearance, so a token
## already overlapping (legacy position, door closed on it) can still leave to a clear spot.
## shortcut: a token standing exactly on a wall can't move off it; server must keep tokens off walls.
for w in walls:
if w.blocks and (segsCross(a, b, w.a, w.b) or segDist(b, w.a, w.b) < r): return true
proc inside*(poly: openArray[Vec], p: Vec): bool =
## even-odd point-in-polygon (boundary ambiguous)
var j = poly.len - 1
for i in 0 ..< poly.len:
if (poly[i].y > p.y) != (poly[j].y > p.y) and
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x:
result = not result
j = i
proc cellsTouched*(poly: openArray[Vec], cell: float): seq[(int, int)] =
## grid cells (ix, iy) overlapped by the polygon (area overlap, boundary touch included), sorted.
if poly.len < 3: return
var x0, y0 = Inf
var x1, y1 = -Inf
for p in poly:
x0 = min(x0, p.x); x1 = max(x1, p.x); y0 = min(y0, p.y); y1 = max(y1, p.y)
for iy in int(floor(y0 / cell)) .. int(floor(y1 / cell)):
for ix in int(floor(x0 / cell)) .. int(floor(x1 / cell)):
let (cx0, cy0, cx1, cy1) = (ix.float * cell, iy.float * cell, (ix + 1).float * cell, (iy + 1).float * cell)
let c = [(cx0, cy0), (cx1, cy0), (cx1, cy1), (cx0, cy1)]
# no edge crosses => cell wholly inside poly (a corner decides) or poly wholly inside cell (a vertex decides) or disjoint
var hit = inside(poly, c[0]) or
(poly[0].x >= cx0 and poly[0].x <= cx1 and poly[0].y >= cy0 and poly[0].y <= cy1)
if not hit:
for i in 0 ..< poly.len:
let p = poly[i]; let q = poly[(i + 1) mod poly.len]
for k in 0 .. 3:
if segsCross(p, q, c[k], c[(k + 1) mod 4]): hit = true; break
if hit: break
if hit: result.add (ix, iy)
@@ -0,0 +1,366 @@
## Server-authoritative vision. Players are untrusted: only what is in their vision reaches them.
## One global Lock: validate -> mutate -> recompute vision -> persist -> send, so gseq order == send order.
import std/[json, tables, sets, locks, os, monotimes, times, strutils, sysrand, strformat, algorithm]
import mummy, db_connector/db_sqlite
import geometry
type
Tok = object
id, name, kind: string
pos: Vec
gmOnly: bool
Role = ref object # per player: shared by all that player's connections
polys: seq[seq[Vec]]
ver: int # bumped when polys change
explored: HashSet[int]
fresh: seq[int] # cells added by the current mutation
Conn = ref object
ws: WebSocket
role: string # "gm" | "A" | "B"
ver: int
known: Table[string, Vec] # tokens this client currently has
bytes: int
Ev = object # what the current mutation was
door: int
doorOpen: bool
moved, by: string
reqId: int
Stat = object
n: int
sum, worst: float
# nginx public port; 8080 per spec, PORT overrides when taken
let origin = "http://localhost:" & getEnv("PORT", "8080")
# RUN_DIR: db/invites dir (tools/withserver.sh sets run/test); BACKEND_PORT: mummy listen port (nginx proxies to it)
let runDir = getEnv("RUN_DIR", "run")
let backendPort = parseInt(getEnv("BACKEND_PORT", "9000"))
var
lk: Lock
db: DbConn
walls: seq[Wall] # index == wall id
toks: seq[Tok]
worldW, worldH, tileSize, cell, cw: int
radius, tokRadius: float
roles: Table[string, Role]
secrets: Table[string, string] # secret -> "gm"|"A"|"B"
conns: Table[string, Conn]
gseq: int
vstat, bstat: Table[string, Stat]
nMut: int
# per-mutation timing (ms), all set under lk: tLock = lock acquired, tSql = sqlite phase, tSend = send phase start
lockWaitMs, sqlMs: float
tLock, tSend: MonoTime
tm: array[5, seq[float]] # wait, vision, sql, send, total; one entry per mutation
let slowMs = parseFloat(getEnv("SLOW_MS", "50")) # mutations over this get a SLOW line with the breakdown
const tmNames = ["lock_wait", "vision", "sqlite", "send", "total"]
proc msSince(t: MonoTime): float = (getMonoTime() - t).inNanoseconds.float / 1e6
lk.initLock
# TEST BUILD ONLY (-d:leakfault, tools/faulttest.sh): deliberate leaks picked at run time by env LEAK_FAULT.
# Without the define fault() is a constant false and neither this code nor the env name is compiled in.
when defined(leakfault):
let faultName = getEnv("LEAK_FAULT")
template fault(n: string): bool =
when defined(leakfault): faultName == n else: false
proc add(s: var Stat, v: float) = inc s.n; s.sum += v; s.worst = max(s.worst, v)
proc printStats() =
for k, s in vstat: echo &"STATS vision_ms {k}: n={s.n} avg={s.sum / s.n.float:.3f} worst={s.worst:.3f}"
for k, s in bstat: echo &"STATS bytes/delivery {k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
for i, n in tmNames:
var a = tm[i]
if a.len == 0: continue
a.sort
var sum = 0.0
for v in a: sum += v
echo &"STATS timing_ms {n}: n={a.len} avg={sum / a.len.float:.3f} p50={a[a.len div 2]:.3f} p99={a[min(a.len - 1, a.len * 99 div 100)]:.3f} worst={a[^1]:.3f}"
stdout.flushFile
# shortcut: WebSocket has no ==/hash and private fields; key by raw bytes, fine while the layout is plain POD
proc key(ws: WebSocket): string =
result = newString(sizeof(ws)); copyMem(addr result[0], unsafeAddr ws, sizeof(ws))
proc owns(role, id: string): bool = role == "gm" or role == id
proc pt(v: Vec): JsonNode = %[%v.x, %v.y]
proc tokIdx(id: string): int =
for i, t in toks:
if t.id == id: return i
-1
proc send(c: Conn, t: string, j: JsonNode) =
j["t"] = %t; j["gseq"] = %gseq
let s = $j
c.bytes += s.len
c.ws.send(s)
proc err(c: Conn, msg: string) = c.send("error", %*{"msg": msg})
proc recompute(rn: string) =
let r = roles[rn]
var np: seq[seq[Vec]]
for t in toks:
if owns(rn, t.id): np.add visibilityPolygon(t.pos, walls, radius)
if np == r.polys: return
r.polys = np; inc r.ver
for p in np:
for (ix, iy) in cellsTouched(p, cell.float):
if ix >= 0 and iy >= 0 and ix < cw and iy < cw:
let k = iy * cw + ix
if not r.explored.containsOrIncl(k): r.fresh.add k
proc persistCells(rn: string) =
for k in roles[rn].fresh: db.exec(sql"INSERT OR IGNORE INTO exp VALUES (?,?)", rn, k)
proc sync(c: Conn, ev: Ev, initial: bool) =
## bring one client up to date; diff against what it already has
let player = c.role != "gm"
var r: Role
if player:
r = roles[c.role]
if c.ver != r.ver or (fault("other-vision") and c.role == "A"):
c.ver = r.ver
var ps = newJArray()
for p in (if fault("other-vision") and c.role == "A": r.polys & roles["B"].polys else: r.polys):
var a = newJArray()
for v in p: a.add pt(v)
ps.add a
c.send("vision", %*{"polys": ps})
var cells = newJArray()
let leakB = fault("other-explored") and c.role == "A"
if initial:
for k in r.explored: cells.add %[k mod cw, k div cw]
if leakB:
for k in roles["B"].explored: cells.add %[k mod cw, k div cw]
else:
for k in r.fresh: cells.add %[k mod cw, k div cw]
if leakB:
for k in roles["B"].fresh: cells.add %[k mod cw, k div cw]
if cells.len > 0: c.send("explored", %*{"cells": cells})
elif ev.door >= 0:
c.send("door", %*{"id": ev.door, "open": ev.doorOpen})
for t in toks:
var vis = c.role == "gm" or t.id == c.role
if not vis:
for p in r.polys:
if inside(p, t.pos): vis = true; break
if player and ((fault("hidden") and t.id == "M5") or (fault("withhold") and t.id == "M1")):
vis = t.id == "M5"
if vis:
if c.known.getOrDefault(t.id, (-1.0, -1.0)) != t.pos or initial:
c.known[t.id] = t.pos
let j = %*{"id": t.id, "name": t.name, "kind": t.kind, "pos": pt(t.pos), "mine": owns(c.role, t.id)}
if t.id == ev.moved and ev.reqId >= 0: j["by"] = %ev.by; j["reqId"] = %ev.reqId
c.send("token", j)
elif c.known.hasKey(t.id):
c.known.del t.id
if not (fault("noremove") and player): c.send("remove", %*{"id": t.id})
proc finish(ev: Ev, kind: string, visMs: float, mover: Conn = nil) =
## send phase of a mutation (caller holds lk, DB already committed)
for c in conns.values:
if c != mover: c.bytes = 0
sync(c, ev, false)
for r in roles.values: r.fresh.setLen 0
let sendMs = tSend.msSince
vstat.mgetOrPut(kind, Stat()).add visMs
var line = &"MUT gseq={gseq} {kind} vision_ms={visMs:.3f}"
for c in conns.values:
if c.bytes > 0: bstat.mgetOrPut(kind & " " & c.role, Stat()).add c.bytes.float # only recipients that got something
line.add &" {c.role}:{c.bytes}B"
echo line
inc nMut
if nMut mod 5000 == 0: printStats()
stdout.flushFile
# total = lock wait + everything under the lock (incl. the MUT line write); SLOW line is written after, not counted
let tot = lockWaitMs + tLock.msSince
for i, v in [lockWaitMs, visMs, sqlMs, sendMs, tot]: tm[i].add v
if tot > slowMs:
echo &"SLOW gseq={gseq} {kind} total={tot:.1f} lock_wait={lockWaitMs:.1f} vision={visMs:.1f} sqlite={sqlMs:.1f} send={sendMs:.1f} other={tot - lockWaitMs - visMs - sqlMs - sendMs:.1f}"
stdout.flushFile
proc handleMove(c: Conn, m: JsonNode) =
let p = m{"pos"}
if m{"reqId"}.isNil or m["reqId"].kind != JInt or m{"id"}.isNil or m["id"].kind != JString or
p.isNil or p.kind != JArray or p.len != 2 or p[0].kind notin {JInt, JFloat} or p[1].kind notin {JInt, JFloat}:
c.err("bad move"); return
let id = m["id"].getStr
let ti = tokIdx(id)
if ti < 0 or not owns(c.role, id): c.err("not yours"); return # no pos echoed: could leak unseen tokens
let reqId = m["reqId"].getInt
let np: Vec = (p[0].getFloat, p[1].getFloat)
let old = toks[ti].pos
if np.x < 0 or np.y < 0 or np.x > worldW.float or np.y > worldH.float or moveBlocked(walls, old, np, tokRadius):
c.send("moveAck", %*{"reqId": reqId, "ok": false, "pos": pt(old)}); return
toks[ti].pos = np
inc gseq
for x in conns.values: x.bytes = 0
let t0 = getMonoTime()
if roles.hasKey(id): recompute(id)
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
let t1 = getMonoTime()
db.exec(sql"BEGIN")
db.exec(sql"INSERT OR REPLACE INTO tok VALUES (?,?,?)", id, np.x, np.y)
if roles.hasKey(id): persistCells(id)
db.exec(sql"COMMIT")
sqlMs = t1.msSince; tSend = getMonoTime()
c.send("moveAck", %*{"reqId": reqId, "ok": true, "pos": pt(np)})
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), (if roles.hasKey(id): "move-player" else: "move-monster"), visMs, c)
proc handleDoor(c: Conn, m: JsonNode) =
if c.role != "gm": c.err("gm only"); return
if m{"id"}.isNil or m["id"].kind != JInt or m{"open"}.isNil or m["open"].kind != JBool:
c.err("bad door"); return
let id = m["id"].getInt
if id < 0 or id >= walls.len or not walls[id].door: c.err("not a door"); return
let open = m["open"].getBool
if walls[id].open == open: return
walls[id].open = open
inc gseq
for x in conns.values: x.bytes = 0
let t0 = getMonoTime()
for rn in roles.keys: recompute(rn)
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
let t1 = getMonoTime()
db.exec(sql"BEGIN")
db.exec(sql"INSERT OR REPLACE INTO door VALUES (?,?)", id, ord(open))
for rn in roles.keys: persistCells(rn)
db.exec(sql"COMMIT")
sqlMs = t1.msSince; tSend = getMonoTime()
finish(Ev(door: id, doorOpen: open, moved: "", reqId: -1), "door", visMs, c)
proc openConn(ws: WebSocket, role: string) =
let c = Conn(ws: ws, role: role, ver: -1)
conns[key(ws)] = c
let ids = newJArray()
for t in toks:
if owns(role, t.id) or (fault("other-owner") and role == "A" and t.id == "B"): ids.add %t.id
c.send("hello", %*{"role": (if role == "gm": "gm" else: "player"), "tokens": ids,
"world": {"w": worldW, "h": worldH}, "tileSize": tileSize, "exploredCell": cell, "tokenRadius": tokRadius})
if role == "gm" or fault("walls"):
var ws = newJArray()
for i, w in walls: ws.add %*{"id": i, "a": pt(w.a), "b": pt(w.b), "door": w.door, "open": w.open}
c.send("walls", %*{"walls": ws})
sync(c, Ev(door: -1, reqId: -1), true)
proc wsHandler(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
{.gcsafe.}:
let tq = getMonoTime()
withLock lk:
lockWaitMs = tq.msSince; tLock = getMonoTime()
case event
of MessageEvent:
let c = conns.getOrDefault(key(ws))
if c.isNil or message.kind != TextMessage: return
try:
let m = parseJson(message.data)
case m{"t"}.getStr
of "move": handleMove(c, m)
of "door": handleDoor(c, m)
else: c.err("unknown type")
except CatchableError:
c.err("malformed")
of CloseEvent, ErrorEvent: conns.del key(ws)
else: discard
proc cookieSecret(request: Request): string =
for (k, v) in request.headers:
if k.toLowerAscii == "cookie":
for part in v.split(';'):
let p = part.strip
if p.startsWith("sid="): return p[4 .. ^1]
proc handler(request: Request) {.gcsafe.} =
{.gcsafe.}:
let path = request.path
if path.startsWith("/join/") and request.httpMethod == "GET":
let s = path[6 .. ^1]
withLock lk:
if s notin secrets: request.respond(403); return
var h: HttpHeaders
h["Location"] = "/"
h["Set-Cookie"] = &"sid={s}; Path=/; HttpOnly; SameSite=Strict"
request.respond(302, h)
elif path == "/ws":
withLock lk:
let s = cookieSecret(request)
if s notin secrets: request.respond(403); return
openConn(request.upgradeToWebSocket(), secrets[s])
elif path.startsWith("/tiles/") and path.endsWith(".png"):
let parts = path[7 .. ^5].split('_')
if parts.len != 2 or parts[0].len notin 1..3 or parts[1].len notin 1..3 or
not parts[0].allCharsInSet(Digits) or not parts[1].allCharsInSet(Digits):
request.respond(404); return
let (tx, ty) = (parseInt(parts[0]), parseInt(parts[1]))
if tx >= worldW div tileSize or ty >= worldH div tileSize: request.respond(404); return
var ok = false
withLock lk:
let s = cookieSecret(request)
if s in secrets:
let rn = secrets[s]
ok = rn == "gm" or fault("tile")
if not ok:
let per = tileSize div cell # shortcut: assumes tileSize % exploredCell == 0
for cy in ty * per ..< (ty + 1) * per:
for cx in tx * per ..< (tx + 1) * per:
if (cy * cw + cx) in roles[rn].explored: ok = true
if ok:
var h: HttpHeaders
h["X-Accel-Redirect"] = &"/_tiles/{tx}_{ty}.png"
request.respond(200, h)
else: request.respond(403)
else: request.respond(404)
proc loadState() =
let sc = parseFile("data/scene.json")
worldW = sc["world"]["w"].getInt; worldH = sc["world"]["h"].getInt
tileSize = sc["tileSize"].getInt; cell = sc["exploredCell"].getInt
radius = sc["visionRadius"].getFloat
tokRadius = sc["tokenRadius"].getFloat
cw = (worldW + cell - 1) div cell
for w in sc["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w["door"].getBool, open: w["open"].getBool)
for t in sc["tokens"]:
toks.add Tok(id: t["id"].getStr, name: t["name"].getStr, kind: t["kind"].getStr,
pos: (t["pos"][0].getFloat, t["pos"][1].getFloat), gmOnly: t["gmOnly"].getBool)
createDir runDir
db = open(runDir / "state.db", "", "", "")
discard db.getAllRows(sql"PRAGMA journal_mode=WAL")
db.exec(sql"PRAGMA synchronous=NORMAL") # WAL: commit no longer fsyncs (power loss may drop the last commits, never corrupts; process kill loses nothing)
for s in ["CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)",
"CREATE TABLE IF NOT EXISTS tok (id TEXT PRIMARY KEY, x REAL, y REAL)",
"CREATE TABLE IF NOT EXISTS door (id INTEGER PRIMARY KEY, open INTEGER)",
"CREATE TABLE IF NOT EXISTS exp (role TEXT, c INTEGER, PRIMARY KEY (role, c))"]:
db.exec(sql(s))
for r in db.getAllRows(sql"SELECT id,x,y FROM tok"):
toks[tokIdx(r[0])].pos = (parseFloat(r[1]), parseFloat(r[2]))
for r in db.getAllRows(sql"SELECT id,open FROM door"): walls[parseInt(r[0])].open = r[1] == "1"
var invites = ""
for rn in ["gm", "A", "B"]:
var s = db.getValue(sql"SELECT v FROM meta WHERE k=?", rn)
if s == "":
for b in urandom(16): s.add toHex(b.int, 2).toLowerAscii
db.exec(sql"INSERT INTO meta VALUES (?,?)", rn, s)
secrets[s] = rn
invites.add &"{rn} {origin}/join/{s}\n"
if rn != "gm":
roles[rn] = Role(ver: 0)
for r in db.getAllRows(sql"SELECT c FROM exp WHERE role=?", rn): roles[rn].explored.incl parseInt(r[0])
echo invites
writeFile(runDir / "invites.txt", invites)
db.exec(sql"BEGIN")
for rn in roles.keys:
recompute(rn); persistCells(rn); roles[rn].fresh.setLen 0
db.exec(sql"COMMIT")
loadState()
setControlCHook(proc() {.noconv.} =
{.gcsafe.}:
printStats() # shortcut: reads stats without the lock; fine at exit
quit 0)
let server = newServer(handler, wsHandler, workerThreads = 8)
echo "listening 127.0.0.1:" & $backendPort
stdout.flushFile
server.serve(Port(backendPort), "127.0.0.1")
@@ -0,0 +1,238 @@
import std/[unittest, json, os]
import geometry
proc W(ax, ay, bx, by: float, door = false, open = false): Wall =
Wall(a: (ax, ay), b: (bx, by), door: door, open: open)
proc box(x0, y0, x1, y1: float): seq[Wall] =
@[W(x0, y0, x1, y0), W(x1, y0, x1, y1), W(x1, y1, x0, y1), W(x0, y1, x0, y0)]
proc sees(walls: openArray[Wall], o, p: Vec, r = 500.0): bool =
visibilityPolygon(o, walls, r).inside(p)
proc hasVertex(poly: openArray[Vec], p: Vec): bool =
for v in poly:
if abs(v.x - p.x) < 1e-6 and abs(v.y - p.y) < 1e-6: return true
suite "visibility":
test "open space is a circle":
let poly = visibilityPolygon((0.0, 0.0), @[], 100)
check poly.inside((60.0, 0.0))
check not poly.inside((101.0, 0.0))
check poly.inside((0.0, -95.0))
test "wall blocks":
let w = @[W(50, -50, 50, 50)]
check not sees(w, (0.0, 0.0), (80.0, 0.0))
check sees(w, (0.0, 0.0), (40.0, 0.0))
test "shared endpoint: no leak at the vertex":
# L corner at (50,0): vertical arm (50,-50)-(50,0), horizontal arm (50,0)-(100,0)
let w = @[W(50, -50, 50, 0), W(50, 0, 100, 0)]
# viewer on the diagonal through the shared vertex: the ray touches both arms' endpoint
let v: Vec = (0.0, -25.0)
check visibilityPolygon(v, w, 500).hasVertex((50.0, 0.0))
check not sees(w, v, (70.0, 9.0)) # just below the ray through the vertex (y=10 at x=70): vertical arm shadows it
check sees(w, v, (70.0, 11.0)) # just above the ray: past the vertex, the corner is not a crack
# token on the line of the horizontal arm: a point just above the line is visible past the arm's end-on
# edge, just below it is shadowed by the vertical arm
check sees(w, (0.0, 0.0), (70.0, 5.0))
check not sees(w, (0.0, 0.0), (70.0, -5.0))
test "'<' apex: ray through the shared tip must not leak":
for flip in [false, true]: # each wall in both directions: the tip is an upper end of one and a lower end of the other
let w = if flip: @[W(100, 0, 50, -40), W(100, 0, 50, 40)] else: @[W(50, -40, 100, 0), W(50, 40, 100, 0)]
check visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
check not sees(w, (0.0, 0.0), (150.0, 0.0))
check not sees(w, (0.0, 0.0), (300.0, 0.0))
check sees(w, (0.0, 0.0), (90.0, 0.0))
test "every segment endpoint is a polygon vertex (lower and upper end inclusive)":
# free-standing wall, nothing else shares the endpoints: an exclusive end would drop the exact-endpoint ray
let w = @[W(50, -30, 80, 10)]
let poly = visibilityPolygon((0.0, 0.0), w, 500)
check poly.hasVertex((50.0, -30.0)) # lower end (u = 0)
check poly.hasVertex((80.0, 10.0)) # upper end (u = 1)
let r = @[W(80, 10, 50, -30)] # same wall, ends swapped
let pr = visibilityPolygon((0.0, 0.0), r, 500)
check pr.hasVertex((50.0, -30.0))
check pr.hasVertex((80.0, 10.0))
test "rays nudged past a corner: area just beyond a wall end is visible":
# viewer heights are chosen so the corner ray sits mid-way between two circle rays: no other ray can mask a missing nudge ray
# wall (50,-50)-(50,0) seen from (0,7.4): the ray through the end (50,0) continues to (100,-7.4)
let w = @[W(50, -50, 50, 0)]
check sees(w, (0.0, 7.4), (100.0, -6.0)) # lit side of that ray
check not sees(w, (0.0, 7.4), (100.0, -9.0)) # shadow side
# mirror: wall (50,0)-(50,50) seen from (0,-7.4)
let m = @[W(50, 0, 50, 50)]
check sees(m, (0.0, -7.4), (100.0, 6.0))
check not sees(m, (0.0, -7.4), (100.0, 9.0))
# box (pillar) seen from (0,-24): the rays through corners (100,50) and (100,-50) continue to (200,124) and (200,-76)
let b = box(100, -50, 150, 50)
check sees(b, (0.0, -24.0), (200.0, 130.0))
check not sees(b, (0.0, -24.0), (200.0, 118.0))
check sees(b, (0.0, -24.0), (200.0, -85.0))
check not sees(b, (0.0, -24.0), (200.0, -70.0))
test "shared endpoint: closed corner of box has no crack":
let w = box(-100, -100, 100, 100)
check not sees(w, (0.0, 0.0), (130.0, 130.0), 1000)
check not sees(w, (-90.0, -90.0), (-130.0, -130.0), 1000)
check sees(w, (0.0, 0.0), (95.0, 95.0), 1000) # the corner itself is visible from inside
check sees(w, (-90.0, -90.0), (90.0, 90.0), 1000)
test "collinear walls act as one":
let w = @[W(50, -50, 50, 0), W(50, 0, 50, 50)]
check not sees(w, (0.0, 0.0), (80.0, 0.0)) # ray through the join
check not sees(w, (0.0, 30.0), (80.0, 30.0))
check sees(w, (0.0, 0.0), (40.0, 0.0)) # in front of the join
check sees(w, (0.0, 0.0), (-80.0, 0.0)) # behind the viewer
check sees(w, (0.0, 0.0), (80.0, 100.0)) # past the far end of the line
check not sees(w, (0.0, 0.0), (80.0, -30.0))
test "collinear walls with a gap let light through":
let w = @[W(50, -50, 50, -5), W(50, 5, 50, 50)]
check sees(w, (0.0, 0.0), (80.0, 0.0))
check not sees(w, (0.0, 0.0), (80.0, 30.0))
test "T-junction: no leak and correct shadow":
# horizontal y=0 from x=-100..100, vertical stem from (0,0) up to (0,-100)
let w = @[W(-100, 0, 100, 0), W(0, 0, 0, -100)]
check not sees(w, (-30.0, -30.0), (30.0, -30.0)) # stem blocks
check not sees(w, (-30.0, -30.0), (-30.0, 30.0)) # base blocks
check sees(w, (-30.0, -30.0), (-80.0, -60.0))
check not sees(w, (-30.0, -30.0), (10.0, -5.0), 500)
check sees(w, (-30.0, -30.0), (-10.0, -5.0)) # same side of the stem, above the base
check sees(w, (30.0, -30.0), (80.0, -60.0)) # mirror side
check not sees(w, (30.0, -30.0), (-10.0, -5.0))
test "pillar mid-room casts a shadow, sides visible":
var w = box(-200, -200, 200, 200)
w.add box(-10, -10, 10, 10)
check not sees(w, (-100.0, 0.0), (100.0, 0.0))
check sees(w, (-100.0, 0.0), (100.0, 50.0))
check sees(w, (-100.0, 0.0), (0.0, 50.0))
check not sees(w, (-100.0, 0.0), (50.0, 3.0))
test "closed door blocks, open door passes":
let closed = @[W(50, -50, 50, -10), W(50, -10, 50, 10, true, false), W(50, 10, 50, 50)]
var opened = closed
opened[1].open = true
check not sees(closed, (0.0, 0.0), (90.0, 0.0))
check sees(opened, (0.0, 0.0), (90.0, 0.0))
check not sees(opened, (0.0, 0.0), (90.0, 40.0))
test "token exactly at wall endpoint":
let w = @[W(0, 0, 100, 0), W(0, 0, 0, 100)] # corner, token on it
let poly = visibilityPolygon((0.0, 0.0), w, 200)
check poly.inside((-50.0, -50.0)) # open outward quadrant
check poly.inside((100.0, -30.0))
check poly.inside((50.0, 50.0)) # arms radiate from the token: the inner quadrant is open too
check poly.inside((-50.0, 50.0))
check not poly.inside((150.0, 150.0)) # beyond the radius (212 > 200)
check not poly.inside((0.0, 250.0))
test "token at endpoint of free-standing wall sees along it":
let w = @[W(0, 0, 100, 0)]
check sees(w, (0.0, 0.0), (50.0, -20.0))
check sees(w, (0.0, 0.0), (-50.0, 20.0))
check sees(w, (0.0, 0.0), (50.0, 20.0))
check not sees(w, (0.0, 0.0), (600.0, 0.0)) # beyond the 500 radius
test "long thin corridor":
# 1000 long, 20 wide, token at one end; radius 2000
let w = @[W(0, -10, 1000, -10), W(0, 10, 1000, 10), W(1000, -10, 1000, 10)]
check sees(w, (5.0, 0.0), (990.0, 0.0), 2000)
check not sees(w, (5.0, 0.0), (500.0, 15.0), 2000)
check not sees(w, (5.0, 0.0), (1010.0, 0.0), 2000)
check sees(w, (5.0, 0.0), (900.0, 8.0), 2000)
test "wall endpoints behind the viewer: fan stays angularly ordered":
# regression: circle angles in [0,2pi) were sorted against atan2 angles in (-pi,pi] -> bow-tie polygon
let w = box(600, 600, 680, 680) & @[W(1024, 256, 1024, 608)]
check sees(w, (908.66, 672.03), (789.36, 584.65), 400)
check sees(w, (789.36, 584.65), (908.66, 672.03), 400)
check not sees(w, (908.66, 672.03), (1100.0, 500.0), 400) # the x=1024 wall (y 256..608) is in the way
test "radius clips":
check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200)
suite "moves":
let wall = W(0, -50, 0, 50)
test "crossing blocked, parallel ok":
check moveBlocked([wall], (-10.0, 0.0), (10.0, 0.0))
check not moveBlocked([wall], (-10.0, 0.0), (-10.0, 30.0))
check not moveBlocked([wall], (-10.0, 60.0), (10.0, 60.0)) # passes beyond the end
test "grazing an endpoint is blocked":
check moveBlocked([wall], (-10.0, 50.0), (10.0, 50.0))
check moveBlocked([wall], (-10.0, -60.0), (10.0, -40.0)) # crosses
test "no leak through shared vertex":
let w = [W(0, -50, 0, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (-10.0, 0.0), (10.0, 0.0))
test "diagonal squeeze through corner vertex of L":
let w = [W(0, 0, 50, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (10.0, -10.0), (-10.0, 10.0))
test "moving along a collinear wall is blocked":
check moveBlocked([wall], (0.0, -100.0), (0.0, 100.0))
test "doors":
var d = W(0, -10, 0, 10, true, false)
check moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
d.open = true
check not moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
test "zero-length move":
check not moveBlocked([wall], (-5.0, 0.0), (-5.0, 0.0))
suite "cells":
test "square polygon":
let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)]
check cellsTouched(sq, 32) == @[(0, 0), (1, 0), (0, 1), (1, 1)]
test "tiny polygon inside one cell":
check cellsTouched([(1.0, 1.0), (5.0, 1.0), (3.0, 5.0)], 32) == @[(0, 0)]
test "polygon spanning a cell with no vertex in it":
# thin horizontal strip crossing 3 cells
let strip = [(1.0, 10.0), (95.0, 10.0), (95.0, 12.0), (1.0, 12.0)]
check cellsTouched(strip, 32) == @[(0, 0), (1, 0), (2, 0)]
test "big polygon includes fully covered interior cells":
let big = [(0.0, 0.0), (200.0, 0.0), (200.0, 200.0), (0.0, 200.0)]
check (3, 3) in cellsTouched(big, 32)
suite "seed":
test "every token in seed sees itself and is not walled in":
let sp = currentSourcePath().parentDir / ".." / "data" / "scene.json"
if not fileExists(sp): skip()
else:
let j = parseFile(sp)
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w{"door"}.getBool, open: w{"open"}.getBool)
for t in j["tokens"]:
let p: Vec = (t["pos"][0].getFloat, t["pos"][1].getFloat)
let poly = visibilityPolygon(p, walls, j["visionRadius"].getFloat)
check poly.len > 8
check cellsTouched(poly, j["exploredCell"].getFloat).len > 0
check not moveBlocked(walls, p, p, j["tokenRadius"].getFloat)
suite "token clearance (r=20)":
const r = 20.0
test "near pillar: circle overlapping blocked, clear ok":
let pil = box(600, 600, 680, 680)
check moveBlocked(pil, (500.0, 640.0), (585.0, 640.0), r) # center outside, circle inside wall
check not moveBlocked(pil, (500.0, 640.0), (570.0, 640.0), r) # 30 away
test "near closed door blocks, open door passes":
let cl = @[W(0, 0, 0, 64, door = true)]
check moveBlocked(cl, (-50.0, 32.0), (10.0, 32.0), r) # dest 10 from the wall
check moveBlocked(cl, (-50.0, 32.0), (-10.0, 32.0), r)
let op = @[W(0, 0, 0, 64, door = true, open = true)]
check not moveBlocked(op, (-50.0, 32.0), (50.0, 32.0), r)
test "64px corridor and doorway passable on centerline":
let c = @[W(0, 0, 500, 0), W(0, 64, 500, 64)]
check not moveBlocked(c, (10.0, 32.0), (490.0, 32.0), r)
check not moveBlocked(c, (10.0, 32.0), (11.0, 32.0), r)
let door = @[W(0, -200, 0, -32), W(0, 32, 0, 200)]
check not moveBlocked(door, (-30.0, 0.0), (30.0, 0.0), r)
test "legacy overlap can escape, not stay overlapped":
let w = @[W(0, 0, 100, 0)]
check not moveBlocked(w, (50.0, 5.0), (50.0, 40.0), r)
check moveBlocked(w, (50.0, 5.0), (50.0, 15.0), r)
@@ -0,0 +1,29 @@
## Vision microbench: nim c -d:release -r tools/bench.nim (devbox run bench)
import std/[json, monotimes, times, strformat]
import geometry
let j = parseFile("data/scene.json")
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat), door: w["door"].getBool, open: w["open"].getBool)
let r = j["visionRadius"].getFloat
var ps: seq[Vec]
for t in j["tokens"]: ps.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
proc bench(name: string, n: int, f: proc(i: int)) =
var sum, worst = 0.0
for i in 0 ..< n:
let t0 = getMonoTime(); f(i)
let ms = (getMonoTime() - t0).inNanoseconds.float / 1e6
sum += ms; worst = max(worst, ms)
echo &"{name}: n={n} avg={sum / n.float:.3f}ms worst={worst:.3f}ms"
var sink = 0
bench("1 poly (jittered start positions)", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("6 polys (one 6-token party)", 500, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("1 poly + cellsTouched", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
bench("6 polys + cellsTouched", 300, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
echo "(sink ", sink, ")"
@@ -0,0 +1,82 @@
// A, B, GM hammer the server concurrently (moves every 20-50 ms per token, GM toggles doors), then compare views to fresh connections.
import { connect, sleep } from './lib.mjs'
const DUR = (process.env.DUR ?? 60) * 1000
const fails = []
const check = (c, m) => { if (!c) { fails.push(m); console.log('FAIL', m) } }
const sendT = new Map(), lat = { self: [], other: [] }
function mkState(name) {
const st = { name, toks: new Map(), doors: new Map(), explored: new Set(), poly: '[]', last: -1, backwards: 0, msgs: 0, bytes: 0, errors: 0, sent: 0, acks: 0, nack: 0, pending: new Set(), req: 0 }
st.on = (m, b) => {
st.msgs++; st.bytes += b
if (m.gseq < st.last) st.backwards++
st.last = m.gseq
switch (m.t) {
case 'hello': st.toks.clear(); st.explored.clear(); st.doors.clear(); st.poly = '[]'; break
case 'walls': for (const w of m.walls) if (w.door) st.doors.set(w.id, w.open); break
case 'door': st.doors.set(m.id, m.open); break
case 'vision': st.poly = JSON.stringify(m.polys); break
case 'explored': for (const c of m.cells) st.explored.add(c + ''); break
case 'token':
st.toks.set(m.id, m.pos + '')
if (m.reqId !== undefined) { const t0 = sendT.get(m.by + ':' + m.reqId); if (t0 && m.by !== st.name) lat.other.push(performance.now() - t0) }
break
case 'remove': st.toks.delete(m.id); break
case 'moveAck': st.acks++; st.pending.delete(m.reqId); if (!m.ok) st.nack++; st.onAck?.(m); break
case 'error': st.errors++; break
}
}
return st
}
const S = { gm: mkState('gm'), A: mkState('A'), B: mkState('B') }
const C = {}
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, S[r].on)
// random walkers: [client, token id, box]
const walkers = [['A', 'A', [300, 300, 980, 980], [400, 400]], ['B', 'B', [300, 2100, 980, 2780], [400, 2200]],
['gm', 'M1', [300, 300, 980, 980], [900, 900]], ['gm', 'M2', [1600, 300, 2250, 980], [1920, 640]], ['gm', 'M3', [2870, 300, 3530, 980], [3400, 500]],
['gm', 'M4', [300, 2100, 980, 2780], [900, 2700]], ['gm', 'M5', [1600, 2100, 2250, 2780], [1920, 2400]], ['gm', 'M6', [2870, 2100, 3530, 2780], [3200, 2400]]]
let running = true
const rnd = (a, b) => a + Math.random() * (b - a)
const loops = walkers.map(async ([who, id, [x0, y0, x1, y1], p]) => {
const st = S[who]
while (running) {
p = [Math.min(x1, Math.max(x0, p[0] + rnd(-40, 40))), Math.min(y1, Math.max(y0, p[1] + rnd(-40, 40)))]
const r = ++st.req; st.pending.add(r); st.sent++
sendT.set(who + ':' + r, performance.now())
st.onAck = m => { const t0 = sendT.get(who + ':' + m.reqId); if (t0) lat.self.push(performance.now() - t0); if (!m.ok) p = m.pos } // blocked: resync to server pos (shortcut: GM shares one onAck, only the last walker resyncs)
C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p }))
await sleep(rnd(20, 50))
}
})
const doorLoop = (async () => { let o = true; while (running) { await sleep(rnd(1000, 3000)); o = !o; C.gm.ws.send(JSON.stringify({ t: 'door', id: 10, open: o })); C.gm.ws.send(JSON.stringify({ t: 'door', id: 27, open: !o })) } })()
const t0 = performance.now()
await sleep(DUR)
running = false
await Promise.all([...loops, doorLoop])
for (let i = 0; i < 100 && Object.values(S).some(s => s.pending.size); i++) await sleep(100)
await sleep(500)
// quiesced: compare against fresh connections
const F = {}
for (const r of ['gm', 'A', 'B']) { F[r] = mkState(r); await connect(r, F[r].on) }
const sig = m => JSON.stringify([...m].sort())
for (const r of ['gm', 'A', 'B']) {
const s = S[r], f = F[r]
check(s.pending.size === 0, `${r}: ${s.pending.size} moves never acked`)
check(s.sent === s.acks, `${r}: sent ${s.sent} acks ${s.acks}`)
check(s.backwards === 0, `${r}: gseq went backwards ${s.backwards}x`)
check(s.errors === 0, `${r}: ${s.errors} error msgs`)
check(sig(s.toks) === sig(f.toks), `${r}: token view != fresh snapshot`)
check(sig(s.doors) === sig(f.doors), `${r}: doors != fresh`)
check(s.poly === f.poly, `${r}: vision != fresh`)
check(sig(s.explored) === sig(f.explored), `${r}: explored != fresh (${s.explored.size} vs ${f.explored.size})`)
}
const q = (a, p) => a.length ? a.slice().sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(a.length * p))] : NaN
const st = a => `n=${a.length} avg=${(a.reduce((x, y) => x + y, 0) / a.length).toFixed(2)}ms p95=${q(a, 0.95).toFixed(2)}ms p99=${q(a, 0.99).toFixed(2)}ms worst=${Math.max(...a).toFixed(2)}ms`
const secs = (performance.now() - t0) / 1000
for (const r of ['gm', 'A', 'B']) console.log(`${r}: sent ${S[r].sent} moves (${(S[r].sent / secs).toFixed(0)}/s), acks ${S[r].acks} (nack ${S[r].nack}), recv ${S[r].msgs} msgs ${(S[r].bytes / 1024).toFixed(0)} KiB, final gseq ${S[r].last}, tokens in view ${S[r].toks.size}`)
console.log('latency intent->ack (sender):', st(lat.self))
console.log('latency intent->arrival at other clients:', st(lat.other))
console.log(fails.length ? `FAILED ${fails.length}` : 'concurrency: PASS')
process.exit(fails.length ? 1 : 0)
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# Deliberate-leak test: the checker must FAIL, under the right class, for every fault injected into a -d:leakfault server build.
# usage: tools/faulttest.sh (isolated via withserver.sh; also proves the normal build has no hook, and a clean build still passes)
cd "$(dirname "$0")/.." || exit 1
mkdir -p run/test results
nim c -d:release --hints:off -o:run/test/leakcheck tools/leakcheck.nim >/dev/null || exit 1
bad=0
# 1. normal build carries no hook
nim c -d:release --hints:off --nimblePath:"${NIMBLE_DIR:-.devbox/nimble}/pkgs2" --nimcache:run/test/nimcache-clean -o:run/test/server-clean src/server.nim >/dev/null || exit 1
for f in run/test/server-clean; do
[ -f $f ] || continue
if grep -aq LEAK_FAULT $f; then echo "FAIL $f contains the fault hook"; bad=1; else echo "PASS $f has no fault hook"; fi
done
# 2. each fault: "fault-name class" (class must appear as FAILCLASS in checker output, exit must be nonzero)
: > results/faults.log
while read -r fault cls extra; do
out=$(SERVER_FLAGS=-d:leakfault LEAK_FAULT=$fault SUBJECT=A tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' 2>&1); rc=$?
{ echo "== fault $fault"; echo "$out" | grep -E '^(FAIL|leakcheck)'; } >> results/faults.log
got=$(echo "$out" | sed -n 's/^FAILCLASS \([A-Z_]*\) .*/\1/p' | sort | xargs)
want=$(echo "$cls $extra" | tr ' ' '\n' | sort | xargs)
# exact class set: the intended class fires and nothing unrelated does (a checker that flags everything would not prove anything)
if [ $rc -ne 0 ] && [ "$got" = "$want" ]; then echo "PASS fault $fault caught as: $got"
else echo "FAIL fault $fault (rc=$rc) classes [$got] expected [$want]"; echo "$out" | tail -5; bad=1; fi
done <<'LIST'
hidden HIDDEN_TOKEN
walls WALLDATA
tile TILE
withhold WITHHELD
other-vision OTHER_PLAYER OWN_VIEW
other-explored OTHER_PLAYER EXPLORED
other-owner OTHER_PLAYER
noremove NO_REMOVE
LIST
# 3. clean build still passes
if SUBJECT=A tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' >/dev/null 2>&1; then echo "PASS clean build passes"; else echo "FAIL clean build rejected"; bad=1; fi
exit $bad
@@ -0,0 +1,106 @@
// One command: node tools/genmap.mjs -> data/scene.json (source of truth) + data/tiles/<x>_<y>.png
// `--from-seed` skips scene generation and re-renders tiles from the existing data/scene.json.
// Deterministic: layout is hand-authored (no RNG) so the seed edge cases are guaranteed.
import fs from 'node:fs'
import zlib from 'node:zlib'
const SIZE = 4096, TILE = 256, DIR = new URL('../data/', import.meta.url).pathname
const seedPath = DIR + 'scene.json'
function build() {
const walls = []
const add = (a, b, extra = {}) => walls.push({ id: walls.length, a, b, door: false, open: false, ...extra })
const H = (y, x0, x1, e) => add([x0, y], [x1, y], e)
const V = (x, y0, y1, e) => add([x, y0], [x, y1], e)
// split [lo,hi] by gaps [a,b,door?]; plain gap = opening, door gap = door segment
const side = (lo, hi, gaps, emit) => {
let c = lo
for (const [a, b, d] of [...gaps].sort((p, q) => p[0] - q[0])) {
if (a > c) emit(c, a)
if (d) emit(a, b, { door: true, open: d === 'open' })
c = b
}
if (c < hi) emit(c, hi)
}
const room = (x0, y0, x1, y1, g = {}) => {
side(x0, x1, g.n ?? [], (a, b, e) => H(y0, a, b, e))
side(x0, x1, g.s ?? [], (a, b, e) => H(y1, a, b, e))
side(y0, y1, g.w ?? [], (a, b, e) => V(x0, a, b, e))
side(y0, y1, g.e ?? [], (a, b, e) => V(x1, a, b, e))
}
const rooms = [
[256, 256, 1024, 1024, { e: [[608, 672]], s: [[608, 672]] }], // R1 (pillar)
[1536, 256, 2304, 1024, { w: [[608, 672, 'closed']], e: [[608, 672]], s: [[1888, 1952]] }], // R2: door 1
[2816, 256, 3584, 1024, { w: [[608, 672]], s: [[3168, 3232]] }], // R3 (T-junction, split north wall)
[256, 2048, 1024, 2816, { n: [[608, 672]], e: [[2400, 2464]] }], // R4
[1536, 2048, 2304, 2816, { n: [[1888, 1952, 'open']], w: [[2400, 2464]], e: [[2400, 2464]] }], // R5: door 2
[2816, 2048, 3584, 2816, { n: [[3168, 3232]], w: [[2400, 2464]] }], // R6
]
const floors = rooms.map(r => r.slice(0, 4))
rooms.forEach(r => room(...r))
// collinear: split R3's north wall into two touching pieces at x=3200
const n3 = walls.find(w => w.a[0] === 2816 && w.a[1] === 256 && w.b[0] === 3584 && w.b[1] === 256)
n3.b = [3200, 256]; H(256, 3200, 3584)
// corridors: two parallel walls + floor
const hc = (y0, y1, x0, x1) => { H(y0, x0, x1); H(y1, x0, x1); floors.push([x0, y0, x1, y1]) }
const vc = (x0, x1, y0, y1) => { V(x0, y0, y1); V(x1, y0, y1); floors.push([x0, y0, x1, y1]) }
hc(608, 672, 1024, 1536); hc(608, 672, 2304, 2816) // R1-R2 (door at R2 end), R2-R3
hc(2400, 2464, 1024, 1536); hc(2400, 2464, 2304, 2816) // R4-R5, R5-R6
vc(1888, 1952, 1024, 2048) // R2-R5: 1024 long, 64 wide (long thin)
vc(3168, 3232, 1024, 2048); vc(608, 672, 1024, 2048) // R3-R6, R1-R4
// pillar mid-room R1 (centre 640,640)
H(600, 600, 680); H(680, 600, 680); V(600, 600, 680); V(680, 600, 680)
// T-junction: partition ends mid-way on R3's south wall piece (2816..3168) at x=3000
V(3000, 700, 1024)
const tok = (id, kind, name, pos, gmOnly) => ({ id, kind, name, pos, gmOnly })
const tokens = [
tok('A', 'player', 'Player A', [400, 400], false),
tok('B', 'player', 'Player B', [400, 2200], false),
...[[900, 900], [1920, 640], [3400, 500], [900, 2700], [1920, 2400], [3200, 2400]]
.map((p, i) => tok(`M${i + 1}`, 'monster', `Monster ${i + 1}`, p, true)),
]
return { world: { w: SIZE, h: SIZE }, tileSize: TILE, visionRadius: 400, tokenRadius: 20, exploredCell: 32, walls, floors, tokens }
}
// --- raster ---
const crcT = Uint32Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0 })
const crc = b => { let c = ~0; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return ~c >>> 0 }
const chunk = (t, d) => { const b = Buffer.alloc(12 + d.length); b.writeUInt32BE(d.length); b.write(t, 4); d.copy(b, 8); b.writeUInt32BE(crc(b.subarray(4, 8 + d.length)), 8 + d.length); return b }
function png(rgb, w, h) {
const raw = Buffer.alloc((w * 3 + 1) * h)
for (let y = 0; y < h; y++) rgb.copy(raw, y * (w * 3 + 1) + 1, y * w * 3, (y + 1) * w * 3)
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])
}
function render(scene) {
const img = Buffer.alloc(SIZE * SIZE * 3)
const fill = (x0, y0, x1, y1, [r, g, b]) => {
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = (y * SIZE + x) * 3; img[i] = r; img[i + 1] = g; img[i + 2] = b }
}
fill(0, 0, SIZE, SIZE, [24, 22, 28])
for (const [x0, y0, x1, y1] of scene.floors) fill(x0, y0, x1, y1, [120, 112, 100])
const HALF = 4
for (const w of scene.walls) {
const [ax, ay] = w.a, [bx, by] = w.b
// door look is state-independent: tiles must not reveal or go stale on open/closed
const col = w.door ? [150, 80, 30] : [10, 10, 12]
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy
for (let y = Math.max(0, Math.min(ay, by) - HALF); y <= Math.min(SIZE - 1, Math.max(ay, by) + HALF); y++)
for (let x = Math.max(0, Math.min(ax, bx) - HALF); x <= Math.min(SIZE - 1, Math.max(ax, bx) + HALF); x++) {
const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / L2))
if (Math.hypot(x - ax - t * dx, y - ay - t * dy) <= HALF) { const i = (y * SIZE + x) * 3; img[i] = col[0]; img[i + 1] = col[1]; img[i + 2] = col[2] }
}
}
fs.rmSync(DIR + 'tiles', { recursive: true, force: true }); fs.mkdirSync(DIR + 'tiles', { recursive: true })
const tile = Buffer.alloc(TILE * TILE * 3)
for (let ty = 0; ty < SIZE / TILE; ty++) for (let tx = 0; tx < SIZE / TILE; tx++) {
for (let y = 0; y < TILE; y++) img.copy(tile, y * TILE * 3, ((ty * TILE + y) * SIZE + tx * TILE) * 3, ((ty * TILE + y) * SIZE + (tx + 1) * TILE) * 3)
fs.writeFileSync(`${DIR}tiles/${tx}_${ty}.png`, png(tile, TILE, TILE))
}
}
fs.mkdirSync(DIR, { recursive: true })
if (!process.argv.includes('--from-seed')) fs.writeFileSync(seedPath, JSON.stringify(build(), null, 1))
render(JSON.parse(fs.readFileSync(seedPath, 'utf8')))
console.log('scene.json + 256 tiles ->', DIR)
@@ -0,0 +1,65 @@
// Leak test driver: scripted walk of A, GM + B as ground truth/noise. Writes run/leak-transcript.jsonl; tools/leakcheck.nim verifies it.
// SUBJECT=A|B (default A) is the player whose tile sweeps/view are checked (leakcheck reads the same env); the other walks as noise.
// Everything is sequential (one actor at a time) so every tile sweep sees a quiescent server at a known gseq.
import fs from 'node:fs'
import { O, RUN, connect, sleep } from './lib.mjs'
const out = fs.createWriteStream(`${RUN}/leak-transcript.jsonl`)
const log = o => out.write(JSON.stringify(o) + '\n')
let gmG = 0
const S = process.env.SUBJECT ?? 'A'
const acks = new Map(), req = { A: 0, B: 0, GM: 0 }
const mk = who => connect(who === 'GM' ? 'gm' : who, m => {
log({ k: 'msg', who, m })
if (who === 'GM') gmG = m.gseq
if (m.t === 'moveAck') acks.get(who + m.reqId)?.(m)
})
const [gm, A, B] = [await mk('GM'), await mk('A'), await mk('B')]
const cl = { GM: gm, A, B }
const pos = { A: [400, 400], B: [400, 2200], M1: [900, 900], M2: [1920, 640], M5: [1920, 2400] }
const owner = id => (id === 'A' || id === 'B' ? id : 'GM')
const mv = (id, p) => new Promise(res => { const w = owner(id), r = ++req[w]; acks.set(w + r, res); cl[w].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p })) })
const tiles = Object.keys(Array.from({ length: 256 })).map(i => [i % 16, Math.floor(i / 16)])
async function sweep(label) {
await sleep(40)
const g = gmG
for (let i = 0; i < tiles.length; i += 32)
await Promise.all(tiles.slice(i, i + 32).map(async ([x, y]) => {
const r = await fetch(`${O}/tiles/${x}_${y}.png`, { headers: { Cookie: cl[S].cookie } })
await r.arrayBuffer(); log({ k: 'tile', g, x, y, s: r.status, label })
}))
}
const acts = []
const cur = { ...pos }
const walk = (id, to, expectFail = false) => {
const [x, y] = cur[id], d = Math.hypot(to[0] - x, to[1] - y), n = Math.ceil(d / 40)
for (let i = 1; i <= n; i++) acts.push({ id, p: [x + (to[0] - x) * i / n, y + (to[1] - y) * i / n], fail: expectFail && i === n })
if (!expectFail) cur[id] = to
}
const door = (id, open) => acts.push({ door: [id, open] })
const sw = label => acts.push({ sweep: label })
sw('start')
walk('B', [700, 2300])
walk('A', [400, 800]); walk('A', [800, 800]); sw('M1 in view')
walk('A', [800, 640]); walk('A', [1000, 640]); walk('A', [1510, 640])
walk('A', [1540, 640], true); sw('closed door blocks')
walk('M2', [1700, 640]); sw('M2 behind closed door')
door(10, true); sw('door open'); walk('A', [1700, 640]); walk('M2', [1900, 700]); walk('A', [1900, 640]); sw('M2 close')
walk('M2', [2200, 300]); sw('M2 left'); walk('M1', [900, 640]); walk('M1', [1200, 640]); sw('M1 into corridor')
walk('A', [1920, 900]); walk('A', [1920, 1900]); sw('corridor')
door(27, false); sw('door 27 closed'); walk('A', [1920, 2020]); walk('A', [1920, 2060], true); sw('blocked'); door(27, true); sw('door 27 open')
walk('A', [1920, 2300]); sw('R5')
walk('B', [700, 2430]); walk('B', [1400, 2430]); walk('B', [1700, 2430]); sw('B visible?'); walk('B', [1000, 2430]); sw('B away')
walk('A', [1920, 2500]); sw('M5 in view'); walk('M5', [2200, 2700]); sw('M5 away'); walk('A', [1700, 2700]); sw('end')
let nA = 0, bad = 0
for (const a of acts) {
if (a.sweep) { await sweep(a.sweep); continue }
if (a.door) { cl.GM.ws.send(JSON.stringify({ t: 'door', id: a.door[0], open: a.door[1] })); await sleep(40); continue }
const m = await mv(a.id, a.p)
if (m.ok === !!a.fail) { bad++; console.log('unexpected ack', a, m) }
if (a.id === S && ++nA % 5 === 0) await sweep('walk'); else await sleep(15)
}
await sleep(200)
for (const c of [gm, A, B]) c.ws.close()
out.end()
console.log(`driver done: ${acts.length} actions, ${bad} unexpected acks, final gseq ${gmG}`)
process.exit(bad ? 1 : 0)
@@ -0,0 +1,154 @@
## Leak checker: replays run/leak-transcript.jsonl. Ground truth = GM socket (tokens+doors per gseq);
## subject (SUBJECT env, A|B)'s vision/explored are recomputed with geometry.nim, never taken from A's own messages.
import std/[json, tables, sets, strutils, os, math]
import geometry
let me = getEnv("SUBJECT", "A") # subject whose view is checked; the other player is noise
let other = if me == "A": "B" else: "A"
type Side = enum Out, Amb, In
# every failure carries a class (HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE | OWN_VIEW EXPLORED GEOMETRY PROTOCOL);
# tools/faulttest.sh asserts each injected server fault is reported under its class
var fails = 0
var classes: CountTable[string]
proc fail(cls, s: string) =
inc fails; classes.inc cls
if fails <= 20: echo "FAIL [", cls, "] ", s
# boundary is ambiguous in inside(): In/Out only if the point and its 0.5px neighbours agree
proc side(poly: seq[Vec], p: Vec): Side =
var n = 0
for d in [(0.0, 0.0), (0.5, 0.0), (-0.5, 0.0), (0.0, 0.5), (0.0, -0.5)]:
if poly.inside((p.x + d[0], p.y + d[1])): inc n
if n == 0: Out elif n == 5: In else: Amb
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
const banned = ["walls", "door", "open", "a", "b", "segments", "segs", "wall"]
const allowed = ["hello", "vision", "explored", "token", "remove", "moveAck"]
proc scan(j: JsonNode, t: string) =
if j.kind == JObject:
for k, v in j:
if k in banned: fail "WALLDATA", "A msg " & t & " has wall-like key " & k
scan(v, t)
elif j.kind == JArray:
for v in j: scan(v, t)
var gm, am: seq[JsonNode]
var tiles: seq[JsonNode]
for line in lines(getEnv("RUN_DIR", "run") / "leak-transcript.jsonl"):
let j = parseJson(line)
if j["k"].getStr == "tile": tiles.add j
elif j["who"].getStr == "GM": gm.add j["m"]
elif j["who"].getStr == me: am.add j["m"]
# the other player's transcript is deliberately unused: it is only noise
let radius = parseFile("data/scene.json")["visionRadius"].getFloat
var walls: seq[Wall]
var truth: Table[string, Vec]
var tileSize, cell, cw: int
var firstG: Table[int, int] # explored cell -> gseq it first became explored (independent)
var view: Table[string, Vec] # what A has been told
var aExp: HashSet[int]
var oFirst: HashSet[int] # cells the OTHER player has explored so far (independent), to attribute leaks
var leaked: HashSet[string] # tokens already reported as HIDDEN_TOKEN (their stale view entry is not a missing remove)
var ai, removes, groups, expN: int
var seen: HashSet[string]
proc same(j: JsonNode, poly: seq[Vec]): bool =
if j.len != poly.len: return false
for i in 0 ..< poly.len:
if abs(j[i][0].getFloat - poly[i].x) > 1e-6 or abs(j[i][1].getFloat - poly[i].y) > 1e-6: return false
true
proc finalize(g: int) =
inc groups
let poly = visibilityPolygon(truth[me], walls, radius)
let polyO = visibilityPolygon(truth[other], walls, radius)
for (ix, iy) in cellsTouched(polyO, cell.float): oFirst.incl iy * cw + ix
# independent oracle (segment tests, not the ray fan): clear straight line to a point in range => point is in the polygon
for i in 0 ..< 64:
for k in [0.3, 0.6, 0.95]:
let o = truth[me]
let p: Vec = (o.x + k * radius * cos(2 * PI * i.float / 64), o.y + k * radius * sin(2 * PI * i.float / 64))
if not moveBlocked(walls, o, p) and side(poly, p) == Out: fail "GEOMETRY", "polygon misses clear-LOS point " & $p & " at g=" & $g
for (ix, iy) in cellsTouched(poly, cell.float):
if ix >= 0 and iy >= 0 and ix < cw and iy < cw and (iy * cw + ix) notin firstG:
firstG[iy * cw + ix] = g; inc expN
while ai < am.len and am[ai]["gseq"].getInt <= g:
let m = am[ai]; inc ai
let t = m["t"].getStr
if t == "error": fail "PROTOCOL", "A got error " & $m
if t notin allowed: fail (if t in ["walls", "door"]: "WALLDATA" else: "PROTOCOL"), "A got forbidden type " & t; continue
if t == "moveAck": continue
scan(m, t)
if m["gseq"].getInt != g: fail "PROTOCOL", "A msg gseq " & $m["gseq"] & " not in GM log (group " & $g & ")"
if t notin ["token", "remove"] and "\"" & other & "\"" in $m: fail "OTHER_PLAYER", other & " mentioned in " & $m
case t
of "hello": (if m["tokens"] != %[me]: fail "OTHER_PLAYER", "hello tokens " & $m["tokens"])
of "token":
let id = m["id"].getStr
if id notin truth: fail "HIDDEN_TOKEN", "unknown token " & id; continue
if vec(m["pos"]) != truth[id]: fail "OWN_VIEW", "token " & id & " pos != truth at g=" & $g
if m["mine"].getBool != (id == me): fail "OTHER_PLAYER", "mine flag " & id
if id != other and m{"by"}.getStr == other: fail "OTHER_PLAYER", other & " leak via by on " & id
if id != me and side(poly, truth[id]) == Out: leaked.incl id; fail "HIDDEN_TOKEN", "LEAK token " & id & " outside A vision at g=" & $g
view[id] = vec(m["pos"]); seen.incl id
of "remove":
let id = m["id"].getStr
if id notin view: fail "PROTOCOL", "remove of unknown " & id
if id in truth and side(poly, truth[id]) == In: fail "WITHHELD", "remove of token still visible " & id
view.del id; inc removes
of "vision":
let ps = m["polys"]
for q in ps:
if same(q, polyO): fail "OTHER_PLAYER", "vision carries " & other & "'s polygon at g=" & $g
if ps.len != 1 or ps[0].len != poly.len: fail "OWN_VIEW", "vision shape at g=" & $g; continue
if not same(ps[0], poly): fail "OWN_VIEW", "vision vertex differs at g=" & $g
of "explored":
for c in m["cells"]:
let k = c[1].getInt * cw + c[0].getInt
if firstG.getOrDefault(k, int.high) > g: fail (if k in oFirst: "OTHER_PLAYER" else: "EXPLORED"), "LEAK explored cell not yet explored " & $c
aExp.incl k
else: discard
if aExp.len != expN: fail "EXPLORED", "explored count at g=" & $g & ": A " & $aExp.len & " expected " & $expN
for id, p in truth:
let s = side(poly, p)
if s == Amb and id != me: continue
let want = id == me or s == In
if want != (id in view): fail (if want: "WITHHELD" elif id in leaked: "HIDDEN_TOKEN" else: "NO_REMOVE"), "view mismatch " & id & " want=" & $want & " at g=" & $g
elif want and view[id] != p: fail "OWN_VIEW", "view pos stale " & id & " at g=" & $g
var curG = -1
for m in gm:
let g = m["gseq"].getInt
if curG >= 0 and g != curG: finalize(curG)
curG = g
case m["t"].getStr
of "hello": tileSize = m["tileSize"].getInt; cell = m["exploredCell"].getInt; cw = (m["world"]["w"].getInt + cell - 1) div cell
of "walls":
for w in m["walls"]: walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["door"].getBool, open: w["open"].getBool)
of "door": walls[m["id"].getInt].open = m["open"].getBool
of "token": truth[m["id"].getStr] = vec(m["pos"])
else: discard
finalize(curG)
if ai < am.len: fail "PROTOCOL", "A messages after last GM gseq: " & $am[ai]
var n200, n403, nOther: int
for t in tiles:
let g = t["g"].getInt
var exp = false
let per = tileSize div cell
for cy in t["y"].getInt * per ..< (t["y"].getInt + 1) * per:
for cx in t["x"].getInt * per ..< (t["x"].getInt + 1) * per:
if firstG.getOrDefault(cy * cw + cx, int.high) <= g: exp = true
let s = t["s"].getInt
if s == 200: inc n200 elif s == 403: inc n403 else: inc nOther
if s != (if exp: 200 else: 403): fail "TILE", "tile " & $t["x"] & "_" & $t["y"] & " g=" & $g & " (" & t["label"].getStr & ") status " & $s & " expected " & (if exp: "200" else: "403")
# coverage: the scripted path must actually exercise enter/leave
for id in (if me == "A": @["M1", "M2", "B", "M5"] else: @["A", "M5"]):
if id notin seen: fail "WITHHELD", "scenario never showed subject token " & id
if removes < (if me == "A": 3 else: 1): fail "NO_REMOVE", "only " & $removes & " removes"
for c, n in classes: echo "FAILCLASS ", c, " ", n
echo "leakcheck: ", groups, " gseq groups, subject msgs ", am.len, ", tokens seen ", seen.len - 1, " others, removes ", removes,
", tiles ", tiles.len, " (200:", n200, " 403:", n403, " other:", nOther, "), explored cells ", expN, ", failures ", fails
quit(if fails > 0: 1 else: 0)
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# usage: tools/leaktest.sh -> results/leak-{A,B}.log (driver + checker output) and .jsonl (transcript), one pair per subject
cd "$(dirname "$0")/.." || exit 1
mkdir -p results run/test
nim c -d:release --hints:off -o:run/test/leakcheck tools/leakcheck.nim >/dev/null || exit 1
for s in A B; do
SUBJECT=$s tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' > results/leak-$s.log 2>&1; rc=$?
cp run/test/leak-transcript.jsonl results/leak-$s.jsonl
echo "== SUBJECT=$s"; cat results/leak-$s.log
[ $rc = 0 ] || exit 1
done
@@ -0,0 +1,17 @@
// shared by leak.mjs / concurrency.mjs. Node 22 WebSocket (undici) accepts {headers}.
import fs from 'node:fs'
export const RUN = process.env.RUN_DIR ?? 'run'
export const O = `http://localhost:${process.env.PORT ?? 8080}`
export const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
export const sleep = ms => new Promise(r => setTimeout(r, ms))
export const login = async role => (await fetch(inv[role], { redirect: 'manual' })).headers.get('set-cookie').split(';')[0]
// resolves once hello+initial state arrived (socket quiet for 300 ms)
export async function connect(role, onMsg) {
const cookie = await login(role)
const ws = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: { Cookie: cookie } })
let last = Date.now()
ws.onmessage = e => { last = Date.now(); onMsg(JSON.parse(e.data), Buffer.byteLength(e.data)) }
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej })
while (Date.now() - last < 300) await sleep(50)
return { ws, cookie }
}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# usage: tools/mutation.sh mutation check of src/geometry.nim on a TEMP COPY (src/ is never touched).
# Control (unmutated copy) must pass; each mutation must fail >=1 of the corner tests in $NEW.
# Logs: results/mutation-{a,b,c}.log (a: no +-RayEps rays; b: upper segment end exclusive; c: lower end exclusive).
# Segment-end inclusion lives only in rayHit (visibility); moveBlocked's segsCross is a separate, intentionally inclusive test.
cd "$(dirname "$0")/.." || exit 1
mkdir -p results
NEW="shared endpoint: no leak at the vertex|'<' apex|every segment endpoint|rays nudged past a corner"
T=$(mktemp -d); trap 'rm -rf $T' EXIT
rc=0
run() { # $1 id $2 title $3 sed script ("" = control)
rm -rf $T/w; mkdir -p $T/w; cp -r src tests data nim.cfg $T/w/; rm -f $T/w/tests/tgeometry
[ -n "$3" ] && sed -i "$3" $T/w/src/geometry.nim
L=results/mutation-$1.log
{ echo "# mutation $1: $2"; echo "# run on a temp copy; diff orig -> mutated src/geometry.nim:"
diff src/geometry.nim $T/w/src/geometry.nim | sed 's/^/# /'; echo; } > $L
(cd $T/w && nim c -r --hints:off --nimcache:$T/nc tests/tgeometry.nim) >> $L 2>&1; r=$?
F=$(grep '\[FAILED\]' $L | grep -E "$NEW")
{ echo; echo "# test exit=$r"; echo "# NEW tests failed:"; echo "${F:-(none)}"; } >> $L
if [ -z "$3" ]; then [ $r -eq 0 ] || { echo "control FAILED"; rc=1; }
else [ -n "$F" ] || { echo "mutation $1 SURVIVED"; rc=1; }; fi
echo "$1: exit=$r newfailed=$(echo "$F" | grep -c .)"
}
run control "unmutated copy (must pass)" ""
run a "remove the +-RayEps rays" '/angles.add ang [-+] RayEps/d'
run b "upper segment end exclusive" 's/u <= 1 + Eps/u < 1 - Eps/'
run c "lower segment end exclusive" 's/u >= -Eps/u > Eps/'
rm -f results/mutation-control.log
exit $rc
@@ -0,0 +1,85 @@
// Restart durability: mutate, stop the server (SIGTERM, then SIGKILL), restart on the same DB, compare everything.
// Run via `NOSERVE=1 tools/withserver.sh node tools/restart.mjs` (withserver only builds run/test/server). Talks to the backend directly.
import fs from 'node:fs'
import { spawn } from 'node:child_process'
process.env.PORT = process.env.BACKEND_PORT // lib.mjs: origin = backend port (no nginx needed for ws/join)
const RUN = process.env.RUN_DIR
const sleep = ms => new Promise(r => setTimeout(r, ms))
let fails = 0
const check = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
let proc
const start = async () => {
fs.writeFileSync(`${RUN}/server.log`, '', { flag: 'a' })
proc = spawn(`./${RUN}/server`, { env: process.env, stdio: ['ignore', fs.openSync(`${RUN}/server.log`, 'a'), 'inherit'] })
for (let i = 0; i < 100 && !fs.readFileSync(`${RUN}/server.log`, 'utf8').includes('listening'); i++) await sleep(100)
await sleep(200)
}
const stop = sig => new Promise(res => { proc.once('exit', res); proc.kill(sig) })
const invites = () => fs.readFileSync(`${RUN}/invites.txt`, 'utf8')
// reduce a connection's messages to comparable state (gseq is in-memory only, so it is not compared)
async function view(role, keep) {
const st = { toks: {}, doors: {}, explored: new Set(), poly: '[]', hello: null }
const c = await connect(role, m => {
switch (m.t) {
case 'hello': st.hello = JSON.stringify({ ...m, gseq: 0 }); break
case 'walls': for (const w of m.walls) if (w.door) st.doors[w.id] = w.open; break
case 'door': st.doors[m.id] = m.open; break
case 'vision': st.poly = JSON.stringify(m.polys); break
case 'explored': for (const x of m.cells) st.explored.add(x + ''); break
case 'token': st.toks[m.id] = m.pos + ''; break
case 'remove': delete st.toks[m.id]; break
}
})
if (!keep) c.ws.close()
return { st, c }
}
const norm = st => JSON.stringify({ ...st, explored: [...st.explored].sort(), toks: Object.entries(st.toks).sort(), doors: Object.entries(st.doors).sort() })
const snap = async () => { const o = {}; for (const r of ['gm', 'A', 'B']) o[r] = norm((await view(r)).st); return o }
let req = 0
async function mutate(steps) {
const C = {}, acks = new Map()
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, m => { if (m.t === 'moveAck') acks.get(m.reqId)?.(m) })
for (const [who, id, pos] of steps) {
if (who === 'door') { C.gm.ws.send(JSON.stringify({ t: 'door', id, open: pos })); await sleep(100); continue }
const r = ++req
const p = new Promise(res => acks.set(r, res)); C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos }))
check((await p).ok, `move ${id} -> ${pos}`)
}
await sleep(200)
const live = {} // the long-lived clients' own accumulated view is not tracked; fresh views are the reference
for (const r of ['gm', 'A', 'B']) C[r].ws.close()
return live
}
async function cycle(label, steps, sig) {
await mutate(steps)
const before = await snap(), inv = invites()
await stop(sig)
await start()
const after = await snap()
check(invites() === inv, `${label}: invite secrets identical`)
for (const r of ['gm', 'A', 'B']) check(before[r] === after[r], `${label}: ${r} state identical after ${sig} restart`)
return after
}
await start()
const { connect } = await import('./lib.mjs') // lib reads invites.txt at import, so only after the first start
const s0 = await snap()
const a = JSON.parse(s0.A), g = JSON.parse(s0.gm)
const sA = await cycle('cycle1', [['A', 'A', [400, 800]], ['A', 'A', [800, 800]], ['A', 'A', [800, 640]], ['A', 'A', [1000, 640]], ['A', 'A', [1510, 640]],
['B', 'B', [700, 2300]], ['gm', 'M1', [900, 640]], ['gm', 'M2', [2200, 300]], ['door', 10, true], ['door', 27, false],
['A', 'A', [1700, 640]]], 'SIGTERM')
const a1 = JSON.parse(sA.A), g1 = JSON.parse(sA.gm)
check(a1.explored.length > a.explored.length, `A explored new area (${a.explored.length} -> ${a1.explored.length})`)
check(g1.toks.find(t => t[0] === 'A')[1] === '1700,640' && g1.toks.find(t => t[0] === 'B')[1] === '700,2300' && g1.toks.find(t => t[0] === 'M2')[1] === '2200,300', 'cycle1: token positions are the moved ones')
check(g1.doors.find(d => d[0] === '10')[1] === true && g1.doors.find(d => d[0] === '27')[1] === false, 'cycle1: door states are the toggled ones')
check(JSON.stringify(g.doors) !== JSON.stringify(g1.doors), 'cycle1: doors differ from initial (test is not vacuous)')
const sB = await cycle('cycle2', [['A', 'A', [1900, 640]], ['B', 'B', [1000, 2300]], ['gm', 'M1', [1200, 640]], ['door', 10, false], ['door', 27, true]], 'SIGKILL')
check(JSON.parse(sB.A).explored.length > a1.explored.length, 'cycle2: A explored more before kill -9')
check(JSON.parse(sB.B).explored.length > JSON.parse(sA.B).explored.length, 'cycle2: B explored more before kill -9')
await stop('SIGKILL')
console.log(fails ? `restart: FAILED ${fails}` : 'restart: PASS')
process.exit(fails ? 1 : 0)
@@ -0,0 +1,53 @@
// node tools/smoke.mjs [pos] -- needs server+nginx up. Node 22 WebSocket (undici) accepts {headers}.
import fs from 'node:fs'
const O = `http://localhost:${process.env.PORT ?? 8080}`
const RUN = process.env.RUN_DIR ?? 'run'
const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) process.exitCode = 1 }
const join = async u => { const r = await fetch(u, { redirect: 'manual' }); return r }
const ws = (cookie, ms = 800) => new Promise(res => {
const msgs = [], s = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: cookie ? { Cookie: cookie } : {} })
s.onmessage = e => msgs.push(JSON.parse(e.data))
s.onerror = () => res({ s, msgs, failed: true })
setTimeout(() => res({ s, msgs, failed: false }), ms)
})
const nextAck = (s, reqId) => new Promise(res => s.addEventListener('message', function f(e) { const m = JSON.parse(e.data); if (m.t === 'moveAck' && m.reqId === reqId) { s.removeEventListener('message', f); res(m) } }))
const r1 = await join(inv.A.replace('A ', ''))
const cookie = r1.headers.get('set-cookie')?.split(';')[0]
if (process.argv[2] === 'pos') {
const a = await ws(cookie); console.log('A pos', a.msgs.find(m => m.t === 'token' && m.id === 'A').pos); process.exit()
}
ok(r1.status === 302 && /HttpOnly/i.test(r1.headers.get('set-cookie')) && /SameSite=Strict/i.test(r1.headers.get('set-cookie')), 'join A: 302 + HttpOnly SameSite cookie')
ok((await join(`${O}/join/deadbeef`)).status === 403, 'bad secret 403')
ok((await ws(null)).failed, 'ws without cookie refused')
ok((await ws('sid=nope')).failed, 'ws bad cookie refused')
const a = await ws(cookie)
const types = a.msgs.map(m => m.t)
console.log('player A msgs:', types.join(','))
ok(types[0] === 'hello' && a.msgs[0].role === 'player' && a.msgs[0].tokens[0] === 'A', 'hello first, player owns A')
ok(!types.includes('walls') && !types.includes('door'), 'no walls/door to player')
ok(types.includes('vision') && types.includes('explored'), 'vision + explored sent')
const toks = a.msgs.filter(m => m.t === 'token')
ok(toks.length === 1 && toks[0].id === 'A' && toks[0].mine, 'only own token visible')
const get = (p, c = cookie) => fetch(O + p, { headers: { Cookie: c } })
const t1 = await get('/tiles/1_1.png'); const b1 = await t1.arrayBuffer()
ok(t1.status === 200 && b1.byteLength > 100 && !t1.headers.get('x-accel-redirect'), `explored tile 200, ${b1.byteLength} bytes`)
ok((await get('/tiles/15_15.png')).status === 403, 'unexplored tile 403')
ok((await fetch(`${O}/tiles/1_1.png`)).status === 403, 'tile without cookie 403')
ok((await fetch(`${O}/_tiles/1_1.png`, { headers: { Cookie: cookie } })).status === 404, '/_tiles not reachable directly')
ok([400, 404].includes((await get('/tiles/..%2f..%2fscene.json')).status), 'path trick rejected')
const gmc = (await join(inv.gm)).headers.get('set-cookie').split(';')[0]
ok((await get('/tiles/15_15.png', gmc)).status === 200, 'GM gets any tile')
a.s.send(JSON.stringify({ t: 'move', reqId: 1, id: 'B', pos: [1, 1] }))
a.s.send(JSON.stringify({ t: 'door', id: 10, open: true }))
a.s.send('garbage{')
await new Promise(r => setTimeout(r, 300))
ok(a.msgs.filter(m => m.t === 'error').length === 3, 'steal/door/garbage -> 3 errors')
let p = nextAck(a.s, 2); a.s.send(JSON.stringify({ t: 'move', reqId: 2, id: 'A', pos: [1100, 400] }))
ok(!(await p).ok, 'move through wall rejected')
p = nextAck(a.s, 3); a.s.send(JSON.stringify({ t: 'move', reqId: 3, id: 'A', pos: [500, 450] }))
const ack = await p; ok(ack.ok && ack.pos[0] === 500, 'legal move acked')
const g = await ws(gmc)
ok(g.msgs.some(m => m.t === 'walls') && !g.msgs.some(m => m.t === 'explored') && g.msgs.filter(m => m.t === 'token').length === 8, 'GM: walls, all 8 tokens, no explored')
process.exit()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# usage: tools/withserver.sh cmd... isolated stack in run/test (own DB/invites/nginx conf+logs/binary), own ports TEST_PORT (nginx, 18088) + TEST_BACKEND_PORT (server, 19000); never touches live run/ or :8088/:9000. SIGINT => server prints STATS
cd "$(dirname "$0")/.." || exit 1
export RUN_DIR=run/test PORT=${TEST_PORT:-18088} BACKEND_PORT=${TEST_BACKEND_PORT:-19000}
R=$RUN_DIR
case "$PORT:$BACKEND_PORT" in 8088:*|*:9000|*:8088) echo "withserver: refusing live port (8088/9000)" >&2; exit 1;; esac
mkdir -p $R/temp client/dist
rm -f $R/state.db* $R/invites.txt
nim c -d:release $SERVER_FLAGS --nimcache:$R/nimcache$(echo $SERVER_FLAGS | tr -dc a-z) --hints:off --nimblePath:"${NIMBLE_DIR:-.devbox/nimble}/pkgs2" -o:$R/server src/server.nim >/dev/null || exit 1
sed -e "s/NGX_PORT/$PORT/" -e "s/NGX_BACKEND/$BACKEND_PORT/" -e "s#run/#$R/#g" -e "s#\.\./nginx/mime#$PWD/nginx/mime#" nginx/nginx.conf > $R/nginx.conf
if [ -z "$NOSERVE" ]; then # NOSERVE=1: build only, the command starts/stops the server itself (tools/restart.mjs)
./$R/server > $R/server.log 2>&1 & S=$!
nginx -p "$PWD/" -c $R/nginx.conf -e $R/error.log > $R/nginx.out 2>&1 & N=$!
trap 'kill -INT $S; sleep 1; kill $N 2>/dev/null' EXIT
for i in $(seq 50); do [ -s $R/invites.txt ] && curl -s -o /dev/null "localhost:$PORT/" && break; sleep 0.2; done
fi
"$@"
@@ -0,0 +1,10 @@
.devbox/
nimble.paths
data/
run/
bin/
nimble.develop
nimbledeps
devbox.d/
node_modules/
dist/
+170
View File
@@ -0,0 +1,170 @@
# prototype-tile-leak (throwaway): DESIGN.md Q4 / H8 / T5, tile-edge leak
## Question
DESIGN 3.3: a 256 px tile is served iff >=1 explored 32 px cell overlaps it, so up to 255x255 px of unexplored art reaches the browser (devtools). Which fix is cheapest: (A) server-side per-player masked 256 px tiles, or (B) tiles the size of an explored cell (32 px; 64 px for comparison) served as-is?
**Fact, not prototyped:** client-side fog, flattening or masking cannot fix this. The bytes are already in the browser (network tab, cache, decoded texture) before any client code runs. Only what the server sends counts.
## Method
- Art: procedural pure function of world coords (`src/art.nim`), so every tile size slices the same picture. Two noise levels bracket real art: `g6` (smooth, 256 px PNG ~83 KB) and `g40` (grainy, ~133 KB). **Synthetic: absolute sizes/ms depend on real art, ratios are what matter.**
- A: `src/maskbench.nim`. Decode PNG, set unexplored 32 px cells to opaque black (0,0,0,255), encode. Median of 200 runs, single thread, `-d:release`. Then replay of the real explored transcripts of `prototype-server-vision/results/leak-A.jsonl` (subjects A: 94 explored msgs, 2142 cells; B: 39 msgs, 1114 cells) on the 4096 px / 256 px-tile / 32 px-cell scene: every tile whose mask changed is re-masked for real.
- B: `src/gen.nim` slices the 4096 px map into 32/64/256 px PNG files, measures disk. `src/authsrv.nim` (mummy, same shape as the vision prototype tile route: strict path parse, cookie lookup, explored-cell range check under a lock, `X-Accel-Redirect`) behind nginx (4 workers, `internal` alias). Load by `h2load` (nghttp2) on loopback, `tools/netbench.sh`. Requests/step computed by replaying the same transcripts.
- Machine: AMD Ryzen 7 7840U, 16 threads, NixOS, kernel 6.18, governor left on `powersave` (as in the other prototypes). Page cache hot (cold disk not measured). Run-to-run noise on req/s is roughly +-30%.
- Lib check (pixie 6.1.0, nimPNG 0.3.6): APIs checked in source + context7 docs, not memory.
## Library choice (A)
| | pixie 6.1.0 | nimPNG 0.3.6 |
|---|---|---|
| dec+mask+enc, 1..63 of 64 cells explored | 1.6..10.9 ms | 9.3..26.5 ms |
| output size vs pixie | baseline | 5-25% smaller (auto palette/gray, MINSUM filter); all-black tile 88 B vs 853 B |
| deps | 7 pure-Nim pkgs (vmath chroma bumpy flatty zippy nimsimd crunchy), ~1.4 MB source | 0, ~0.24 MB source |
Pick **pixie**: 2-3x faster, `decodePng`/`encodePng` expose raw RGBA so masking is a plain loop; nimPNG only if bytes matter more than CPU. No C libs in either (devbox stays minimal). Pixie has no compression-level knob via `encodePng` (zippy default). [MEASURED `results/maskbench.log`]
## Numbers
### A. Masked 256 px tiles (MEASURED, `results/maskbench.log`)
Per tile, pixie, ms (out bytes), explored cells of 64:
| cells | g6 ms (B) | g40 ms (B) |
|---|---|---|
| 0 | 1.5 (853) | 1.8 (853) |
| 1 | 1.7 (3.2K) | 1.9 (4.0K) |
| 8 | 2.4 (12.7K) | 2.5 (19.7K) |
| 32 | 6.0 (43.6K) | 5.5 (69.0K) |
| 63 | 10.9 (82.2K) | 9.5 (131.5K) |
| 64 (all) | 0: serve the original file, no image work | 0 |
Decode alone 0.8-1.0 ms; encode dominates (8-10 ms for a full tile). Exact-polygon variant (naive per-pixel even-odd, 32-gon): 6.3-6.7 ms, an upper bound, a scanline fill would be about cell-mask cost.
Replay, subject A (B similar), 4096 px map, g6 / g40:
- tiles touched 71 (of 256); **366 re-masks in 94 steps = 3.9 tiles/step avg (max 13, the connect burst)**; CPU **20 ms/step avg, worst 70 ms**, per-step cost parallelisable over tiles, must run outside the state lock (vision recompute for comparison: 1.18 ms/move).
- Bytes to client: masked **13.1 / 20.7 MB** vs whole-tile 5.8 / 9.5 MB (each tile once) = **x2.0-2.2**, because every tile whose mask grows must be refetched (new URL/version per tile, client must be told which tiles changed: protocol + client change).
- Per-player cache of final masked tiles: A **2.9 / 4.6 MB** (71 tiles, ~41-65 KB each), B 1.5 / 2.4 MB (35 tiles). It scales with explored area, not map size. 16384 px map (4096 tiles) worst case if every tile were partial: <= the original art, 340-545 MB per player [INFERRED, = 4096 x tile size]. Old versions evictable.
- Re-mask when explored grows: only tiles whose cell set changed (above), results keyed (tile, mask-hash) so reconnects/other connections of the same player are free.
- Leak assert (MEASURED): for n in {0,1,8,32,63} cells, through pixie AND nimPNG, a 8x8 pure-red "secret" is planted in every unexplored cell; asserts: no red pixel in output, every unexplored pixel == (0,0,0,255), every explored pixel identical to source. Pass.
### B. Cell-size tiles
Tile counts [arithmetic]: 4096 px map: 32 px 16,384 / 64 px 4,096 / 256 px 256. 16384 px map: **262,144 / 65,536 / 4,096**.
Disk, 4096 px map, MEASURED (`results/disk4096.log`); 16384 px = x16 [INFERRED]. "on-disk" = 4 KiB filesystem blocks (ext4):
| tile | files | apparent g6 / g40 | on-disk g6 / g40 | 16384 px apparent g6/g40 | 16384 px on-disk g6/g40 |
|---|---|---|---|---|---|
| 256 | 256 | 21.1 / 34.1 MB | 21.2 / 33.8 MB | 337 / 545 MB | 339 / 541 MB |
| 64 | 4,096 | 24.6 / 38.6 MB (+17/+13%) | 32.9 / 49.3 MB | 393 / 618 MB | 526 / 788 MB |
| 32 | 16,384 | 28.4 / 43.5 MB (+35/+28%) | 66.0 / 66.0 MB | 454 / 696 MB | 1.06 GB (262k inodes) |
Small PNGs lose compression context and pay ~60 B header + one 4 KiB block each; no image work at serve time.
Requests per exploration step, MEASURED by transcript replay (`results/steps.log`), NEW tiles per step (a cell tile is fetched once, never again):
| | connect burst | steady median | p95 | max | total (A, 94 steps) |
|---|---|---|---|---|---|
| 32 px | 292 | 11 | 37 | 164 | 2142 |
| 64 px | 87 | 3 | 11 | 46 | 603 |
| 256 px whole (today) | 13 | 0 | 3 | 6 | 71 |
| 256 px masked (refetch on change) | - | - | - | 13 | 366 |
Bytes for A: 32 px 3.7 / 5.7 MB, 64 px 3.6 / 5.7 MB (count x avg tile bytes, g6 / g40) vs whole-256 5.8 / 9.5 MB vs masked-256 13.1 / 20.7 MB. Cell tiles send LESS than today, masking sends 2x more.
Serving, MEASURED (`results/netbench.log`), loopback, 20000 reqs, nginx -> Nim auth -> X-Accel-Redirect, upstream keepalive on:
| case | req/s | median / p99 |
|---|---|---|
| 32 px h1 c=1 (unloaded) | 10.4k | 90 us / 149 us |
| 256 px h1 c=1 (unloaded) | 7.2k | 132 us / 211 us |
| 32 px h1 c=6 (browser-like) | 46k | 122 us / 188 us |
| 64 px h1 c=6 | 45k | 127 us / 213 us |
| 256 px h1 c=6 | 19k | 296 us / 636 us (byte bound, ~83 KB each) |
| 32 px h1 c=32 | 54k | 480 us / 724 us |
| 32 px STATIC (no Nim, no auth) h1 c=32 | 87k | 332 us / 534 us |
| 32 px h2 c=1 m=100 | 18.6k | 5.1 ms / 8.9 ms (queued 100 deep) |
| 32 px h2 c=4 m=100 | 19.9k | 5.6 ms / 25 ms |
| burst 292 x 32 px, h1 c=6 | 7-16 ms wall (3 runs) | |
| burst 292 x 32 px, h2 c=1 m=100 | ~16-22 ms wall | |
| upstream keepalive off, 32 px h1 c=32 | 55k | same as on (loopback connect is cheap) |
- Nim auth hop costs ~35% throughput vs static nginx (54k vs 87k) and ~50 us unloaded, still 1000x the need (steady 11 req/step).
- HTTP/2 on loopback: **no gain** (one h2 connection is served by one nginx worker, ~20k req/s; h1 c=32 spreads over 4 workers). Loopback has RTT ~0, so the real h2 benefit (no 6-connection limit) is **not measurable here**. INFERRED: burst of 292 over h1 with 6 conns = ~49 round trips, ~2.4 s at 50 ms RTT, vs ~1-2 RTT + transfer on h2. TLS not measured. Needs h2 in the real nginx (HTTPS deploy gets it with `http2 on`). Note nginx default `keepalive_requests 1000` closes the h2 connection; h2load does not reconnect, hence `keepalive_requests 1000000` in the bench conf (a browser reconnects transparently).
- Not measured: client cost of 2142+ small Pixi sprites/textures (INFERRED fine with batching; the client can also blit received cell tiles into one RenderTexture per 256 px block).
### C. Leak bound demo (MEASURED, `devbox run netbench`, first section; asserts exit 1 on mismatch)
Explored = left half + one lone cell (64,3) just outside it; every tile of each size requested; allowed count must be half + 1 (PASS all three).
| tile | unexplored px revealed by the lone cell's tile |
|---|---|
| 32 px | **0** |
| 64 px | 3,072 (3 cells) |
| 256 px (today) | 64,512 (63 cells) |
Masked 256 px: 0 beyond explored cells, asserted pixel-exact in A (above).
## Comparison
| | 256 whole (today) | A masked 256 | B1 32 px tiles | B2 64 px tiles |
|---|---|---|---|---|
| leak beyond explored cells | up to 63 cells/tile | 0 | **0** | <= 3 cells/tile |
| server CPU | 0 | ~20 ms per step (avg), 70 ms burst, pixie | ~0.1 ms/req (auth) | same |
| bytes per run (A) | 5.8-9.5 MB | 13.1-20.7 MB | 3.7-5.7 MB | 3.6-5.7 MB |
| requests per step (median/burst) | 0 / 13 | ~4 / 13 refetch | 11 / 292 | 3 / 87 |
| storage 4096 px | 21-34 MB | + per-player cache 1.5-4.6 MB | 28-43 MB (66 MB on disk) | 25-39 MB (33-49 on disk) |
| storage 16384 px | 340-545 MB | + per-player <= 340-545 MB worst | 454-696 MB, 1.06 GB on disk, 262k files | 393-618 MB, 526-788 MB on disk, 65k files |
| deps / new code | none | pixie (7 pkgs), mask+cache+versioned URLs+refetch protocol | importer cuts 32 px tiles | importer cuts 64 px tiles |
| HTTP/2 needed | no | no | yes (INFERRED) | helpful |
| cacheability | immutable | per-version | immutable, never refetched | same |
## Recommendation
**B1: set `tile_size` = explored cell (32 px).** DESIGN already requires `tile_size % cell == 0`, so this is a scene-config change plus importer slicing; no image library in the server, no per-player state, rule "tile allowed iff its cell is explored" becomes exact (zero beyond-cell leak, MEASURED assert C). Total bytes to the client go DOWN vs today; masking doubles them and costs ~20 ms CPU/step plus a refetch protocol for the same residual leak. Fall back to **64 px** if 262k files / ~1 GB on-disk for a 16384 px map is unwelcome (leak <= 3 cells per allowed tile, 4x fewer files). Keep masking (pixie) only if tiles must stay large for another reason; do not build it for Q4 alone. Require h2 in the nginx config.
**Residual leak (all options, incl. masked):** granularity of fog = the explored cell. A cell the polygon only grazed is disclosed entirely (<= 32x32 px beyond what LOS actually saw), and once sent never revoked. Authoring rule shrinks from "~256 px around reachable areas" to "~32 px". Exact-polygon masking would close it but needs per-pixel explored state and ~same CPU as cell masking (6-7 ms/tile naive), not worth it. Also unchanged: static art only, doors not in tiles.
## Caveats
Synthetic art (real painted maps compress differently; ratios hold, absolutes move). Loopback only: no RTT, no TLS, no real browser; h2 benefit INFERRED. Hot page cache. Single laptop in powersave. 16384 px figures are x16 extrapolations. One scene/one player load; no concurrency mix with WS traffic.
## Run
```
cd prototype-tile-leak
devbox run setup # nimble setup (fetches pixie, nimPNG, mummy)
devbox run build # bin/maskbench bin/gen bin/authsrv
devbox run gen # data/g6, data/g40 tiles (~20 s, ~0.3 GB, gitignored) + results/disk4096.log
devbox run maskbench # results/maskbench.log (~30 s)
devbox run netbench # leak-bound demo + h2load matrix -> results/netbench.log
```
`results/steps.log`: `python3 tools/steps.py > results/steps.log` (replays `../prototype-server-vision/results/leak-A.jsonl`; first message = connect burst, excluded from steady stats).
## Phone test (client-side risk of 32 px tiles)
Question: does a Pixi v8 client cope with 32 px tiles (262,144 on a 16384 px map) vs 64 / 256 on a real phone? Unmeasured so far (Q4 "Not measured: client cost").
### Run
```
cd prototype-tile-leak
devbox run phone # first run: npm install + generates 16384 px tiles x {32,64,256} (g6 art, minutes, ~1.1 GB gitignored in data/phone) + builds; then serves
```
Prints `http://<LAN-IP>:8099/` (one line per interface; override with `PORT=`, `WORLD=`; changing WORLD regenerates tiles). Ctrl-C stops. Server: `src/phonesrv.nim`, plain static server (mummy; **no auth, no nginx, no X-Accel**: this tests the client, not the auth path, which `netbench` already covers), binds 0.0.0.0, rejects non-private peers (403), `Cache-Control: no-store` so every load is cold network. NixOS firewall: port 8099/tcp must be open (e.g. temporary `sudo iptables -I nixos-fw -p tcp --dport 8099 -j nixos-fw-accept`, removed with `-D`, or `networking.firewall.allowedTCPPorts`); not changed by this prototype.
`POST /results` (LAN only, JSON object <= 64 KB, whole file <= 2 MB per server run) appends one line per Send to `results/phone-<timestamp>.jsonl`.
### On the phone (~5 min)
1. Open the URL. Overlay top-left. Check `renderer` (webgl/webgpu), `dpr`, UA.
2. Tile size = **32**, **Open map** mode. Pan with one finger for 20 s (long drags, fast flicks), pinch zoom in/out for 10 s. Note moving fps.
3. **Reveal viewport (cold)**: drops all tiles, refetches everything in view; read `viewport loaded ms`. Press 3x, also at zoom 0.5 (worst case, ~1.3k tiles).
4. **Explore: start**: simulated connect burst (~290 cells, one disc) then a step every 400 ms (~11 new cells/step, leak-A median). Let it run 60 s; camera follows, you can still pan/pinch.
5. Pick **64**, repeat 2-4; pick **256**, repeat 2-4. (Switching size stores a snapshot of the previous size.)
6. **Send results** (also snapshots the current size). Check `results/phone-*.jsonl` on the laptop.
### What the numbers mean
- `fps(5s)`: all frames incl. idle (vsync cap: 60 or 120). `moving avg/p5/min`: only frames within 300 ms of a pan/pinch/sim step, accumulated per tile size since selecting it. **p5 = 1000/p95 frame time**, the figure to judge; min = worst single frame.
- `sprites`/`textures`: tile sprites on stage / loaded textures. Only tiles in view + 1 tile margin load; those beyond 2 tiles are released (sprite pooled, texture + source destroyed). Both must stay bounded (~ view area / tile^2) while panning, not grow: growth means a leak.
- `req inflight/done/failed`; cap 24 in flight (browser limits HTTP/1.1 to ~6 per host, so the server hop is HTTP/1.1; real deployment should use h2). `fetch+decode ms` = request to ImageBitmap ready.
- `viewport loaded ms` (ttvl): from click (cold reveal / size change / explore start) until every allowed tile in view is loaded. The explore start value is the connect burst.
- `heap`: only Chrome-based browsers (not iOS Safari). GPU memory is not visible; use `peakTextures` x tile^2 x 4 B as an estimate (32 px: 4 KB each).
- Fog mode: a tile loads iff it overlaps >= 1 revealed 32 px cell (same rule as the server auth), so 256 px mode also loads partly unexplored tiles.
### Proposed pass criteria (32 px, mid-range phone, Wi-Fi)
- moving p5 fps >= 30 while panning at zoom 1 (avg >= 45); no thermal collapse over the 60 s explore run.
- viewport load (cold) < 1 s at zoom 1; connect burst < 2 s.
- failed requests 0; sprites/textures bounded; heap not growing between size switches.
- 32 px not worse than ~1.5x of 64 px on the same metrics. If 32 fails but 64 passes: fall back to 64 px (README recommendation above).
Headless smoke check (server running): `devbox run -- node tools/headless.mjs` (software GL, not representative for fps).
## Phone run 2026-11-08
Device: Android 10, Chrome 157, dpr 2.625, 412x869 CSS px, WebGL. Source: `results/phone-20261108T113701.jsonl` (one line, 3 snaps, open-map mode). One run, 5-year-old phone (worst-case reference).
| tile | zoom | run s | moving fps avg / p5 / min | req done / failed | fetch+decode med / p95 ms | ttvl ms (as logged) | peak sprites | heap MB |
|---|---|---|---|---|---|---|---|---|
| 32 | 0.5 | 109 | 60 / 59.5 / 59.2 | 12094 / 0 | 46 / 75 | 1090, 2882, 3253, 148 | 1420 | ~10 |
| 64 | 0.5 | 37 | 60 / 59.5 / 58.8 | 4588 / 0 | 48 / 125 | 942, 389, 340, 1002, 1006 | 416 | ~10 |
| 256 | 0.6 | 28 | 59.8 / 59.5 / 20 | 404 / 0 | 118 / 220 | 453, 372, 390, 299 | 78 | ~10 |
- 32 px: 60 fps at all snaps, 1420 sprites/textures at zoom 0.5, heap ~10 MB, 0 failed of 12094 requests (17086 requests over all three sizes, 0 failed). Bounded, no growth seen.
- ttvl (cold reveal, size change, explore start; order as logged): 32 px first 1.1 s, worst 3.3 s at zoom 0.5. Transport was HTTP/1.1, `Cache-Control: no-store`, so this is pessimistic against the real path (h2, caching). Zoom 0.5 is the worst case (more tiles in view); the DESIGN gate is zoom 1 on the real path, not measured here.
- 256 px min moving frame 20 fps (single frame, p5 still 59.5): a one-off stall, not a sustained drop. Not investigated.
- Not recorded: zoom 1, explore run (60 s connect burst + steps). Still required by DESIGN 13 M4 (a) and (b).
- Conclusion: 32 px client cost is not the blocker on this phone. Cold viewport load at zoom 1 (< 1 s target) is still unproven.
@@ -0,0 +1,4 @@
# begin Nimble config (version 2)
when withDir(thisDir(), system.fileExists("nimble.paths")):
include "nimble.paths"
# end Nimble config
@@ -0,0 +1,41 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": {
"nim": "2",
"nimble": "latest",
"nginx": "latest",
"nghttp2": "latest",
"curl": "latest",
"nodejs": "latest",
"chromium": "latest"
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
},
"shell": {
"init_hook": [],
"scripts": {
"setup": [
"nimble setup -y",
"mkdir -p bin results"
],
"build": [
"for f in maskbench gen authsrv; do nim c -d:release --hints:off --warnings:off -o:bin/$f src/$f.nim || exit 1; done"
],
"gen": [
"bin/gen data/g6 6",
"bin/gen data/g40 40",
"for g in g6 g40; do for s in 256 64 32; do d=data/$g/tiles$s; echo \"$g $s files=$(ls $d | wc -l) apparent=$(du -sb $d | cut -f1) onDisk(4K blocks)=$(du -sk $d | cut -f1)KiB\"; done; done | tee results/disk4096.log"
],
"maskbench": [
"bin/maskbench ../prototype-server-vision/results/leak-A.jsonl | tee results/maskbench.log"
],
"netbench": [
"tools/netbench.sh | tee results/netbench.log"
],
"phone": [
"tools/phone.sh"
]
}
}
}
@@ -0,0 +1,589 @@
{
"lockfile_version": "1",
"packages": {
"chromium@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#chromium",
"source": "devbox-search",
"version": "155.0.8059.39",
"systems": {
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/a1w34yg08mvma03xps5dsy8vw5hrdy9w-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/5hpd396v5byrfp1vnw7zmpfscqd3b1zv-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39"
}
}
},
"curl@latest": {
"last_modified": "2025-12-05T15:03:55Z",
"resolved": "github:NixOS/nixpkgs/a672be65651c80d3f592a89b3945466584a22069#curl",
"source": "devbox-search",
"version": "8.17.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/qfwqcndy8bji6xww0gizclf2nqi2qpph-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/rk815zvrhwzbi7c6d589v2mhxzyzb400-curl-8.17.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/ydp55g2mbd6rk6lfw0krkk3jwgdiqj5d-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/8s884m82fmrbiyz8malglqc4sd632dkc-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/yxv8fxaz0fyhc31dv3rz89kc50zw5hgj-curl-8.17.0"
}
],
"store_path": "/nix/store/qfwqcndy8bji6xww0gizclf2nqi2qpph-curl-8.17.0-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/4x19j6zihdl6pya63xs8g360f2r614sx-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/b29qbmbfvzkm34k0jnj8ykqg2gzj3rdy-curl-8.17.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/5hmbdk99knmbg8b0fzh96bv6bkcf6v5i-curl-8.17.0-debug"
},
{
"name": "dev",
"path": "/nix/store/iqs9mjscns3h5npgkrhgr5xa7qzwd0si-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/1fwncv08c8g78k3hj3cj375vx92ndrp8-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/b0a6qc92vybjiggh0kg387cg0zp3kl6j-curl-8.17.0"
}
],
"store_path": "/nix/store/4x19j6zihdl6pya63xs8g360f2r614sx-curl-8.17.0-bin"
},
"x86_64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/w2336wv560g1n58cwashmmczdn3bfkq1-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/i6xmhcan8g4abda7ivv20nvwxrsssjqj-curl-8.17.0-man",
"default": true
},
{
"name": "devdoc",
"path": "/nix/store/ipa7v9z7pjcnnv0fmdya1fldcxv0a28z-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/x9gyg634fi8mgcyay9mqa1ral7xg72fm-curl-8.17.0"
},
{
"name": "dev",
"path": "/nix/store/39zfdgq9kg3mb4sycf8pj4pdssrzki6c-curl-8.17.0-dev"
}
],
"store_path": "/nix/store/w2336wv560g1n58cwashmmczdn3bfkq1-curl-8.17.0-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/0rfz69vp1nl0q2hxzig20hc60sk72z62-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/ijd0yybyzwm98d3q6x7a9cyixgxk0i5d-curl-8.17.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/h1fxw0xrifxvbhcp7b8hxsgirxxxfzav-curl-8.17.0-debug"
},
{
"name": "dev",
"path": "/nix/store/ikmdk37frjdblkba3wl3xws2wwgln17x-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/jm6irg81cc0hqg43l39lkxr6pb0w2xk5-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/8idis3j5l13c3x74jl8xly0k4qyk9mx6-curl-8.17.0"
}
],
"store_path": "/nix/store/0rfz69vp1nl0q2hxzig20hc60sk72z62-curl-8.17.0-bin"
}
}
},
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"nghttp2@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nghttp2",
"source": "devbox-search",
"version": "1.70.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8p19fbn4slkvk18j3bvjjh4yhp0d32wf-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/ijqj81fibram571b285bv0knwz5r3qki-nghttp2-1.70.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/idl71hpg6zlvwdm4flp2hr9pxmxw6ppr-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/r7dwv4hibaqkbkq0kr4g80ci6a9fdl2w-nghttp2-1.70.0-doc"
},
{
"name": "lib",
"path": "/nix/store/imwjr83lb0xlhz4ssq96kj8qbqk6qivs-nghttp2-1.70.0-lib"
}
],
"store_path": "/nix/store/8p19fbn4slkvk18j3bvjjh4yhp0d32wf-nghttp2-1.70.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/kgnsbgqd6wbfkk0w9ggsfmaphhfycdpw-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/mf4xap4xwy757l2mn6z19c9vlwnsg9az-nghttp2-1.70.0-man",
"default": true
},
{
"name": "lib",
"path": "/nix/store/6pv315yv0ccxd5h26zhj0i6mgn7q3brj-nghttp2-1.70.0-lib"
},
{
"name": "dev",
"path": "/nix/store/bvf03id3xxgkpkw2ay29j5k6hcqivgk7-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/dg8m57h861pzxb4xml1rpxakvkkli1nn-nghttp2-1.70.0-doc"
}
],
"store_path": "/nix/store/kgnsbgqd6wbfkk0w9ggsfmaphhfycdpw-nghttp2-1.70.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/dpacn35xr3iajmgvcprb63hnxby21gpx-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/rja4jsc58spfj44gscpaa6shnmqgijj7-nghttp2-1.70.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/9ia7882m3hhvdk6qi4p3p650pfhxg75r-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/w9fm1rnnl71p5m9wy6sn9hb11p35bf5p-nghttp2-1.70.0-doc"
},
{
"name": "lib",
"path": "/nix/store/sky8mslz50n51np0z4vhdq61jba12fh2-nghttp2-1.70.0-lib"
}
],
"store_path": "/nix/store/dpacn35xr3iajmgvcprb63hnxby21gpx-nghttp2-1.70.0"
}
}
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
"source": "devbox-search",
"version": "2.2.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"nimble@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
"source": "devbox-search",
"version": "0.24.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
}
}
},
"nodejs@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
}
}
}
@@ -0,0 +1,29 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Pixi v8 tile-size phone test (throwaway)</title>
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #000; font: 11px monospace; color: #eee; overscroll-behavior: none; }
canvas { display: block; touch-action: none; }
.panel { position: fixed; background: rgba(0,0,0,.72); padding: 4px 6px; border-radius: 4px; }
#stats { top: 2px; left: 2px; white-space: pre; pointer-events: none; font-size: 10px; }
#ctl { bottom: 2px; left: 2px; right: 2px; display: flex; flex-wrap: wrap; gap: 4px; }
button, select { font: inherit; padding: 8px 6px; }
#msg { bottom: 110px; left: 2px; white-space: pre-wrap; pointer-events: none; }
</style>
</head>
<body>
<div id="stats" class="panel"></div>
<div id="msg" class="panel"></div>
<div id="ctl" class="panel">
<select id="size"><option>32</option><option>64</option><option>256</option></select>
<button id="explore">Explore: start</button>
<button id="open">Open map</button>
<button id="reveal">Reveal viewport (cold)</button>
<button id="send">Send results</button>
</div>
<script type="module" src="/web/main.ts"></script>
</body>
</html>
@@ -0,0 +1,3 @@
--path:"src"
--threads:on
--mm:orc
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
{
"name": "prototype-tile-leak-phone",
"private": true,
"type": "module",
"scripts": { "build": "tsc && vite build" },
"dependencies": { "pixi.js": "^8.22.0" },
"devDependencies": { "playwright-core": "^1.64.1", "typescript": "^7.0.2", "vite": "^8.3.5" }
}

Some files were not shown because too many files have changed in this diff Show More