feat(m4): cap map images at Full HD and shrink on import (#85)

The owner fixed the map cap at 1920 px on the long side and 1080 px on the
short side (either orientation). fff-vtt import now shrinks a larger source
with ImageMagick Lanczos before tiling (alpha kept, proportions preserved,
no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a
source at or below the cap is untouched, so the pixel-identity tests still
hold. A scene row already above the cap is not rewritten: the server logs
`map_above_cap` at startup and serve prints the re-import advice.

Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README,
HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement
now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows
stay as labelled server stress references. import-scale now proves a 16384²
input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded.

Part of #63, #85. #77 is blocked by this issue.
This commit is contained in:
2026-11-21 22:37:34 +01:00
parent 52ab50d765
commit a79d809394
22 changed files with 515 additions and 193 deletions
+9 -6
View File
@@ -1,6 +1,8 @@
## Vision and egress microbench: devbox run bench (nim c -d:release -r tools/bench.nim; log: results/bench.log).
## No timing code lives in server/: this harness times from outside with O(1) accumulators (sum, worst), no sample arrays.
## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on 5k walls.
## Targets (DESIGN 5.3 / 13 M2, PROPOSED): polygon + cells <= 0.451 ms avg on the prototype scene; polygon < 1 ms avg on the 5k-wall stress scene.
## The product map maximum is Full HD (1920x1080, #85); the 16384 px and 262144-cell rows below are labelled
## stress references for the server, not the product target.
## The egress rows record the absolute averages the in-process gate (tests/tviews.nim, TESTING 5.3) deliberately does not assert.
import std/[json, monotimes, times, strformat, os, math, options, sets, tables]
import db_connector/db_sqlite
@@ -72,10 +74,10 @@ proc big(label: string, world: float) =
discard bench(&"1 move check (pathClear, cap-length step), {label}", 20000, proc(i: int) =
let o: Vec = (rng.uni(400, world - 400), rng.uni(400, world - 400))
sink += int(pathClear(walls, o, (o.x + 300, o.y), 20)))
if label == "5k sparse": target("polygon, 5k-wall scene", po, 1.0)
big("5k sparse", 16384)
big("5k dense", 4096)
echo "== egress (#28: 6 players x 40 encountered entries, 262144 explored cells) =="
if label == "5k sparse (stress)": target("polygon, 5k-wall stress scene", po, 1.0)
big("5k sparse (stress)", 16384)
big("5k dense (stress)", 4096)
echo "== egress (#28 stress: 6 players x 40 encountered entries, 262144 explored cells) =="
proc egressStore(cells: int): ref ContextStore =
var tokens: seq[TokenRec]
for i in 0 ..< 6:
@@ -136,7 +138,8 @@ discard bench("tile gate old: parse + SHA-256 + session JOIN + HashSet", 2000, p
discard bench("tile gate new: parse + SHA-256 + cache lookup + bitmap", 2000, proc(i: int) =
let h = sha256Hex(benchToken)
if gc.gateTile(h, "1", "v1", "9_9.png").allowed: inc sink)
# Explored ops: the snapshot build at the 16384 px size (512x512 cells) and the incremental mark.
# Explored ops: the snapshot build at a synthetic 16384 px stress size (512x512 cells) and the
# incremental mark. The product maximum is Full HD (2040 cells at cell 32, #85).
let bigScene = SceneRec(id: 1, name: "Scene", w: 16384, h: 16384, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1,
nextWallId: 1, extra: newJObject())
+22 -17
View File
@@ -1,10 +1,11 @@
## M4 fog benchmark (#76): the 50-token, 16384 px tile map measurement the finish ticket records
## in `results/m4-fog-bench.md`. `devbox run fogbench` compiles and runs it; the log lands in
## `results/m4-fog-bench.log`.
## M4 fog benchmark (#76): the 50-token, Full HD (1920x1080) tile map measurement the finish ticket
## records in `results/m4-fog-bench.md`. `devbox run fogbench` compiles and runs it; the log lands in
## `results/m4-fog-bench.log`. The Full HD cap is the owner decision of 2026-11-21 (#85), so this is
## the product maximum, not the old 16384 px stress map.
##
## Two numbers the phone gate needs to make sense of:
## 1. server recompute on a move: one player's vision refresh (one polygon, ~5k sparse walls,
## 16384 px map) plus the egress pass for that player with 50 visible tokens;
## 1. server recompute on a move: one player's vision refresh (one polygon, 5k-wall generator
## clipped to the Full HD scene) plus the egress pass for that player with 50 visible tokens;
## 2. the client's headless frame time is measured separately by `client/e2e/fogbench.test.mjs`
## (SwiftShader, so it is a floor, never the phone number it is compared with).
##
@@ -26,31 +27,35 @@ proc bench(name: string, n: int, f: proc(i: int)): float =
echo &"{name}: n={n} avg={sum / n.float:.3f}ms worst={worst:.3f}ms"
sum / n.float
const World = 16384.0
const
WorldW = 1920.0
WorldH = 1080.0
const PlayerId = 2
## 50 tokens: the player's one sighted token at the map centre, 49 NPCs inside its radius. The
## cluster is the phone scene (50 tokens rendered with the fog on), so the wall generator's walls
## inside that box are removed: the sight cost still comes from the ~5k walls elsewhere.
## inside that box are removed. The 5k-wall generator runs on a WorldW square and is clipped to the
## Full HD height, so the sight cost still comes from thousands of walls elsewhere.
proc build(): ref ContextStore =
var tokens: seq[TokenRec]
tokens.add TokenRec(id: "vision-token", scene: 1, kind: "pc", descriptiveName: "Ann",
actualName: "Ann", pos: (World / 2, World / 2), owner: PlayerId,
actualName: "Ann", pos: (WorldW / 2, WorldH / 2), owner: PlayerId,
flags: %*{"vision": true}, visionRadius: some(300.0), radius: some(20.0),
props: newProps())
for i in 0 ..< 49:
let dx = float((i mod 7) - 3) * 28.0
let dy = float((i div 7) - 3) * 28.0
tokens.add TokenRec(id: &"npc-{i}", scene: 1, kind: "npc", descriptiveName: &"T{i}",
actualName: &"T{i}", pos: (World / 2 + dx, World / 2 + dy),
actualName: &"T{i}", pos: (WorldW / 2 + dx, WorldH / 2 + dy),
owner: GmControlled, flags: %*{}, props: newProps())
let centre = World / 2
let centre = (WorldW / 2, WorldH / 2)
var walls: seq[WallRec]
var id = 0
for w in genScene(World, 5000, 1):
let near = max(w.a.x, w.b.x) >= centre - 400 and min(w.a.x, w.b.x) <= centre + 400 and
max(w.a.y, w.b.y) >= centre - 400 and min(w.a.y, w.b.y) <= centre + 400
for w in genScene(WorldW, 5000, 1):
if w.a.y > WorldH or w.b.y > WorldH: continue # clipped away by the Full HD scene height
let near = max(w.a.x, w.b.x) >= centre[0] - 400 and min(w.a.x, w.b.x) <= centre[0] + 400 and
max(w.a.y, w.b.y) >= centre[1] - 400 and min(w.a.y, w.b.y) <= centre[1] + 400
if near: continue
inc id
walls.add WallRec(id: id, a: w.a, b: w.b, thickness: 0, position: wpCenter,
@@ -60,7 +65,7 @@ proc build(): ref ContextStore =
flags: newJObject())
result = (ref ContextStore)(scene: SceneRec(
id: 1, name: "Scene", w: World, h: World, tileSize: 32, cell: 32,
id: 1, name: "Scene", w: WorldW, h: WorldH, tileSize: 32, cell: 32,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: id + 1,
extra: newJObject(), walls: walls), tokens: tokens)
for pid in 2 .. 7:
@@ -70,11 +75,11 @@ proc build(): ref ContextStore =
result.encountered[pid] = initTable[string, characters.EncounteredEntry]()
let store = build()
echo &"== M4 fog bench: 16384 px map, cell 32 ({store.scene.cols}x{store.scene.rows} cells), " &
echo &"== M4 fog bench: Full HD map 1920x1080, cell 32 ({store.scene.cols}x{store.scene.rows} cells), " &
&"{store.tokens.len} tokens, {store.scene.walls.len} walls =="
# 1. A move refreshes the mover's player: one polygon + its explored cells (main.refreshPlayer).
let refreshAvg = bench("server vision refresh, one player (1 polygon, radius 300, ~5k walls)", 500, proc(i: int) =
let refreshAvg = bench("server vision refresh, one player (1 polygon, radius 300, 5k-wall generator clipped to the scene)", 500, proc(i: int) =
store.visions[PlayerId].refresh(store.scene, store.tokens, PlayerId)
sink += store.visions[PlayerId].polys.len)
@@ -95,7 +100,7 @@ discard egressFrames(Recipient(isGm: false, playerId: PlayerId), ctx, warmKnown)
discard bench("player egress pass, warm Known (no changes)", 2000, proc(i: int) =
sink += egressFrames(Recipient(isGm: false, playerId: PlayerId), ctx, warmKnown).len)
echo &"explored snapshot size: {store.visions[PlayerId].explored.card} cells on the 16384 px map"
echo &"explored snapshot size: {store.visions[PlayerId].explored.card} cells on the Full HD map"
let budget = 16.7
echo &"TARGET move path: refresh + 50-token egress {refreshAvg + egressAvg:.3f} ms vs <= {budget} ms " &
&"(one 60 fps frame): {(if refreshAvg + egressAvg <= budget: \"PASS\" else: \"MISS\")}"
+66
View File
@@ -10,6 +10,7 @@ import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { DatabaseSync } from 'node:sqlite'
import { createPlayer, freePort, httpsBaseUrl, namePlayer } from './lib.mjs'
import { buildServer, gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
@@ -192,6 +193,71 @@ test('map import CLI: the streamed slice matches the one-shot crop pixel for pix
}
})
function sceneDims(stateDir) {
const db = new DatabaseSync(path.join(stateDir, 'state.db'), { readOnly: true })
try {
const row = db.prepare('SELECT w, h FROM scene WHERE id = 1').get()
return [row.w, row.h]
} finally {
db.close()
}
}
test('map import CLI: images above Full HD are shrunk to the cap, smaller ones untouched (#85)', () => {
const stateDir = makeStateDir()
try {
const cases = [
// [name, source w/h, expected scene w/h, expected stdout]
['landscape', 4000, 3000, 1440, 1080, 'scaled 4000×3000 → 1440×1080'],
['portrait', 3000, 4000, 1080, 1440, 'scaled 3000×4000 → 1080×1440'],
['square', 2000, 2000, 1080, 1080, 'scaled 2000×2000 → 1080×1080'],
['exactly-at-cap', 1920, 1080, 1920, 1080, null],
['one-px-over', 1921, 1080, 1920, 1079, 'scaled 1921×1080 → 1920×1079'],
['smaller', 256, 192, 256, 192, null],
]
for (const [name, w, h, wantW, wantH, scaled] of cases) {
const state = path.join(stateDir, name)
const img = path.join(state, `${name}.png`)
fs.mkdirSync(state, { recursive: true })
fs.writeFileSync(img, pngBytesWH(w, h, (x, y) => [x & 0xff, y & 0xff, 128]))
const imported = runImport(state, [`--image=${img}`, '--tile-size=64'])
assert.equal(imported.status, 0, `${name}: ${imported.stderr}`)
assert.deepEqual(sceneDims(state), [wantW, wantH], `${name}: scene row is the imported size`)
assert.match(imported.stdout, new RegExp(`${wantW}x${wantH} px, tile 64 px`),
`${name}: stdout reports the final size`)
if (scaled) assert.ok(imported.stdout.includes(scaled), `${name}: shrink is printed: ${imported.stdout}`)
else assert.equal(imported.stdout.includes('scaled '), false, `${name}: no needless resize`)
const cols = Math.ceil(wantW / 64)
const rows = Math.ceil(wantH / 64)
assert.equal(tileNames(path.join(state, 'tiles', '1', 'v1')).length, cols * rows,
`${name}: the tile grid follows the shrunk size`)
}
// Alpha survives the resize: a 50% transparent RGBA source is still RGBA at the cap size.
const alphaState = path.join(stateDir, 'alpha')
const alphaImg = path.join(alphaState, 'alpha.png')
fs.mkdirSync(alphaState, { recursive: true })
const made = spawnSync('magick', ['-size', '2000x1500', 'xc:rgba(255,0,0,0.5)',
'-depth', '8', alphaImg], { encoding: 'utf8' })
assert.equal(made.status, 0, made.stderr)
const alphaRun = runImport(alphaState, [`--image=${alphaImg}`, '--tile-size=64'])
assert.equal(alphaRun.status, 0, alphaRun.stderr)
assert.deepEqual(sceneDims(alphaState), [1440, 1080])
const tile = path.join(alphaState, 'tiles', '1', 'v1', '0_0.png')
const channels = spawnSync('magick', ['identify', '-format', '%[channels]', tile],
{ encoding: 'utf8' })
assert.equal(channels.status, 0, channels.stderr)
assert.match(channels.stdout, /a/, 'the tile still has an alpha channel')
const alphaMean = spawnSync('magick', [tile, '-format', '%[fx:mean.a]', 'info:'],
{ encoding: 'utf8' })
assert.equal(alphaMean.status, 0, alphaMean.stderr)
assert.ok(Math.abs(Number(alphaMean.stdout) - 0.50196) < 0.02,
`the alpha value survives the resize: ${alphaMean.stdout}`)
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}
})
test('map import CLI: a truncated source fails loudly and publishes nothing (#83)', () => {
// The streaming path reads the decoder's stdout band by band; a decode that dies mid-stream must
// surface magick's own message, not an empty tile tree or a byte-count mystery.
+27 -18
View File
@@ -1,10 +1,13 @@
// #83: the map import at the real target scale — a 16384x16384 source at tile size 64, i.e. 65,536
// tiles. The one-shot `-crop ... +adjoin` this replaces died here with "Too many open files" after
// minutes at 4-8 GB RSS, so this gate is the regression proof: bounded memory, bounded file
// descriptors (it runs under a low `ulimit -n`), a streamed progress trail, and the full tile tree.
// #83/#85: the map import at the old 16384 px input scale, now under the Full HD cap: the source is
// shrunk to 1080x1080 before tiling (289 tiles at 64 px, not 65,536). The one-shot
// `-crop ... +adjoin` this replaces died here with "Too many open files" after minutes at 4-8 GB
// RSS, so this gate is the regression proof: the huge input is shrunk quickly, memory and file
// descriptors stay bounded (it runs under a low `ulimit -n`), the streamed progress trail appears,
// and the output tile tree follows the shrunk scene.
//
// It is deliberately NOT part of `devbox run test`: generating the source and writing 65,536 PNGs
// takes ~40 s on a 16-core box. `devbox run import-scale` runs it and leaves results/import-scale.log.
// It is deliberately NOT part of `devbox run test`: generating the 16384 px source takes seconds,
// and the shrink is real ImageMagick work. `devbox run import-scale` runs it and leaves
// results/import-scale.log.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
@@ -17,8 +20,9 @@ import { pngSize } from './tilefixture.mjs'
const enabled = process.env.IMPORT_SCALE === '1'
const SIDE = 16384
const OUT = 1080
const TILE = 64
const TILE_COUNT = (SIDE / TILE) ** 2
const TILE_COUNT = Math.ceil(OUT / TILE) ** 2
const CRC_TABLE = (() => {
const table = new Int32Array(256)
@@ -134,7 +138,7 @@ async function runMeasured(args, ulimitN) {
peakFds, peakProcs }
}
test('map import CLI: 16384 px source at 64 px stays memory- and fd-bounded (#83)',
test('map import CLI: a 16384 px source is shrunk to Full HD and stays memory- and fd-bounded (#83, #85)',
{ skip: enabled ? false : 'scale test: run `devbox run import-scale`' }, async () => {
const stateDir = makeStateDir()
const img = path.join(stateDir, 'map16384.png')
@@ -154,23 +158,28 @@ test('map import CLI: 16384 px source at 64 px stays memory- and fd-bounded (#83
`peakFds=${run.peakFds} peakProcs=${run.peakProcs} tiles=${tiles.length}`)
assert.equal(run.status, 0, run.stderr)
assert.equal(tiles.length, TILE_COUNT, 'every tile of the 256x256 grid exists')
assert.equal(tiles.length, TILE_COUNT, 'the shrunk 1080x1080 scene has all 289 tiles at 64 px')
assert.match(fs.readFileSync(`${dir}/0_0.png`).slice(0, 8).toString('latin1'), /^\x89PNG/,
'tiles are PNGs')
assert.deepEqual(pngSize(`${dir}/255_255.png`), { width: TILE, height: TILE })
assert.deepEqual(pngSize(`${dir}/255_0.png`), { width: TILE, height: TILE })
assert.deepEqual(pngSize(`${dir}/15_15.png`), { width: TILE, height: TILE })
assert.deepEqual(pngSize(`${dir}/15_0.png`), { width: TILE, height: TILE })
assert.deepEqual(pngSize(`${dir}/16_16.png`),
{ width: OUT - 16 * TILE, height: OUT - 16 * TILE }, 'the last edge tile is 56x56')
assert.equal(fs.existsSync(`${dir}/255_255.png`), false,
'the 16384 px grid is gone: the scene is the Full HD shrink')
// Progress must be visible while it runs, not only at the end.
assert.match(run.stderr, /slicing 16384x16384 into 65536 tiles at 64 px/)
assert.match(run.stderr, /rows 12\/256, tiles 3072\/65536/)
assert.match(run.stderr, /rows 256\/256, tiles 65536\/65536/)
assert.match(run.stdout, /16384x16384 px, tile 64 px, 256x256 tiles/)
// The shrink itself is reported, then the slice of the shrunk image.
assert.match(run.stdout, /scaled 16384×16384 → 1080×1080/)
assert.match(run.stdout, /1080x1080 px, tile 64 px, 17x17 tiles/)
assert.match(run.stderr, /slicing 1080x1080 into 289 tiles at 64 px/)
assert.match(run.stderr, /rows 17\/17, tiles 289\/289/)
// The numbers are the point of this gate: 4-8 GB and 1024 fds were the old failure.
// The numbers are the point of this gate: 4-8 GB and 1024 fds were the old failure, and a
// 16384 px input used to mean minutes and 65k tiles.
assert.ok(run.peakRssMiB < 1024, `peak RSS ${run.peakRssMiB.toFixed(0)} MiB must stay under 1 GiB`)
assert.ok(run.peakFds < 256, `peak fds ${run.peakFds} must stay far under the 256 ulimit`)
assert.ok(run.peakProcs <= 12, `only the importer, one decoder and <=8 children may run (saw ${run.peakProcs})`)
assert.ok(run.ms < 600_000, `a 16384/64 import must finish in minutes, took ${run.ms} ms`)
assert.ok(run.ms < 180_000, `the huge input must be shrunk and tiled in minutes, took ${run.ms} ms`)
assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1'))
.some(n => n.startsWith('.import-')), false, 'no temporary directory is left behind')
+28 -7
View File
@@ -127,23 +127,32 @@ function importImage(opts, stateDir) {
}
}
/** The map a no-image start will serve, read from the state db without starting anything. */
function describeScene(stateDir) {
// The Full HD map cap (FIXED owner decision 2026-11-21, #85); the server warns in its own log,
// this is the same warning on the console where the operator actually looks.
const CAP_LONG = 1920
const CAP_SHORT = 1080
function readSceneRow(stateDir) {
const dbFile = path.join(stateDir, 'state.db')
if (!fs.existsSync(dbFile)) return 'fresh state: default 4096x4096, tile 32, art v1'
if (!fs.existsSync(dbFile)) return { text: 'fresh state: default 4096x4096, tile 32, art v1' }
let db
try {
db = new DatabaseSync(dbFile, { readOnly: true })
const row = db.prepare('SELECT w, h, tile_size, art_version FROM scene WHERE id = 1').get()
if (!row) return `no scene row in ${dbFile}`
return `${row.w}x${row.h}, tile ${row.tile_size}, art v${row.art_version}`
if (!row) return { text: `no scene row in ${dbFile}` }
return { row, text: `${row.w}x${row.h}, tile ${row.tile_size}, art v${row.art_version}` }
} catch (e) {
return `unreadable ${dbFile} (${e.message})`
return { text: `unreadable ${dbFile} (${e.message})` }
} finally {
db?.close()
}
}
/** The map a no-image start will serve, read from the state db without starting anything. */
function describeScene(stateDir) {
return readSceneRow(stateDir).text
}
/** `--dry-run`: prove the `--` arguments reached this script, then exit without side effects. */
function printDryRun(opts, stateDir) {
const lines = [
@@ -157,7 +166,14 @@ function printDryRun(opts, stateDir) {
` image: ${opts.image ? path.resolve(opts.image) : '<none, keeping current map>'}`,
` tile-size: ${opts.tileSize ?? '<none>'}`,
]
if (!opts.image) lines.push(` current map: ${describeScene(stateDir)}`)
if (!opts.image) {
lines.push(` current map: ${describeScene(stateDir)}`)
const { row } = readSceneRow(stateDir)
if (row && (Math.max(row.w, row.h) > CAP_LONG || Math.min(row.w, row.h) > CAP_SHORT)) {
lines.push(` WARNING: map is ${row.w}x${row.h}, above the Full HD cap ` +
`(at most ${CAP_LONG} px long side, ${CAP_SHORT} px short side); re-import to shrink.`)
}
}
process.stdout.write(lines.join('\n') + '\n')
}
@@ -213,6 +229,11 @@ function printStartup(handle) {
if (!fs.existsSync(distDir)) {
lines.push(`WARNING: no client build at ${distDir}; "/" will 404 until it is built.`, '')
}
const { row } = readSceneRow(stateDir)
if (row && (Math.max(row.w, row.h) > CAP_LONG || Math.min(row.w, row.h) > CAP_SHORT)) {
lines.push(`WARNING: map is ${row.w}x${row.h}, above the Full HD cap ` +
`(at most ${CAP_LONG} px long side, ${CAP_SHORT} px short side); re-import to shrink.`, '')
}
lines.push('The certificate only names this LAN address; if the laptop\'s address changes,',
'`devbox run serve` regenerates it and prints these steps again.', '')
process.stdout.write(lines.join('\n') + '\n')