CyberCity/tools/headless.cjs
MiguelCarino 574d4113e6 CyberCity: a walkable ASCII cyberpunk city in one HTML file
A first-person street canyon rendered at character resolution, fullscreen,
self-contained: index.html has zero external references and is built from
src/ by `node build.js`. Never edit index.html by hand.

Renderer is voxel-space (heightmap) raycasting, not a wall grid: each screen
COLUMN marches front-to-back keeping a running silhouette row, which gives
occlusion, varying building heights, cross-streets and the slot of sky
between rooftops for free.

- src/city.js       endless deterministic heightmap; districts, lots, signs,
                    the walk, and a 192-candidate search for a start point
                    that opens inside a canyon on every seed
- src/weather_state.js  one weather director: six presets on a seeded schedule
                    with weighted transitions. Every element reads rel(), which
                    is 1.0 under the preset the build was tuned as
- src/control.js    arbitration, not replacement -- the autopilot never stops
                    running, the viewer's pose is cross-faded over it, and
                    letting go re-anchors to the nearest point on the route.
                    Keyboard, mouse-look, touch, gamepad; pitch slides the
                    horizon because at this resolution that IS pitch
- src/surfaces.js   facade/floor/sky texture, puddles, wet reflection
- src/raycast.js    the column march
- src/elements/     38 ambient elements: rain, steam, fog, lightning, stars,
                    moon, aircraft, blimps, drones, searchlights, beacons,
                    crowds with clothing archetypes, traffic, a cat, food
                    stalls, litter, props, skybridges, cables, neon, holo,
                    signals, shop spill, and the optics passes
- tools/            headless.cjs renders a frame with no browser; topng.py
                    prints it; metrics.py measures it; domshim.cjs boots the
                    BUILT page under a fake DOM; flicker-rate.cjs and
                    lightning-rate.cjs are the photosensitivity gates

Verified: deterministic (byte-identical renders across processes), 252/252
domshim checks, flicker-rate PASS under all six skies, lightning-rate PASS
on the four skies that carry storms and NOT_APPLICABLE on the two that do not.

Not yet verified in a real browser: glyph legibility, bloom appearance,
on-screen colour, frame budget, and touch/gamepad on hardware.
2026-08-16 02:20:18 -06:00

151 lines
9 KiB
JavaScript

/* Render one frame with no browser. Usage:
node tools/headless.cjs [seed] [frame] [cols] [rows] [--cold] > f.txt
Loads whatever src modules exist, so it stays useful while the build is half-written.
THIS HARNESS REPLAYS THE WHOLE FRAME, NOT JUST THE UPDATES. See the replay loop below: until
this round it called update() on every tick and draw() exactly once at the end, which is not
the shape of main.js and quietly pinned three optics passes at their cold-start values in every
offline frame this project had measured up to that point. */
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
/* Flags are stripped before the positional args are read, so --cold can go anywhere on the line
instead of having to come after four positionals nobody wants to type. Matched on the double
dash and not on a leading '-', because a lone '-' is how a negative seed would arrive. */
const argv = process.argv.slice(2);
const flags = argv.filter(a => a.slice(0, 2) === '--');
const pos = argv.filter(a => a.slice(0, 2) !== '--');
const cold = flags.indexOf('--cold') >= 0;
const seed = parseInt(pos[0] || '1', 10);
const frameN= parseInt(pos[1] || '0', 10);
const cols = parseInt(pos[2] || '200', 10);
const rows = parseInt(pos[3] || '60', 10);
global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined;
const order = ['src/weather_state.js','src/city.js','src/surfaces.js','src/raycast.js','src/control.js','src/compose.js'];
for (const rel of order) {
const p = path.join(root, rel);
if (fs.existsSync(p)) require(p);
}
const edir = path.join(root, 'src/elements');
if (fs.existsSync(edir))
for (const f of fs.readdirSync(edir).sort()) if (f.endsWith('.js')) require(path.join(edir, f));
const CC = global.CC;
const f = CC.makeFrame(cols, rows);
const t = frameN / 60;
const city = CC.City ? CC.City.make(seed) : null;
if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635));
if (CC.Control) CC.Control.reset();
const cam = {
x: city && city.startX !== undefined ? city.startX : 0.5,
z: city && city.startZ !== undefined ? city.startZ : 0.5,
yaw: 0, eyeY: 1.7, fov: 1.25, horizon: rows * 0.56, scale: rows * 0.9, t: t
};
// The camera advance MUST come from the city itself, exactly as main.js drives it. An earlier
// version of this harness advanced cam.z here on its own, which faked motion the browser never
// had and hid a shipped bug where the walk never started at all.
// Camera is advanced inside the replay loop below, once per tick, exactly as main.js's step()
// does — see the comment there. Advancing it once to the final pose and then replaying updates
// against that frozen pose is what the second review caught: five street elements spawn and cull
// relative to the camera basis inside update(), so a pinned pose gives them a history that never
// happened.
const rng = CC.mulberry(seed ^ 0x9e3779b9);
// Layer-sorted BEFORE init, because main.js does the same and every element pulls from this one
// shared rng: a different init order gives every downstream element a different stream, and the
// offline reference frame stops being the frame the browser draws.
const els = CC.ELEMENTS.slice().sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) { if (el.init) el.init(city, rng, {cols, rows}); }
/* One rendered frame, in main.js's render() order and with main.js's clear. Nothing here is
optional on a warm-up tick: an element that measures the frame measures the FINISHED frame, so
the world pass and every element below it have to have run before it looks. */
function renderAt(kt) {
cam.t = kt;
CC.clearFrame(f);
if (CC.Cast) CC.Cast.render(f, cam, city);
for (const el of els) if (el.draw) el.draw(f, cam, kt);
if (CC.Compose && CC.Compose.post) CC.Compose.post(f, cam, kt);
}
/* THE REPLAY. One outer loop over ticks: camera, then every element's update(), then the frame is
* DRAWN — the exact shape of main.js's tick(), which calls step() and then render() every time
* round. Element updates must see the camera pose of THEIR OWN tick, not the final one.
*
* WHY THE WARM-UP DRAWS ARE NOT WASTE, which is the bug this loop was rewritten to fix. Three
* passes in src/elements/optics.js measure the FRAME inside draw() and integrate that measurement
* inside update(): the exposure pass's two lagged luminance filters, the light-shaft detector, and
* the light-wash detector. Their update() opens by returning if no frame has been measured yet, so
* a replay that called update() 9000 times and draw() once left all three sitting at exactly their
* cold-start values — exposure's adaptation pinned at 1.000 with its filters never seeded, the
* shafts landing on a first detection with no easing history behind them, and the wash's lean term
* (which IS the eased position's lag, so it can only exist once easing has run) at a flat zero, so
* no offline frame ever rendered has shown the wedge leaning. Every palette share, black
* percentage and luminance histogram this project has published was therefore measured on a frame
* the browser only draws once, at start-up.
*
* The audit behind that list was run over all 38 elements by proxying every element object and
* recording which fields are written in draw() and read in update(); those three are the whole
* set. (pedestrians also refreshes this.cols/rows/cells in draw(), but init() is handed the same
* dims by this harness, so it reads the right numbers from its first tick and has no hole.)
*
* WHAT IT COST THE OLD NUMBERS, measured cold against warm over seeds 5,10,...,150 (thirty seeds,
* an arithmetic list, not four hand-picked ones) at 400x100. POOLED, almost nothing: at frame 600
* the lit-energy pillars move amber 38.62% -> 38.55% and azure 33.90% -> 33.97%, black 60.58% ->
* 60.66%. PER SEED, quite a lot: the exposure gain at frame 600 runs from 0.897 (seed 150) to
* 1.060 (seed 80) where the old harness reported exactly 1.000 for every seed, and half the seeds
* are more than 2% off it. That moves one frame's census by up to 1.8 points of black, 1.1 points
* of hot tail and 2.3 of mean printed value at frame 600, and up to 3.8 / 1.6 / 3.1 at frame 3000.
* So: a pooled palette share fitted the old way is still good, and any threshold fitted to a
* SINGLE frame was fitted to that frame's adaptation as much as to the print curve.
*
* The cost is honest and it is the raycast's: a warm tick is a full 400x100 render, about 8 ms, of
* which 5.8 ms is CC.Cast.render. --cold skips the warm-up and restores the old behaviour for the
* cases where only the seed's geometry matters and the wait does not pay — it is NOT the frame the
* browser draws, and it says so on stderr. Sweeps are per-seed independent, so the wait is a
* `seq ... | xargs -P 8` away from being eight times shorter. */
const t0 = Date.now();
for (let k = 0; k <= frameN; k++) {
const kt = k / 60;
// Weather first: an element's update() this tick must see this tick's weather.
if (CC.Weather) CC.Weather.update(1 / 60, kt);
// Through Control, exactly as main.js drives it. With no DOM attached it is pure autopilot,
// so this is the same walk city.camera produced before control.js existed -- and that is the
// point: an untouched keyboard has to render the frame this harness renders.
if (CC.Control) CC.Control.update(1 / 60, kt, cam, city);
else if (city && city.camera) city.camera(cam, city, kt);
for (const el of els) if (el.update) el.update(1 / 60, kt, cam);
// The last tick's draw is the frame we print, and it happens below so that cam.t is the
// requested t exactly. Every earlier tick is drawn and thrown away, for its side effects on the
// three measuring passes above.
if (!cold && k < frameN) renderAt(kt);
}
renderAt(t);
const ms = Date.now() - t0;
const out = [];
out.push('CCFRAME 2'); // v2 adds the kind byte as a fourth field per cell
out.push(cols + ' ' + rows);
out.push('PALETTE ' + CC.PALETTE.map(c => c.join(',')).join(' '));
out.push('GLYPHS ' + JSON.stringify(CC.GLYPHS.join('')));
for (let y = 0; y < rows; y++) {
const line = [];
for (let x = 0; x < cols; x++) {
const i = y * cols + x;
line.push(f.ch[i] + ',' + f.col[i] + ',' + f.lum[i] + ',' + f.kind[i]);
}
out.push(line.join(' '));
}
process.stdout.write(out.join('\n') + '\n');
/* The exposure gain is reported on stderr because it is the one thing about this frame that no
census of the dump can recover: it is a scalar already multiplied into every lum, so a reader
comparing two seeds cannot tell a darker city from an eye that had just walked out of one.
Measured over seeds 5..150 step 5 at frame 600 it lands between 0.897 and 1.060, so quoting a
frame's numbers without it is quoting a measurement taken at an unstated exposure. */
const ex = els.filter(e => e.name === 'exposure' && typeof e.adapt === 'number')[0];
process.stderr.write(`rendered seed=${seed} frame=${frameN} ${cols}x${rows} elements=${CC.ELEMENTS.length} ` +
(cold ? 'COLD-START (adaptation pinned, NOT the browser frame) ' : `replay=${frameN + 1} frames `) +
(ex ? `exposure=${ex.adapt.toFixed(3)} ` : '') +
`in ${ms}ms\n`);