prototype-tile-leak: phone test page (Pixi tile-size client check)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 11:34:48 +01:00
co-authored by Claude Sonnet 5.5
parent f28cb902e5
commit b091882d7d
13 changed files with 1822 additions and 4 deletions
+2
View File
@@ -6,3 +6,5 @@ bin/
nimble.develop
nimbledeps
devbox.d/
node_modules/
dist/
+34
View File
@@ -119,3 +119,37 @@ 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).
+7 -2
View File
@@ -5,7 +5,9 @@
"nimble": "latest",
"nginx": "latest",
"nghttp2": "latest",
"curl": "latest"
"curl": "latest",
"nodejs": "latest",
"chromium": "latest"
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
@@ -30,7 +32,10 @@
],
"netbench": [
"tools/netbench.sh | tee results/netbench.log"
],
"phone": [
"tools/phone.sh"
]
}
}
}
}
+75
View File
@@ -1,6 +1,42 @@
{
"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",
@@ -509,6 +545,45 @@
"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"
}
}
}
}
}
+29
View File
@@ -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>
File diff suppressed because it is too large Load Diff
+8
View File
@@ -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" }
}
+2 -2
View File
@@ -1,7 +1,7 @@
## slice the procedural 4096^2 map into square tiles of each size. usage: gen <outdir> <grain>
## slice the procedural 4096^2 map into square tiles of each size. usage: gen <outdir> <grain> [world=4096]
import pixie, pixie/fileformats/png, std/[os, strformat, strutils]
import art
let (outDir, grain, world) = (paramStr(1), paramStr(2).parseFloat, 4096)
let (outDir, grain, world) = (paramStr(1), paramStr(2).parseFloat, if paramCount() > 2: paramStr(3).parseInt else: 4096)
for size in [256, 64, 32]:
let d = outDir / ("tiles" & $size)
createDir d
+71
View File
@@ -0,0 +1,71 @@
## Phone test: plain static server (no auth, no nginx) for dist/ + data/phone tiles + POST /results. LAN only (peer must be private/loopback).
## usage: phonesrv <port> <world px>
import std/[strutils, os, json, times, locks]
import mummy
const MaxBody = 64 * 1024
const MaxFile = 2 * 1024 * 1024 # total bytes appended per server run
let port = parseInt(paramStr(1))
let world = parseInt(paramStr(2))
let resFile = "results" / ("phone-" & now().format("yyyyMMdd'T'HHmmss") & ".jsonl")
var lk: Lock
var written = 0
initLock lk
createDir "results"
proc lanPeer(a: string): bool =
a.startsWith("127.") or a.startsWith("10.") or a.startsWith("192.168.") or a.startsWith("169.254.") or
a == "::1" or a.toLowerAscii.startsWith("fe80") or a.toLowerAscii.startsWith("::ffff:192.168.") or
a.toLowerAscii.startsWith("::ffff:10.") or a.toLowerAscii.startsWith("::ffff:127.") or
(a.startsWith("172.") and a.split('.').len > 1 and a.split('.')[1].parseInt in 16..31)
proc reply(r: Request, code: int, ctype: string, body: string, cache = "no-store") =
var h: HttpHeaders
h["Content-Type"] = ctype
h["Cache-Control"] = cache # no-store: measure cold network loads, not the HTTP cache
r.respond(code, h, body)
proc ctypeOf(p: string): string =
case p.splitFile.ext
of ".html": "text/html; charset=utf-8"
of ".js": "text/javascript"
of ".css": "text/css"
of ".png": "image/png"
of ".json": "application/json"
else: "application/octet-stream"
proc handler(request: Request) {.gcsafe.} =
{.gcsafe.}:
if not lanPeer(request.remoteAddress): request.respond(403); return
let path = request.path
if request.httpMethod == "POST" and path == "/results":
if request.body.len > MaxBody: request.respond(413); return
var node: JsonNode
try: node = parseJson(request.body)
except CatchableError: request.respond(400); return
if node.kind != JObject: request.respond(400); return
let line = $node & "\n"
withLock lk:
if written + line.len > MaxFile: request.respond(413); return
written += line.len
let f = open(resFile, fmAppend)
f.write line
f.close
request.reply(200, "application/json", "{\"ok\":true,\"file\":" & $(%resFile) & "}")
return
if request.httpMethod != "GET": request.respond(405); return
var file = ""
if path == "/" : file = "dist/index.html"
elif path == "/meta.json": request.reply(200, "application/json", "{\"world\":" & $world & "}"); return
elif path.startsWith("/assets/") and path.len < 100 and
path[8 .. ^1].allCharsInSet(Letters + Digits + {'.', '-', '_'}) and ".." notin path: file = "dist" & path
elif path.startsWith("/tiles/"): # /tiles/<32|64|256>/<x>_<y>.png
let parts = path[7 .. ^1].split('/')
if parts.len == 2 and parts[0] in ["32", "64", "256"] and parts[1].endsWith(".png"):
let xy = parts[1][0 .. ^5].split('_')
if xy.len == 2 and xy[0].len in 1..3 and xy[1].len in 1..3 and xy[0].allCharsInSet(Digits) and xy[1].allCharsInSet(Digits):
file = "data/phone/tiles" & parts[0] / parts[1]
if file == "" or not fileExists file: request.respond(404); return
request.reply(200, ctypeOf file, readFile file)
newServer(handler, workerThreads = 8).serve(Port(port), "0.0.0.0")
+13
View File
@@ -0,0 +1,13 @@
// headless smoke check of the phone page (server must be running): node tools/headless.mjs [url]
import { chromium } from 'playwright-core';
const b = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || 'chromium', args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
const p = await b.newPage({ viewport: { width: 412, height: 800 }, hasTouch: true });
const errs = []; p.on('pageerror', (e) => errs.push(String(e))); p.on('console', (m) => m.type() === 'error' && errs.push(m.text()));
await p.goto(process.argv[2] || 'http://127.0.0.1:8099/');
const stats = async () => (await p.textContent('#stats')).split('\n').slice(0, 7).join('\n');
await p.waitForTimeout(3000); console.log('open:\n' + await stats());
await p.selectOption('#size', '64'); await p.waitForTimeout(1500);
await p.selectOption('#size', '32'); await p.click('#explore'); await p.waitForTimeout(4000); console.log('explore:\n' + await stats());
await p.click('#reveal'); await p.waitForTimeout(3000); console.log('reveal:\n' + await stats());
await p.click('#send'); await p.waitForTimeout(500); console.log(await p.textContent('#msg'));
console.log('errors:', errs); await b.close();
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# `devbox run phone`: build client + server, ensure tiles, serve on 0.0.0.0:$PORT (LAN only), print URLs. Ctrl-C stops.
set -eu
cd "$(dirname "$0")/.."
PORT=${PORT:-8099}; WORLD=${WORLD:-16384}
[ -d node_modules/pixi.js ] || npm install --no-audit --no-fund
nimble setup -y >/dev/null; mkdir -p bin results
[ -x bin/gen ] || nim c -d:release --hints:off --warnings:off -o:bin/gen src/gen.nim
if [ "$(ls data/phone/tiles32 2>/dev/null | wc -l)" != "$(( (WORLD/32)*(WORLD/32) ))" ] || [ "$(ls data/phone/tiles64 2>/dev/null | wc -l)" != "$(( (WORLD/64)*(WORLD/64) ))" ] || [ "$(ls data/phone/tiles256 2>/dev/null | wc -l)" != "$(( (WORLD/256)*(WORLD/256) ))" ]; then
echo "generating ${WORLD}px tiles (one-off, minutes, ~1.1 GB on disk)..."; rm -rf data/phone; mkdir -p data/phone; bin/gen data/phone 6 "$WORLD"
fi
nim c -d:release --hints:off --warnings:off -o:bin/phonesrv src/phonesrv.nim
npm run build >/dev/null
bin/phonesrv "$PORT" "$WORLD" & SRV=$!
trap 'kill $SRV 2>/dev/null' EXIT INT TERM
sleep 1; kill -0 $SRV 2>/dev/null || { echo "server failed to start (port $PORT busy?)"; exit 1; }
echo; echo "Open on the phone (same Wi-Fi):"
ip -4 -o addr show scope global | awk -v p="$PORT" '{split($4,a,"/"); print " http://" a[1] ":" p "/ (" $2 ")"}'
echo "Results -> $PWD/results/phone-*.jsonl. Ctrl-C to stop."
wait $SRV
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM"],
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["vite/client"]
},
"include": ["web"]
}
+228
View File
@@ -0,0 +1,228 @@
// THROWAWAY phone test: does Pixi v8 cope with 32 px tiles? See ../README.md "Phone test".
import { Application, Container, ImageSource, Sprite, Texture } from 'pixi.js';
const CELL = 32;
const MAX_INFLIGHT = 24;
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const meta = await (await fetch('/meta.json')).json();
const WORLD: number = meta.world;
const app = new Application();
await app.init({
resizeTo: window, background: 0x000000, antialias: false,
resolution: Math.min(devicePixelRatio, 2), autoDensity: true,
eventFeatures: { move: false, globalMove: false, click: false, wheel: false }, // DOM pointer events below
});
document.body.prepend(app.canvas);
const world = new Container();
app.stage.addChild(world);
// ---------- state ----------
type Tile = { sprite: Sprite; tex: Texture };
let size = 32;
let mode: 'open' | 'fog' = 'open';
let cam = { x: WORLD / 2, y: WORLD / 2, z: 1 }; // world point at screen centre, zoom
let dirty = true, lastMove = 0;
const loaded = new Map<number, Tile>();
const inflight = new Set<number>();
const pool: Sprite[] = [];
let revealedCells: number[] = []; // fog mode: cell ids (cy*CW+cx)
const CW = WORLD / CELL;
const revealedMask = new Uint8Array(CW * CW);
let allowed = new Set<number>(); // fog mode: tile ids of current size overlapping >=1 revealed cell
const tw = () => WORLD / size;
const tid = (x: number, y: number) => y * tw() + x;
// ---------- per-size accumulators ----------
const mk = () => ({ started: 0, done: 0, failed: 0, bytes: 0, lat: [] as number[], frames: [] as number[], ttvl: [] as number[],
peakSprites: 0, peakTextures: 0, peakHeapMB: 0, t0: performance.now() });
let acc = mk();
const snaps: Record<string, unknown> = {};
const pct = (a: number[], p: number) => { if (!a.length) return null; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
const mean = (a: number[]) => a.length ? a.reduce((x, y) => x + y, 0) / a.length : null;
const r1 = (v: number | null) => v === null ? null : Math.round(v * 10) / 10;
function snapshot() {
const f = acc.frames; // frame ms while camera moving / sim running
return {
size, mode, zoom: r1(cam.z), seconds: r1((performance.now() - acc.t0) / 1000),
movingFrames: f.length, movingFpsAvg: r1(f.length ? 1000 / mean(f)! : null),
movingFpsP5: r1(f.length ? 1000 / pct(f, 0.95)! : null), movingFpsMin: r1(f.length ? 1000 / Math.max(...f) : null),
reqStarted: acc.started, reqDone: acc.done, reqFailed: acc.failed, MB: r1(acc.bytes / 1e6),
fetchDecodeMsMed: r1(pct(acc.lat, 0.5)), fetchDecodeMsP95: r1(pct(acc.lat, 0.95)),
ttvlMs: acc.ttvl.map(Math.round), peakSprites: acc.peakSprites, peakTextures: acc.peakTextures, peakHeapMB: acc.peakHeapMB || null,
};
}
// ---------- tiles ----------
function view(margin: number) { // tile index range covering the screen (+margin px, world units)
const hw = app.screen.width / 2 / cam.z + margin, hh = app.screen.height / 2 / cam.z + margin;
const x0 = Math.max(0, Math.floor((cam.x - hw) / size)), x1 = Math.min(tw() - 1, Math.floor((cam.x + hw) / size));
const y0 = Math.max(0, Math.floor((cam.y - hh) / size)), y1 = Math.min(tw() - 1, Math.floor((cam.y + hh) / size));
return { x0, x1, y0, y1 };
}
const isAllowed = (id: number) => mode === 'open' || allowed.has(id);
function release(id: number) {
const t = loaded.get(id)!;
loaded.delete(id);
world.removeChild(t.sprite);
t.sprite.texture = Texture.EMPTY;
t.tex.destroy(true); // true = also destroy the TextureSource (frees GPU memory + closes the ImageBitmap)
pool.push(t.sprite);
}
function dropAll() { for (const id of [...loaded.keys()]) release(id); }
async function fetchTile(id: number, x: number, y: number, mySize: number) {
inflight.add(id); acc.started++;
const t0 = performance.now();
try {
const res = await fetch(`/tiles/${mySize}/${x}_${y}.png`, { cache: 'no-store' });
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
const bmp = await createImageBitmap(blob);
if (mySize !== size) { bmp.close(); return; } // size switched while in flight
const tex = new Texture({ source: new ImageSource({ resource: bmp }) });
const sprite = pool.pop() ?? new Sprite();
sprite.texture = tex;
sprite.position.set(x * size, y * size);
world.addChild(sprite);
loaded.set(id, { sprite, tex });
acc.done++; acc.bytes += blob.size; acc.lat.push(performance.now() - t0);
} catch { acc.failed++; } finally { inflight.delete(id); dirty = true; }
}
let ttvlT0: number | null = null;
function updateTiles() {
const need = view(size), keep = view(size * 2);
for (const id of [...loaded.keys()]) {
const x = id % tw(), y = Math.floor(id / tw());
if (x < keep.x0 || x > keep.x1 || y < keep.y0 || y > keep.y1 || !isAllowed(id)) release(id);
}
const q: { id: number; x: number; y: number; d: number }[] = [];
for (let y = need.y0; y <= need.y1; y++) for (let x = need.x0; x <= need.x1; x++) {
const id = tid(x, y);
if (!loaded.has(id) && !inflight.has(id) && isAllowed(id))
q.push({ id, x, y, d: Math.hypot((x + .5) * size - cam.x, (y + .5) * size - cam.y) }); // nearest first
}
q.sort((a, b) => a.d - b.d);
for (const t of q) { if (inflight.size >= MAX_INFLIGHT) break; fetchTile(t.id, t.x, t.y, size); }
// time-to-viewport-loaded: all allowed tiles strictly in view are loaded
if (ttvlT0 !== null) {
const v = view(0); let all = true;
for (let y = v.y0; y <= v.y1 && all; y++) for (let x = v.x0; x <= v.x1; x++) { const id = tid(x, y); if (isAllowed(id) && !loaded.has(id)) { all = false; break; } }
if (all && inflight.size === 0) { acc.ttvl.push(performance.now() - ttvlT0); ttvlT0 = null; }
}
}
// ---------- fog / exploration ----------
function reveal(cx: number, cy: number) {
if (cx < 0 || cy < 0 || cx >= CW || cy >= CW || revealedMask[cy * CW + cx]) return;
revealedMask[cy * CW + cx] = 1; revealedCells.push(cy * CW + cx);
allowed.add(tid(Math.floor(cx * CELL / size), Math.floor(cy * CELL / size)));
}
function revealDisc(px: number, py: number, rCells: number) {
const cx = Math.floor(px / CELL), cy = Math.floor(py / CELL), r = Math.ceil(rCells);
for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) if (dx * dx + dy * dy <= rCells * rCells) reveal(cx + dx, cy + dy);
}
function resetFog() { revealedMask.fill(0); revealedCells = []; allowed = new Set(); }
function rebuildAllowed() { allowed = new Set(); for (const c of revealedCells) allowed.add(tid(Math.floor((c % CW) * CELL / size), Math.floor(Math.floor(c / CW) * CELL / size))); }
let sim: { x: number; y: number; h: number; timer: number } | null = null;
function startSim() {
stopSim(); dropAll(); resetFog(); mode = 'fog';
sim = { x: WORLD / 2, y: WORLD / 2, h: Math.random() * 6.28, timer: 0 };
cam.x = sim.x; cam.y = sim.y;
revealDisc(sim.x, sim.y, 9.6); // connect burst, ~290 cells (leak-A hello)
ttvlT0 = performance.now(); dirty = true;
sim.timer = window.setInterval(() => { // steady: ~0.6 cell per step reveals ~11 new cells (leak-A median)
const s = sim!; s.h += (Math.random() - .5) * 0.8;
s.x = Math.min(WORLD - 400, Math.max(400, s.x + Math.cos(s.h) * 0.6 * CELL)); s.y = Math.min(WORLD - 400, Math.max(400, s.y + Math.sin(s.h) * 0.6 * CELL));
revealDisc(s.x, s.y, 9.6);
cam.x = s.x; cam.y = s.y; lastMove = performance.now(); dirty = true;
}, 400);
$('explore').textContent = 'Explore: stop';
}
function stopSim() { if (sim) clearInterval(sim.timer); sim = null; $('explore').textContent = 'Explore: start'; }
// ---------- controls ----------
function setSize(s: number) {
snaps[size] = snapshot(); stopSim(); dropAll();
size = s; acc = mk(); rebuildAllowed(); ttvlT0 = performance.now(); dirty = true;
}
$('size').onchange = (e) => setSize(Number((e.target as HTMLSelectElement).value));
$('explore').onclick = () => (sim ? stopSim() : startSim());
$('open').onclick = () => { stopSim(); mode = 'open'; dirty = true; };
$('reveal').onclick = () => {
dropAll(); // cold: every tile in view must come over the network again
if (mode === 'fog') { const v = view(0); for (let y = v.y0 * size / CELL; y < (v.y1 + 1) * size / CELL; y++) for (let x = v.x0 * size / CELL; x < (v.x1 + 1) * size / CELL; x++) reveal(x, y); }
// fog: reveal exactly the cells under the screen
ttvlT0 = performance.now(); dirty = true;
};
$('send').onclick = async () => {
snaps[size] = snapshot();
const body = { t: new Date().toISOString(), ua: navigator.userAgent, dpr: devicePixelRatio, screen: [screen.width, screen.height], inner: [innerWidth, innerHeight],
renderer: app.renderer.name, world: WORLD, snaps };
try { const r = await fetch('/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); msg(`send: ${r.status} ${await r.text()}`); }
catch (e) { msg(`send failed: ${e}`); }
};
function msg(s: string) { $('msg').textContent = s; }
// ---------- touch: 1 pointer pan, 2 pointers pinch ----------
const ptrs = new Map<number, { x: number; y: number }>();
const clampZ = (z: number) => Math.min(4, Math.max(0.5, z)); // min 0.5: at 32 px a full viewport is already ~1.3k tiles
function zoomAt(sx: number, sy: number, nz: number) { // keep world point under (sx,sy) fixed
const wx = cam.x + (sx - app.screen.width / 2) / cam.z, wy = cam.y + (sy - app.screen.height / 2) / cam.z;
cam.z = clampZ(nz); cam.x = wx - (sx - app.screen.width / 2) / cam.z; cam.y = wy - (sy - app.screen.height / 2) / cam.z;
}
const cv = app.canvas;
cv.addEventListener('pointerdown', (e) => { cv.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY }); });
const up = (e: PointerEvent) => ptrs.delete(e.pointerId);
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('pointermove', (e) => {
const p = ptrs.get(e.pointerId); if (!p) return;
if (ptrs.size === 1) { cam.x -= (e.clientX - p.x) / cam.z; cam.y -= (e.clientY - p.y) / cam.z; }
else if (ptrs.size === 2) {
const [a, b] = [...ptrs.entries()].map(([id, v]) => ({ id, ...v }));
const d0 = Math.hypot(a.x - b.x, a.y - b.y);
p.x = e.clientX; p.y = e.clientY;
const d1 = Math.hypot(a.id === e.pointerId ? e.clientX - b.x : a.x - e.clientX, a.id === e.pointerId ? e.clientY - b.y : a.y - e.clientY);
if (d0 > 0) zoomAt((a.x + b.x) / 2, (a.y + b.y) / 2, cam.z * d1 / d0);
}
p.x = e.clientX; p.y = e.clientY; lastMove = performance.now(); dirty = true;
});
cv.addEventListener('wheel', (e) => { e.preventDefault(); zoomAt(e.clientX, e.clientY, cam.z * Math.exp(-e.deltaY / 500)); lastMove = performance.now(); dirty = true; }, { passive: false });
cv.addEventListener('contextmenu', (e) => e.preventDefault());
// ---------- frame loop + overlay ----------
const recent: { t: number; dt: number }[] = [];
let lastOverlay = 0;
const heapMB = () => { const m = (performance as any).memory; return m ? m.usedJSHeapSize / 1048576 : null; };
const gl = (app.renderer as any).gl as WebGL2RenderingContext | undefined;
app.ticker.add((tk) => {
const now = performance.now(), dt = tk.deltaMS;
world.scale.set(cam.z);
world.position.set(app.screen.width / 2 - cam.x * cam.z, app.screen.height / 2 - cam.y * cam.z);
const moving = now - lastMove < 300;
recent.push({ t: now, dt }); while (recent[0].t < now - 5000) recent.shift();
if (moving && acc.frames.length < 50000) acc.frames.push(dt);
if (dirty) { dirty = false; updateTiles(); }
else if (ttvlT0 !== null || inflight.size) updateTiles();
acc.peakSprites = Math.max(acc.peakSprites, world.children.length); acc.peakTextures = Math.max(acc.peakTextures, loaded.size);
const h = heapMB(); if (h) acc.peakHeapMB = Math.max(acc.peakHeapMB, Math.round(h));
if (now - lastOverlay > 500) {
lastOverlay = now;
const sum = recent.reduce((s, r) => s + r.dt, 0), fpsAvg = recent.length * 1000 / sum, fpsMin = 1000 / Math.max(...recent.map((r) => r.dt));
const s = snapshot();
$('stats').textContent =
`fps(5s) avg ${fpsAvg.toFixed(0)} min ${fpsMin.toFixed(0)} | moving avg ${s.movingFpsAvg ?? '-'} p5 ${s.movingFpsP5 ?? '-'} min ${s.movingFpsMin ?? '-'}
tile ${size}px mode ${mode} zoom ${cam.z.toFixed(2)} world ${WORLD}
sprites ${world.children.length} textures ${loaded.size} pool ${pool.length}
req inflight ${inflight.size} done ${acc.done} failed ${acc.failed} (${(acc.bytes / 1e6).toFixed(1)} MB)
fetch+decode ms med ${s.fetchDecodeMsMed ?? '-'} p95 ${s.fetchDecodeMsP95 ?? '-'}
viewport loaded ms: ${ttvlT0 !== null ? 'loading...' : (s.ttvlMs.at(-1) ?? '-')} (all: ${s.ttvlMs.join(',')})
heap ${h ? h.toFixed(0) + ' MB' : 'n/a'} dpr ${devicePixelRatio} res ${app.renderer.resolution}
renderer ${app.renderer.name}${gl ? ' ' + String(gl.getParameter(gl.VERSION)) : ''}
${navigator.userAgent}`;
}
});
ttvlT0 = performance.now();