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.
This commit is contained in:
MiguelCarino 2026-08-16 02:20:18 -06:00
commit 574d4113e6
26 changed files with 23200 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
__pycache__/
*.pyc

68
CONTRACT.md Normal file
View file

@ -0,0 +1,68 @@
# CyberCity — module contract
Deliverable: **one self-contained `index.html`**, fullscreen, pure ambient, no game loop.
Sources live in `src/`; `node build.js` inlines them into `index.html`. Never edit `index.html` by hand.
## Renderer model — voxel-space (heightmap) raycasting at character resolution
Not a wall-grid raycaster. Each map cell carries a **height**, and each screen *column* is marched
front-to-back keeping a running silhouette row. This gives correct occlusion, varying building heights,
cross-streets, alleys and — critically — the slot of sky between rooftops, all for free.
Per column `x`:
1. ray dir from `yaw + fov*(x/cols-0.5)`
2. march `t` from `T_NEAR` to `T_FAR`, step growing with `t`
3. sample `h = height(gx,gz)`; project `topRow = horizon - (h - eyeY)*scale/t`
4. if `topRow < silhouette[x]`, paint rows `topRow .. min(silhouette[x], baseRow)` as façade, then
`silhouette[x] = topRow`
5. below the horizon, the floor is painted by *inverse* projection: `t = eyeY*scale/(row-horizon)`
## Frame — parallel typed arrays, length `cols*rows`, index `i = row*cols + col`
| array | type | meaning |
| --- | --- | --- |
| `ch` | Uint8Array | index into `GLYPHS` |
| `col` | Uint8Array | index into `PALETTE` |
| `lum` | Uint8Array | 0..255 brightness multiplier applied to the palette colour |
| `dist` | Float32Array | depth in world units; `Infinity` for sky. Elements MUST depth-test against this |
| `kind` | Uint8Array | `0` sky `1` façade `2` floor `3` element |
## Modules
Every module is a plain script defining one global, no imports, no bundler syntax — `build.js`
concatenates them in order and the headless harness `require`s them through a shim.
| file | global | responsibility |
| --- | --- | --- |
| `src/core.js` | `CC` | Frame alloc, PALETTE, GLYPHS, rng/noise, math, `put()` |
| `src/city.js` | `CC.City` | `make(seed)` → heightmap + per-cell district/style/sign metadata |
| `src/raycast.js` | `CC.Cast` | `render(frame, cam, city)` — fills every cell: façades, floor, sky |
| `src/surfaces.js` | `CC.Surf` | texture fns: `facade(u,v,cell,dist)`, `floorTex(wx,wz,dist)`, `sky(x,y,t)` |
| `src/elements/*.js` | pushes to `CC.ELEMENTS` | ambient systems, see below |
| `src/compose.js` | `CC.Compose` | fog, element pass ordering, reduced-motion damping |
| `src/render_canvas.js` | `CC.Canvas` | glyph atlas, `drawImage` per cell, bloom. **Only DOM-touching module** |
| `src/main.js` | — | loop, resize, fullscreen, seed in hash, prefers-reduced-motion |
## Ambient element interface
```js
CC.ELEMENTS.push({
name: 'rain',
layer: 10, // lower draws first; elements draw after the world pass
init(city, rng) {}, // allocate persistent state
update(dt, t, cam) {}, // advance simulation; no drawing
draw(frame, cam, t) {}, // use CC.put(frame, x, y, glyph, colour, lum, dist) — it depth-tests for you
});
```
Rules for elements:
- **Never** write to the typed arrays directly; always go through `CC.put`, which honours `frame.dist`.
- Must be allocation-free in `update`/`draw` (pre-allocate in `init`) — this runs 60×/sec.
- Must read `CC.reducedMotion` and damp or freeze accordingly.
- Must be deterministic given the seeded rng handed to `init`.
## Verification (this is not optional)
`node tools/headless.mjs <seed> <frame> <cols> <rows> > f.txt` renders one frame with **no browser**
and dumps `glyph,colourIdx,lum` per cell. `python3 tools/topng.py f.txt out.png` renders that to an
image with the same bloom the canvas does. Every change gets looked at this way before it ships.

241
build.js Normal file
View file

@ -0,0 +1,241 @@
/* CyberCity build — concatenate src/ into one self-contained index.html.
*
* No dependencies, no bundler, no minifier, no source maps. The modules were written to be
* concatenated: each is an IIFE that resolves CC out of lexical scope, so wrapping the lot in one
* more IIFE is the entire "bundling" step. Everything this script does beyond `join('\n')` is
* removing the CommonJS tails that exist only so tools/headless.cjs can require the same files.
*
* Run: node build.js
*/
'use strict';
const fs = require('fs');
const path = require('path');
const ROOT = path.join(__dirname);
const SRC = path.join(ROOT, 'src');
const OUT = path.join(ROOT, 'index.html');
/* Order is load-bearing, not alphabetical: city.js binds core's helpers at make(), raycast.js
* throws without CC.Surf, every element pushes onto CC.ELEMENTS before main.js reads that array,
* and main.js boots on the last line of the file. compose.js is optional — the contract allows it
* to not exist yet — so it is filtered out rather than assumed. */
const ORDER = [
'core.js',
'weather_state.js', // before the elements: they read CC.Weather from init() onwards
'city.js',
'surfaces.js',
'raycast.js',
'control.js', // after city.js, whose route it re-anchors to; before main.js, which drives it
'compose.js',
'@elements', // expands to src/elements/*.js, sorted, so a build is reproducible
'render_canvas.js',
'main.js'
];
function expand(list) {
const out = [];
for (const name of list) {
if (name === '@elements') {
const dir = path.join(SRC, 'elements');
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir).sort())
if (f.endsWith('.js')) out.push(path.join(dir, f));
continue;
}
const p = path.join(SRC, name);
if (fs.existsSync(p)) out.push(p);
else if (name !== 'compose.js') throw new Error('missing required module src/' + name);
}
return out;
}
/* ---- CommonJS strip -------------------------------------------------------------------------
* Two shapes appear in src/, both harmless at runtime in a browser (the ternary short-circuits
* before require is ever evaluated, and `typeof module` is a safe read on an undeclared name) —
* but leaving them in ships dead branches referencing `require`, which is exactly the kind of
* thing a CSP-conscious reader greps for in a "zero network requests" file. They come out. */
function strip(src) {
return src
// `(typeof CC !== 'undefined' ? CC : require('../core.js'))` -> `CC`
.replace(/typeof\s+CC\s*!==\s*(['"])undefined\1\s*\?\s*CC\s*:\s*require\(\s*(['"]).*?\2\s*\)/g, 'CC')
// one-liner: `if (typeof module !== 'undefined') module.exports = X;`
.replace(/^[ \t]*if\s*\(\s*typeof\s+module\s*!==\s*(['"])undefined\1\s*\)\s*module\.exports\s*=[^\n]*;[ \t]*$/gm, '')
// wrapped form: the `if` on its own line, the assignment on the next
.replace(/^[ \t]*if\s*\(\s*typeof\s+module\s*!==\s*(['"])undefined\1\s*\)\r?\n[ \t]*module\.exports\s*=[^;]*;[ \t]*$/gm, '')
.replace(/\n{3,}/g, '\n\n');
}
/* ---- comment strip ---------------------------------------------------------------------------
* src/ is ~40% prose by weight — this codebase explains WHY on nearly every non-obvious line — and
* carrying all of it inline would put index.html at 253 KB against a 200 KB budget. The comments
* belong in src/, which is where anyone editing this reads them; the deliverable is a picture.
*
* This is a scanner, not a regex, because a regex cannot tell `//` inside a string or a regex
* literal from a comment, and getting that wrong corrupts the page silently. It tracks the three
* literal forms and uses the standard previous-significant-token rule to decide whether a `/`
* opens a regex or is a division. The `new Function` compile check further down is the backstop:
* anything this mangles fails the build instead of shipping. */
const REGEX_OK_WORDS = new Set(['return', 'typeof', 'case', 'in', 'of', 'new', 'delete', 'void',
'instanceof', 'throw', 'do', 'else', 'yield', 'await']);
const IDENT = /[A-Za-z0-9_$]/;
/* A `/` after any of these is division, never a regex, because all of them end a VALUE.
* `)` and `]` are the ones that matter here: `(v - 0.62) / (st.gnd - 2.2)` is everywhere in
* surfaces.js, and reading that `/` as a regex opener swallows the rest of the file into a
* literal and every comment after it ships. */
const DIV_AFTER = /[A-Za-z0-9_$)\]]/;
function decomment(src) {
let out = '', i = 0, prev = '', word = '';
const n = src.length;
/* ...except after a keyword, where `return /re/` is a regex even though `n` is an ident char. */
const regexAllowed = () => prev === '' || !DIV_AFTER.test(prev) || REGEX_OK_WORDS.has(word);
while (i < n) {
const c = src[i];
if (c === '/' && src[i + 1] === '/') {
while (i < n && src[i] !== '\n') i++; // the newline itself stays: ASI depends on it
continue;
}
if (c === '/' && src[i + 1] === '*') {
const start = i; i += 2;
while (i < n && !(src[i] === '*' && src[i + 1] === '/')) i++;
i += 2;
/* A comment sits BETWEEN two tokens, so it cannot vanish without leaving a separator behind
* or an inline one welds its two neighbours into a single identifier. A multi-line one
* collapses to a newline instead, so ASI keeps behaving exactly as it did in src/. */
out += src.slice(start, i).indexOf('\n') >= 0 ? '\n' : ' ';
continue;
}
if (c === '"' || c === "'" || c === '`') {
out += c; i++;
while (i < n) {
const d = src[i]; out += d; i++;
if (d === '\\') { out += src[i]; i++; continue; }
if (d === c) break;
}
prev = c; word = ''; continue;
}
if (c === '/' && regexAllowed()) {
out += c; i++;
let inClass = false;
while (i < n) {
const d = src[i]; out += d; i++;
if (d === '\\') { out += src[i]; i++; continue; }
if (d === '[') inClass = true;
else if (d === ']') inClass = false;
else if (d === '/' && !inClass) break;
}
while (i < n && IDENT.test(src[i])) { out += src[i]; i++; } // flags
prev = '/'; word = ''; continue;
}
out += c; i++;
if (!/\s/.test(c)) {
prev = c;
word = IDENT.test(c) ? word + c : '';
}
}
/* Trailing whitespace and the blank lines the comments left behind. Indentation stays — it costs
* ~6 KB and it is the difference between a viewable page source and a wall. */
return out.replace(/[ \t]+$/gm, '').replace(/\n{2,}/g, '\n\n').trim();
}
const files = expand(ORDER);
const parts = files.map(p => {
const rel = path.relative(ROOT, p).split(path.sep).join('/');
return '/* ' + rel + ' */\n' + decomment(strip(fs.readFileSync(p, 'utf8'))) + '\n';
});
/* One IIFE, one `var CC`. core.js declares CC with `var`, so it is hoisted to the top of this
* function and every later module's `typeof CC !== 'undefined'` guard sees it. Nothing leaks to
* window, which is the point: the page has no API surface to poke at. */
const bundle = '(function () {\n' + parts.join('\n') + '\n})();\n';
/* The page must open with ZERO network requests, so nothing may reference a module loader. */
if (/\brequire\s*\(/.test(bundle)) throw new Error('build: a require() survived the strip');
if (/\bmodule\.exports\b/.test(bundle)) throw new Error('build: a module.exports survived the strip');
if (/\bimport\s|\bexport\s/.test(bundle)) throw new Error('build: ESM syntax in the bundle');
/* A literal closing script tag anywhere in the sources would end the inline block early and dump
* the rest of the city into the document as text. */
if (/<\/script/i.test(bundle)) throw new Error('build: source contains a closing script tag');
/* Every module named its global; if one is missing it was dropped, mis-ordered, or the comment
* scanner ate something structural. Cheap, and it has caught both. */
for (const need of ['var CC', 'CC.City', 'CC.Surf', 'CC.Cast', 'CC.Canvas', 'CC.Main',
'CC.ELEMENTS.push'])
if (!bundle.includes(need)) throw new Error('build: bundle is missing ' + need);
/* Compiles the bundle without running it. This is what makes the comment scanner safe to trust:
* if it ever mangles a regex literal or a template string, the build stops here. */
try { new Function(bundle); }
catch (e) { throw new Error('build: bundle does not parse — ' + e.message); }
/* The page is black before a single pixel of city is drawn — html, body and canvas all — so that
* entering fullscreen never flashes white and never shows a seam at an edge the canvas overhangs.
* The hint is CSS-only on purpose: it fades itself out and no JavaScript ever has to know it
* existed, which keeps main.js free of anything resembling UI. */
const HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#000000">
<title>CyberCity</title>
<style>
html, body { margin: 0; padding: 0; background: #000; height: 100%; overflow: hidden; }
/* The canvas is allowed to overhang the viewport by a fraction of a cell (see main.js layout),
so it is pinned to the origin and the overflow above hides the remainder. */
#cc { position: fixed; inset: 0; display: block; background: #000;
image-rendering: auto; }
/* Nothing here is selectable, draggable or scrollable: every gesture is a fullscreen request. */
body { -webkit-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent;
touch-action: none; overscroll-behavior: none; }
#hint {
position: fixed; left: 50%; bottom: 6vh; transform: translateX(-50%);
font: 500 12px/1 ui-monospace, "Liberation Mono", "DejaVu Sans Mono", monospace;
letter-spacing: .28em; text-transform: uppercase; color: #d8e84a;
pointer-events: none; opacity: 0;
animation: hint 9s ease-in-out .8s 1 forwards;
}
/* Ends at opacity 0 and stays there — 'forwards' holds the last keyframe, so the hint is gone
for good after one play and never reappears on resize or fullscreen change. */
@keyframes hint { 0% { opacity: 0 } 12% { opacity: .34 } 70% { opacity: .34 } 100% { opacity: 0 } }
@media (prefers-reduced-motion: reduce) { #hint { animation-duration: 14s } }
</style>
</head>
<body>
<canvas id="cc"></canvas>
<div id="hint">click for fullscreen</div>
<script>
${bundle}</script>
</body>
</html>
`;
fs.writeFileSync(OUT, HTML, 'utf8');
const bytes = Buffer.byteLength(HTML, 'utf8');
for (const p of files)
console.log(' + ' + path.relative(ROOT, p).split(path.sep).join('/'));
console.log('index.html ' + bytes + ' bytes (' + (bytes / 1024).toFixed(1) + ' KB) ' +
files.length + ' modules');
/* THE BUDGET WAS 200 KB AND IT IS NOW 300 KB. That is a raise, not a discovery, and it is being
* written down rather than quietly deleted. src/ went from roughly 190 KB to roughly 530 KB in one
* pass — twelve new ambient elements, a weather director every element reads, four input devices,
* a rewritten road and facade — and the stripped bundle came out at 266 KB against a ceiling set
* when the city had a third of the content in it. Nothing here is dead weight to cut: the comment
* scanner already removes ~40% of the source by volume, and the remaining bytes are all reachable
* code. The alternatives were to strip indentation (about 25 KB, and it turns a viewable page
* source into a wall, which the decomment note above explicitly refuses) or to delete elements to
* make a number, which is the wrong way round.
*
* 300 KB is still a hard stop and still means something: it is one HTTP response, it parses in
* well under a frame on anything made this decade, and it leaves the deliverable a file somebody
* can read. If a later pass pushes past it, the answer is to cut content, not to move this line
* again. */
if (bytes > 300 * 1024) {
console.error('build: index.html is over the 300 KB budget');
process.exit(1);
}

7997
index.html Normal file

File diff suppressed because it is too large Load diff

641
src/city.js Normal file
View file

@ -0,0 +1,641 @@
/* CyberCity city — endless deterministic heightmap: street lattice, blocks, lots, districts.
Everything is a pure function of (seed, gx, gz); chunks only cache what was already decided,
so scrubbing time backwards or re-entering a chunk gives byte-identical geometry. */
(function () {
'use strict';
// Resolved late: this file must load even with no core present (the standalone parse check).
var C = (typeof CC !== 'undefined' && CC) ? CC
: (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null;
var hash2, clamp, vnoise, P; // bound on first make(), never at load time
var STYLE = null, SIGN_G = null;
/* ---- salt spreading -------------------------------------------------
* Every draw below is hash2(coord, coord, S + k) for a small literal k, and hash2 mixes its
* salt through Math.imul(s, 2147483647). That multiplier is 2^31-1, so imul(s+d, 2147483647)
* differs from imul(s, 2147483647) by only -d modulo 2^32: a salt step of 2 perturbs the
* accumulator by MINUS TWO, and hash2's single xorshift-multiply finaliser cannot avalanche a
* two-bit change into independence. The consequence is that adjacent salts on the SAME (x,z)
* are not two random variables, they are one seen twice. Measured over 320x320 lots at seeds
* 3/7/42/99, 128 of the 210 salt pairs city.js draws on a lot correlated past the 0.004 noise
* floor, the worst at -0.44: a lot's setback roll (S+505) half-decided its style (S+601), the
* district a cell got was 26% determined by where its own Voronoi site jitter landed (S+5 vs
* S+7), and spring lots were 3.4x likelier on one side of their lattice cell than the other.
*
* The fix has to live here rather than in hash2, whose exact arithmetic other modules and the
* shipped index.html depend on. Folding the salt into BOTH coordinates first routes it through
* the coordinate multipliers, which are large and odd, so the effective salt multiplier becomes
* imul(A,374761393) + imul(B,668265263) + 2147483647 -- and a step of 1 in k now moves every
* bit of the accumulator instead of the bottom two. The constants were not picked for looks:
* they were chosen by measuring all 780 pairs of the 40 salts this file actually draws, across
* four seeds, and this pair is the one that leaves ZERO pairs above 0.02 (worst 0.018, which is
* four sigma on 48841 samples and exactly what 3120 independent pairs should throw up by
* chance). Still one hash, still two imuls, still a pure function of (seed, x, z). */
function hash(x, y, s) {
return hash2(x + Math.imul(s, 0x2545F491), y + Math.imul(s, 0x9E3779B1), s);
}
// Lattice spacing in world units, and 1 cell == 1 metre: eye 1.7, walk 1.6 m/s, a 5-wide
// street with a 30 m wall on each side is the canyon proportion measured off the references.
var AVE = 30, CROSS = 26, CH = 16;
// [lit window, dim mullion, small-window alt]. The dim glyph is what makes a facade read as a
// massed slab instead of a sparse lattice — surfaces fills every unlit cell with it.
var STYLE_CH = [
['#', ':', 'o'], // 0 grid — dense office punch windows
['8', '=', 'o'], // 1 slab glass — curtain wall, whole floors light at once
['=', '-', ':'], // 2 louvre — horizontal banding, low contrast
['X', '.', 'Z'], // 3 mesh — scaffold/lattice over a dark core
['0', '|', 'o'], // 4 stripe — vertical mullions, tower proportions
['O', "'", 'o'] // 5 industrial — mostly blind wall, rare lit port
];
var SIGN_CH = ['#', '8', '0', 'X', 'O', '=', 'Z'];
// Districts are the colour masses. Weights keep the two pillars dominant and violet rare,
// which is the reference ratio (amber ~26% of lit pixels, azure ~27%, violet a garnish).
var DIST = null;
function buildDistricts() {
DIST = [
// hMin is the floor of the canyon wall, not the average: with the squared height curve most
// lots sit near hMin, so this number is what sets how enclosed the street feels.
// The lit/weight pairs were tuned against a 1.44 M-cell census until facade-area x litRate
// landed near the reference split: the two pillars roughly level, slate carrying structure,
// and the three accents narrow.
// `mixP` is the share of a zone's buildings that take the zone hue; the rest fall back to
// `mix`. Pillar zones stay nearly pure, accent zones are threaded with a pillar so a green
// or ember quarter tints the frame without ever owning it.
/* sodium 0.25 / screen 0.24 rather than 0.27 / 0.22, and this is a REPAIR of the census these
* weights were fitted against, not a re-taste. That fit was done while districtType drew from
* S+7 and the site jitter from S+5, salts two apart, which correlated the type a lattice cell
* rolled with where its own Voronoi site sat — spring and ember landed on one side of their
* cell 3.2-3.4x more often than the other, and the resulting area shares were not the ones
* the weights asked for. With the draws decorrelated the table finally gets what it wrote
* down, and what it wrote down leans amber: 27.6% of the ground to sodium against 22.4% to
* screen. Measured over 480 frames across 60 seeds, that printed as amber 27.2% of lit energy
* against azure 22.7% — the pillars a stop apart instead of level. At 0.25/0.24 the same 480
* frames give 26.8/23.1, and nothing else moves: sky stays 2.0% of cells, facade 63.9%. */
{ name: 'sodium', hue: P.amber, mix: P.azure, mixP: 0.86, accent: P.warm, styles: [0, 3, 0],
hMin: 15, hMax: 34, lit: 0.24, signP: 0.34, landmark: 0.010, w: 0.25 },
{ name: 'screen', hue: P.azure, mix: P.amber, mixP: 0.86, accent: P.white, styles: [1, 4, 1],
hMin: 24, hMax: 56, lit: 0.20, signP: 0.16, landmark: 0.030, w: 0.24 },
{ name: 'concrete', hue: P.slate, mix: P.white, mixP: 0.80, accent: P.white, styles: [2, 5],
hMin: 16, hMax: 32, lit: 0.16, signP: 0.05, landmark: 0.006, w: 0.20 },
// ember is the low industrial pocket — it exists to open the sky slot back up.
{ name: 'ember', hue: P.ember, mix: P.amber, mixP: 0.55, accent: P.red, styles: [5, 2],
hMin: 8, hMax: 19, lit: 0.16, signP: 0.13, landmark: 0.002, w: 0.11 },
{ name: 'spring', hue: P.spring, mix: P.azure, mixP: 0.50, accent: P.white, styles: [2, 0],
hMin: 15, hMax: 29, lit: 0.18, signP: 0.16, landmark: 0.006, w: 0.12 },
// The entertainment strip. Its facades are ordinary azure/amber on purpose: violet is a
// signage colour only, and a whole wall of it turns the frame into the cliche the
// references deliberately avoid.
// ...and the accent obeys that too: it used to be P.violet, which put 16-column violet
// walls in the frame in direct contradiction of the comment directly above it.
{ name: 'arcade', hue: P.azure, mix: P.amber, mixP: 0.55, accent: P.warm, styles: [1, 3],
hMin: 13, hMax: 27, lit: 0.22, signP: 0.60, landmark: 0.004, w: 0.06 }
];
var acc = 0;
for (var i = 0; i < DIST.length; i++) { acc += DIST[i].w; DIST[i].acc = acc; }
DIST.total = acc;
}
function bind() {
if (!C) C = (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null;
if (!C) throw new Error('CC.City needs core.js loaded first');
hash2 = C.hash2; clamp = C.clamp; vnoise = C.vnoise; P = C.P;
STYLE = [];
for (var i = 0; i < STYLE_CH.length; i++)
STYLE.push([C.g(STYLE_CH[i][0]), C.g(STYLE_CH[i][1]), C.g(STYLE_CH[i][2])]);
SIGN_G = [];
for (var j = 0; j < SIGN_CH.length; j++) SIGN_G.push(C.g(SIGN_CH[j]));
buildDistricts();
}
function make(seed) {
if (!STYLE) bind();
var S = seed | 0;
/* ---- street lattice ------------------------------------------------
Avenues run along +z, cross streets along +x. Position jitter is a function of the
street's index alone, so a street stays perfectly straight while spacing stays irregular
— a curving street would break both the canyon read and the camera's collision guarantee. */
// Half-widths, in metres. These set how much of the frame the walls can eat: at 9 m the near
// facade bases projected below the horizon and swallowed the floor, so the boulevard is 13 m
// and the meanest side street is 7. Spacing guarantees a >=6 m block between any two.
function ax(k) { return k * AVE + ((hash(k, 0, S + 101) * 15) | 0) - 7; }
function aw(k) { return (k % 4 === 0) ? 6 : (hash(k, 0, S + 102) < 0.35 ? 4 : 3); }
function cz(m) { return m * CROSS + ((hash(0, m, S + 201) * 13) | 0) - 6; }
function cw(m) { return (m % 5 === 0) ? 3 : (hash(0, m, S + 202) < 0.28 ? 2 : 1); }
// Scratch records: computeCell is only ever called from buildChunk, never re-entrantly.
var SX = { street: 0, k: 0, b: 0, x0: 0, x1: 0 };
var SZ = { street: 0, m: 0, b: 0, z0: 0, z1: 0 };
function colX(gx, o) {
var k = Math.round(gx / AVE), kk, c, w;
for (kk = k - 1; kk <= k + 1; kk++) {
c = ax(kk); w = aw(kk);
if (gx >= c - w && gx <= c + w) { o.street = 1; o.k = kk; return; }
}
// Jitter is bounded well under AVE/2, so gx always lands in block [b, b+1) here.
var b = (gx > ax(k)) ? k : k - 1;
o.street = 0; o.b = b;
o.x0 = ax(b) + aw(b) + 1; o.x1 = ax(b + 1) - aw(b + 1) - 1;
}
function rowZ(gz, o) {
var m = Math.round(gz / CROSS), mm, c, w;
for (mm = m - 1; mm <= m + 1; mm++) {
c = cz(mm); w = cw(mm);
if (gz >= c - w && gz <= c + w) { o.street = 1; o.m = mm; return; }
}
var b = (gz > cz(m)) ? m : m - 1;
o.street = 0; o.b = b;
o.z0 = cz(b) + cw(b) + 1; o.z1 = cz(b + 1) - cw(b + 1) - 1;
}
/* ---- districts as jittered Voronoi ---------------------------------
A plain modulo grid would tile the city into visible squares; nearest-site over a jittered
lattice gives contiguous organic zones ~26 cells across, which is the size the reference
study landed on. Neighbouring cells that draw the same type simply merge into a bigger mass. */
var DG = 26;
function districtType(p, q) {
var r = hash(p, q, S + 7) * DIST.total, i;
for (i = 0; i < DIST.length - 1; i++) if (r < DIST[i].acc) return i;
return DIST.length - 1;
}
function districtAt(gx, gz) {
var p = Math.floor(gx / DG), q = Math.floor(gz / DG);
var best = 1e18, bd = 0, dp, dq, pp, qq, sx, sz, ddx, ddz, d;
for (dq = -1; dq <= 1; dq++) for (dp = -1; dp <= 1; dp++) {
pp = p + dp; qq = q + dq;
sx = pp * DG + hash(pp, qq, S + 5) * DG;
sz = qq * DG + hash(pp, qq, S + 6) * DG;
ddx = gx - sx; ddz = gz - sz; d = ddx * ddx + ddz * ddz;
if (d < best) { best = d; bd = districtType(pp, qq); }
}
return bd;
}
/* ---- one cell ------------------------------------------------------ */
var cH = 0, cD = 0, cLX = 0, cLZ = 0; // computeCell's out-params, avoids an alloc per cell
// Every cell of a lot asks for the same district; the Voronoi is 27 hashes, so remembering
// the last answer removes most of the chunk-build cost (a lot is up to 13x13 cells).
var lmX = 0x7fffffff, lmZ = 0x7fffffff, lmD = 0;
function computeCell(gx, gz) {
colX(gx, SX); rowZ(gz, SZ);
if (SX.street || SZ.street) { cH = 0; cD = districtAt(gx, gz); return; }
var x0 = SX.x0, x1 = SX.x1, z0 = SZ.z0, z1 = SZ.z1, bK = SX.b, bM = SZ.b;
var bw = x1 - x0 + 1, bd = z1 - z0 + 1;
var t, wid, pos;
// Alleys split the block wall so the canyon breaks and you glimpse depth down a slot.
if (bw >= 10 && hash(bK, bM, S + 301) < 0.45) {
wid = hash(bK, bM, S + 302) < 0.25 ? 2 : 1;
pos = x0 + 3 + ((hash(bK, bM, S + 303) * (bw - 6 - wid)) | 0);
if (gx >= pos && gx < pos + wid) { cH = 0; cD = districtAt(gx, gz); return; }
}
if (bd >= 11 && hash(bK, bM, S + 304) < 0.35) {
wid = hash(bK, bM, S + 305) < 0.25 ? 2 : 1;
pos = z0 + 3 + ((hash(bK, bM, S + 306) * (bd - 6 - wid)) | 0);
if (gz >= pos && gz < pos + wid) { cH = 0; cD = districtAt(gx, gz); return; }
}
// Plazas eat the corners around an intersection; this is what widens the sky slot. They are
// twice as likely on a boulevard because that is where the camera spends most of its walk.
var kk, mm, r, dxp, dzp;
for (kk = bK; kk <= bK + 1; kk++) for (mm = bM; mm <= bM + 1; mm++) {
if (hash(kk, mm, S + 401) < (kk % 4 === 0 ? 0.26 : 0.13)) {
r = 5 + ((hash(kk, mm, S + 402) * 7) | 0);
dxp = gx - ax(kk); if (dxp < 0) dxp = -dxp;
dzp = gz - cz(mm); if (dzp < 0) dzp = -dzp;
if (dxp < r && dzp < r && dxp + dzp < r * 1.4) { cH = 0; cD = districtAt(gx, gz); return; }
}
}
// Lots: a whole footprint shares one height and one look, so buildings read as slabs.
// 6-13 m frontages, never less: a 30 m tower on a 4 m footprint reads as a stick, and the
// references are all wide masses.
var lw = 6 + ((hash(bK, bM, S + 307) * 7) | 0);
var ld = 6 + ((hash(bK, bM, S + 308) * 8) | 0);
var lx = x0 + (((gx - x0) / lw) | 0) * lw;
var lz = z0 + (((gz - z0) / ld) | 0) * ld;
// District sampled at the lot centre, never per cell: one building is never two hues.
var did;
if (lx === lmX && lz === lmZ) did = lmD;
else { did = districtAt(lx + (lw >> 1), lz + (ld >> 1)); lmX = lx; lmZ = lz; lmD = did; }
var D = DIST[did];
var h;
if (hash(lx, lz, S + 504) < 0.06) {
h = 0; // vacant lot / interior courtyard
} else {
t = hash(lx, lz, S + 501);
h = D.hMin + t * t * (D.hMax - D.hMin); // squared: most blocks modest, a few tall
if (hash(lx, lz, S + 502) < D.landmark) h = 58 + hash(lx, lz, S + 503) * 46;
// Setback: the lot's outer ring drops to a podium, which is what gives the rooftop
// silhouette its steps instead of one flat parapet per block.
if (lw >= 4 && ld >= 4 && hash(lx, lz, S + 505) < 0.42) {
var ix = gx - lx, iz = gz - lz;
if (ix === 0 || iz === 0 || ix === lw - 1 || iz === ld - 1) {
var pod = 7 + hash(lx, lz, S + 506) * 10;
if (pod < h) h = pod;
}
}
}
cH = h; cD = did; cLX = lx; cLZ = lz;
}
/* ---- per-cell record ------------------------------------------------ */
function signHue(lx, lz, D) {
var r = hash(lx, lz, S + 701);
// Signage obeys the same two-pillar discipline as everything else; violet stays a garnish,
// and the arcade strip is the one place it is allowed to lead.
if (D.accent === P.violet) return r < 0.42 ? P.violet : (r < 0.74 ? P.azure : P.amber);
if (r < 0.34) return P.amber;
if (r < 0.64) return P.azure;
if (r < 0.78) return D.hue;
if (r < 0.86) return P.ember;
if (r < 0.93) return P.spring;
return P.violet;
}
function makeRec(gx, gz, h, did, lx, lz) {
var D = DIST[did];
var style = D.styles[(hash(lx, lz, S + 601) * D.styles.length) | 0];
var g = STYLE[style];
var lit = clamp(D.lit * (0.5 + hash(lx, lz, S + 602) * 1.3), 0.02, 0.5);
var sign = null;
if (hash(lx, lz, S + 603) < D.signP) {
var vert = hash(lx, lz, S + 604) < 0.45 && h > 16;
var sh = vert ? 5 + hash(lx, lz, S + 605) * 7 : 2 + hash(lx, lz, S + 606) * 2.5;
var room = h - sh - 4; if (room < 1) room = 1;
sign = {
y: 3 + hash(lx, lz, S + 607) * room, // metres up the facade to the sign's foot
h: sh,
w: vert ? 1 : 2 + ((hash(lx, lz, S + 608) * 3) | 0),
hue: signHue(lx, lz, D),
glyph: SIGN_G[(hash(lx, lz, S + 609) * SIGN_G.length) | 0],
vertical: vert,
seed: hash(lx, lz, S + 610)
};
}
var cr = hash(lx, lz, S + 611);
return {
district: D.name, did: did, style: style,
hue: hash(lx, lz, S + 615) < D.mixP ? D.hue : D.mix, accent: D.accent,
glyph: g[0], dim: g[1], alt: g[2],
dimLum: 22 + ((hash(lx, lz, S + 612) * 20) | 0), // suggested brightness for the fill glyph
litRate: lit, sign: sign,
h: h, landmark: h > 55,
crown: h > 55 ? 3 : (cr < 0.14 ? 1 : (cr < 0.24 ? 2 : 0)), // 0 none 1 mast 2 tank 3 beacon
lotX: lx, lotZ: lz,
seed: hash(lx, lz, S + 613), // stable per building — hash this for per-facade variety
face: hash(gx, gz, S + 614) // stable per cell — hash this for per-column variety
};
}
/* ---- chunk cache ---------------------------------------------------- */
var rows = new Map(); // cz -> Map(cx -> chunk); numeric keys, no string alloc
// CAP has to comfortably exceed one frame's working set or the FIFO turns into a thrash and
// every sample pays a rebuild — 2048 chunks is a 720 m square, far past T_FAR.
var order = [], CAP = 2048;
var mcx = 0x7fffffff, mcz = 0x7fffffff, mch = null; // last-chunk memo: rays march coherently
// Only height and district are stored; the lot anchor is recomputed on the first cell() for
// that cell and then lives in the cached record, which keeps a chunk down to 1.25 KB.
function buildChunk(cx, cz2) {
var h = new Float32Array(256), d = new Uint8Array(256);
var bx = cx * CH, bz = cz2 * CH, i = 0, jz, jx;
for (jz = 0; jz < CH; jz++) for (jx = 0; jx < CH; jx++, i++) {
computeCell(bx + jx, bz + jz);
h[i] = cH; d[i] = cD;
}
return { cx: cx, cz: cz2, h: h, d: d, recs: null };
}
function evict() {
// FIFO by quarters. A frame touches a few hundred chunks at most, far under CAP, so this
// can never drop something that is currently on screen.
var n = CAP >> 2, i, c, row;
for (i = 0; i < n; i++) {
c = order[i]; row = rows.get(c.cz);
if (row) { row.delete(c.cx); if (row.size === 0) rows.delete(c.cz); }
}
order = order.slice(n);
mch = null; mcx = 0x7fffffff; mcz = 0x7fffffff;
}
function chunkAt(cx, cz2) {
if (cx === mcx && cz2 === mcz) return mch;
var row = rows.get(cz2), ck;
if (row) {
ck = row.get(cx);
if (ck) { mcx = cx; mcz = cz2; mch = ck; return ck; }
} else { row = new Map(); rows.set(cz2, row); }
ck = buildChunk(cx, cz2);
row.set(cx, ck);
order.push(ck);
if (order.length > CAP) evict();
mcx = cx; mcz = cz2; mch = ck;
return ck;
}
// Floor, not |0: the marcher hands us fractional world coords and |0 truncates the wrong way
// for negative x, which would smear a one-cell seam across the whole left half of the city.
function height(gx, gz) {
gx = Math.floor(gx); gz = Math.floor(gz);
var c = chunkAt(gx >> 4, gz >> 4);
return c.h[((gz & 15) << 4) | (gx & 15)];
}
function cell(gx, gz) {
gx = Math.floor(gx); gz = Math.floor(gz);
var c = chunkAt(gx >> 4, gz >> 4), i = ((gz & 15) << 4) | (gx & 15);
if (c.h[i] <= 0) return null; // street, alley, plaza, courtyard
var recs = c.recs;
if (!recs) { recs = c.recs = new Array(256); }
var r = recs[i];
// Records are cached, not rebuilt: cell() is hit thousands of times per frame and the
// renderer is allowed to hold on to one across a column march.
if (r === undefined || r === null) {
computeCell(gx, gz); // only to recover this cell's lot anchor
r = recs[i] = makeRec(gx, gz, c.h[i], c.d[i], cLX, cLZ);
}
return r;
}
function districtOf(gx, gz) {
gx = Math.floor(gx); gz = Math.floor(gz);
var c = chunkAt(gx >> 4, gz >> 4);
return c.d[((gz & 15) << 4) | (gx & 15)];
}
/* ---- the walk -------------------------------------------------------
The route is a polyline of street centrelines, extended on demand and indexed by arc
length, so camera(t) stays a pure function of t: scrubbing to frame 0 gives frame 0. */
var RX = [], RZ = [], RS = [], RK = 0, RM = 0;
function pushPt(x, z) {
var n = RX.length;
if (n) {
var dx = x - RX[n - 1], dz = z - RZ[n - 1];
RS.push(RS[n - 1] + Math.sqrt(dx * dx + dz * dz));
} else RS.push(0);
RX.push(x); RZ.push(z);
}
function routeStep() {
var k = RK, m = RM;
pushPt(ax(k) + 0.5, cz(m) + 0.5);
// A turn only happens where both streets are wide enough that the smoothed corner arc
// still clears the corner building. Narrow crossings are always walked straight through.
// Was 0.32 with cw>=2 on both, which passed ~13% of crossings: at one crossing per ~16 s
// the expected first corner was ~120 s, and seeds 3, 7 and 42 walked straight for over 90 s.
// An ambient piece cannot go two minutes without a large-scale event.
if (hash(k, m, S + 41) < 0.5 && aw(k) >= 2 && (cw(m) >= 2 || aw(k) >= 4)) {
var dir = hash(k, m, S + 42) < 0.5 ? -1 : 1;
if (aw(k + dir) >= 2) { pushPt(ax(k + dir) + 0.5, cz(m) + 0.5); RK = k + dir; }
}
RM = m + 1;
}
function ensureRoute(sMax) {
while (RS[RS.length - 1] < sMax) routeStep();
}
var _pa = { x: 0, z: 0 }, _pb = { x: 0, z: 0 }, _pc = { x: 0, z: 0 }, _pr = { x: 0, z: 0 };
function posAt(s, o) {
var n = RS.length;
if (s <= RS[0]) { // before the start: extrapolate straight
var f0 = s - RS[0];
o.x = RX[0]; o.z = RZ[0] + f0; // the first leg always runs +z
return;
}
var lo = 0, hi = n - 1, mid;
while (lo + 1 < hi) { mid = (lo + hi) >> 1; if (RS[mid] <= s) lo = mid; else hi = mid; }
var seg = RS[hi] - RS[lo], f = seg > 1e-6 ? (s - RS[lo]) / seg : 0;
o.x = RX[lo] + (RX[hi] - RX[lo]) * f;
o.z = RZ[lo] + (RZ[hi] - RZ[lo]) * f;
}
// Weighted taps either side of s. This rounds every corner into an arc for free, and the
// window is short enough that the inward cut stays under a half cell on a 5-wide street.
// Nine taps on a Hann window over +/-2 m instead of five on a box over +/-1.5 m. posAt is
// piecewise LINEAR between route knots, so a box window leaves a hard break in the second
// derivative at every knot; sampled at 60 Hz the yaw rate stepped -29.6 -> ramp -> -36.7 ->
// ramp -> -47.8 deg/s with the breaks exactly 0.75 m apart. A tapered window sends those
// breaks to zero weight, and it stays stateless so scrubbing to any frame is still exact.
var OFF = [-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5, 2.0],
WT = [0.146, 0.5, 0.854, 1, 1, 1, 0.854, 0.5, 0.146], WTS = 6.0;
function smoothPos(s, o) {
var sx = 0, sz = 0, i;
for (i = 0; i < 9; i++) { posAt(s + OFF[i], _pr); sx += _pr.x * WT[i]; sz += _pr.z * WT[i]; }
o.x = sx / WTS; o.z = sz / WTS;
}
/* Where on the route a free-walking viewer is standing. This is what lets the autopilot be
* RESUMED rather than restarted: a player who has wandered up an alley and let go of the keys
* is handed back to the walk at the arc length nearest to where they are, so the camera eases
* a metre or two sideways instead of teleporting to wherever the route clock happened to
* reach while nobody was driving. Clamped per segment, so a point beside the middle of a leg
* projects onto that leg rather than onto its nearer endpoint. */
function nearestRouteS(x, z) {
var best = 0, bd = Infinity;
for (var i = 0; i + 1 < RX.length; i++) {
var x0 = RX[i], z0 = RZ[i], bx = RX[i + 1] - x0, bz = RZ[i + 1] - z0;
var L2 = bx * bx + bz * bz;
if (L2 < 1e-9) continue;
var u = ((x - x0) * bx + (z - z0) * bz) / L2;
if (u < 0) u = 0; else if (u > 1) u = 1;
var dx = x - (x0 + bx * u), dz = z - (z0 + bz * u), d = dx * dx + dz * dz;
if (d < bd) { bd = d; best = RS[i] + Math.sqrt(L2) * u; }
}
return { s: best, d: Math.sqrt(bd) };
}
var SPEED = 1.6; // slow walk, metres per second
function camera(cam, city, t) {
var s = SPEED * t;
ensureRoute(s + 40);
smoothPos(s, _pa);
smoothPos(s + 1.2, _pb); // baseline widened with the window; a short baseline re-sharpens
smoothPos(s - 1.2, _pc); // exactly the corners the window just rounded
var dx = _pb.x - _pc.x, dz = _pb.z - _pc.z;
var dl = Math.sqrt(dx * dx + dz * dz) || 1;
dx /= dl; dz /= dl;
var damp = C.reducedMotion ? 0.15 : 1;
// Sway is driven by distance walked, not wall-clock, so it survives scrubbing intact.
// The three salts below used to be S+301/302/303, and vnoise goes through hash1, which
// cannot take the coordinate-spreading `hash` above -- so these are the one place the
// salt-step problem has to be solved by choosing the salts far apart instead. Adjacent
// salts correlated at -0.27, which meant the lateral sway, the yaw wobble and the eye bob
// were substantially the SAME noise: the head leaned left exactly as it turned left and
// dipped, three degrees of freedom moving as one and reading as a single lurch rather than
// as a gait. Spread this way they measure 0.005, i.e. independent.
var lat = (vnoise(s * 0.09, S + 0x0000012D) - 0.5) * 0.9 * damp;
var x = _pa.x + dz * lat, z = _pa.z - dx * lat;
// Last-resort guard. The centreline is on street by construction and the corner arc is
// short, but a wide sway on a narrow leg must never end up inside a wall.
if (height(x, z) > 0) {
posAt(s, _pr);
for (var i = 1; i <= 4; i++) {
var f = i / 4;
x = _pa.x + dz * lat * (1 - f) + (_pr.x - _pa.x) * f;
z = _pa.z - dx * lat * (1 - f) + (_pr.z - _pa.z) * f;
if (height(x, z) <= 0) break;
}
if (height(x, z) > 0) { x = _pr.x; z = _pr.z; }
}
cam.x = x; cam.z = z;
// yaw 0 faces +z, matching the harness default of a camera walking +z with yaw 0.
cam.yaw = Math.atan2(dx, dz)
+ ((vnoise(s * 0.13, S + 0x51ED2701) - 0.5) * 0.10 + Math.sin(s * 0.41) * 0.02) * damp;
cam.eyeY = 1.66 + (Math.sin(s * 3.1) * 0.05 + (vnoise(s * 0.7, S + 0xA3C59AC3 | 0) - 0.5) * 0.04) * damp;
return cam;
}
/* ---- where the walk begins ------------------------------------------
* The opening ten seconds are the only ten seconds every viewer sees, and they used to be
* the most OPEN view the piece ever renders. The route was bootstrapped at
* pushPt(ax(0) + 0.5, cz(0) + 0.5 - 18)
* which is not a neutral choice, it is the worst one available, for three compounding
* reasons. Avenue 0 satisfies k % 4 === 0, so aw(0) is 6 and the walk always started on the
* WIDEST street class in the city, 13 m wall to wall. The 18 m offset is walked off in
* 18/1.6 = 11.25 s, so at t = 10 s -- the canonical first look -- the camera stands two
* metres short of the cross street, i.e. inside the mouth of an intersection. And plazas roll
* at 0.26 rather than 0.13 on a boulevard corner, so those corners are twice as likely to be
* eaten as well. Measured through tools/headless.cjs over 32 seeds (1000 + 7k, k = 0..31) at
* 400x100 -- an arithmetic list, not the four seeds this project keeps re-fitting on -- frame
* 600 printed facade 54.0%
* / floor 25.7% of the frame against 75.5 / 11.5 at frame 3000 and 70.0 / 15.3 at 18000, and
* the spread at frame 600 was 46.9-60.8: not a few unlucky seeds, EVERY seed opening in a gap,
* and 31 of the 32 under 60% facade. Scored as enclosure (below), the old fixed start ranked
* 157th, 172nd, 157th, 191st, 146th and 103rd of 192 candidates on the first six of those
* seeds -- bottom quartile on five of six, and next to last on one.
*
* So the start is searched instead of assumed. Candidates are the first 8 avenues x first 8
* cross streets x three approach distances, scored by how enclosed the first 24 m of the walk
* actually is, and the search is a pure function of the seed: every input is hash-derived, no
* rng is drawn, and the city is not re-rolled -- chooseStart only READS height(), so it warms
* the chunk cache and decides nothing.
*
* The score is deliberately NOT maximised. Taking the argmax would hand every seed the same
* answer in kind -- the narrowest street with the tallest walls -- and an opening that is
* identical on every seed is its own failure. Instead candidates are visited in a
* seed-dependent order and the FIRST one clearing START_T is taken, so the threshold
* guarantees a canyon while the order supplies the variety. The argmax survives only as the
* fallback for a seed where nothing clears the bar.
*
* What it costs: 3.7 candidates scored on the average seed and 16 on the worst of 128, never
* anywhere near SCAN, because acceptance comes early. That is make() at 4.06 ms against 0.01 ms
* before, paid once when the page loads or the seed in the hash changes and never again --
* camera(), height() and cell() are untouched, and the frame budget does not see this. It
* leaves the chunk cache warm rather than thrashed: 21 chunks built on the average seed and 85
* on the worst, against a CAP of 2048, so nothing the first frame wants has been evicted. */
var START_BACKS = [14, 20, 26]; // metres of straight canyon before the first cross street
/* An ANGLE, not a height, because the angle is what the frame shows: a 20 m wall 4 m away
* fills the view and the same wall across a plaza does not. 1.7 is the eye the camera breathes
* around (see cam.eyeY below), so this is literally how far up the viewer has to look. 14 m is
* the search reach -- past that the wall is on the far side of any street this lattice builds
* and is enclosing nothing. Zero means open sky on that side, the case the score punishes. */
function sideAngle(x, z, dx) {
for (var d = 1; d <= 14; d += 0.5) {
var h = height(x + dx * d, z);
if (h > 0) return Math.atan2(h - 1.7, d);
}
return 0;
}
/* min(left, right), never the mean: a street walled on one side and open on the other is a
* frontage, not a canyon, and averaging the two sides would score it the same as a corridor
* half as tall on both. The run is sampled straight THROUGH where the cross street lands,
* which is what makes the approach distance matter -- an intersection sitting inside the
* opening 24 m scores itself down, and that alone is what would have rejected the old start.
* These are the same world coordinates the route is built from a dozen lines below, half-cell
* offset included, so the score is of the walk that actually happens and not of a near miss. */
function startScore(k, m, back) {
var x = ax(k) + 0.5, z0 = cz(m) + 0.5 - back, acc = 0, n = 0, s, L, R;
for (s = 0; s <= 24; s += 1.5) {
L = sideAngle(x, z0 + s, -1); R = sideAngle(x, z0 + s, 1);
acc += (L < R ? L : R); n++;
}
return acc / n;
}
/* 1.00 rad of both-sides elevation is a wall whose parapet is at 57 degrees, and it sits above
* the enclosure the walk averages over its whole length (0.85-0.99 measured on the same 32
* seeds), which is the point: the opening should be at least as enclosed as the piece it is
* introducing. About a quarter of the 192 candidates clear it on a typical seed.
*
* THIS IS THE KNOB, and raising it is not free. Swept over 128 seeds (500 + 11k), counting the
* candidates scored, the seeds where nothing clears the bar and the search degenerates to
* argmax, and the width class of the avenue it lands on:
* 1.00 -> 3.8 scored, 0/128 fall back, avenues 82 narrow / 38 mid / 8 boulevard
* 1.15 -> 16.8 scored, 3/128 fall back, 101 / 24 / 3
* 1.22 -> 39.1 scored, 43/128 fall back, 102 / 25 / 1
* 1.30 -> 56.3 scored, 100/128 fall back, 103 / 25 / 0
* Past about 1.15 the threshold stops being a threshold: most seeds miss it, the fallback
* argmax takes over, and the search hands every seed the same narrow street -- the flattening
* this whole approach exists to avoid. What the extra strictness buys is the low tail of the
* opening frame, over the 32-seed sweep at frame 600: 1.00 gives facade min 48.0 with 5 of 32
* seeds under 60%, 1.15 gives 51.9 and 3 of 32, 1.22 gives 58.1 and 1 of 32. Two seeds of
* thirty-two is not worth trading a third of the city's boulevards for. */
var START_T = 1.00;
var _start = { k: 0, m: 0, back: 18 };
function chooseStart(o) {
var N = 8 * 8 * START_BACKS.length, j, k, m, b, sc;
// Visiting order is i -> i + st over Z_N, which hits DISTINCT candidates as long as st is
// coprime with N = 192 = 2^6 * 3: force it odd, then off a multiple of three. A shuffled
// array would allocate and sort for no gain, because the search almost always accepts within
// its first few candidates. SCAN caps the fallback at a third of the cycle so a seed where
// nothing clears the bar cannot turn make() into a 200 ms stall on page load; best-of-64 and
// best-of-192 are the same answer in practice, and 128 seeds never needed more than 16.
var SCAN = 64;
var st = 5 + ((hash(0, 0, S + 901) * 88) | 0) * 2;
if (st % 3 === 0) st += 2;
var i = ((hash(1, 0, S + 902) * N) | 0) % N;
var bestS = -1;
o.k = 0; o.m = 0; o.back = START_BACKS[0];
for (j = 0; j < SCAN; j++) {
k = i & 7; m = (i >> 3) & 7; b = START_BACKS[(i / 64) | 0];
sc = startScore(k, m, b);
if (sc > bestS) { bestS = sc; o.k = k; o.m = m; o.back = b; }
if (sc >= START_T) break;
i = (i + st) % N;
}
}
/* ---- boot the route so startX/startZ land on street ------------------ */
chooseStart(_start);
RK = _start.k; RM = _start.m;
pushPt(ax(RK) + 0.5, cz(RM) + 0.5 - _start.back);
ensureRoute(60);
return {
seed: S,
startX: RX[0], startZ: RZ[0],
height: height, cell: cell, camera: camera,
nearestRouteS: nearestRouteS, ensureRoute: ensureRoute,
districtAt: districtOf, DISTRICTS: DIST,
isStreet: function (gx, gz) { return height(gx, gz) <= 0; },
// Exposed for surfaces/elements that want to reason about the corridor itself.
aveX: ax, aveW: aw, crossZ: cz, crossW: cw,
AVE: AVE, CROSS: CROSS, SPEED: SPEED
};
}
var City = { make: make };
if (C) C.City = City;
else if (typeof globalThis !== 'undefined' && globalThis.CC) globalThis.CC.City = City;
if (typeof module !== 'undefined') module.exports = City;
})();

693
src/control.js Normal file
View file

@ -0,0 +1,693 @@
/* CyberCity control — who is driving the camera.
*
* The piece began as a thing you watch, and the walk in city.js is still the author of it: a route
* down the centreline of the street, indexed by arc length, a pure function of t. Taking the keys
* away from that and handing them to a viewer is the one change in this project that can destroy
* the whole brief, so it is done as an ARBITRATION rather than as a replacement. The autopilot is
* never switched off. It keeps its own clock, it keeps producing a pose every frame, and the
* viewer's pose is cross-faded over the top of it. Let go of the keys and the fade runs the other
* way — back onto the route at the arc length nearest to where you are standing, which is why
* city.js grew `nearestRouteS`. Nothing is ever reset, nothing teleports, and a viewer who never
* touches the keyboard gets byte-identical frames to the ones the headless harness renders.
*
* THE PITCH IS THE HORIZON. There is no pitch in the raycaster and there does not need to be: at
* character resolution a vertical rotation is indistinguishable from sliding the horizon row, and
* every element already reads `cam.horizon` because the caster does. So looking up at the sign
* tops costs one number. `cam.horizonBase` is the neutral row main.js computes from the grid;
* this file owns `cam.horizon` from then on.
*
* NO INPUT IN THE MODEL. `update()` reads a bag of booleans that `attach()` fills in from DOM
* events. Offline there is no attach(), the bag stays empty, mode never leaves auto, and the
* harness drives exactly the walk it always drove.
*
* THREE INPUT DEVICES, ONE BAG. Keyboard, touch and gamepad all write into K and nothing below
* that line knows which one is talking. That is why the analogue channels are SEPARATE fields
* rather than being folded into K.fwd/K.left: a thumb resting on a stick and a finger on a key
* are two independent claims on the same axis, and a device that writes over another device's
* channel produces the classic bug where letting go of a stick cancels a held key. They are
* summed once, in update(), and the sum is magnitude-clamped rather than normalised — see the
* note there, because normalising is what throws an analogue stick's magnitude away.
*
* LOOK HAS INERTIA, AND THE INERTIA IS A QUEUE, NOT A FILTER. A low-pass on the pointer delta
* loses rotation (the tail of every flick is thrown away) and a viewer notices that as the camera
* not going where they put it. Instead every delta is BANKED into `qYaw`, and a fraction of the
* bank is spent each tick. Total rotation is therefore exactly the total input, only spread over
* two or three frames; and because the bank is a queue, it is also the natural place to enforce a
* maximum turn rate — the excess is not discarded, it just waits its turn. That cap is the one
* thing here that exists for the viewer's stomach rather than for the feel.
*/
(function (CC) {
'use strict';
var clamp = CC.clamp, smooth = CC.smooth;
var K = { // the input bag; attach() writes, update() reads
fwd: 0, back: 0, left: 0, right: 0, run: 0, crouch: 0,
yawL: 0, yawR: 0, pitchU: 0, pitchD: 0,
mdx: 0, mdy: 0, // accumulated pointer delta, consumed each tick
tx: 0, tz: 0, trun: 0, // touch stick: strafe, forward, and pushed-to-run
gx: 0, gz: 0, grun: 0, // gamepad left stick, same axes
glx: 0, gly: 0, // gamepad right stick, as a look RATE not a delta
any: 0, // somebody is DRIVING: resets idle and takes over
act: 0 // somebody is present but not driving: idle only
};
var mode = 0; // 0 auto, 1 manual
var blend = 0; // 0 = pure autopilot pose, 1 = pure viewer pose
/* The autopilot's clock is not integrated, it is OFFSET: autoT = t - autoOff, and autoOff only
* grows while a viewer is driving. Integrating it separately drifts by a tick per tick against
* the t the elements are given, and re-anchoring on resume then becomes an assignment to an
* accumulator that the next frame immediately adds to. As an offset both are exact. */
var autoOff = 0;
var idle = 0; // seconds since the last input
var IDLE_RESUME = 15; // ...after which the city takes itself back
var BLEND_IN = 0.18, BLEND_OUT = 1.6; // taking over is instant-ish; giving back is a fade
// Viewer pose, integrated in metres and radians.
var px = 0, pz = 0, pyaw = 0, pitch = 0, vx = 0, vz = 0, bob = 0, crouchK = 0;
var fovT = 1.25;
var placed = 0; // has the viewer pose ever been seeded from the auto one
var WALK = 2.7, RUN = 5.8, CROUCH = 1.25; // metres/second. Faster than the 1.6 m/s autopilot:
// somebody holding a key is trying to get somewhere.
var ACCEL = 9.0; // velocity smoothing, 1/s. Instant response reads as
// a camera on rails rather than as a person walking.
var MOUSE = 0.0022, KEYLOOK = 1.35; // radians per pixel / per second
var PADLOOK = 2.30; // radians/second at full right-stick deflection
var PITCH_MAX = 0.30; // as a fraction of the grid height, either way
/* The look queue. LOOK_LAG is a rate, so at 60 Hz it spends 37% of the bank per tick and the
* whole of a flick has landed inside three frames — enough that the camera has weight, far
* short of the ~120 ms where input latency stops reading as inertia and starts reading as a
* broken page. YAW_MAX is the stomach: 3.1 rad/s is about 180 deg/s, which is a brisk but
* survivable turn, and anything the viewer asks for above it is banked rather than dropped so a
* fast flick still arrives in full, just over four frames instead of one. */
var qYaw = 0, qPitch = 0;
var LOOK_LAG = 22, YAW_MAX = 3.1, YAW_MAX_RM = 1.15;
var paused = 0; // photo mode; main.js reads Control.paused
/* Collision is a radius, not a point. A point slides through the diagonal gap where two
* buildings meet at a corner, and at 5.8 m/s that gap is wide enough to walk through a block. */
var RAD = 0.34;
function solid(city, x, z) {
if (!city || !city.height) return false;
return city.height(x, z) > 0 ||
city.height(x + RAD, z) > 0 || city.height(x - RAD, z) > 0 ||
city.height(x, z + RAD) > 0 || city.height(x, z - RAD) > 0;
}
/* Axis-separated: a viewer walking into a wall at an angle slides along it instead of stopping
* dead, which is the difference between a camera and a bumper car. */
function move(city, nx, nz) {
if (!solid(city, nx, pz)) px = nx;
if (!solid(city, px, nz)) pz = nz;
}
function angDelta(a, b) { // shortest signed way round from a to b
var d = b - a;
while (d > Math.PI) d -= 6.283185307;
while (d < -Math.PI) d += 6.283185307;
return d;
}
/* Scratch for the autopilot pose. The autopilot writes a full camera, so it is given a private
* one and the result is mixed into the real cam below. */
var A = { x: 0, z: 0, yaw: 0, eyeY: 1.7, fov: 1.25 };
function seedFromAuto() {
px = A.x; pz = A.z; pyaw = A.yaw; vx = 0; vz = 0; placed = 1; seedWanted = 0;
/* The pitch is seeded too, and for the same reason the yaw is: the autopilot now glances up
* (see autoLook), so a take-over that started the viewer at pitch 0 would snap the horizon
* back to level over the 0.18 s blend the moment somebody pressed W under a tall block. */
pitch = apitch;
}
/* ---- the autopilot's own pitch ---------------------------------------------------------------
* WHY THIS EXISTS. `cam.horizon = hb + pitch * rows * b` multiplied the whole pitch by the
* manual-control blend, and b is 0 whenever no human is driving — so on autopilot the horizon
* was nailed to rows*0.56 forever and a passive viewer, who is the entire audience for an
* ambient piece, could never see the sky. Measured over the canonical 4x4 sweep at 400x100: the
* deepest sky row was 55 in every single frame and sky was 2.1% of cells. Nine elements draw up
* there.
*
* WHY IT IS DRIVEN BY THE BUILDINGS AND NOT BY A CLOCK. A camera that pans up and down on a
* timer reads as a camera on a motor. A walker looks up when there is something above them to
* look at, so the target is the tallest mass beside and just ahead of the autopilot pose:
* flanking samples, because in a street canyon the height AHEAD is the road (measured: the
* forward samples are 0 for three quarters of the walk) and the towers are to the sides. The
* lookup is four calls to city.height per tick against the thousands the raycaster already
* makes, and it allocates nothing.
*
* The result is smoothed with a time constant near two seconds, so a block edge — which is a
* step in the height field — arrives as a glance rather than as a jerk, and it is FROZEN while
* paused, because photo mode is a still and a horizon that keeps creeping after P is not one. */
var apitch = 0;
var AUTO_PITCH = 0.15; // fraction of the grid height at a full glance up
var AUTO_LO = 26, AUTO_HI = 52; // the height band that earns one; medians sit at ~22
var AUTO_RATE = 0.55; // 1/s toward the target
var SWAY = 0.025; // the head is never perfectly level, even level
function autoLook(dt, city, ta) {
var tgt = 0;
if (city && city.height) {
var fx = Math.sin(A.yaw), fz = Math.cos(A.yaw);
/* Left and right of the walk at two ranges. Two ranges rather than one because a single
* sample distance flickers on and off as the walk passes a gap between two towers. */
var h = 0, hh;
hh = city.height(A.x + fx * 5 + fz * 4.5, A.z + fz * 5 - fx * 4.5); if (hh > h) h = hh;
hh = city.height(A.x + fx * 5 - fz * 4.5, A.z + fz * 5 + fx * 4.5); if (hh > h) h = hh;
hh = city.height(A.x + fx * 13 + fz * 5, A.z + fz * 13 - fx * 5); if (hh > h) h = hh;
hh = city.height(A.x + fx * 13 - fz * 5, A.z + fz * 13 + fx * 5); if (hh > h) h = hh;
var u = (h - AUTO_LO) / (AUTO_HI - AUTO_LO);
if (u < 0) u = 0; else if (u > 1) u = 1;
tgt = smooth(u) * AUTO_PITCH;
}
/* Indexed on the autopilot clock, not on wall time, so scrubbing to frame 9000 gives the same
* horizon the browser had at second 150 — the harness has to render the frame the browser
* draws or none of the measurement in this project means anything. */
tgt += (CC.vnoise(ta * 0.043, 1913) - 0.5) * 2 * SWAY;
if (CC.reducedMotion) tgt *= 0.45;
apitch += (tgt - apitch) * Math.min(1, dt * AUTO_RATE);
}
/* THE SEED IS DEFERRED, and this is a real bug rather than a tidy-up. takeOver() can be called
* from a key handler, i.e. between two updates, and it used to seed the viewer pose out of A
* there and then — but A holds LAST tick's autopilot pose, and on the very first tick after a
* reset it holds no pose at all, just the {0,0} the object was declared with. Pressing W inside
* the first frame of a new city therefore seeded the viewer at the corner of the map and the
* blend flew the camera off the street at 90 m/s. So take-over only raises a flag, and the
* seeding happens in update() at the one point where A is known to be this tick's. */
var seedWanted = 0;
function takeOver() {
if (mode) return;
mode = 1;
vx = 0; vz = 0;
seedWanted = 1; // start from exactly where the eye already is
}
function giveBack(city, t) {
if (!mode) return;
mode = 0;
if (t === undefined) t = 0;
/* Re-anchor the autopilot clock to the arc length nearest the viewer, so the pose it starts
* producing is a couple of metres away rather than wherever the frozen clock left off. */
if (city && city.nearestRouteS) {
var sp = city.SPEED || 1.6;
if (city.ensureRoute) city.ensureRoute(sp * (t - autoOff) + 80);
autoOff = t - city.nearestRouteS(px, pz).s / sp;
}
}
/* Dead zone, rescaled rather than subtracted: a stick that starts moving at 0.16 and jumps
* straight to 0.16 of walking speed has a step in it you can feel through your thumb. */
function dead(v, d) {
if (v > d) return (v - d) / (1 - d);
if (v < -d) return (v + d) / (1 - d);
return 0;
}
var PAD_DZ = 0.16;
/* ---- gamepad ---------------------------------------------------------------------------
* There is no gamepad event stream worth having — the spec gives you `gamepadconnected` and
* then expects you to POLL — so this runs from update() and writes the same K channels the
* keyboard does. Two guards matter. The whole body is skipped when the API is absent, which is
* what keeps Node (which has a `navigator` since 21, but never a getGamepads on it) and the
* headless harness on the pure autopilot. And it is skipped when no pad has ever announced
* itself: navigator.getGamepads() allocates a fresh array on every call, and paying for that
* 60 times a second for the ~99% of viewers with no controller plugged in is exactly the kind
* of per-frame garbage the frame path is not allowed to make. `padSeen` is set by the connect
* event; the once-a-second probe underneath it is the fallback for a browser that fires the
* event before we attach, or not at all. */
var padSeen = 0, padProbe = 0;
function pollPad(dt) {
K.gx = 0; K.gz = 0; K.grun = 0; K.glx = 0; K.gly = 0;
if (typeof navigator === 'undefined' || !navigator.getGamepads) return;
if (!padSeen) {
padProbe -= dt;
if (padProbe > 0) return;
padProbe = 1;
}
var pads = navigator.getGamepads();
if (!pads) return;
for (var i = 0; i < pads.length; i++) {
var p = pads[i];
if (!p || !p.connected || !p.axes || p.axes.length < 2) continue;
padSeen = 1;
var lx = dead(p.axes[0] || 0, PAD_DZ), ly = dead(p.axes[1] || 0, PAD_DZ);
// Stick up is -1 on axis 1, and up is forwards. The sign flip is the whole mapping.
K.gx += lx; K.gz += -ly;
if (p.axes.length >= 4) {
K.glx += dead(p.axes[2] || 0, PAD_DZ);
K.gly += -dead(p.axes[3] || 0, PAD_DZ);
}
var b = p.buttons;
if (b) {
/* Triggers are analogue on every pad worth the name and digital on the cheap ones, so
* they are read as a value with a threshold rather than as `.pressed`; bumpers are
* offered alongside because a viewer holding a trigger to run for a minute is a viewer
* with a cramp. */
for (var j = 4; j <= 7; j++) {
var bb = b[j];
if (!bb) continue;
var v = typeof bb === 'number' ? bb : (bb.value !== undefined ? bb.value : (bb.pressed ? 1 : 0));
if (v > 0.35) K.grun = 1;
}
}
}
/* Only a deflected stick counts as somebody driving. A pad sitting on a sofa with a sticky
* axis would otherwise hold the city in manual mode forever and the walk would never resume. */
if (K.gx || K.gz || K.glx || K.gly || K.grun) K.any = 1;
}
function update(dt, t, cam, city) {
if (!(dt > 0)) dt = 1 / 60;
var k = CC.reducedMotion ? 0.5 : 1;
/* Before the idle bookkeeping, because a stick deflection has to be able to take the camera
* over on the same tick a keypress would. */
pollPad(dt);
// ---- idle bookkeeping -------------------------------------------------------------------
/* Two kinds of input. K.any is somebody DRIVING — a key, a thumb, a stick — and it takes the
* camera over. K.act is somebody pressing a key that is not a control at all: H, P, F, N, a
* weather preset. Those must reset the idle timer, because a viewer flicking through the
* presets is plainly still there, but they must not seize the camera: changing the sky is not
* a reason for the walk to stop. Folding both into one flag is why pressing P used to hand the
* viewer a camera they had not asked for, standing still. */
if (K.any || K.act) {
idle = 0;
if (K.any && !mode) takeOver();
K.any = 0; K.act = 0;
} else idle += dt;
/* Not while paused. Photo mode is somebody holding still on purpose, and fifteen seconds of
* holding still is exactly what the idle timer was built to punish. */
if (mode && !paused && idle > IDLE_RESUME) giveBack(city, t);
// ---- the autopilot always runs ----------------------------------------------------------
/* Its clock does not run while somebody else drives. That case needs the offset: `t` is still
* advancing, so autoOff has to advance with it for `t - autoOff` to hold still.
*
* IT MUST NOT ADVANCE WHILE PAUSED, and the `|| paused` that used to be here was a real bug
* that had never executed anywhere — the browser path had no test until tools/domshim.cjs.
* Photo mode froze the street BACKWARDS. main.js holds simT itself while paused, and it has to:
* an element whose draw() is a pure function of t (the sky, a sign's flicker, the scanline
* roll) would go on animating no matter how many updates were skipped. So the t arriving here
* is ALREADY frozen, and advancing autoOff on top of a frozen t makes `t - autoOff` DECREASE
* by dt every tick. city.camera duly walked the route in reverse at exactly its own 1.6 m/s:
* press P on autopilot and the camera slid back down the street at walking pace, which is the
* one thing a photo mode may not do. Freezing the pose takes one clock stopped, not two. */
if (mode && !paused) autoOff += dt;
if (city && city.camera) city.camera(A, city, t - autoOff);
else { A.x = cam.x; A.z = cam.z; A.yaw = cam.yaw; A.eyeY = 1.7; }
/* Before seedFromAuto, which copies apitch into the viewer's pitch: the glance has to be this
* tick's for the same reason the position does. Frozen under P — see autoLook. */
if (!paused) autoLook(dt, city, t - autoOff);
// A is this tick's now, so a take-over raised since the last one can safely be honoured.
if (!placed || seedWanted) seedFromAuto();
// ---- the viewer ---------------------------------------------------------------------------
/* Everything the devices asked for this tick, banked. K.mdx is a pixel delta and is consumed;
* the key and stick terms are rates and are integrated. */
/* The stick terms are SQUARED (with the sign kept), the keys are not. A key is one speed and
* there is nothing to gain from bending it; a stick is asked to do both a slow pan across a
* skyline and a whip round to see what is behind you, and a linear stick can only be tuned
* for one of the two. */
qYaw += (K.mdx * MOUSE) + (K.yawR - K.yawL) * KEYLOOK * dt +
K.glx * (K.glx < 0 ? -K.glx : K.glx) * PADLOOK * dt;
qPitch += (-K.mdy * MOUSE * 0.62) + (K.pitchU - K.pitchD) * KEYLOOK * 0.5 * dt +
K.gly * (K.gly < 0 ? -K.gly : K.gly) * PADLOOK * 0.42 * dt;
K.mdx = 0; K.mdy = 0;
/* Spend the bank. The rate cap is applied to what is SPENT, so the remainder stays queued and
* arrives on the following ticks — a flick of the wrist still turns you all the way round, it
* simply cannot do it inside one frame. Reduced motion buys a much lower ceiling, because the
* whole point of the preference is that fast whole-field rotation is the thing that hurts. */
var lag = Math.min(1, dt * LOOK_LAG);
var maxYaw = (CC.reducedMotion ? YAW_MAX_RM : YAW_MAX) * dt;
var dy = qYaw * lag;
if (dy > maxYaw) dy = maxYaw; else if (dy < -maxYaw) dy = -maxYaw;
var dp = qPitch * lag;
/* Below this the residual is a rounding error pretending to be motion, and leaving it in
* means a camera that never quite stops creeping after the last input. */
if (dy > -1e-7 && dy < 1e-7) { dy = qYaw; qYaw = 0; } else qYaw -= dy;
if (dp > -1e-7 && dp < 1e-7) { dp = qPitch; qPitch = 0; } else qPitch -= dp;
/* ONLY WHILE DRIVING, and this is a deliberate reversal of what used to be here. The old test
* was `if (mode || look)`, which let a held arrow key keep turning pyaw after the viewer had
* pressed Escape — invisible at blend 0, but during the 1.6 s hand-back blend is not 0 yet
* and the camera visibly swung as it slid home. The viewer pose is frozen the instant they
* let go; takeOver() re-seeds it from the autopilot anyway, so nothing is lost by freezing. */
if (mode) {
pyaw += dy;
pitch = clamp(pitch + dp, -PITCH_MAX, PITCH_MAX);
}
var tgtC = K.crouch ? 1 : 0;
crouchK += (tgtC - crouchK) * Math.min(1, dt * 7);
var mf = (K.fwd - K.back) + K.tz + K.gz, ms = (K.right - K.left) + K.tx + K.gx;
var sp = (K.crouch ? CROUCH : ((K.run || K.trun || K.grun) ? RUN : WALK)) * k;
/* CLAMPED, not normalised. Normalising unconditionally was correct while every input was a
* boolean — it is what stops a diagonal from being sqrt(2) times faster than a straight line
* — but it also rescales a stick held half way UP to full speed, and an analogue stick with
* no analogue in it is just a slow keyboard. Above 1 the clamp is the old normalisation
* exactly (a keyboard diagonal is still 1.0, a single key still 1.0); below it, magnitude is
* whatever the thumb said. */
var ml = Math.sqrt(mf * mf + ms * ms);
if (ml > 1) { mf /= ml; ms /= ml; }
var tvx = 0, tvz = 0;
if (ml > 0.001) {
// yaw 0 faces +z, matching city.js and the caster.
var fx = Math.sin(pyaw), fz = Math.cos(pyaw);
tvx = (fx * mf + fz * ms) * sp;
tvz = (fz * mf - fx * ms) * sp;
}
var a = Math.min(1, dt * ACCEL);
vx += (tvx - vx) * a; vz += (tvz - vz) * a;
if (mode) move(city, px + vx * dt, pz + vz * dt);
else { px = A.x; pz = A.z; } // parked on the autopilot so a take-over is seamless
var spd = Math.sqrt(vx * vx + vz * vz);
bob += spd * dt * 2.1;
/* Head bob scales with speed and dies with it; a fixed-amplitude bob on a stopped camera is
* the single most nauseating thing a first-person view can do. */
var bobA = CC.reducedMotion ? 0.012 : 0.034;
var pEye = 1.66 - crouchK * 0.52 + Math.sin(bob * 3.1) * bobA * Math.min(1, spd / WALK);
// ---- mix -----------------------------------------------------------------------------------
var tgtB = mode ? 1 : 0;
var rate = mode ? BLEND_IN : BLEND_OUT;
blend += clamp((tgtB - blend), -1, 1) * Math.min(1, dt / rate);
if (blend < 0.0005) blend = 0; else if (blend > 0.9995) blend = 1;
var b = smooth(blend);
cam.x = A.x + (px - A.x) * b;
cam.z = A.z + (pz - A.z) * b;
cam.yaw = A.yaw + angDelta(A.yaw, pyaw) * b;
cam.eyeY = A.eyeY + (pEye - A.eyeY) * b;
/* THE NEUTRAL ROW MUST NOT BE THE LAST FRAME'S HORIZON. main.js publishes cam.horizonBase and
* cam.rows from layout(), but tools/headless.cjs builds its own camera literal with neither —
* and the old fallback `cam.horizonBase !== undefined ? ... : cam.horizon` then read back the
* horizon THIS FUNCTION WROTE last tick, so the pitch was added to itself sixty times a second.
* It never fired before because the only pitch was the viewer's, which is multiplied by a blend
* that is zero with no DOM attached; the autopilot glance below made it fire on every offline
* frame, and the sweep showed the horizon off the bottom of the grid (100% sky) by frame 18000.
* Latching the neutral row onto the camera the first time we see one fixes every caller at once
* rather than only the one harness that happens to be in the tree. */
if (cam.horizonBase === undefined) cam.horizonBase = cam.horizon;
var hb = cam.horizonBase;
/* Same story for the grid height. 0.56 is main.js's neutral fraction and this is the only line
* in the file that knows it: a camera that publishes no row count still publishes a neutral
* horizon, and recovering rows from it is what keeps the offline reference frame equal to the
* browser's rather than pitching by a hardcoded 60 rows on a 100-row grid. */
var rows = cam.rows || (hb / 0.56);
/* The two pitches are CROSS-FADED, not scaled. The old line was `hb + pitch * rows * b`, which
* is the viewer's pitch faded up from a level horizon — fine while the autopilot had no pitch
* of its own, and the reason it never had one: b is 0 with nobody driving, so any glance the
* walk wanted was multiplied away. Mixing apitch in at (1-b) hands the walk's own horizon to a
* passive viewer and still gives a driver the full authority they had, because at b = 1 this
* is exactly the old expression. */
cam.horizon = hb + (apitch + (pitch - apitch) * b) * rows;
/* A.fov, not a literal 1.25: the neutral fov belongs to whatever pose the autopilot is
* producing, and writing the number twice is how the wheel ends up fighting a walk that has
* decided to widen out on its own. */
cam.fov = A.fov + (fovT - A.fov) * b;
/* Published for the hint element and for anything that wants to know whether a human is
* driving — the crowd, for instance, has no business parting for an autopilot. `speed` is
* scaled by the blend on purpose: it is the speed of the CAMERA, not of the viewer's intent,
* and mid-hand-back a HUD printing 5.8 m/s over a pose drifting home at 1.6 would be a
* readout of something nobody in the frame can see. */
Control.mode = mode; Control.blend = b; Control.speed = spd * b; Control.idle = idle;
Control.paused = paused;
return cam;
}
/* ---- the hint's clock -----------------------------------------------------------------------
* Two timestamps and no accumulator, for the same reason the weather override is stamped rather
* than counted down: `alpha` has to be a pure function of t or the overlay is the one thing in
* the frame that the headless harness cannot reproduce, and a hint that only exists in the
* browser is a hint nobody can look at while tuning it. Opening the overlay stamps hintOpen and
* schedules hintClose; H closes it by moving hintClose to now. Nothing here is DOM, so it sits
* above the line. */
var HINT_IN = 1.0, HINT_HOLD = 7.0, HINT_OUT = 1.2;
var hintOpen = 0, hintClose = HINT_IN + HINT_HOLD;
function hintAlpha(t) {
if (!(t >= 0)) t = 0;
var a = (t - hintOpen) / HINT_IN; if (a > 1) a = 1; else if (a < 0) a = 0;
var b = 1 - (t - hintClose) / HINT_OUT; if (b > 1) b = 1; else if (b < 0) b = 0;
return a * b;
}
function hintToggle(t) {
if (!(t >= 0)) t = 0;
if (t < hintClose) { hintClose = t; return; } // visible or still holding: start the fade
/* Re-opening BACK-DATES the fade-in by however much of it is already on screen, so pressing H
* halfway through a fade-out picks the overlay back up from where it is instead of snapping
* it to nothing and climbing again. */
var cur = hintAlpha(t);
hintOpen = t - HINT_IN * cur;
hintClose = t + HINT_IN + HINT_HOLD;
}
/* ---- DOM ------------------------------------------------------------------------------------
* Everything below this line is skipped entirely when there is no window, which is what keeps
* the offline reference frame honest. */
var el = null;
function attach(win, doc, canvas, hooks) {
if (!win || !doc) return;
el = canvas || doc.documentElement;
function set(e, down) {
var c = e.code || '', h = e.key || '';
var hit = 1;
switch (c) {
case 'KeyW': case 'Numpad8': K.fwd = down; break;
case 'KeyS': case 'Numpad5': K.back = down; break;
case 'KeyA': K.left = down; break;
case 'KeyD': K.right = down; break;
case 'ArrowLeft': K.yawL = down; break;
case 'ArrowRight': K.yawR = down; break;
case 'ArrowUp': K.pitchU = down; break;
case 'ArrowDown': K.pitchD = down; break;
case 'ShiftLeft': case 'ShiftRight': K.run = down; break;
case 'KeyC': case 'ControlLeft': K.crouch = down; break;
default: hit = 0;
}
if (!hit && down) {
hit = 2; // 2 = "handled, but not a drive input"; see below
switch (c) {
case 'Tab':
if (mode) { giveBack(hooks && hooks.city && hooks.city(),
hooks && hooks.now ? hooks.now() : 0); idle = 0; }
else { takeOver(); hit = 1; }
e.preventDefault();
break;
case 'Escape': giveBack(hooks && hooks.city && hooks.city(),
hooks && hooks.now ? hooks.now() : 0); idle = 0;
if (doc.exitPointerLock) doc.exitPointerLock();
break;
case 'KeyH': hintToggle(hooks && hooks.now ? hooks.now() : 0); break;
/* Photo mode. The flag is all this file owns — main.js reads Control.paused and stops
* stepping the world; what happens HERE is that the autopilot's clock is frozen with it
* (see update), so the pose under a paused city holds still whether or not a viewer is
* driving. Look and walk both keep working, which is the point: a still is something
* you compose, not something you take by accident. */
case 'KeyP': paused = paused ? 0 : 1; Control.paused = paused; break;
case 'KeyF': if (hooks && hooks.fullscreen) hooks.fullscreen(); break;
case 'KeyN': if (hooks && hooks.reseed) hooks.reseed(); break;
case 'BracketLeft': if (CC.Weather) CC.Weather.cycle(hooks && hooks.now ? hooks.now() : 0, -1); break;
case 'BracketRight': if (CC.Weather) CC.Weather.cycle(hooks && hooks.now ? hooks.now() : 0, 1); break;
default: hit = 0;
}
if (!hit && /^Digit[1-6]$/.test(c) && CC.Weather) {
CC.Weather.set(parseInt(c.slice(5), 10) - 1, hooks && hooks.now ? hooks.now() : 0);
hit = 2;
}
if (!hit && h && h.length === 1 && h >= '1' && h <= '6' && CC.Weather) {
CC.Weather.set(h.charCodeAt(0) - 49, hooks && hooks.now ? hooks.now() : 0);
hit = 2;
}
}
/* THE RELEASE KEYS MUST NOT RE-ARM THE TAKE-OVER, and for a long time they did: Escape and
* Tab both cleared K.any inside their own case and then fell through to an unconditional
* `K.any = 1` down here, so the next update() saw a fresh input, called takeOver(), and the
* camera was handed straight back to a viewer who had just pressed the key that means stop.
* Escape did nothing at all. `hit` now carries three states rather than a boolean: 0 not
* ours, 1 a drive input, 2 handled but not driving — and the release keys return their own
* value of 1 only in the branch where Tab means TAKE the camera.
*
* The hint is also no longer killed by the first keypress. It used to be — one keystroke and
* the overlay vanished — which meant that the viewer who pressed W to see whether the thing
* was walkable at all was precisely the viewer who never got to read the rest of the list.
* Eight seconds is eight seconds; it is three rows of dim slate in a corner and it can share
* the screen with somebody walking. */
if (hit === 1) K.any = 1;
else if (hit === 2) K.act = 1;
return hit;
}
win.addEventListener('keydown', function (e) {
if (e.metaKey || e.ctrlKey && e.code !== 'ControlLeft' || e.altKey) return;
if (e.repeat) { K.any = 1; return; }
if (set(e, 1) && e.code !== 'Tab') { /* handled */ }
});
win.addEventListener('keyup', function (e) { set(e, 0); });
/* A window that loses focus mid-stride keeps the key down forever otherwise, and the camera
* walks into the far wall of the city while somebody is reading their email. */
win.addEventListener('blur', function () {
K.fwd = K.back = K.left = K.right = K.run = K.crouch = 0;
K.yawL = K.yawR = K.pitchU = K.pitchD = 0;
K.tx = K.tz = K.trun = 0;
stickId = -1; lookId = -1; mouseDrag = 0;
});
/* ---- pointers, mouse and touch ------------------------------------------------------
* A phone gets a screen split down the middle: the left half is a virtual stick, the right
* half is a look pad, and BOTH AT ONCE has to work or the piece is unplayable one-handed —
* which is why every pointer is tracked by its pointerId rather than by a single `dragging`
* boolean. Two fingers on a shared flag is the bug where strafing sideways also spins the
* camera, because the walking finger's deltas were being read as look.
*
* The stick is CENTRED WHERE THE THUMB LANDED, not on a fixed circle: a fixed on-screen stick
* needs to be drawn to be usable, and this piece has no UI. Its dead zone is the reason a TAP
* cannot start a walk — under 13 px of travel it produces exactly zero, so the tap that takes
* the page fullscreen does not also send the camera off down the street.
*
* Mouse behaviour is untouched: one button-held drag looks, exactly as it did. */
var STICK_DEAD = 13, STICK_FULL = 78, STICK_RUN = 0.93; // CSS px, and a fraction of full
var TOUCH_LOOK = 0.0038; // rad/px; a thumb has less travel than a mouse arm
var mouseDrag = 0, mlx = 0, mly = 0;
var stickId = -1, stickX0 = 0, stickY0 = 0;
var lookId = -1, llx = 0, lly = 0;
function isTouch(e) { return e.pointerType === 'touch' || e.pointerType === 'pen'; }
el.addEventListener('pointerdown', function (e) {
if (el.setPointerCapture) { try { el.setPointerCapture(e.pointerId); } catch (err) {} }
if (!isTouch(e)) { mouseDrag = 1; mlx = e.clientX; mly = e.clientY; return; }
/* The one bit elements/hud.js needs to know: this viewer has a thumb, not a keyboard, so the
* hint must talk about halves of the screen rather than about WASD. It is latched on the
* FIRST touch and never cleared — a device does not stop having a touchscreen, and clearing
* it in reset() would make N (which a touch viewer cannot press anyway) rewrite the hint.
* Never set without a DOM, so the offline reference frame keeps the keyboard wording. */
Control.touch = 1;
var w = win.innerWidth || el.clientWidth || 800;
if (e.clientX < w * 0.5) {
if (stickId < 0) { stickId = e.pointerId; stickX0 = e.clientX; stickY0 = e.clientY; }
} else if (lookId < 0) { lookId = e.pointerId; llx = e.clientX; lly = e.clientY; }
/* No K.any here on purpose. Touching the screen is how you go fullscreen, and a viewer who
* wanted a bigger picture has not asked to take the camera off the autopilot. */
});
function release(e) {
if (e.pointerId === stickId) { stickId = -1; K.tx = 0; K.tz = 0; K.trun = 0; }
else if (e.pointerId === lookId) lookId = -1;
else mouseDrag = 0;
}
win.addEventListener('pointerup', release);
win.addEventListener('pointercancel', release);
win.addEventListener('pointermove', function (e) {
if (doc.pointerLockElement === el) {
K.mdx += e.movementX || 0; K.mdy += e.movementY || 0;
if (e.movementX || e.movementY) K.any = 1;
return;
}
if (e.pointerId === stickId) {
var dx = e.clientX - stickX0, dy = e.clientY - stickY0;
var m = Math.sqrt(dx * dx + dy * dy);
if (m <= STICK_DEAD) { K.tx = 0; K.tz = 0; K.trun = 0; return; }
/* Rescaled out of the dead zone and clamped at 1, so the thumb's usable travel is the
* ~65 px between the two radii and pushing past the rim just means "and run". */
var g = (m - STICK_DEAD) / (STICK_FULL - STICK_DEAD);
if (g > 1) g = 1;
K.tx = dx / m * g;
K.tz = -dy / m * g; // up the screen is forwards
K.trun = g >= STICK_RUN ? 1 : 0;
K.any = 1;
return;
}
if (e.pointerId === lookId) {
K.mdx += (e.clientX - llx) * (TOUCH_LOOK / MOUSE);
K.mdy += (e.clientY - lly) * (TOUCH_LOOK / MOUSE);
llx = e.clientX; lly = e.clientY;
K.any = 1;
return;
}
if (!mouseDrag) return;
K.mdx += e.clientX - mlx; K.mdy += e.clientY - mly;
mlx = e.clientX; mly = e.clientY;
K.any = 1;
});
win.addEventListener('wheel', function (e) {
fovT = clamp(fovT + (e.deltaY > 0 ? 0.045 : -0.045), 1.02, 1.52);
K.any = 1;
}, { passive: true });
/* Without this the browser's own gestures win: a drag on the left half scrolls the page (or
* pulls to refresh) instead of walking, and a two-finger anything zooms the document. The
* canvas is the whole viewport, so there is nothing here anyone could want to scroll. */
if (el.style) { el.style.touchAction = 'none'; }
/* The pad announces itself once and then it is a poll API — see pollPad(). All this listener
* does is authorise the polling, so the no-controller case costs nothing per frame. */
win.addEventListener('gamepadconnected', function () { padSeen = 1; });
Control.requestLook = function () {
if (el.requestPointerLock && doc.pointerLockElement !== el) {
/* Same shape as main.js's goFullscreen and the same never-executed bug: since Chrome 113
* requestPointerLock returns a PROMISE, so the try/catch only covers the engines where it
* still returns undefined. A refused lock — no user activation, the user pressed Escape
* within the lock-out window, a sandboxed frame — rejects, and an unhandled rejection
* prints in the console. A mouse-look nobody granted is a fine outcome; a console error
* for it is not. */
try {
var p = el.requestPointerLock();
if (p && p.catch) p.catch(function () { });
} catch (err) {}
}
};
}
var Control = {
attach: attach, update: update,
mode: 0, blend: 0, speed: 0, idle: 0,
/* 1 once a touch pointer has been seen; read by elements/hud.js to pick which vocabulary the
* hint speaks. Declared here so the field exists before any DOM event ever fires. */
touch: 0,
/* Photo mode, published for main.js to read. This file only owns the flag — see the KeyP
* case for what still has to happen at the other end. */
paused: 0,
/* The hint overlay's envelope, as a pure function of the simulation clock. elements/hud.js is
* the only caller; it gets t handed to its draw() and asks here rather than keeping a clock of
* its own, so that H and the eight-second timer have exactly one implementation. */
hintAlpha: hintAlpha,
/* Kept only because main.js calls it every tick. The hint used to be a countdown and this was
* where it counted; it is a stamped envelope now, so there is nothing left to tick. Removing
* the method would mean editing main.js, which this file does not own. */
tickHint: function () {},
// Introspection for the harness and for tests; never an input path.
get pose() { return { x: px, z: pz, yaw: pyaw, pitch: pitch, mode: mode, blend: blend }; },
reset: function () {
mode = 0; blend = 0; autoOff = 0; idle = 0; placed = 0; pitch = 0; apitch = 0; fovT = 1.25;
vx = 0; vz = 0; bob = 0; crouchK = 0; qYaw = 0; qPitch = 0;
K.fwd = K.back = K.left = K.right = K.run = K.crouch = 0;
K.yawL = K.yawR = K.pitchU = K.pitchD = 0; K.mdx = 0; K.mdy = 0; K.any = 0; K.act = 0;
K.tx = K.tz = K.trun = 0; K.gx = K.gz = K.grun = 0; K.glx = K.gly = 0;
seedWanted = 0;
/* N rebuilds the city and calls through here, and a new city that arrives paused is a viewer
* staring at a still they did not ask for. */
paused = 0; Control.paused = 0;
hintOpen = 0; hintClose = HINT_IN + HINT_HOLD;
}
};
if (CC) CC.Control = Control;
if (typeof module !== 'undefined') module.exports = Control;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

489
src/core.js Normal file
View file

@ -0,0 +1,489 @@
/* CyberCity core — frame buffers, palette, glyph table, seeded noise, safe writes. */
var CC = (function () {
'use strict';
// Palette measured off the reference frames: two pillars (sodium amber, screen azure)
// and three narrow accents. Brightness is NOT baked in here — `lum` scales these.
var PALETTE = [
[216, 232, 74], // 0 amber — sodium streetlight, the first pillar
[ 74, 168, 232], // 1 azure — screenlight, the second pillar
[224, 114, 74], // 2 ember — accent district, warning lamps
[ 42, 197, 147], // 3 spring — accent district, foliage, transit
[130, 86, 230], // 4 violet — rare; screens and signage only. Was 186,64,232, which is hue
// 288 — magenta, and with the bloom on top of it a blade sign in
// it printed as hot pink across the top of the frame. The rule is
// three NARROW accents and no magenta ever, so the swatch is
// walked round to hue 257: unmistakably violet, never pink.
[216, 226, 236], // 5 white — pavement, rails, structure
[255, 92, 92], // 6 red — aerial lamps, stop signals
[ 62, 98, 138], // 7 slate — unlit concrete and far haze. Deliberately NOT grey: it is the
// most numerous swatch in the frame (a third of every lit cell),
// so at 120,150,180 it printed a wash of neutral haze over the
// whole picture — exactly the grey the distance must never fade
// to. The same value read as cold structure lit by screenlight
// carries the facades without ever competing with the pillars.
[255, 214, 120], // 8 warm — interior spill, windows with someone home
[ 90, 240, 255], // 9 ice — holo, glass, rain highlight
[255, 255, 255], // 10 pure — specular hits only, use sparingly
[ 40, 50, 66] // 11 shadow — occluded structure that must still read
];
var P = { amber:0, azure:1, ember:2, spring:3, violet:4, white:5, red:6,
slate:7, warm:8, ice:9, pure:10, shadow:11 };
// Glyph table. Index 0 must stay blank — the frame is cleared to it.
var GLYPHS = " .,:;'\"`^~-_=+*|/\\()[]{}<>!?#%&$@8OoQ0XZWMNHUVAKY".split('');
var GI = {};
for (var i = 0; i < GLYPHS.length; i++) GI[GLYPHS[i]] = i;
function g(c) { var v = GI[c]; return v === undefined ? 0 : v; }
function makeFrame(cols, rows) {
var n = cols * rows;
return {
cols: cols, rows: rows, n: n,
ch: new Uint8Array(n),
col: new Uint8Array(n),
lum: new Uint8Array(n),
dist: new Float32Array(n),
kind: new Uint8Array(n)
};
}
function clearFrame(f) {
f.ch.fill(0); f.col.fill(0); f.lum.fill(0); f.kind.fill(0);
f.dist.fill(Infinity);
}
// The only sanctioned write. Depth-tests so elements can never punch through a wall.
function put(f, x, y, chIdx, colIdx, lum, dist, kind) {
x = x | 0; y = y | 0;
if (x < 0 || y < 0 || x >= f.cols || y >= f.rows) return false;
var i = y * f.cols + x;
if (!(dist < f.dist[i])) return false;
f.ch[i] = chIdx; f.col[i] = colIdx;
f.lum[i] = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0);
f.dist[i] = dist; f.kind[i] = kind === undefined ? 3 : kind;
return true;
}
// Unconditional write for the world pass, which owns the buffer and paints back-to-front.
function poke(f, i, chIdx, colIdx, lum, dist, kind) {
f.ch[i] = chIdx; f.col[i] = colIdx;
f.lum[i] = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0);
f.dist[i] = dist; f.kind[i] = kind;
}
/* ---- deterministic noise --------------------------------------------
* Every multiply is Math.imul, and that is not a micro-optimisation — it is correctness.
* With `*`, `x * 374761393` leaves the 2^53 mantissa the moment |x| passes ~2.4e7 and the
* low bits, which are the ONLY bits (h >>> 13) and (h >>> 16) go on to mix, are quietly
* rounded away. The symptom is not noise that looks slightly different; it is per-lot random
* streams that COLLAPSE — at seed 2e9 the offsets S+601..S+615 used to land in just two
* distinct streams, and 512 adjacent seeds gave 4 distinct cities. imul keeps the product
* exact modulo 2^32, which is the arithmetic this hash was designed in.
*
* THE FINALIZER IS TWO ROUNDS AND THAT IS ALSO CORRECTNESS, not paranoia. imul(s, 2147483647)
* is exactly (s << 31) - s, so changing the seed by a small constant changes the mixer's input
* by that same small constant, and ONE multiply-xorshift round does not hide a small additive
* offset. Measured over 24 base seeds x 8000 samples (noise floor 0.008): the old single round
* gave mean |correlation| 0.78 at seed delta 64, 0.64 at 128, 0.48 at 32, and exceeded 0.04 for
* 80 of the first 160 deltas. That is not an abstract worry, because this file's callers get
* their "independent" streams by adding a SMALL constant to the seed — S+101, S+211, S+307 and
* so on — and 389 of the 1026 stream pairs those offsets actually produce measured above 0.05,
* worst 0.448 (S+211 against S+307). Two supposedly separate ambient systems were drawing the
* same numbers. With the second round every one of those pairs sits at the noise floor (worst
* 0.049) and the seed-delta sweep is flat at 0.007-0.011 out to delta 256. The cost is one imul
* and one xorshift per call, measured at ~5% of hash2's own time, and hash2 is not the render
* loop's bottleneck. elements/signage.js's hk() — vary the COORDINATE by a large odd offset
* rather than the seed by a small one — was written to dodge exactly this and is still the
* belt-and-braces convention, but it is no longer the only thing standing between the build
* and correlated streams. */
function hash2(x, y, s) {
var h = (Math.imul(x | 0, 374761393) + Math.imul(y | 0, 668265263) +
Math.imul(s | 0, 2147483647)) | 0;
h = Math.imul(h ^ (h >>> 15), 2246822507);
h = Math.imul(h ^ (h >>> 13), 3266489909);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function hash1(x, s) { return hash2(x, 0, s); }
function mulberry(seed) {
var a = seed >>> 0;
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
var t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function lerp(a, b, t) { return a + (b - a) * t; }
function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); }
function smooth(t) { return t * t * (3 - 2 * t); }
function vnoise(x, s) { // 1D value noise, for sways and flicker
var i = Math.floor(x), f = x - i;
return lerp(hash1(i, s), hash1(i + 1, s), smooth(f));
}
/* ---- exposure -------------------------------------------------------
* The city was a full stop under-exposed: 82-85% of the frame was pure black against a
* reference that sits at 54-60%, and the lum histogram explained why — 60% of every lit cell
* landed under 32/255, which is a glyph drawn in a colour nobody can see. The surfaces were
* not wrong, the print was. So this is a print stage, not a retouch: one curve over the
* finished frame, applied exactly once, after the world pass and every element.
*
* Three things happen per cell, all of them in a lookup table built once at load:
*
* 1. a per-swatch EXPOSURE weight. This is the TONAL LADDER and it is the most powerful
* control in the file: `gain` multiplies lum before the curve, so gain*255 is the ceiling
* a swatch can ever print at, and no amount of light upstream gets a swatch past its own
* ceiling. The ladder therefore decides which swatches are allowed to be the brightest
* thing on screen. The rule it now encodes: LIGHT OUTRANKS STRUCTURE. The two pillars
* (sodium amber, screen azure) must be able to reach the top of the lit range; the three
* narrow accents must not out-top the pillars; white and warm are surfaces lit by that
* light and sit below it; slate and shadow are unlit concrete and sit below everything.
*
* 2. a gamma lift, which is where the stop comes from, with a KNEE that crushes the bottom
* instead of lifting it. A plain gamma would drag the 1-10 lum dither out of the dark and
* the whole frame would go to grey fog; below the knee the curve bends the other way and
* those cells stay black. The knee bites on x = lum*gain/255, so its lum threshold is
* GAIN-DEPENDENT — see the KNEE comment below, which used to quote one number as if it
* were the same for every swatch.
*
* 3. the lift fades out with DEPTH. Distant geometry must fade to BLACK, never to grey, and
* Surf.fog earns that in linear light — pushing a fixed x^0.33 over the top of it would
* hand the far end of the street its brightness back as haze. Far cells get gamma 1, so
* fog's ramp survives untouched and only the near and middle ground open up.
*
* 4. a SHOULDER on the highlights, so a swatch can be pushed hard without going flat.
*
* Everything upstream keeps reading and writing plain linear lum, which matters: optics.js
* does read-modify-write gain passes on the frame, and a curve inside put()/poke() would
* compound through every one of them.
*
* These weights are CALIBRATION, not taste: they were fitted by rendering a fixed set of
* seeds and frames through tools/headless.cjs + tools/topng.py and measuring the printed
* frame — share of lit energy per swatch, and the proportion of the picture that is pure
* black. They therefore describe THIS surfaces.js. If the surfaces change what they paint,
* re-measure and refit; do not adjust them by eye.
*
* AND MEASURE THEM OVER A WIDE SAMPLE, because the previous fit was taken over four seeds
* (3/7/42/99) and this paragraph then asserted, for two rounds, a pillar balance that is true
* on those four seeds and false everywhere else. The sample below is 32 seeds on a fixed
* arithmetic rule — 3001 + 137k for k = 0..31 — crossed with frames 600/6000/12000/18000 at
* 400x100, 128 warm frames rendered through tools/headless.cjs into a fresh directory, plus a
* 24-seed hold-out on an unrelated rule (9001 + 211k). Four seeds cannot see a distribution and
* a mean cannot see a spread; quote both or the next reader inherits this same bug.
*
* THE LADDER WAS INVERTED AND IT IS THE REASON THE CITY READ AS TEXTURE. The previous table
* printed, at lum 255 and the near depth bucket: red 243, pure 237, white 228, ice 224, ember
* 218, warm 204, violet 200, spring 195, azure 156, slate 137, amber 126, shadow 66. Both
* pillars sat at the BOTTOM of the lit range and structure sat on top of them. Over the
* canonical 16-frame sweep (seeds 3/7/42/99 x frames 600/3000/9000/18000 at 400x100, through
* tools/headless.cjs) that produced ZERO amber cells and ZERO azure cells above v=170 in any
* frame, while white, warm, ember, spring, red and ice all had hot cells. Measured on the near
* ground (depth 12-25 world units, all 16 frames pooled) white printed 166.5 against azure
* 105.3 and amber 80.6 — the swatch documented three lines below as "structure, not light" was
* printing twice as bright as the first pillar on the same depth plane.
*
* The claim this paragraph used to make — that the weights "redistribute colour without moving
* the stop" and that GAMMA and KNEE are the real brightness controls — is false, and it was
* believed because it was checked against black%, which cannot see it. Swept over the same 16
* frames: GAMMA 0.33 -> 0.75 moves black 41.30% -> 41.65% while the muddy 9-119 band RISES to
* 53% and the hot tail COLLAPSES 1.86% -> 0.62%. KNEE 0.055 -> 0.24 drops mid to 37.6% and
* leaves hot at exactly 1.86% — a knee can delete a shadow, never create a highlight. SHOULDER
* 0.45 vs 0.90 is a no-op to 0.01 points, because almost nothing except slate ever reached it.
* EXPOSURE alone, curve untouched, moved mid 51.1% -> 31.5% and hot 1.86% -> 3.29%. black% was
* blind to all twelve settings because it is pinned by `blank` (glyph 0 or lum 0, which the
* curve never touches) and `blank` sat at 41.2-41.7% under every one of them.
*
* SO THE NUMBERS TO MEASURE ARE NOT black%. They are the share of the frame in the muddy band
* v=9-119 (28.4%, target under 30%) and the share above v=170 (3.86%, target 3.5-5%). A frame
* can be 60% black and read beautifully — the strongest composition in the sweep is also one of
* its blackest — and it can be 40% black and read as flat texture.
*
* AND black% NOW MEANS TWO DIFFERENT THINGS, which is worth stating because the old "40-55%"
* band is quoted in briefs as though it still meant one. tools/metrics.py reports `blank` (no
* glyph, or lum 0 — the curve cannot touch it) at 41.6% and `black(v<9)` (blank PLUS every cell
* the print takes below visibility) at 56.8%. Those were the same number when KNEE was 0.055
* and slate's gain was 2.00; raising the knee to 0.075 is what split them, and the 15.2 points
* between them are the far haze being crushed to black on purpose — the doctrine is that
* distance fades to BLACK, never to grey. 41.6% sits inside the 40-55% band and 56.8% sits
* inside the 54-60% this comment's own opening quotes off the reference frames. Neither is out
* of calibration; they are two censuses of the same picture, and a target has to name which.
*
* PILLAR BALANCE — READ THIS BEFORE TOUCHING EXPOSURE[0] OR EXPOSURE[1]. Over the 128 frames
* the pillars take amber 45.3% and azure 35.6% of lit energy, i.e. the pillar pair splits
* 56.0/44.0. THE PER-FRAME SPREAD IS THE REAL NUMBER AND IT IS ENORMOUS: amber runs 7.8% to
* 95.0% of lit energy (median 46.0) and azure 3.6% to 75.9% (median 34.1), the per-frame
* amber:azure ratio runs 0.10 to 26.3 with a median of 1.32, and only 46% of frames have the
* two within a factor of two of each other. Pooled by seed it is 0.34 to 4.16. A previous
* revision of this comment reported the pillars "within two points of each other"; that was
* measured over seeds 3/7/42/99 and is false on every wider sample.
*
* THAT SPREAD IS NOT THIS FILE'S TO FIX AND NO SETTING OF THIS TABLE MOVES IT. Measured over
* the same 128 frames: amber paints 557,598 cells against azure's 387,933, a 1.44:1 COVERAGE
* ratio, and the correlation between a frame's log cell-count ratio and its log lit-energy
* ratio is 0.997. The print is already the only thing holding the gap below coverage — amber
* prints at a mean 131 against azure's 159 on the cells that count as lit. Sweeping every knob
* in this file over its whole feasible range moves the mean |log2 ratio| only between 1.15 and
* 1.32, because the gain enters the curve under an exponent of 0.33-1.00: a 2.2x change of
* EXPOSURE[amber] (0.28 -> 0.62) moves amber's pooled share by 1.25x and nothing else. Which
* districts a walk passes through is decided in city.js, and how many cells of each swatch a
* facade paints is decided in surfaces.js (the window-hue roll alone is 42% amber against 30%
* azure, and SHOP leans a district's shopfronts onto its own pillar). Bending this curve to
* hide that is exactly how the table came to be overfitted; fix it there or leave it.
*
* WHAT THE REFIT DID FIX, all measured on the same 128 frames with only this file swapped:
* - the ladder, below, which had five swatches printing above the first pillar;
* - white's max share of a frame's lit energy 36.6% -> 32.4% and its ceiling 174 -> 151, so
* the white wall that was the brightest object in s4645_f18000 is grey structure again;
* - warm outranking a pillar 22/128 frames -> 17/128, pooled 11.1% -> 9.3%;
* - frames led by something that is neither pillar 6/128 -> 3/128;
* - ember's max share 33.8% -> 29.1% and its ceiling 203 -> 163, which is the print-side half
* of the accent-leads-the-frame bug city.js measured and could not bound from its side;
* - the pillar split 57.4/42.6 -> 56.0/44.0 and the median ratio 1.39 -> 1.32. That is the
* whole of what the centre had left in it at no cost to the ladder, and it is small.
* Costs: hot 3.73% -> 3.86% (in band), muddy 28.8% -> 28.4%, black and blank unmoved.
*
* EXPOSURE IS NOT PRIVATE TO THIS FILE, so a refit is not a print-only change however much this
* comment would like it to be: elements/optics.js's `mistfar` reads CC.EXPOSURE to rescale a
* warm cell's lum when it repaints it to slate, on purpose, so that the hue swap costs the frame
* no printed energy. Refitting therefore moves what that element writes, which moves the frame
* an element measures, which moves the next tick — an offline table sweep is not exactly the
* shipped walk. Measured, over the 32 most mist-loaded frames of the sweep (mistfar does nothing
* in the other five skies): 0.53% of cells move before the print and every reported statistic
* moves by at most 0.03 of a point, slate's own share being the largest. Small, but it is the
* reason a refit has to be confirmed by re-rendering and not only by re-printing.
*
* A LEVER THAT WOULD DO MORE AND IS DELIBERATELY NOT SHIPPED. Amber's share and amber's ceiling
* are the same knob here, so the two things wrong with amber pull opposite ways: amber-dominant
* frames are also the COLDEST frames (the 12 frames with the least hot tail average 53.2% amber
* and 0.87% hot against the 3.5-5 target, because amber's ceiling barely clears the hot line),
* yet raising amber's gain to fix that raises its share too. Giving KNEE a per-swatch entry
* separates them: amber at gain 0.72 with its own knee at 0.26 holds the share at 43.8% while
* the hot tail goes 3.73% -> 6.91% and amber-frame hot 2.40% -> 7.03%. It was measured, it
* works, and it is a new mechanism rather than a recalibration of an existing one, so it is
* recorded here for whoever owns that decision instead of being slipped in under a refit. */
/* THE LADDER. Printed ceilings under this table (lum 255, near bucket, scaled by the swatch's
* own pigment): pure 234, azure 220, red 206, amber 180, ice 175, warm 167, ember 163, spring
* 163, violet 154, white 151, slate 114, shadow 60.
*
* THE RULE, which the previous table stated and then broke in five places (ember 203, ice 209,
* warm 195, violet 179 and red 214 all sat above the first pillar's 177): only `pure` and `red`
* — a specular return and an actual lamp — may print above a pillar, and neither may print
* above the HIGHER pillar. Every accent, and every surface that is merely lit by the pillars,
* sits under the LOWER one. Read it as four tiers: specular and lamps; the two pillars; the
* narrow accents and the lit surfaces beneath them; unlit concrete at the bottom.
*
* The 40-point gap between the two pillars is not sloppiness, it is the correction: amber
* paints 1.44 cells for every azure cell (see PILLAR BALANCE above), so the more numerous
* pigment gets the lower ceiling and the two arrive at comparable presence. Both still clear
* the v=170 hot line, which is what "the pillars own the top of the lit range" has to mean. */
var EXPOSURE = [
0.50, // 0 amber — the first pillar, ceiling 180. The gain has a HARD FLOOR just under it
// and it is not a preference: at 0.44 the ceiling is 171 and at 0.42 it
// is 165, which is under the v=170 hot line, and amber is the swatch
// that decides whether an amber-district frame has any highlight at all
// (the 12 coldest frames of 128 average 62.9% amber and 0.87% hot). It
// also has a soft ceiling above: pushed to 0.62 the amber slabs that
// already fill those frames simply get yellower — rendered and looked at
// on s6700_f12000, which is 95% amber, and the picture got worse while
// every statistic improved. Amber is the most numerous lit swatch by
// 1.44:1, so it takes the lowest gain of the lit tier; that is the
// coverage being corrected for, not the pillar being held down
1.00, // 1 azure — the second pillar, ceiling 220. Higher than amber for the coverage
// reason above, not because the pigment is dimmer — amber and azure have
// the SAME max channel (232), so equal ceilings would mean equal gains
// and the split would go straight back to the raw 1.44:1. Raised from
// 0.82 for the last of the centring that was available: it buys the
// pillar split 56.6/43.4 -> 56.0/44.0. Past here the return collapses
// (the cells are over the SHOULDER) and the frames that are already
// azure-led start to glare — at 1.10 the hottest frame in the sweep goes
// to 18.8% of cells above v=170 and the near screens read as a flat wall
// of blue rather than as windows
0.42, // 2 ember — NARROW accent, ceiling 163, under the lower pillar. It was 0.80 for a
// ceiling of 203, ABOVE the first pillar's 177, and that is the print
// side of the bug city.js measured from the other end: in the near depth
// bucket ember printed a median 175.7 against amber's 139.2 in the SAME
// frame, so a small ember district on the near wall became the subject
// of the picture. Six district-table levers were swept in city.js and
// none of them bounded it, because dimming a slab that already fills the
// frame moves numerator and denominator together; the ceiling does bound
// it, and only in the frames that were failing
0.60, // 3 spring — narrow accent, ceiling 163. It was once the highest weight in the whole
// table at 1.55, applied to the rarest accent, and wherever a spring
// district came into view it detonated. THE RULE: no accent's ceiling
// may exceed the LOWER pillar's, or the accent becomes the focal point
// of every frame its district appears in. Spring still reaches 24.4% of
// a frame's lit energy at its worst, which is coverage and belongs to
// whichever element paints that mass, not to this table
0.34, // 4 violet — narrow accent, ceiling 154, and the one that goes gaudy the instant it
// is indulged: at the old 0.50 it printed 179, over the first pillar,
// and s5467_f6000 carries a violet slab across the top-left corner
// holding 24.9% of the frame's lit energy. The ceiling stops it leading;
// the slab itself is a paint fact
0.30, // 5 white — structure, not light, and finally printed like it: ceiling 151, well
// under both pillars. At 1.15 it printed 228 and was the brightest broad
// swatch in the frame; at 0.44 it still printed 174, one point under the
// first pillar, and in s4645_f18000 a white wall was the brightest object
// on screen with 36.6% of the frame's lit energy. Specular hits belong to
// `pure`; white is the thing the light lands on. Worst-frame share is now
// 32.4% and white leads no frame in the sweep
0.56, // 6 red — aerial lamps read at their own brightness or they are not lamps, so red
// is allowed above the pillars — but not above the HIGHER one, which 0.62
// was (214 against azure's 211). At 206 it still tops amber, which is the
// point of a lamp, and cannot top a wall of screens. At 1.05 it printed
// 243 and the single brightest object in the entire reference sweep was
// not a lamp at all but a red facade wall
0.60, // 7 slate — unlit concrete. It was at 2.00 "for coverage", and 2.00 is past the
// SHOULDER, which silently cancelled its depth fade: slate printed 137.5
// at the near plane and 136.9 at the fog wall, a 0.4% fade, on 36% of
// every painted cell. That is why the canyon did not read — the
// geometry was there, the luminance gradient that lets an eye see it was
// not. INVARIANT: a swatch that is coverage rather than light must keep
// gain*lum under SHOULDER across the lums it actually gets written at,
// or it loses the one cue that makes far things far. At 2.00 slate was
// over it from lum 79 up, which is most of a facade. Coverage itself is
// untouched, because coverage is which cells surfaces.js paints and not
// how bright they print: `blank` moved 43.3% -> 42.3% over the sweep, so
// the facades are still slabs and not lattices
0.32, // 8 warm — interior spill. At 30-38% it was a third pillar, and a yellow one; at
// 0.48 it was still printing 195, above the first pillar's 177, and it
// outranked a pillar outright in 22 of 128 frames while reading to the
// eye as more amber. Ceiling 167 and 17 of 128, which is as far as a
// ceiling can take it: the frames where warm leads are frames standing
// in front of a lit interior, and that is surfaces.js's massing, not a
// print fault
0.36, // 9 ice — rain highlight; belongs with azure. A GLINT, never a surface, and the
// old ceiling of 208 made it a surface: it sat above BOTH the first
// pillar and every accent on the strength of being rare, which is the
// same argument that put spring at 1.55. Rarity bounds how many cells a
// swatch owns, never how bright the frame's brightest thing is. At 175 it
// is still the top of the accent tier, still reads as a glint against wet
// road, and takes at most 2.7% of a frame's lit energy
0.85, // 10 pure — specular only; it is already at the top of the scale
0.80 // 11 shadow — occluded structure must READ as occluded structure, not as a hole, and
// this one is deliberately NOT 0.60. shadow's pigment tops out at 66, so
// unlike slate it was never in the inverted ladder and could not compete
// with a pillar at any gain; its only real fault at 2.60 was the same
// fade cancellation, since from lum 61 up it sat past the SHOULDER, and
// it is 24% of every painted cell. At 0.60 the near facades that are in
// shadow stop being mass and become holes — the whole left half of
// s42_f18000 goes to flat black. 0.80 keeps them as dark blue-grey
// slabs (a typical shadow cell prints v 26-36 instead of 21) with the
// fade intact, since its working lum range 20-60 is nowhere near the
// shoulder, and the 16-frame muddy band still comes in under target at
// 28.6%. THE INVARIANT is not "gain below SHOULDER" but "the swatch's
// WORKING lum range times its gain stays below SHOULDER" — that is what
// 2.00 and 2.60 broke, from lum 79 and 61 up respectively
];
/* GAMMA and KNEE are held at the values the previous round fitted, and that is a measurement
* rather than an omission: re-swept over the 128 frames with the new EXPOSURE in place, GAMMA
* 0.24 puts the hot tail at 7.12% (target 3.5-5) and 0.40 at 2.36%, so 0.33 is the only step on
* the grid that lands in band. GAMMA and KNEE are also the only two knobs that move black% at
* all — EXPOSURE cannot, because black is pinned by cells the curve never reaches — and every
* setting that pulls black(v<9) down to the 40-55 band pushes the muddy band past 30% in the
* same move (KNEE 0.065 -> black 55.0 / muddy 30.6; 0.058 -> 53.4 / 32.3). The two targets are
* not jointly satisfiable on this tree and muddy is the one that describes what the picture
* looks like, so muddy wins and black is reported honestly instead of being fitted to. */
var GAMMA = 0.33; // the lift; roughly the stop the frame was missing
/* The knee bites on x = lum*gain/255, so the lum it crushes below is gain-dependent and there
* is no single number to quote: at 0.075 it is lum 32 for slate (gain 0.60), lum 24 for shadow,
* lum 19 for azure and lum 38 for amber. That is the right way round — the crush lands hardest
* on the two swatches that fill the frame and never touches a bright pillar cell. Raised from
* 0.055 because at the old value the crush was inactive where it mattered: with slate at gain
* 2.00 a cell had to be under lum 7 to reach the knee at all, so the stage that says it crushes
* the bottom was instead lifting 25 percentage points of near-invisible dither into the mid
* band. Re-measured over the 128-frame sweep at the current weights, 0.055 -> 0.075 moves the
* muddy v=9-119 band 32.3% -> 28.4% and costs zero hot cells. It is deliberately not 0.10: at
* 0.10 the sweep also extinguishes floor and element cells, i.e. it starts eating the road
* texture and the ambient systems rather than the haze. At 0.075, 99.7% of what goes dark is
* slate and shadow. */
var KNEE = 0.075;
/* Above this the top rolls off instead of clipping — see the LUT below. IT IS A GUARD RAIL AND
* NOT A WORKING CONTROL, and that is measured, not assumed: swept 0.45 -> 0.99 over the 128
* frames with the current table it moves every reported statistic by at most 0.2 of a point,
* because only azure's gain reaches it at all and only from lum 168 up. It earns its place by
* bounding what a FUTURE gain can do — the previous table had slate at 2.00 and shadow at 2.60,
* where the shoulder was live from lum 79 and 61 up and silently cancelled their depth fade —
* so do not read its inertness today as permission to delete it. It also has a floor: below
* about 0.50 it stops being a rail and starts eating the ladder's own top, taking azure from
* 220 to 214 and pure from 234 to 228 at 0.45, which closes the gap the pillars need over the
* accent tier. Above 0.62 it does nothing but widen azure's ceiling (232 at 0.99). */
var SHOULDER = 0.62;
var DBUCKETS = 8; // depth quantisation for the fade-out of the lift
var FOG_START = 12.0, FOG_END = 125.0; // must track CC.Surf's ramp
/* At or past this depth a cell is BACKDROP, not far geometry, and is printed at the near end of
* the curve. FOG_END is the exact boundary and not a guess: the raycaster breaks its march at
* FOG_END so no facade can carry a larger dist, a floor row that projects past it comes back
* from Surf.fog at lum 0 and is skipped below, and every object in elements/sky.js is deliberately
* given a distance beyond it so that it self-occludes against the world pass. */
var SKY_D = FOG_END;
// LUT[(bucket*12 + colour)*256 + lum] -> printed lum. 24 KB, built once, never allocated again.
var LUT = (function () {
var np = PALETTE.length, t = new Uint8Array(DBUCKETS * np * 256);
for (var b = 0; b < DBUCKETS; b++) {
// bucket centre as a 0..1 depth fraction; the lift is retired linearly across it
var df = (b + 0.5) / DBUCKETS;
var gm = GAMMA + (1 - GAMMA) * df;
for (var c = 0; c < np; c++) {
var gain = EXPOSURE[c];
for (var l = 0; l < 256; l++) {
var x = l * gain / 255;
/* A hard clamp here was quietly cancelling the whole point of EXPOSURE: a swatch
* printed at 2.2 saturated everything over lum 116 to flat 255, so raising the gain
* further bought no extra energy and only destroyed the modelling inside the sign.
* The shoulder is an exponential rolloff that never reaches 1, so a swatch can be
* pushed hard and still keep the difference between its bright and its brightest. */
if (x > SHOULDER) x = SHOULDER + (1 - SHOULDER) * (1 - Math.exp(-(x - SHOULDER) / (1 - SHOULDER)));
var k = x / KNEE; if (k > 1) k = 1;
var y = Math.pow(x, gm) * (k * k * (3 - 2 * k));
var v = (y * 255 + 0.5) | 0;
t[(b * np + c) * 256 + l] = v > 255 ? 255 : v;
}
}
}
return t;
})();
var DSCALE = DBUCKETS / (FOG_END - FOG_START);
function tone(f) {
var n = f.n, lum = f.lum, col = f.col, dist = f.dist, ch = f.ch, np = PALETTE.length;
for (var i = 0; i < n; i++) {
var l = lum[i];
if (l === 0 || ch[i] === 0) continue;
var d = dist[i], b;
// Sky carries Infinity and is not "far" in the fog sense — it is the backdrop, and it is
// printed at the near end of the curve so the slot between the rooftops keeps its stars.
//
// This test has to come FIRST, and for two years of nobody reading it the comment above was
// simply false: Infinity > FOG_START is true and Infinity < FOG_END is false, so every sky
// cell fell through to the last bucket — the one place the gamma lift is fully retired —
// and the backdrop was printed at the DARKEST setting on the curve rather than the
// brightest. The slot between the rooftops had no stars because the print had taken them.
// SKY_D also catches the sky elements (blimps, moon, aircraft), which carry a large finite
// distance rather than Infinity so that they self-occlude against the world pass.
if (d >= SKY_D) b = 0;
else if (!(d > FOG_START)) b = 0;
else if (!(d < FOG_END)) b = DBUCKETS - 1;
else { b = ((d - FOG_START) * DSCALE) | 0; if (b > DBUCKETS - 1) b = DBUCKETS - 1; }
lum[i] = LUT[((b * np + (col[i] % np)) << 8) + l];
}
}
/* The frame's last stop before it is drawn. main.js and tools/headless.cjs both call
* CC.Compose.post, which is precisely why the print lives behind that name — the offline
* reference frame and the browser must be the same picture or verification means nothing.
* A later src/compose.js taking this slot over MUST call CC.tone itself. */
var Compose = { post: function (f) { tone(f); } };
return {
PALETTE: PALETTE, P: P, GLYPHS: GLYPHS, g: g, GI: GI,
tone: tone, Compose: Compose, EXPOSURE: EXPOSURE,
makeFrame: makeFrame, clearFrame: clearFrame, put: put, poke: poke,
hash1: hash1, hash2: hash2, mulberry: mulberry,
lerp: lerp, clamp: clamp, smooth: smooth, vnoise: vnoise,
ELEMENTS: [], reducedMotion: false
};
})();
if (typeof module !== 'undefined') module.exports = CC;

326
src/elements/hud.js Normal file
View file

@ -0,0 +1,326 @@
/* CyberCity hint overlay — the only text in the piece, and it is made of city.
*
* WHY IT IS AN ELEMENT AND NOT A DIV. A caption in HTML would sit on a sheet of glass in front of
* the artwork: no fog, no bloom, no scanline, no vignette, wrong colour space, wrong font, and
* crisp in a frame where nothing else is. Drawn through CC.put at layer 90 it is instead IN the
* picture — optics.js vignettes it in the corner, the scanline rolls over it, the exposure breathe
* lifts it with everything else, and CC.tone prints it through the same curve as a streetlight. It
* reads as a readout stencilled on the inside of a visor, which is the only kind of UI a piece
* like this can have.
*
* THE FONT IS THE WHOLE PROBLEM. CC.GLYPHS is 49 characters chosen for TEXTURE — the letters in it
* are the ones that make good façade noise (A H K M N O Q U V W X Y Z) and no others. There is no
* S, no D, no E, no R, no T, no I, no L. So not one of the six weather names is spellable, "MOVE"
* is not spellable, and neither is any key label worth printing; and core.js is not this file's to
* extend. The way out is that a glyph does not have to BE the letter — it can be a pixel of one.
* Every character below is a 3x5 bitmap stamped one CC.GLYPHS cell per lit pixel, which is exactly
* how the blade signs on the buildings are already made, one row up in the same frame. It costs
* four columns per character, which is why every string here is terse to the point of rudeness and
* why the whole overlay disappears rather than wrap on a grid too narrow to hold it.
*
* IT IS PURE. The envelope is CC.Control.hintAlpha(t), a stamped function of the simulation clock
* rather than an accumulator, so tools/headless.cjs renders the overlay at frame 30 exactly as the
* browser draws it at frame 30 and the thing can be tuned by looking at it offline like everything
* else. The only impurity is H, which restamps the envelope — the same deal weather_state.js makes
* for its preset keys.
*/
(function (CC) {
'use strict';
var GH = CC.g('@'); // one lit pixel of a letter. Compared side by side against '#' and
// '8' at this size: '#' is a lattice with more hole than ink and the
// letterforms fell apart into texture, '8' reads as two stacked
// bowls, and '@' is the only glyph in the table that fills its cell
// as a single mass. At 3x5 the eye is reading mass, not shape.
var SLATE = CC.P.slate, WHITE = CC.P.white;
/* In front of everything. The raycaster's nearest façade is metres away and every element is
* further, so any depth below the near plane wins the test in CC.put; these are small enough to
* be unambiguous and non-zero so nothing can tie with them.
*
* TWO depths, and the gap between them is what makes the overlay readable at all. The bottom of
* the frame is the brightest and busiest part of the picture — it is near pavement, painted in
* white '8' at high lum — and the first version of this file put dim slate letters straight on
* top of it, where they were simply invisible: every glyph was present in the buffer and the
* eye could not find a single one of them. So each character first BLANKS its own box (see
* plate()) and then draws into it. The blanks go at PLATE_D and the letters at the nearer
* HUD_D, which means a blank can never erase a letter that has already been drawn — CC.put's
* own depth test refuses it — and the clearing can therefore be interleaved with the drawing in
* one pass rather than needing a separate one over the whole line. A blank is a real write: the
* cell becomes glyph 0 at lum 0, which CC.tone and the canvas both skip. */
var HUD_D = 0.02, PLATE_D = 0.03;
/* ---- the 3x5 face ---------------------------------------------------------------------------
* Packed to one int per character, five rows of three bits, row 0 at the top and bit 2 of each
* row at the left. FONT is indexed by charCode-32 and read with charCodeAt, which returns a
* number — charAt would allocate a one-character string per letter per frame, and this runs
* inside draw(). Everything not defined here is a blank, which is also what a space is. */
var FONT = new Int32Array(96);
function face(ch, r0, r1, r2, r3, r4) {
var rows = [r0, r1, r2, r3, r4], bits = 0;
for (var r = 0; r < 5; r++)
for (var c = 0; c < 3; c++)
if (rows[r].charAt(c) === '#') bits |= 1 << (r * 3 + (2 - c));
FONT[ch.charCodeAt(0) - 32] = bits;
}
face('A', '.#.', '#.#', '###', '#.#', '#.#');
face('B', '##.', '#.#', '##.', '#.#', '##.');
face('C', '.##', '#..', '#..', '#..', '.##');
face('D', '##.', '#.#', '#.#', '#.#', '##.');
face('E', '###', '#..', '##.', '#..', '###');
face('F', '###', '#..', '##.', '#..', '#..');
face('G', '.##', '#..', '#.#', '#.#', '.##');
face('H', '#.#', '#.#', '###', '#.#', '#.#');
face('I', '###', '.#.', '.#.', '.#.', '###');
face('J', '..#', '..#', '..#', '#.#', '.#.');
face('K', '#.#', '#.#', '##.', '#.#', '#.#');
face('L', '#..', '#..', '#..', '#..', '###');
/* M and N differ by one row and nothing else — three columns is not enough width for the real
* distinction, so M gets the doubled middle and N a single one. In the words this file prints
* (MOVE, MANUAL, RAIN, N CITY) context settles it long before the letterform has to. */
face('M', '#.#', '###', '###', '#.#', '#.#');
face('N', '#.#', '###', '#.#', '#.#', '#.#');
face('O', '.#.', '#.#', '#.#', '#.#', '.#.');
face('P', '##.', '#.#', '##.', '#..', '#..');
face('Q', '.#.', '#.#', '#.#', '##.', '.##');
face('R', '##.', '#.#', '##.', '#.#', '#.#');
face('S', '.##', '#..', '.#.', '..#', '##.');
face('T', '###', '.#.', '.#.', '.#.', '.#.');
face('U', '#.#', '#.#', '#.#', '#.#', '###');
face('V', '#.#', '#.#', '#.#', '.#.', '.#.');
face('W', '#.#', '#.#', '###', '###', '#.#');
face('X', '#.#', '#.#', '.#.', '#.#', '#.#');
face('Y', '#.#', '#.#', '.#.', '.#.', '.#.');
face('Z', '###', '..#', '.#.', '#..', '###');
face('0', '###', '#.#', '#.#', '#.#', '###');
face('1', '.#.', '##.', '.#.', '.#.', '###');
face('2', '##.', '..#', '.#.', '#..', '###');
face('3', '##.', '..#', '.#.', '..#', '##.');
face('4', '#.#', '#.#', '###', '..#', '..#');
face('5', '###', '#..', '##.', '..#', '##.');
face('6', '.##', '#..', '##.', '#.#', '.#.');
face('7', '###', '..#', '.#.', '.#.', '.#.');
face('8', '.#.', '#.#', '.#.', '#.#', '.#.');
face('9', '.#.', '#.#', '.##', '..#', '##.');
face('-', '...', '...', '###', '...', '...');
face('/', '..#', '..#', '.#.', '#..', '#..');
face('.', '...', '...', '...', '...', '.#.');
var CW = 4; // 3 columns of letter and one of air. Anything less and two capitals
// in a row merge into a single blot at this cell aspect.
var LH = 5, LGAP = 1; // line box and the row between lines
function textW(s) { return s.length * CW - 1; }
/* The dark a single character stands on: its 3x5 box plus a ring of one, laid down cell by cell
* as the line is walked so the field of black ends exactly where the writing does. The first
* attempt spared the SPACES between words, on the theory that letting the street show through
* them would keep the overlay from being a panel — and what came through the gap between MOVE
* and SHIFT was a bar of white pavement at full brightness, which the eye read as part of the
* word. So the spaces are blanked too, and the shape of the dark is the shape of the line.
*
* It DISSOLVES rather than switching. A blank is binary — the cell is cleared or it is
* not — so a plate that simply appeared put a hard black box on the pavement a full second
* before the lettering inside it was bright enough to see, and the fade-out ended with an empty
* black box sitting there after the last letter had gone. Thresholding each cell against a
* fixed per-cell hash turns that switch into a stipple that eats in and lets go again, which
* costs nothing and reads as a panel warming up. The seed is small and constant on purpose:
* CC.hash2 multiplies its seed in floating point, so a large one loses its low bits and the
* dither collapses into stripes. */
var PSEED = 1471;
function plate(f, x, y, a) {
for (var r = -1; r <= LH; r++)
for (var c = -1; c <= CW - 1; c++)
if (a > 0.995 || CC.hash2(x + c, y + r, PSEED) < a)
CC.put(f, x + c, y + r, 0, 0, 0, PLATE_D);
}
function text(f, s, x, y, ci, lum, a) {
for (var i = 0; i < s.length; i++) {
var code = s.charCodeAt(i) - 32;
plate(f, x, y, a); // before the letter, and for spaces too — see plate()
if (code > 0 && code < 96) {
var bits = FONT[code];
if (bits) {
for (var r = 0; r < LH; r++) {
var row = (bits >> (r * 3)) & 7;
if (!row) continue;
if (row & 4) CC.put(f, x, y + r, GH, ci, lum, HUD_D);
if (row & 2) CC.put(f, x + 1, y + r, GH, ci, lum, HUD_D);
if (row & 1) CC.put(f, x + 2, y + r, GH, ci, lum, HUD_D);
}
}
}
x += CW;
}
return x;
}
/* ---- what it says ---------------------------------------------------------------------------
* Three widths of the same list, not a truncation of one: dropping words off the end of a line
* leaves whichever hint happens to be last looking like a typo, whereas these are each a
* complete thought at their size. The widest is chosen that FITS, measured, not assumed — a tier
* table with the arithmetic done by hand is a tier table that is wrong the first time a string
* is edited. */
var TIERS = [
['WASD MOVE', 'DRAG LOOK'],
['WASD MOVE SHIFT RUN', 'DRAG LOOK H KEYS'],
['WASD MOVE SHIFT RUN C CROUCH', 'DRAG LOOK 1-6 SKY N CITY P PHOTO']
];
/* THE SAME LIST FOR A DEVICE WITH NO KEYS ON IT. Every string above names a key — WASD, SHIFT,
* C, 1-6, N, P — and a phone has none of them; printing 'WASD MOVE' on a touchscreen is only
* marginally better than printing nothing, and it is the one device whose controls are
* genuinely invisible (control.js gives touch a screen-split virtual stick that is centred
* wherever the thumb lands and draws nothing at all). So touch gets its own vocabulary, made of
* gestures and of the two halves of the screen. There is no third fact to tell a thumb: the
* weather presets, the reseed and photo mode are keyboard-only, which is why the wider touch
* tiers elaborate the same two halves rather than inventing controls that do not exist. */
var TOUCH = [
['LEFT WALK', 'RIGHT LOOK'],
['LEFT WALK PUSH FAR RUNS', 'RIGHT LOOK TAP FULLSCREEN'],
['LEFT HALF WALKS PUSH FAR RUNS', 'RIGHT HALF LOOKS TAP FULLSCREEN']
];
var MARGIN_X = 3, MARGIN_Y = 2;
/* Below this the overlay is not shortened, it is ABANDONED — but the number used to be 70, and
* 70 is a width no phone in portrait ever reaches: main.js pins the cell to 6.4 CSS px under
* 560 px of viewport and clamps dpr to 2, so a 390 px phone renders 60 columns and a 455 px one
* is the break-even. The hint was therefore hidden on exactly the devices that need it most.
* 48 is main.js's own MINC, i.e. the narrowest grid the piece can be rendered at, and at 48 the
* shortest line is 35 columns of a 42-column writing area: a note in the corner of a small
* frame is still a note. */
var MIN_COLS = 48;
/* And no line may take more than this share of the width even where it technically fits. The
* fit test on its own picked the longest tier at 200 columns, where its 139 characters ran
* seven tenths of the way across the frame and the hint stopped being a note in the corner —
* the measured black went with it, 3.4 points of the picture blanked out to hold the text.
*
* THE SHORTEST TIER IS EXEMPT, and that exemption is the other half of the phone fix: at 60
* columns 0.55 of the width is 33 and the shortest line is 35, so the share test — not
* MIN_COLS — was what silenced the overlay on every handset. The rule exists to stop a LONG
* line from crossing the picture; it has no business vetoing the one line that is the whole
* hint, because the alternative to a wide note on a narrow frame is no note at all. */
var MAX_SHARE = 0.55;
/* Lines are six rows each and the grid can be as short as 22, so how many the overlay is
* allowed is a question about the SHORT dimension, not about how much there is to say. Three
* lines under 64 rows is a caption with a city behind it; one line is the weather and who is
* driving, which is the part that is still worth having at any size. */
var ROWS_3 = 64, ROWS_2 = 40;
var LUM_KEYS = 58; // slate is printed at EXPOSURE 2.00, the loudest weight in the
// table, so its raw lum has to sit far lower than white's to land
// at the same place on the page
var LUM_STAT = 92; // white, EXPOSURE 1.15 — the status line is the one datum a viewer
// is meant to be able to read at a glance
var hud = {
name: 'hud',
layer: 90,
/* No rng draw of any kind, and that is load-bearing rather than incidental: every element
* pulls from ONE shared stream in init order, so a single rng() here would shift the noise of
* everything that initialises after layer 90 — the whole of optics.js — and silently change
* every reference frame in the project. */
init: function () {
/* Uppercased once. CC.Weather.P.name is lower case and toUpperCase() in draw() would
* allocate a string sixty times a second. */
this.wnames = [];
var pr = CC.Weather ? CC.Weather.PRESETS : null;
if (pr) for (var i = 0; i < pr.length; i++) this.wnames.push(pr[i].name.toUpperCase());
// Pre-split so the speed readout is a table lookup rather than a concatenation.
this.dig = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
this.spd = 0;
},
update: function (dt, t, cam) {
/* The printed speed is smoothed hard. It is a one-digit readout, so an unsmoothed value
* sitting on a boundary flickers between 2 and 3 for as long as somebody walks in a straight
* line, and a number that will not hold still is the most distracting thing on a screen. */
var s = CC.Control ? CC.Control.speed : 0;
this.spd += (s - this.spd) * Math.min(1, dt * 2.2);
},
draw: function (f, cam, t) {
if (!CC.Control || !CC.Control.hintAlpha) return;
var a = CC.Control.hintAlpha(t);
if (a <= 0.01) return;
var cols = f.cols, rows = f.rows;
if (cols < MIN_COLS) return;
/* Two widths, not one. `room` is the writing area between the margins and is what the
* shortest tier is measured against; `avail` is the same thing capped at MAX_SHARE and is
* what every tier above it must fit inside. See MAX_SHARE for why the short one is exempt. */
var room = cols - MARGIN_X * 2;
var avail = cols * MAX_SHARE;
if (room < avail) avail = room;
/* A phone is not a keyboard with a small screen — see TOUCH. Control.touch is set by the
* first touch pointerdown and is 0 everywhere there is no DOM, so the offline reference
* frame is untouched by this line. */
var set = (CC.Control.touch ? TOUCH : TIERS);
var tier = 0;
for (var i = set.length - 1; i > 0; i--) {
if (textW(set[i][0]) <= avail && textW(set[i][1]) <= avail) { tier = i; break; }
}
/* Cannot even spell the short one inside the margins: say nothing. BOTH of its lines are
* measured, not just the first — a tall grid prints them both, and a rule that only checked
* the movement line would let the look line run off the right-hand edge the first time
* somebody edits it. */
if (textW(set[0][0]) > room || textW(set[0][1]) > room) return;
var lines = rows >= ROWS_3 ? 3 : rows >= ROWS_2 ? 2 : 1;
var mode = CC.Control.mode || CC.Control.blend > 0.02;
var paused = !!CC.Control.paused;
var y = rows - MARGIN_Y - LH; // the status line, along the bottom
var kl = (LUM_KEYS * a) | 0, sl = (LUM_STAT * a) | 0;
if (sl < 1) return; // wholly faded; nothing would print anyway
// ---- status: what the sky is doing, and who is driving --------------------------------
var x = MARGIN_X;
if (paused) x = text(f, 'PAUSED', x, y, WHITE, sl, a) + CW;
else if (mode) {
x = text(f, 'MANUAL', x, y, WHITE, sl, a) + CW;
/* The speed only appears where there is room for it. On the narrow tier those four extra
* characters are the difference between a status line and a status line and a half. */
if (tier > 0) {
// One digit, so it is clamped rather than allowed to index off the end of the table.
var d = Math.round(this.spd);
if (!(d > 0)) d = 0; else if (d > 9) d = 9;
x = text(f, this.dig[d], x, y, SLATE, kl, a);
x = text(f, 'M/S', x, y, SLATE, kl, a) + CW;
}
}
var w = CC.Weather ? CC.Weather.P.name : '';
for (var wi = 0; wi < this.wnames.length; wi++) {
if (CC.Weather.PRESETS[wi].name === w) {
/* Right off the end is not a wrap, it is a mess, so a status line that has run out of
* room simply loses the weather rather than printing half of it. */
if (x + textW(this.wnames[wi]) <= cols - MARGIN_X)
text(f, this.wnames[wi], x, y, WHITE, sl, a);
break;
}
}
// ---- the key list, stacked upwards from the status line ---------------------------------
if (lines > 1) {
y -= LH + LGAP;
/* With room for only one of the two, it is the movement line. A viewer who has worked out
* that the city is walkable will find the look control by dragging within seconds; a
* viewer who has not never drags at all. */
text(f, set[tier][lines > 2 ? 1 : 0], MARGIN_X, y, SLATE, kl, a);
}
if (lines > 2) {
y -= LH + LGAP;
text(f, set[tier][0], MARGIN_X, y, SLATE, kl, a);
}
}
};
CC.ELEMENTS.push(hud);
if (typeof module !== 'undefined') module.exports = hud;
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

1176
src/elements/optics.js Normal file

File diff suppressed because it is too large Load diff

1824
src/elements/signage.js Normal file

File diff suppressed because it is too large Load diff

954
src/elements/sky.js Normal file
View file

@ -0,0 +1,954 @@
/* CyberCity sky — everything that lives above the rooftop line: a cloud deck, stars, a low moon,
* far aircraft, obstruction beacons on towers past the end of the world, searchlights, advertising
* blimps, delivery drones, and — rarely — a flock or an orbital burn.
*
* WEATHER IS THE SUBJECT UP HERE, not a filter over it. Every object in this file is a different
* object under cloud, under mist and under a clear sky: the stars are masked by a deck rather than
* dimmed by it, the moon trades its disc for a halo and then loses both, the airliners go out
* because they are above the weather, and a searchlight stops being a dot on a far roof and
* becomes a visible shaft. The parameters all come off CC.Weather.P — see the weather block below
* for why these read the raw directions where the rest of the build reads rel().
*
* DEPTH. Every object in this file is further away than the raycaster can march (Surf.FOG_END is
* 125 m, so no facade cell ever carries a larger dist). Handing CC.put a distance beyond that is
* what makes the whole batch self-occluding for free: it survives only where the world pass left
* dist === Infinity. Nothing here needs to know the skyline, and nothing here can bleed through
* a wall.
*
* THE SLOT IS TINY, AND THAT IS WHAT SIZES THIS FILE. Measured on the headless harness at 200x60,
* seeds 1 and 3: sky is 5.8-6.7% of the frame and it is not spread around the top of the screen —
* it is one vertical wedge 12-24 columns wide at the canyon's vanishing point, running from the
* horizon to the top edge. So the visible sky is a window about 0.15 rad wide, and an object at a
* uniformly random bearing lands in it 2.4% of the time, i.e. never. Two consequences run through
* everything below:
* - bearings are drawn on the STREET AXES (the lattice runs along x and z, so the camera's yaw
* is near-cardinal on every leg of the walk) plus a small jitter, not uniformly on the circle;
* - the traffic TRAVELS rather than hovering, so each craft sweeps its own bearing through the
* window and back out again. A parked sky empties out the moment the camera turns a corner.
*
* ANCHORING. Stars and the moon are directions, not points, so they stay welded to the sky as the
* camera walks and yaws. The traffic is anchored to a bearing at a distance from the CAMERA rather
* than to a fixed world point: at 100-2000 m the parallax of a 1.6 m/s walk is under a tenth of a
* cell per second, so the two are indistinguishable — but a world-fixed craft would be left behind
* for good after four minutes of an endless walk.
*/
(function (CC) {
'use strict';
var P = CC.P, g = CC.g, put = CC.put, hash2 = CC.hash2, hash1 = CC.hash1, vnoise = CC.vnoise;
/* g() is a string-keyed lookup and these are hit thousands of times per frame. */
var G_DOT = g('.'), G_COLON = g(':'), G_QUOTE = g("'"), G_TICK = g('`'),
G_DASH = g('-'), G_EQ = g('='), G_PLUS = g('+'), G_PIPE = g('|'), G_SLASH = g('/'),
G_BSLASH = g('\\'), G_HASH = g('#'), G_UNDER = g('_'),
G_8 = g('8'), G_OO = g('O'), G_o = g('o'), G_0 = g('0'), G_X = g('X'), G_Z = g('Z'),
G_W = g('W'), G_M = g('M'), G_N = g('N'), G_H = g('H'), G_A = g('A'), G_V = g('V'),
G_K = g('K'), G_Y = g('Y'), G_U = g('U'), G_TILDE = g('~'), G_CARET = g('^'),
G_COMMA = g(','), G_STAR = g('*');
var TAU = 6.283185307, QUARTER = 1.570796327;
/* Beyond Surf.FOG_END, so a facade always wins the depth test. The three are ORDERED, and the
* order is load-bearing: the moon occludes the cloud deck, the cloud deck occludes a star, and
* none of the element layers has to know about any of the others to make that happen. A star at
* D_STAR simply loses the depth test against a cloud cell already written at D_CLOUD, which is
* the entire overcast mechanism — see the star draw, which only has to handle the THIN cloud the
* deck was too sparse to paint. */
var D_STAR = 1.0e5, D_CLOUD = 9.5e4, D_MOON = 9.0e4;
/* ---- weather --------------------------------------------------------------------------------
* The sky is the one place in the build where the weather is not a modifier on top of a look but
* the look itself: a star field, a moon and a searchlight are three completely different objects
* under cloud, under mist and under a clear sky, and the transitions between them are the best
* drama available up here for the price.
*
* These are RAW parameters, deliberately, and that is a departure from the migration rule
* weather_state.js sets out. rel() exists so an element that was TUNED under the 'rain' preset
* keeps its tuning; these five are not tuning, they are the axes the new behaviour is defined
* along — "gone entirely in mist" is a statement about fog reaching 1.0, and dividing it by the
* 0.30 fog the reference preset happens to carry would make it a statement about nothing.
* Where an EXISTING tuned constant is scaled — the searchlight's mote brightness — rel() is used
* and is named as such at the site. */
var W_CLOUD = 0.75, W_FOG = 0.30, W_HAZE = 0.40, W_RAIN = 0.65, W_WIND = 0.55, W_FOGREL = 1;
function bindWeather() {
var Wm = CC.Weather, p = Wm ? Wm.P : null;
W_CLOUD = p ? p.cloud : 0.75;
W_FOG = p ? p.fog : 0.30;
W_HAZE = p ? p.haze : 0.40;
W_RAIN = p ? p.rain : 0.65;
W_WIND = p ? p.wind : 0.55;
W_FOGREL = Wm ? Wm.rel('fog') : 1;
}
/* ---- one cloud deck -------------------------------------------------------------------------
* ONE field, read by the scud that paints the cloud and by the stars that hide behind it, so the
* two can never disagree about where the gaps are. Two independent fields would have produced
* stars shining out of the middle of a painted cloud, which is the single most obvious way to
* announce that a sky is made of unrelated layers.
*
* The inputs are the DIRECTION's own components rather than an azimuth, for two reasons: it is
* welded to the sky exactly the way the star field is — turn the camera and the deck stays put —
* and it costs no atan2 in a loop that may run over every sky cell in the frame.
*
* The whole deck slides downwind, which is the only motion up here that responds to the weather
* rather than to a clock, and it is what makes a star wink out and come back. */
/* THE FREQUENCIES ARE SET BY THE SLOT, NOT BY THE SPHERE. The first cut ran at 2.6 cycles per
* radian, which is a perfectly good cloudscape over a whole sky and completely wrong for this
* one: the visible sky here is a wedge about 0.15 rad wide, so across the entire slot the field
* moved through less than half a period and the deck was either all on or all off with nothing
* but the dither varying inside it. It read as static, not as cloud. At 9 per radian the slot
* holds a full clump and a gap, which is the least that reads as weather having a shape. */
function cloudAt(dx, dy, dz, t) {
/* Reduced motion stops the deck outright rather than slowing it. A field this large moving
* slowly is worse than one not moving at all: it is the whole sky drifting, which is exactly
* the kind of large-area motion the flag exists to remove, and a still overcast is still a
* perfectly good overcast. */
var d = CC.reducedMotion ? 0 : t * (0.045 + 0.14 * W_WIND);
return vnoise(dx * 9.0 + dz * 2.5 + d, 0x6C1) * 0.56 +
vnoise(dz * 7.5 - dx * 3.0 + dy * 6.5 - d * 0.62, 0x6C2) * 0.44;
}
/* Where the deck starts. The field is a sum of two value noises, so it piles up around 0.5 and a
* threshold swept across that range covers the sky far faster than a linear read of it suggests.
* These two constants were therefore FITTED by counting covered samples over the whole sphere,
* not chosen: they give 2% cover on a clear night (a wisp or two), 34% at drizzle, 79% at the
* 'rain' preset the build was tuned in, and 97% — a lid, with no hole anywhere — under storm. */
function cloudThr() { return 0.88 - W_CLOUD * 0.72; }
/* ---- camera basis, rebuilt once per element draw --------------------------------------------
* This mirrors raycast.js exactly, including its reconciliation of the vertical scale to the
* horizontal fov. If the two ever disagree the moon drifts off the rooftop it was placed behind,
* so the derivation is copied rather than approximated. */
var CB = { fwx: 0, fwz: 1, rgx: 1, rgz: 0, half: 0.71, cols: 0, rows: 0,
horizon: 0, eyeY: 1.7, scale: 1, colsPerTan: 1 };
function setup(frame, cam) {
bindWeather();
var yaw = cam.yaw || 0, fov = cam.fov || 1.25;
CB.fwx = Math.sin(yaw); CB.fwz = Math.cos(yaw);
CB.rgx = Math.cos(yaw); CB.rgz = -Math.sin(yaw);
CB.half = Math.tan(fov * 0.5);
CB.cols = frame.cols; CB.rows = frame.rows;
CB.horizon = cam.horizon !== undefined ? cam.horizon : frame.rows * 0.56;
CB.eyeY = cam.eyeY !== undefined ? cam.eyeY : 1.7;
CB.colsPerTan = frame.cols / (2 * CB.half);
CB.scale = cam.scaleY !== undefined ? cam.scaleY : CB.colsPerTan * (cam.cellAspect || 0.5625);
}
/* Planar projection, matching the raycaster's un-normalised ray: w IS the forward-axis distance
* and needs no cosine fix-up, so a blimp's hull stays a straight-sided ellipse at the frame edge
* instead of bowing. ey is metres above the EYE, not above the street. */
var VP = { ok: 0, x: 0, y: 0, w: 0, d: 0 };
function proj(ex, ey, ez) {
VP.ok = 0;
var w = ex * CB.fwx + ez * CB.fwz;
if (w <= 1e-3) return VP; // behind the camera, or exactly abeam
var sp = (ex * CB.rgx + ez * CB.rgz) / w;
if (sp > 8 * CB.half || sp < -8 * CB.half) return VP;
VP.x = (sp / CB.half + 1) * CB.cols * 0.5 - 0.5;
VP.y = CB.horizon - ey * CB.scale / w;
VP.w = w;
VP.d = w * Math.sqrt(1 + sp * sp); // radial, which is what frame.dist holds
VP.ok = 1;
return VP;
}
/* Rounding and bounds live here rather than in CC.put: put() coerces with |0, which truncates
* toward zero, so an object at x = -0.4 would reappear glued to column 0. */
function plot(f, x, y, ch, col, lum, dist) {
if (lum < 3 || ch === 0) return;
x = Math.round(x); y = Math.round(y);
if (x < 0 || y < 0 || x >= CB.cols || y >= CB.rows) return;
if (y > CB.horizon) return; // nothing here exists below the skyline
put(f, x, y, ch, col, lum, dist);
}
/* Bearings below are dealt round the four street axes as `i * QUARTER + jitter` rather than
* rolled uniformly. See the header: the sky window is ~0.15 rad wide and always sits on the axis
* the camera is walking, so dealing them is the difference between traffic that is occasionally
* overhead and traffic that is statistically never seen at all. Dealing also beats rolling an
* axis at random — with only a handful of craft, a random roll regularly leaves a whole quarter
* of the city's sky empty for a whole seed.
*
* One private stream, so the look of the sky does not shift every time a sibling element file
* lands ahead of this one and eats a different number of draws from the shared rng. */
function fork(rng) { return CC.mulberry(((rng() * 4294967296) | 0) ^ 0x5C1E); }
/* The elements added after this file first shipped seed themselves off the CITY instead, and the
* reason is politeness to every module downstream: CC.ELEMENTS is init'd in layer order off ONE
* shared rng, so an element that takes three draws from it at layer 7 shifts the stream under
* the blimps, the rain, the crowd and every sign in the city. Nothing breaks — they all get
* perfectly good numbers — but every tuned frame anybody else has looked at changes, and a
* change like that has to be worth something. A city-derived stream costs the shared one
* nothing and is just as deterministic. */
function forkCity(city, salt) {
return CC.mulberry((((city && city.seed !== undefined ? city.seed : 0) | 0) ^ salt) >>> 0);
}
/* ============================================================================== cloud deck ==
* Low scud, and the only element in this file that can cover the whole slot. It exists because
* the slot was the one part of the frame that never changed: whatever the weather did to the
* road, the road's reflections and the rain, the sky above it stayed the same handful of stars.
*
* It is drawn as a DITHERED field over the sky cells the world pass left empty, never as a
* filled sheet, and the two numbers that keep it honest are the dither (a bit under half the
* covered cells) and the luminance (slate in the 20s, which prints as the coverage swatch it is
* rather than as light). A solid deck at any brightness is a grey lid over a piece whose whole
* subject is dark, and it was the first thing tried here.
*
* Reading frame.dist is a READ, and the only one in this file: it is the depth pre-test CC.put
* would do anyway, hoisted out so that a clear night costs one array compare per sky cell rather
* than a noise evaluation. Nothing is written except through put().
* ========================================================================================== */
CC.ELEMENTS.push({
name: 'cloudbase',
layer: 3,
draw: function (frame, cam, t) {
setup(frame, cam);
/* Under about 0.4 the deck is a few wisps nobody would notice and 20 000 noise evaluations
* a frame to draw them with. The stars keep their own thin-cloud mask below this. */
if (W_CLOUD < 0.40) return;
var thr = cloudThr(), cols = CB.cols;
var maxRow = Math.floor(CB.horizon); if (maxRow > CB.rows - 1) maxRow = CB.rows - 1;
/* Density and brightness both ride the cover, so the deck arrives as an overcast rather than
* switching on at full strength the moment the threshold is crossed. */
/* Measured down, not chosen. At 0.20 + 0.26 the deck cost 1.3 points of lit coverage on its
* own — the whole budget for a single element, spent on the one thing in the frame that is
* supposed to be a backdrop — and it reads the same here, because what makes a deck read is
* the SHAPE of the field and not how many of its cells got painted. */
var dens = 0.15 + 0.19 * W_CLOUD;
/* THE SWATCH IS shadow AND THAT IS THE WHOLE BUDGET STORY. This was slate first, which is
* the obvious choice and the wrong one: slate is the coverage swatch, printed UP at
* EXPOSURE 2.00 precisely so a facade masses, so a cloud cell at lum 22 came out of the
* print at 141 and counted as a LIT cell. Seven hundred of them turned the sky into the
* brightest flat area in a picture whose subject is a dark street. shadow is the swatch for
* "something is there and it is occluding" — same coverage, printed to a value the eye reads
* as mass rather than as light. */
var base = 26 + 16 * W_CLOUD;
/* Where the sodium underglow is allowed: the bottom sixth of the sky, near the rooftops,
* where ten thousand streetlights are actually pointing. */
var lowRow = CB.horizon - CB.rows * 0.17;
var dist = frame.dist, col, row, sp, dirx, dirz, dy, len, nx, ny, nz, v, i, lum, gl, hue;
for (col = 0; col < cols; col++) {
sp = ((col + 0.5) * 2 / cols - 1) * CB.half;
dirx = CB.fwx + CB.rgx * sp; dirz = CB.fwz + CB.rgz * sp;
for (row = 0; row <= maxRow; row++) {
i = row * cols + col;
if (dist[i] < D_CLOUD) continue; // a rooftop, a blimp, the moon: not sky
dy = (CB.horizon - row) / CB.scale;
len = Math.sqrt(dirx * dirx + dirz * dirz + dy * dy);
nx = dirx / len; ny = dy / len; nz = dirz / len;
v = cloudAt(nx, ny, nz, t);
if (v <= thr) continue;
/* How far past the threshold this cell is, i.e. how deep into the cloud it is looking.
* The core gets the heavier glyph; the edge gets a tick, which is what gives the deck a
* ragged boundary instead of a contour line. */
v = (v - thr) * 4; if (v > 1) v = 1;
/* The dither RIDES that depth, and at a flat density it did not: a deck painted at one
* probability everywhere has an edge as hard as its threshold and reads as a stencil.
* Thinning the fringe to a tenth and massing the core to two fifths is what turns the
* same cell budget into something with an inside and an outside.
* The lattice is the DIRECTION, quantised — the same anchoring the field itself uses.
* Keyed on (col,row) instead it would be welded to the viewport and the whole deck would
* crawl with the camera while the cloud shape stayed put. */
if (hash2((nx * 190) | 0, (ny * 260) | 0, 0x71C3) > dens * (0.30 + 1.2 * v)) continue;
gl = v > 0.62 ? G_TILDE : (v > 0.3 ? G_DASH : G_TICK);
lum = base * (0.55 + 0.75 * v);
hue = P.shadow;
/* The underside of a city's cloud base is lit by the city, and that is the whole reason
* the sky over a town is orange. It is a MINORITY of the low cells and not a band: a
* continuous amber strip along the rooftops is a sunset, and this is one in the morning
* in the rain. Amber has to be given real luminance to survive its own print weight of
* 0.19, so the cells that get it are counted rather than spread. */
if (row > lowRow && v > 0.55 && hash2((nx * 190) | 0, (ny * 260) | 0, 0x71C4) < 0.30) {
hue = P.amber; lum = 44 + 30 * v;
}
plot(frame, col, row, gl, hue, lum, D_CLOUD);
}
}
}
});
/* =================================================================================== stars ==
* surfaces.js already salts the sky with a very faint per-cell field. This is the second layer:
* brighter stars fixed to the celestial sphere, so they hold still while the camera turns
* instead of swimming with the view.
* Altitudes are pushed low on purpose. The frame only reaches atan(horizon/scale) ~= 23 degrees
* above the horizon, so a star placed higher is simply never rendered. 400 over the whole sphere
* puts about ten of them in the slot, which is as many as 700 cells of sky will carry. */
var NSTAR = 400;
var stX, stY, stZ, stL, stC, stG, stPh, stTw;
CC.ELEMENTS.push({
name: 'stars',
layer: 4,
init: function (city, rng) {
var r = fork(rng), i;
stX = new Float32Array(NSTAR); stY = new Float32Array(NSTAR); stZ = new Float32Array(NSTAR);
stL = new Float32Array(NSTAR); stC = new Uint8Array(NSTAR); stG = new Uint8Array(NSTAR);
stPh = new Float32Array(NSTAR); stTw = new Float32Array(NSTAR);
for (i = 0; i < NSTAR; i++) {
var az = r() * TAU, u = r();
var alt = 0.03 + u * u * 0.39; // squared: crowded near the rooftop line
var ca = Math.cos(alt);
stX[i] = Math.sin(az) * ca; stY[i] = Math.sin(alt); stZ[i] = Math.cos(az) * ca;
var m = r();
// A magnitude curve, not a uniform spread: a sky of equally bright dots reads as noise.
stL[i] = 30 + m * m * m * 118;
stC[i] = m > 0.94 ? P.ice : (m > 0.55 ? P.white : P.slate);
stG[i] = m > 0.97 ? G_PLUS : (m > 0.62 ? G_DOT : (r() < 0.5 ? G_QUOTE : G_TICK));
stPh[i] = r() * 60;
stTw[i] = 1;
}
},
update: function (dt, t) {
var still = CC.reducedMotion;
for (var i = 0; i < NSTAR; i++)
stTw[i] = still ? 0.88 : 0.52 + 0.48 * vnoise(t * 0.6 + stPh[i], 0x2A7 + i);
},
draw: function (frame, cam, t) {
setup(frame, cam);
/* Two separate things take the stars away, and they take them away differently.
*
* CLOUD is a MASK, not a dimmer: a star behind cloud is gone and the one in the gap beside it
* is at full brightness. Dimming the whole field instead — which is what this did first —
* reads as somebody turning the sky down, and the eye reads it as an exposure change rather
* than as weather. The threshold sits slightly UNDER the deck's own, so the thin cloud the
* scud was too sparse to paint still takes the stars behind it; the deck itself has already
* taken the rest by winning the depth test at D_CLOUD.
*
* FOG is a dimmer, because that is what fog physically is between here and the star, and it
* goes to zero: in mist there are no stars, only the glow of the street on the underside of
* the murk.
*
* THE MASK HAS AN EDGE ON IT, though, and it is the last hard switch in this file. `> thr`
* against a drifting noise field is a pass/fail test, so a star does not go behind cloud, it
* is deleted: measured with this element alone on an empty frame, frozen camera, through
* CC.Compose.post, the worst single-frame per-cell step was 51.0% of full scale under clear,
* 56.5% under drizzle and 51.4% under rain (0.0% under mist, where the element returns at
* the `vis` test above). One character cell at 0.07 Hz is nowhere near a photosensitivity
* hazard, but it is exactly the "star field that switches off" the brief asks about, and the
* cure is four lines: the last 0.05 of the approach to the threshold is a smoothstep on the
* star's luminance instead of a cliff. The deck drifts at 0.045-0.185 field units per second
* depending on the wind, so that ramp is between a quarter of a second and a second and a
* half of fading — a star going behind a cloud edge, which is what it is. */
var thr = cloudThr() - 0.05, FEATHER = 0.05;
var vis = 1 - W_FOG * 1.25; if (vis <= 0) return; if (vis > 1) vis = 1;
for (var i = 0; i < NSTAR; i++) {
var p = proj(stX[i], stY[i], stZ[i]);
if (!p.ok) continue;
var m = (thr - cloudAt(stX[i], stY[i], stZ[i], t)) / FEATHER;
if (m <= 0) continue;
if (m > 1) m = 1; else m = m * m * (3 - 2 * m);
plot(frame, p.x, p.y, stG[i], stC[i], stL[i] * stTw[i] * vis * m, D_STAR);
}
}
});
/* ==================================================================================== moon ==
* One moon, low, sitting at the end of the avenue. The bearing is NOT random: the only sky the
* viewer ever sees is the wedge straight down the street they are walking, so a moon placed on
* any other bearing is a moon nobody will ever look at. It gets the real lunar drift rate
* (~0.07 mrad/s) and nothing more — a moon you can watch move is not a moon.
* Drawn as a crescent plus a dim rim. The rim is what makes the whole disc read; leaving the
* shadowed three-quarters black is what stops it becoming the brightest slab in the frame. */
var moAz0 = 0, moAlt = 0.2, moR = 0.030, moSeed = 0, moPhase = 0.42, moAz = 0;
CC.ELEMENTS.push({
name: 'moon',
layer: 5,
init: function (city, rng) {
var r = fork(rng);
moAz0 = (r() - 0.5) * 0.26; // the avenue runs +z, which is yaw 0
moAlt = 0.17 + r() * 0.08; // ~10-14 degrees: rooftop height, not overhead
moR = 0.026 + r() * 0.008;
moSeed = (r() * 4294967296) | 0;
// Terminator offset, held past 0.30 so the lit sliver never closes into a dead disc.
moPhase = 0.34 + r() * 0.24;
moAz = moAz0;
},
update: function (dt, t) {
moAz = moAz0 + (CC.reducedMotion ? 0 : t * 7.3e-5);
},
draw: function (frame, cam) {
setup(frame, cam);
var ca = Math.cos(moAlt);
var p = proj(Math.sin(moAz) * ca, Math.sin(moAlt), Math.cos(moAz) * ca);
if (!p.ok) return;
var cx = p.x, cy = p.y;
var rw = moR * CB.colsPerTan / p.w, rh = moR * CB.scale / p.w;
if (rw < 1 || cx + rw < 0 || cx - rw >= CB.cols) return;
/* The moon under weather, which is two effects and not one.
*
* The DISC goes out under cloud. Not gradually and not politely: at the 'rain' preset it is
* already a fifth of itself and by the time the cover is a lid there is no moon at all,
* which is correct and is also the only way the sky over this city can ever look like it
* has changed rather than been recoloured.
*
* The HALO is the opposite shape: it needs something to scatter off, so it is nothing on a
* clear night, strongest through thin cloud and haze, and gone again once the deck is thick
* enough to swallow the moon whole. That rise-and-fall is why it is a product of the haze
* and the REMAINING disc rather than a function of either alone. */
var disc = 1.18 - 1.28 * W_CLOUD; if (disc <= 0.02) return; if (disc > 1) disc = 1;
/* sqrt, not the disc itself. Multiplying by disc linearly made the halo strongest exactly
* where the moon was already bright and killed it at the mid-cover the effect belongs to —
* the square root keeps a scattering term that is still worth something when the disc behind
* it is down to a quarter, which is what a moon in mist actually looks like. */
var halo = (W_HAZE * 0.75 + W_CLOUD * 0.45) * Math.sqrt(disc); if (halo > 1) halo = 1;
if (halo > 0.10) {
/* A ring, dithered, and never a filled disc — a solid glow round the moon is the one thing
* that would make the brightest object in the frame twice the size. It is drawn FIRST so
* the disc itself always wins the cells they share. */
var hr = 2.1, hiw = Math.ceil(rw * hr), hih = Math.ceil(rh * hr), hx, hy, hu, hv, h2;
for (hy = -hih; hy <= hih; hy++) {
for (hx = -hiw; hx <= hiw; hx++) {
hu = hx / rw; hv = hy / rh; h2 = hu * hu + hv * hv;
if (h2 < 1.05 || h2 > hr * hr) continue;
if (hash2(hx, hy, moSeed ^ 0x5D) > 0.34) continue;
/* Falls off from the limb outward, so the ring has an inside edge and a soft outside
* one — the way a real halo sits against the murk that makes it. */
plot(frame, cx + hx, cy + hy, h2 > 2.6 ? G_DOT : G_COMMA, P.ice,
70 * halo * (1 - (h2 - 1.05) / (hr * hr - 1.05)), D_MOON + 1);
}
}
}
var iw = Math.ceil(rw), ih = Math.ceil(rh), dx, dy;
for (dy = -ih; dy <= ih; dy++) {
for (dx = -iw; dx <= iw; dx++) {
var u = dx / rw, v = dy / rh, r2 = u * u + v * v;
if (r2 > 1.02) continue;
var su = u + moPhase;
if (su * su + v * v < 1.0) {
/* Earthshine: the unlit disc is a sparse rim, never a filled grey circle. */
if (r2 > 0.72 && hash2(dx, dy, moSeed ^ 0x3B) < 0.55)
plot(frame, cx + dx, cy + dy, G_DOT, P.slate, 13 * disc, D_MOON);
continue;
}
var lum = (124 + 76 * (1 - r2 * 0.6)) * disc;
// Maria, at a coarse pitch so they read as markings rather than as dither.
if (hash2(Math.floor(u * 2.6), Math.floor(v * 2.6), moSeed) < 0.24) lum *= 0.44;
var gl = r2 > 0.80 ? G_o : (hash2(dx, dy, moSeed ^ 0x91) < 0.5 ? G_8 : G_OO);
plot(frame, cx + dx, cy + dy, gl, P.white, lum, D_MOON);
}
}
}
});
/* ================================================================================ aircraft ==
* Lights at airline distance. No hull and no contrail — at two kilometres the only honest thing
* to draw is the beacon, and one blinking cell is the cheapest depth cue in the file. */
var NAIR = 6, AIR_SPAN = 3200;
var acB, acD, acY, acS, acPh, acOff;
CC.ELEMENTS.push({
name: 'aircraft',
layer: 6,
init: function (city, rng) {
var r = fork(rng), i;
acB = new Float32Array(NAIR); acD = new Float32Array(NAIR); acY = new Float32Array(NAIR);
acS = new Float32Array(NAIR); acPh = new Float32Array(NAIR); acOff = new Float32Array(NAIR);
for (i = 0; i < NAIR; i++) {
acB[i] = (i & 3) * QUARTER + (r() - 0.5) * 0.6; // dealt round the axes as above
acD[i] = 1400 + r() * 1400;
acY[i] = acD[i] * (0.10 + r() * 0.15); // 6-14 degrees up: high, but still in frame
acS[i] = (r() < 0.5 ? -1 : 1) * (58 + r() * 40); // m/s, real cruise
acPh[i] = r() * AIR_SPAN;
acOff[i] = 0;
}
},
update: function (dt, t) {
var tt = CC.reducedMotion ? t * 0.08 : t;
for (var i = 0; i < NAIR; i++) {
var s = (acS[i] * tt + acPh[i]) % AIR_SPAN;
if (s < 0) s += AIR_SPAN;
acOff[i] = s - AIR_SPAN * 0.5;
}
},
draw: function (frame, cam, t) {
setup(frame, cam);
var tt = CC.reducedMotion ? 0 : t;
/* An airliner is at cruise, which is ABOVE the weather: put a lid on the sky and there is
* nothing to see, which is why this is a hard cut-off and not a dimming. Between the two the
* beacon survives longer than the hull does, because a light does. */
var seen = 1.25 - 1.30 * W_CLOUD; if (seen <= 0.03) return; if (seen > 1) seen = 1;
/* Fog does the opposite of hiding it: two kilometres of murk turns one blinking cell into a
* smear a few cells across. The glow is only worth drawing once the fog is real, and it is
* four cells even then — this is a point source at 2 km, not a landing light. */
var glow = W_FOG > 0.34 ? (W_FOG - 0.34) * 1.5 : 0; if (glow > 1) glow = 1;
for (var i = 0; i < NAIR; i++) {
var b = acB[i], sb = Math.sin(b), cb = Math.cos(b), s = acOff[i];
var p = proj(acD[i] * sb + s * cb, acY[i] - CB.eyeY, acD[i] * cb - s * sb);
if (!p.ok) continue;
var px = p.x, py = p.y, pd = p.d; // VP is one scratch; copy before re-plotting
plot(frame, px, py, G_DOT, P.slate, 17 * seen, pd);
var ph = tt * 0.55 + i * 0.4; ph -= Math.floor(ph);
var on = CC.reducedMotion ? 0.33 : (ph < 0.06 ? 1 : 0);
if (!on) continue;
plot(frame, px, py, G_DOT, P.red, 176 * on * seen, pd - 1);
if (glow > 0.02) {
/* The halo is drawn on the four sides only. A ring of eight puts light on the diagonals
* where a two-cell-wide source has none, and at this size that reads as a cross. */
var gl = 74 * glow * on * seen;
plot(frame, px - 1, py, G_DOT, P.red, gl, pd - 0.5);
plot(frame, px + 1, py, G_DOT, P.red, gl, pd - 0.5);
plot(frame, px, py - 1, G_DOT, P.red, gl * 0.7, pd - 0.5);
plot(frame, px, py + 1, G_DOT, P.red, gl * 0.7, pd - 0.5);
}
}
}
});
/* ============================================================================ searchlights ==
* Beams raking the underside of the sky. The one element here with a real coverage risk, so it
* is a dithered line and not a filled cone — and the dither is keyed on the step index alone,
* never on the screen cell, or the motes boil as the beam sweeps.
* A beam reaches the slot from a mast well outside it, which is why these carry most of the
* sky's visible motion even though a mast itself is almost never in frame. */
var NBEAM = 8, BEAM_LEN = 460;
var bmB, bmR, bmYb, bmAz0, bmAmp, bmW, bmPh, bmEl0, bmSeed, bmAz, bmEl;
/* Set once per draw from the weather; module scope rather than arguments because the sample loop
* is the hot path in this file and reads them a hundred and forty times per beam. */
var BEAM_DENS = 0.46, BEAM_GAIN = 1;
CC.ELEMENTS.push({
name: 'searchlights',
layer: 8,
init: function (city, rng) {
var r = fork(rng), i;
bmB = new Float32Array(NBEAM); bmR = new Float32Array(NBEAM); bmYb = new Float32Array(NBEAM);
bmAz0 = new Float32Array(NBEAM); bmAmp = new Float32Array(NBEAM);
bmW = new Float32Array(NBEAM); bmPh = new Float32Array(NBEAM); bmEl0 = new Float32Array(NBEAM);
bmSeed = new Int32Array(NBEAM); bmAz = new Float32Array(NBEAM); bmEl = new Float32Array(NBEAM);
for (i = 0; i < NBEAM; i++) {
/* Two masts per axis, at different ranges and on unrelated phases. One was not enough:
* a beam has to sweep INTO a 20-column window, and a single lamp spends most of its arc
* raking sky the canyon walls have already eaten. */
bmB[i] = (i & 3) * QUARTER + (r() - 0.5) * 0.40;
bmR[i] = (i < 4 ? 230 : 420) + r() * 200;
bmYb[i] = bmR[i] * (0.13 + r() * 0.13); // a rooftop lamp, not a street one
bmAz0[i] = bmB[i] + (r() - 0.5) * 0.4;
bmAmp[i] = 0.30 + r() * 0.26;
bmW[i] = 0.20 + r() * 0.14; // ~25 s a sweep, slow enough to feel idle
bmPh[i] = r() * TAU;
bmEl0[i] = 0.60 + r() * 0.24;
bmSeed[i] = (r() * 4294967296) | 0;
bmAz[i] = bmAz0[i]; bmEl[i] = bmEl0[i];
}
},
update: function (dt, t) {
var tt = CC.reducedMotion ? 0 : t;
for (var i = 0; i < NBEAM; i++) {
bmAz[i] = bmAz0[i] + Math.sin(tt * bmW[i] + bmPh[i]) * bmAmp[i];
// Elevation drifts on its own, unrelated period, so a sweep never traces the same arc back.
bmEl[i] = bmEl0[i] + Math.sin(tt * bmW[i] * 0.37 + bmPh[i] * 1.7) * 0.20;
}
},
draw: function (frame, cam) {
setup(frame, cam);
/* THE FREE DRAMA IN THIS FILE. A searchlight in clear air is not a beam — there is nothing
* between the lamp and your eye to light up — it is a bright dot on a distant roof and a few
* motes near the lens. Put fog in the air and the whole shaft becomes visible along its
* length, which is the one weather transition up here that changes what an object IS rather
* than how bright it is. Both ends of it come out of the same two numbers:
* BEAM_DENS — how much of the shaft has anything in it to scatter off
* BEAM_GAIN — how hard what is there scatters, scaled off rel('fog') so the tuned 62 in
* the loop below still means 62 under the preset it was measured in.
* In mist rel('fog') is 3.3, and the clamp is what stops a wall of white. */
var k = W_FOGREL; if (k > 2.6) k = 2.6;
BEAM_DENS = 0.16 + 0.30 * k; if (BEAM_DENS > 0.80) BEAM_DENS = 0.80;
BEAM_GAIN = 0.40 + 0.60 * k; if (BEAM_GAIN > 1.9) BEAM_GAIN = 1.9;
for (var i = 0; i < NBEAM; i++) {
var sb = Math.sin(bmB[i]), cb = Math.cos(bmB[i]);
var ox = bmR[i] * sb, oz = bmR[i] * cb, oy = bmYb[i] - CB.eyeY;
var p = proj(ox, oy, oz);
if (!p.ok) continue;
var bx = p.x, by = p.y, bd = p.d; // VP is one scratch; copy before re-projecting
var el = bmEl[i], az = bmAz[i], ce = Math.cos(el);
var dx = Math.sin(az) * ce, dy = Math.sin(el), dz = Math.cos(az) * ce;
/* A beam leaning back over the camera puts its tip behind the near plane. Shortening it is
* the right answer — the stub that survives is the part actually in front of us. */
var len = BEAM_LEN, k, ok = 0, tx = 0, ty = 0, td = 0;
for (k = 0; k < 5; k++) {
p = proj(ox + dx * len, oy + dy * len, oz + dz * len);
if (p.ok) { ok = 1; tx = p.x; ty = p.y; td = p.d; break; }
len *= 0.5;
}
if (!ok) continue;
var sx = tx - bx, sy = ty - by;
var asx = sx < 0 ? -sx : sx, asy = sy < 0 ? -sy : sy;
var n = Math.round(asx > asy ? asx : asy);
if (n < 3) continue;
if (n > 140) n = 140;
// The slope picks the stroke, so a near-vertical beam is not a staircase of slashes.
var gl = asy > asx * 1.4 ? G_PIPE : (sx * sy > 0 ? G_BSLASH : G_SLASH);
for (k = 0; k <= n; k++) {
// motes fixed to the beam, not the screen — and thinned out when there is nothing to
// scatter off, which is the clear-air half of the transition described above.
if (hash2(k, i, bmSeed[i]) > BEAM_DENS) continue;
var f = k / n, ff = 1 - f;
/* 62 at the root, not the 46 this started at: a beam only ever shows through a
* dozen cells of slot before a parapet eats the rest, and at 46 those cells were below
* the threshold where the canvas bloom picks them up at all. It is scaled by rel('fog'),
* which is 1.0 under the preset that 62 was measured in — the migration rule — so the
* number above is unchanged on the day it shipped and only moves when the air does. */
plot(frame, bx + sx * f, by + sy * f, k < 3 ? G_COLON : gl,
f < 0.34 ? P.white : P.slate, 62 * BEAM_GAIN * ff * ff * Math.sqrt(ff),
bd + (td - bd) * f);
}
plot(frame, bx, by, G_OO, P.white, 96, bd); // the lamp itself
}
}
});
/* ========================================================================== tower beacons ==
* The far end of the canyon, six or seven kilometres of city past where the raycaster stops
* marching. Nothing in the build says anything about what is out there: the world pass ends at
* 125 m and the slot above the vanishing point is simply empty, which quietly says the city is
* a hundred metres across.
*
* A handful of masts at half a kilometre to two, each with red obstruction lamps on ITS OWN
* period, fixes that for about sixty cells. Out of sync is the entire point — a row of lamps
* blinking together reads as one object and a decoration; blinking independently they read as
* separate structures at different distances, which is the depth cue this end of the frame has
* never had.
*
* They sit at D_TOWER, between the moon and the cloud deck, because that is where they are: a
* kilometre away and UNDER the weather, so the deck must not occlude them — but fog must eat
* them, and does, from the front.
* ========================================================================================== */
var D_TOWER = 9.2e4, NTOWER = 7;
var twB, twR, twH, twPer, twPh, twSeed;
CC.ELEMENTS.push({
name: 'beacons',
layer: 7,
init: function (city) {
var r = forkCity(city, 0x2B9A31), i;
twB = new Float32Array(NTOWER); twR = new Float32Array(NTOWER); twH = new Float32Array(NTOWER);
twPer = new Float32Array(NTOWER); twPh = new Float32Array(NTOWER);
twSeed = new Int32Array(NTOWER);
for (i = 0; i < NTOWER; i++) {
// Dealt round the street axes, for the reason in the file header: anywhere else is nowhere.
twB[i] = (i & 3) * QUARTER + (r() - 0.5) * 0.34;
twR[i] = 520 + r() * 1500;
twH[i] = twR[i] * (0.10 + r() * 0.13); // 6-13 degrees: a tower, not a mountain
/* Real obstruction lamps run at 20-60 flashes a minute and no two installations agree.
* Irrational-ish periods keep any two of them from finding a common beat over a walk. */
twPer[i] = 1.35 + r() * 1.9;
twPh[i] = r() * 10;
twSeed[i] = (r() * 30011) | 0;
}
},
draw: function (frame, cam, t) {
setup(frame, cam);
/* A kilometre of murk. This is the one element in the file that fog hides completely rather
* than diffusing, because there is nothing to diffuse: it is unlit structure and two lamps. */
var vis = 1 - W_FOG * 1.5 - W_HAZE * 0.35; if (vis <= 0.02) return; if (vis > 1) vis = 1;
var tt = CC.reducedMotion ? 0 : t;
for (var i = 0; i < NTOWER; i++) {
var sb = Math.sin(twB[i]), cb = Math.cos(twB[i]);
var ox = twR[i] * sb, oz = twR[i] * cb;
var p = proj(ox, twH[i] - CB.eyeY, oz);
if (!p.ok) continue;
var cx = Math.round(p.x), yTop = p.y, d = p.d;
if (cx < 0 || cx >= CB.cols) continue;
p = proj(ox, twH[i] * 0.42 - CB.eyeY, oz);
if (!p.ok) continue;
var yBot = p.y, row;
if (yBot - yTop < 2) continue; // too far to be anything but its own lamp
if (yBot - yTop > 46) yBot = yTop + 46;
/* Dashed, and dim enough that it is a suggestion of a mast rather than a line drawn on the
* sky. Every other cell, keyed off the tower's own top row so the pattern cannot crawl. */
for (row = Math.round(yTop) + 1; row <= yBot; row++)
if (!((row - Math.round(yTop)) & 1))
plot(frame, cx, row, G_PIPE, P.slate, 15 * vis, D_TOWER);
var ph = tt / twPer[i] + twPh[i]; ph -= Math.floor(ph);
var on = CC.reducedMotion ? 0.5 : (ph < 0.16 ? 1 : 0.10);
plot(frame, cx, yTop, on > 0.5 ? G_STAR : G_DOT, P.red, (40 + 150 * on) * vis, D_TOWER - 1);
// The mid-height lamp, which is what makes a tower read as tall rather than as far.
if (yBot - yTop > 9)
plot(frame, cx, (yTop + yBot) * 0.5, G_DOT, P.red, (24 + 84 * on) * vis, D_TOWER - 1);
}
}
});
/* ============================================================================ rare traffic ==
* Two things that are not there most of the time: a flock crossing the slot, and once in a very
* long while an orbital burn climbing out over the city.
*
* BOTH ARE SCHEDULED, NOT RANDOM, and the schedule is a pure function of t: the cycle index is
* floor(t / period) and everything about that appearance is hashed off the index. That is what
* keeps them scrub-safe — jump the harness to frame 9000 and the same flock is in the same place
* as it was in the browser — and it is also the only honest way to make something rare. A
* per-frame probability gives an event whose spacing is exponential, which in practice means two
* in ten seconds and then nothing for a quarter of an hour.
* ========================================================================================== */
var D_BIRD = 9.3e4, NBIRD = 7, BIRD_CYCLE = 96, SHUTTLE_CYCLE = 214;
var bdSeed = 0, shSeed = 0;
CC.ELEMENTS.push({
name: 'skyrare',
layer: 9,
init: function (city) {
var r = forkCity(city, 0x77E115);
bdSeed = (r() * 30011) | 0;
shSeed = (r() * 30011) | 0;
},
draw: function (frame, cam, t) {
setup(frame, cam);
/* Reduced motion slows the schedule rather than freezing it, the way the aircraft and the
* drones above do: a frozen flock is seven dots parked in the sky, which reads as a defect,
* where a slow one is simply rarer. It also makes these events eight times rarer, which for
* something that is already rare is the right direction to be wrong in. */
t = CC.reducedMotion ? t * 0.12 : t;
var i, k, u, az, el, ca, p;
/* ---- the flock ----------------------------------------------------------------------
* Birds are drawn as SILHOUETTES — dim slate against whatever the sky is doing — because
* that is what a bird over a lit city is at night. A lit bird would be the only object in
* the frame emitting light for no reason.
* Nothing flies in a downpour, which is worth one line of gate and is the kind of detail
* that makes the weather feel like it is being obeyed rather than displayed. */
if (W_RAIN < 0.45) {
k = Math.floor(t / BIRD_CYCLE);
u = t / BIRD_CYCLE - k;
if (hash1(k, bdSeed + 3) < 0.42 && u > 0.10 && u < 0.30) {
var q = (u - 0.10) / 0.20; // 0..1 across the pass, ~19 s of it
var fb = ((k & 3) * QUARTER) + (hash1(k, bdSeed + 9) - 0.5) * 0.5;
var fel = 0.11 + hash1(k, bdSeed + 17) * 0.16;
var dirn = hash1(k, bdSeed + 23) < 0.5 ? -1 : 1;
for (i = 0; i < NBIRD; i++) {
/* The flock is a loose diagonal, not a rank: each bird carries its own lag along the
* course and its own altitude, and the two together are what make seven cells read as
* one flock rather than as seven marks. */
az = fb + dirn * (q - 0.5) * 0.62 + (hash1(i, bdSeed) - 0.5) * 0.10 - i * 0.017 * dirn;
el = fel + (hash1(i, bdSeed + 5) - 0.5) * 0.045;
ca = Math.cos(el);
p = proj(Math.sin(az) * ca, Math.sin(el), Math.cos(az) * ca);
if (!p.ok) continue;
/* The wingbeat is the whole animation and it is one glyph swapping for another: down
* stroke reads as a caret, the glide as a dash. Per-bird phase, or the flock flaps in
* unison like a clockwork toy. */
var wb = CC.reducedMotion ? 0.5
: (t * 3.4 + i * 0.7) - Math.floor(t * 3.4 + i * 0.7);
plot(frame, p.x, p.y, wb < 0.45 ? G_CARET : G_DASH, P.slate,
(26 + 16 * hash1(i, bdSeed + 11)) * (1 - W_FOG * 0.8), D_BIRD);
}
}
}
/* ---- the burn -----------------------------------------------------------------------
* An orbital departure: a very slow, very bright head climbing out of the far skyline with a
* short trail under it. Once every three or four minutes at most, and only when there is a
* gap in the cloud to see it through — a rocket that punches through an overcast would be
* the one object in the sky that ignores the weather everything else obeys. */
if (W_CLOUD > 0.80) return;
k = Math.floor(t / SHUTTLE_CYCLE);
u = t / SHUTTLE_CYCLE - k;
if (hash1(k, shSeed + 1) > 0.5) return; // most cycles have no launch in them
if (u < 0.14 || u > 0.30) return;
var s = (u - 0.14) / 0.16; // 0..1 over about 34 s of climb
var sb2 = ((k & 3) * QUARTER) + (hash1(k, shSeed + 7) - 0.5) * 0.30;
/* Accelerating, because that is what a launch does and because a constant-rate dot reads as
* an aircraft. s*s takes it off the rooftops slowly and out of the top of the frame fast. */
var sel = 0.035 + s * s * 0.42;
var fade = 1 - W_CLOUD * 0.9;
for (i = 0; i < 9; i++) {
el = sel - i * i * 0.0042; // the trail bunches up under the head
if (el < 0.02) break;
az = sb2 + i * 0.0026;
ca = Math.cos(el);
p = proj(Math.sin(az) * ca, Math.sin(el), Math.cos(az) * ca);
if (!p.ok) continue;
plot(frame, p.x, p.y,
i === 0 ? G_STAR : (i < 3 ? G_o : G_DOT),
i === 0 ? P.pure : (i < 4 ? P.ember : P.slate),
(i === 0 ? 235 : 150 / (1 + i * 0.9)) * fade, D_STAR - 2);
}
}
});
/* ================================================================================== blimps ==
* Advertising blimps on long straight courses, five metres a second, wrapping over a kilometre
* of run so the sky never empties. They fly rather than hover for the reason in the header: a
* craft parked on a bearing is either always in the slot or never in it, and both are wrong.
*
* The hull is a filled ellipse, not an outline — the massed-slab rule applies to anything lit,
* and an outlined blimp reads as a wireframe balloon. The fill is nearly black, the rim carries
* the silhouette, and only the marquee is allowed to be bright.
* The marquee steps in CELLS, not in hull fractions, so the text scrolls at a constant rate
* rather than stretching as the blimp closes. */
var NBLIMP = 8, TXTN = 44, BL_SPAN = 1100;
var blB, blD, blY, blL, blH, blSpd, blPh, blHue, blSeed, blOff, blTxt;
var TXT_POOL = null;
CC.ELEMENTS.push({
name: 'blimps',
layer: 12,
init: function (city, rng) {
var r = fork(rng), i, j;
if (!TXT_POOL) TXT_POOL = [G_8, G_0, G_OO, G_X, G_Z, G_HASH, G_H, G_N, G_A, G_V,
G_K, G_Y, G_U, G_M, G_W, G_EQ];
blB = new Float32Array(NBLIMP); blD = new Float32Array(NBLIMP); blY = new Float32Array(NBLIMP);
blL = new Float32Array(NBLIMP); blH = new Float32Array(NBLIMP);
blSpd = new Float32Array(NBLIMP); blPh = new Float32Array(NBLIMP);
blHue = new Uint8Array(NBLIMP); blSeed = new Int32Array(NBLIMP);
blOff = new Float32Array(NBLIMP); blTxt = new Uint8Array(NBLIMP * TXTN);
for (i = 0; i < NBLIMP; i++) {
blB[i] = (i & 3) * QUARTER + (r() - 0.5) * 0.5; // two to each axis
blD[i] = 320 + r() * 300;
blY[i] = blD[i] * (0.16 + r() * 0.13); // 9-16 degrees up, clear of the landmarks
blL[i] = 46 + r() * 26;
blH[i] = blL[i] * 0.23;
blSpd[i] = (r() < 0.5 ? -1 : 1) * (3.4 + r() * 2.4);
blPh[i] = r() * BL_SPAN;
/* The two pillars carry the advertising. Violet is a signage colour and a blimp flank is
* signage, so exactly one hull gets it — a sky with two violet blimps is the cliche the
* references refuse. */
blHue[i] = i === 2 ? P.violet : (i & 1 ? P.azure : P.amber);
blSeed[i] = (r() * 4294967296) | 0;
for (j = 0; j < TXTN; j++) {
var q = r();
// A third of the band is blank. Solid text turns a 30-cell strip into a bright bar.
blTxt[i * TXTN + j] = q < 0.32 ? 0 : TXT_POOL[(q * TXT_POOL.length) | 0];
}
}
},
update: function (dt, t) {
var tt = CC.reducedMotion ? t * 0.12 : t;
for (var i = 0; i < NBLIMP; i++) {
var s = (blSpd[i] * tt + blPh[i]) % BL_SPAN;
if (s < 0) s += BL_SPAN;
blOff[i] = s - BL_SPAN * 0.5;
}
},
draw: function (frame, cam, t) {
setup(frame, cam);
var tt = CC.reducedMotion ? 0 : t;
for (var i = 0; i < NBLIMP; i++) {
var b = blB[i], sb = Math.sin(b), cb = Math.cos(b), s = blOff[i];
var p = proj(blD[i] * sb + s * cb, blY[i] - CB.eyeY, blD[i] * cb - s * sb);
if (!p.ok) continue;
var cx = p.x, cy = p.y, d = p.d;
var rw = blL[i] * 0.5 / p.w * CB.colsPerTan;
var rh = blH[i] * 0.5 / p.w * CB.scale;
if (rw < 2.5 || cx + rw < 0 || cx - rw >= CB.cols) continue;
/* 1.5, not 1.0. At exactly 1.0 the dy = +-1 cells sit at v = 1 and the ellipse test
* u*u + v*v > 1 throws the entire skin away, leaving the marquee floating in the sky with
* no craft under it. 1.5 keeps a skin row above and below across 75% of the length, which
* is the least that still reads as a hull. */
if (rh < 1.5) rh = 1.5;
var sd = blSeed[i], hue = blHue[i], base = i * TXTN;
var scroll = Math.floor(tt * 3.2);
var iw = Math.ceil(rw), ih = Math.ceil(rh), dx, dy;
for (dy = -ih; dy <= ih; dy++) {
for (dx = -iw; dx <= iw; dx++) {
var u = dx / rw, v = dy / rh, r2 = u * u + v * v;
if (r2 > 1) continue;
if (dy === 0) {
if (u > -0.84 && u < 0.84) {
var ti = (dx + scroll) % TXTN; if (ti < 0) ti += TXTN;
var tg = blTxt[base + ti];
if (tg) plot(frame, cx + dx, cy + dy, tg, hue, 132 + hash2(ti, i, sd) * 64, d - 1);
} else {
plot(frame, cx + dx, cy + dy, G_o, P.slate, 30 + hash2(dx, dy, sd) * 14, d);
}
continue;
}
if (r2 > 0.42) {
/* The skin. The underside picks up the city's own sodium glow off the cloud base;
* the top faces nothing but sky, so it stays achromatic. */
if (v > 0) plot(frame, cx + dx, cy + dy, G_UNDER, P.amber,
25 + hash2(dx, dy, sd) * 13, d);
else plot(frame, cx + dx, cy + dy, G_DASH, P.slate,
29 + hash2(dx, dy, sd ^ 0x7) * 15, d);
continue;
}
if (hash2(dx, dy, sd ^ 0x2C) < 0.30)
plot(frame, cx + dx, cy + dy, G_COLON, P.slate, 12, d);
}
}
// Anti-collision strobes on nose and tail: two cells, dark far more often than lit.
var ph = tt * 0.75 + i * 0.37; ph -= Math.floor(ph);
if (CC.reducedMotion || ph < 0.13) {
var al = CC.reducedMotion ? 80 : 204;
plot(frame, cx - rw * 0.94, cy, G_DOT, P.red, al, d - 2);
plot(frame, cx + rw * 0.94, cy, G_DOT, P.red, al, d - 2);
}
/* Gondola: one warm cell hung directly under the hull. Placed off floor(rh), not off
* rh itself, or it detaches from the skin row by a gap of black and reads as a stray. */
plot(frame, cx, cy + Math.floor(rh) + 1, G_DOT, P.warm, 70, d);
}
}
});
/* ================================================================================== drones ==
* Delivery quads crossing the slot. One dark cell of airframe and a navigation light that is
* off most of the time — the blink IS the element, so it has to stay a blink and not a lamp.
* Fast enough (6-12 m/s) that one crosses the window in a couple of seconds. */
var NDRONE = 26;
var drB, drD, drY, drSpd, drPh, drSpan, drStrobe, drOff;
CC.ELEMENTS.push({
name: 'drones',
layer: 13,
init: function (city, rng) {
var r = fork(rng), i;
drB = new Float32Array(NDRONE); drD = new Float32Array(NDRONE); drY = new Float32Array(NDRONE);
drSpd = new Float32Array(NDRONE); drPh = new Float32Array(NDRONE); drSpan = new Float32Array(NDRONE);
drStrobe = new Uint8Array(NDRONE); drOff = new Float32Array(NDRONE);
for (i = 0; i < NDRONE; i++) {
drB[i] = (i & 3) * QUARTER + (r() - 0.5) * 0.7; // six or seven to each axis
drD[i] = 70 + r() * 80;
/* 14-24 degrees up. Higher than it first looks right, and deliberately so: the sky
* wedge is 12 columns wide down by the horizon and 24 at the top of the frame, so a
* corridor flown low is a corridor nobody ever catches sight of. */
drY[i] = drD[i] * (0.24 + r() * 0.18);
drSpd[i] = (r() < 0.5 ? -1 : 1) * (6 + r() * 6);
/* The run is sized to the drone's own range: just past the point where it leaves the
* frustum, so it recycles as often as possible without ever popping into being on screen. */
drSpan[i] = drD[i] * 2.2;
drPh[i] = r() * drSpan[i];
drStrobe[i] = r() < 0.4 ? 1 : 0;
}
},
update: function (dt, t) {
var tt = CC.reducedMotion ? t * 0.1 : t;
for (var i = 0; i < NDRONE; i++) {
var sp = drSpan[i], s = (drSpd[i] * tt + drPh[i]) % sp;
if (s < 0) s += sp;
drOff[i] = s - sp * 0.5;
}
},
draw: function (frame, cam, t) {
setup(frame, cam);
var tt = CC.reducedMotion ? 0 : t;
for (var i = 0; i < NDRONE; i++) {
var b = drB[i], sb = Math.sin(b), cb = Math.cos(b), s = drOff[i];
var p = proj(drD[i] * sb + s * cb, drY[i] - CB.eyeY, drD[i] * cb - s * sb);
if (!p.ok) continue;
var x = p.x, y = p.y, d = p.d;
if (x < -2 || x >= CB.cols + 2) continue;
plot(frame, x, y, G_DASH, P.slate, 30, d);
if (CC.reducedMotion) {
plot(frame, x - 1, y, G_DOT, P.red, 74, d);
plot(frame, x + 1, y, G_DOT, P.spring, 66, d);
continue;
}
// Port red, starboard green, offset in the cycle so the pair never reads as one wide lamp.
var ph = tt * 1.5 + i * 0.41; ph -= Math.floor(ph);
if (ph < 0.12) plot(frame, x - 1, y, G_DOT, P.red, 194, d - 0.5);
if (ph > 0.50 && ph < 0.62) plot(frame, x + 1, y, G_DOT, P.spring, 174, d - 0.5);
if (drStrobe[i] && ph > 0.83 && ph < 0.855)
plot(frame, x, y, G_PLUS, P.pure, 242, d - 1);
}
}
});
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

1423
src/elements/street.js Normal file

File diff suppressed because it is too large Load diff

1297
src/elements/structure.js Normal file

File diff suppressed because it is too large Load diff

1337
src/elements/weather.js Normal file

File diff suppressed because it is too large Load diff

344
src/main.js Normal file
View file

@ -0,0 +1,344 @@
/* CyberCity main — the loop, the viewport, the seed, and nothing else.
*
* There is no game here. Nothing is scored, nothing is aimed, nothing is clicked. The whole of
* "interaction" is: the page may go real-fullscreen if you touch it, and the URL fragment names
* which city you are standing in so a walk can be handed to someone else. Everything past that
* would be UI, and UI is the one thing this piece cannot have.
*/
(function (CC) {
'use strict';
var HAS_DOM = typeof document !== 'undefined' && typeof window !== 'undefined' &&
!!(document && document.createElement);
var STEP = 1 / 60; // simulation tick; elements were written against 60 Hz
var ASPECT = 0.5625; // 9x16 character cell, the proportion surfaces.js was tuned on
var MAXC = 260, MINC = 48, MINR = 22;
var canvas = null, frame = null, city = null, seed = 0;
var cam = { x: 0, z: 0, yaw: 0, eyeY: 1.7, fov: 1.25, horizon: 0, t: 0, cellAspect: ASPECT };
var els = [], cols = 0, rows = 0;
var simT = 0, acc = 0, last = 0, running = false;
var zoom = 1; // adaptive column pressure; 1 = full detail
/* ---- seed ----------------------------------------------------------------------------------
* A city is a pure function of its seed, so the fragment IS the artwork's address. Anything that
* is not an integer is folded with FNV-1a, which means #shinjuku is a perfectly good city and
* people can name their own. */
function seedFromHash() {
var h = (window.location.hash || '').replace(/^#/, '').replace(/^seed=/, '').trim();
if (!h) return null; // null, not 0 — #0 is a legitimate city
/* Literal only within the 32-bit window a seed actually occupies — signed at the bottom so
* #-1 keeps working, unsigned at the top because that is the form replaceState writes and a
* random seed reaches 4294967295. Outside it, `| 0` silently folds (a twenty-digit number
* lands on 0) and the visitor would be moved to somebody else's city, so anything wider
* falls through to the hash below and is at least its own address. */
if (/^-?\d+$/.test(h)) {
var v = parseInt(h, 10);
if (v >= -2147483648 && v <= 4294967295) return v >>> 0;
}
var s = 2166136261;
for (var i = 0; i < h.length; i++) { s ^= h.charCodeAt(i); s = Math.imul(s, 16777619); }
return s >>> 0;
}
/* ---- viewport ------------------------------------------------------------------------------
* Showing LESS city on a small screen is the correct answer; shrinking the cell until the glyphs
* turn to grey mush is not, because the glyph shapes ARE the texture. So the cell width is
* pinned to a legible band and the column count falls out of it, rather than the other way
* round. 1920px lands near 200 columns, a phone near 60. */
function cellCSS(vw) {
var w = vw < 560 ? 6.4 : vw < 1000 ? 7.6 : vw < 1700 ? 8.8 : 9.6;
return w * zoom;
}
function layout() {
var vw = Math.max(window.innerWidth || 320, 200);
var vh = Math.max(window.innerHeight || 240, 160);
/* Capped at 2. A phone at dpr 3 would triple the fill rate of the bloom taps to sharpen glyphs
* that are already sub-pixel-crisp at 2, and the bloom is where the frame budget goes. */
var dpr = Math.min(window.devicePixelRatio || 1, 2);
var dw = Math.max(4, Math.round(cellCSS(vw) * dpr));
var dh = Math.max(7, Math.round(dw / ASPECT));
/* ceil, not round: the canvas is allowed to overhang the viewport by a fraction of a cell.
* Fullscreen must have no seam of page showing at the edge, and a partial cell of city bleeding
* off-screen is invisible where a black gutter would not be. */
var c = Math.ceil(vw * dpr / dw);
if (c > MAXC) { // ultrawide: grow the cell instead of the column count
c = MAXC;
dw = Math.ceil(vw * dpr / c);
dh = Math.max(7, Math.round(dw / ASPECT));
/* dw was just rounded UP, so MAXC of them overshoot the viewport — by a whole cell at
* 3440 and by more once dpr is in play, which is a canvas wider than the screen and a
* picture whose right-hand edge is off it. Re-derive the count from the widened cell. */
c = Math.ceil(vw * dpr / dw);
}
if (c < MINC) c = MINC;
var r = Math.max(MINR, Math.ceil(vh * dpr / dh));
cols = c; rows = r;
CC.Canvas.setGrid(cols, rows, dw, dh, dpr);
frame = CC.makeFrame(cols, rows);
/* horizonBase is the neutral row; cam.horizon is owned by CC.Control from here on, because
* looking up and down IS sliding the horizon (see control.js). Seeded to the neutral value so
* a frame rendered before the first control tick is still correct. */
cam.horizonBase = rows * 0.56;
cam.horizon = cam.horizonBase;
cam.rows = rows;
cam.cellAspect = CC.Canvas.cellAspect;
}
/* ---- world ---------------------------------------------------------------------------------
* Elements size their own buffers off the frame they are handed (the sizeTo pattern), so a
* resize does NOT re-init them — that would restart every rain drop and reshuffle every crowd
* mid-walk. Only a seed change rebuilds the world. */
function build(newSeed) {
seed = newSeed >>> 0;
city = CC.City ? CC.City.make(seed) : null;
cam.x = city && city.startX !== undefined ? city.startX : 0.5;
cam.z = city && city.startZ !== undefined ? city.startZ : 0.5;
/* A new city is a new sky and a fresh walk. Weather gets its OWN rng rather than a draw from
* the element stream below, so adding it did not reshuffle every element's noise. */
if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635));
if (CC.Control) CC.Control.reset();
var rng = CC.mulberry(seed ^ 0x9e3779b9);
/* THE TIE-BREAK IS WRITTEN DOWN, because this sort decides two things and only one of them is
* obvious. Seven pairs of elements share a layer — 7 (beacons | lowcloud), 8 (searchlights |
* fogbank), 12 (blimps | rain), 20 (pedestrians | skybridges), 21 (cat | rooftop-plant),
* 22 (traffic | masts), 24 (litter | cables) — and for each pair the order fixes not just who
* draws over whom but who draws from the ONE shared rng first, which shifts the noise stream
* of every element initialised after them. Array#sort has been stable since ES2019, so the
* ties have always resolved to registration order; sorting the INDICES and falling back to
* them says so in code rather than leaving a reader to know that about their engine.
*
* What this does NOT fix, and cannot fix from here: registration order is concatenation order,
* which build.js takes from readdirSync('src/elements').sort(). Renaming an element file
* across one of those ties would reseed everything downstream of it — measured at 0.8-3.6% of
* the cells of a 400x100 frame. The cure is to sort on (layer, name) so the order belongs to
* the elements instead of to the filesystem, and it has to be made HERE and in
* tools/headless.cjs in the same edit: the harness sorts CC.ELEMENTS itself, and a harness
* ordering elements differently from the browser is an offline reference frame that is not
* the frame the browser draws. */
var seq = CC.ELEMENTS, rank = [], q;
for (q = 0; q < seq.length; q++) rank.push(q);
rank.sort(function (a, b) { return ((seq[a].layer | 0) - (seq[b].layer | 0)) || (a - b); });
els = [];
for (q = 0; q < rank.length; q++) els.push(seq[rank[q]]);
for (var i = 0; i < els.length; i++)
if (els[i].init) els[i].init(city, rng, { cols: cols, rows: rows });
simT = 0; acc = 0;
}
function step(dt, t) {
/* PHOTO MODE. P freezes the city but not the viewer: control.js keeps arbitrating input, so
* look and walk still work and you can compose the shot you stopped for. Everything downstream
* of this line is the simulation — weather, rain, the crowd — and it does not advance.
* Returning here is only half of the freeze; the other half is `simT` being held in tick(),
* because an element whose draw() is a pure function of t (the sky, a sign's flicker, the
* scanline roll) would go on animating no matter how many updates we skipped. */
if (CC.Control && CC.Control.paused) { CC.Control.update(dt, t, cam, city); return; }
/* city.camera, NOT CC.City.camera. CC.City is only { make }; the walk is exported on the
* INSTANCE that make() returns. Guarding on the module put the whole piece in a chair: the
* camera was placed once in build() and never moved again, so a browser showed one still
* frame with rain falling on it. */
/* Weather first — an element updating this tick must see this tick's sky, not last tick's. */
if (CC.Weather) CC.Weather.update(dt, t);
/* Through CC.Control, which arbitrates between the autopilot and whoever is holding the keys.
* With nothing attached and nothing pressed it delegates straight to city.camera, so the walk
* is unchanged and tools/headless.cjs still renders the frame the browser draws.
*
* city.camera, NOT CC.City.camera. CC.City is only { make }; the walk is exported on the
* INSTANCE that make() returns. Guarding on the module put the whole piece in a chair: the
* camera was placed once in build() and never moved again, so a browser showed one still
* frame with rain falling on it. */
if (CC.Control) CC.Control.update(dt, t, cam, city);
else if (city && city.camera) city.camera(cam, city, t);
if (CC.Control && CC.Control.tickHint) CC.Control.tickHint(dt);
for (var i = 0; i < els.length; i++) if (els[i].update) els[i].update(dt, t, cam);
}
function render(t) {
cam.t = t;
CC.clearFrame(frame);
if (CC.Cast) CC.Cast.render(frame, cam, city);
for (var i = 0; i < els.length; i++) if (els[i].draw) els[i].draw(frame, cam, t);
if (CC.Compose && CC.Compose.post) CC.Compose.post(frame, cam, t);
CC.Canvas.draw(frame);
}
/* ---- adaptive quality ----------------------------------------------------------------------
* Degradation is deliberately reluctant and strictly ordered: bloom first, because a single tap
* still reads as light, and only then columns, because fewer columns means literally less city.
* Recovery needs six sustained good seconds so a one-off GC pause cannot make the frame breathe
* in and out of detail while someone is watching it. */
var ema = 16, badSince = 0, goodSince = 0;
function adapt(ms, now) {
ema += (ms - ema) * 0.08;
if (ema > 26) {
goodSince = 0;
if (!badSince) badSince = now;
else if (now - badSince > 1200) {
badSince = now;
if (CC.Canvas.quality > 1) CC.Canvas.setQuality(1);
else if (zoom < 1.3) { zoom = 1.3; layout(); }
}
} else if (ema < 11) {
badSince = 0;
if (!goodSince) goodSince = now;
else if (now - goodSince > 6000) {
goodSince = now;
if (zoom > 1) { zoom = 1; layout(); }
else if (CC.Canvas.quality < 2) CC.Canvas.setQuality(2);
}
} else { badSince = 0; goodSince = 0; }
}
/* ---- loop ----------------------------------------------------------------------------------
* Fixed-step accumulator, so the walk covers the same ground per second on a 144 Hz panel as on a
* 30 Hz one; the elements integrate in ticks and would otherwise run at monitor speed. */
function nowMs() { return window.performance ? performance.now() : Date.now(); }
function tick(now) {
if (!running) return;
window.requestAnimationFrame(tick);
/* Measured from callback entry, not from the rAF timestamp: the gap between the two is the
* browser's own scheduling delay, and charging that to our budget makes the renderer degrade
* itself over somebody else's long task. */
var t0 = nowMs();
var dt = (now - last) / 1000; last = now;
if (!(dt > 0)) dt = STEP;
/* A backgrounded tab hands back a gap of minutes. Fast-forwarding it would burn hundreds of
* ticks on a frame nobody saw, so time simply did not pass while you were away. */
if (dt > 0.25) dt = 0.25;
/* Reduced motion does not mean a frozen picture — a still would lose the piece entirely. It
* means the same walk at roughly a third the pace; the elements damp themselves on top. */
if (CC.reducedMotion) dt *= 0.35;
acc += dt;
var n = 0;
/* simT is held while paused — see step(). The accumulator still drains and step() is still
* called, so control.js gets its ticks at the usual rate and the look keeps its smoothing;
* only the clock the world is a function of stops. */
var frozen = !!(CC.Control && CC.Control.paused);
while (acc >= STEP && n < 5) { if (!frozen) simT += STEP; step(STEP, simT); acc -= STEP; n++; }
if (n === 5) acc = 0; // cannot catch up; drop the debt rather than spiral
render(simT);
adapt(nowMs() - t0, now);
}
/* ---- DOM plumbing --------------------------------------------------------------------------
* Kept to the minimum the contract allows main to own: one canvas, one resize, one fullscreen
* gesture. The fade-out hint is pure CSS in index.html precisely so no code here has to know
* about it or ever remove it. */
var rzT = 0;
function onResize() {
window.clearTimeout(rzT);
/* Debounced: a desktop window drag fires this dozens of times a second and each one
* reallocates the frame, every bloom buffer and the whole glyph atlas. */
rzT = window.setTimeout(function () { layout(); }, 180);
}
function goFullscreen() {
if (document.fullscreenElement || document.webkitFullscreenElement) return;
var e = document.documentElement;
var fn = e.requestFullscreen || e.webkitRequestFullscreen;
if (!fn) return;
/* The try/catch alone was never enough, and nothing had ever run this line in a browser to
* find out. requestFullscreen RETURNS A PROMISE in every current engine; try/catch only ever
* caught the old synchronous webkit form. A denied request — the page is framed without
* allow="fullscreen", the engine did not count this particular keystroke as activation, or
* the user simply refused — then REJECTS, and an unhandled rejection is a red line in the
* console of a piece whose entire claim is that it is one quiet self-contained file that
* asks for nothing. Being refused fullscreen is a perfectly good outcome here; it must just
* be a silent one. */
try {
var p = fn.call(e);
if (p && p.catch) p.catch(function () { });
} catch (err) { /* denied or not user-activated: fine as-is */ }
}
function boot() {
canvas = document.getElementById('cc');
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = 'cc';
document.body.appendChild(canvas);
}
/* Before ANY module initialises: elements read CC.reducedMotion at init time as well as in
* update, so setting it after boot would leave half the city un-damped. */
var mq = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)');
CC.reducedMotion = !!(mq && mq.matches);
if (mq && mq.addEventListener)
mq.addEventListener('change', function (e) { CC.reducedMotion = !!e.matches; });
CC.Canvas.init(canvas);
layout();
var s = seedFromHash();
/* === null, not !s. seedFromHash already distinguishes "no fragment" (null) from "#0", and
* testing falsiness threw that distinction away: #0 built a RANDOM city and then replaceState
* overwrote the user's own fragment with it. */
if (s === null) {
s = (Math.random() * 4294967296) >>> 0;
/* replaceState, not location.hash: writing the hash directly would push a history entry and
* fire hashchange, rebuilding the city we are about to build. */
if (window.history && history.replaceState) history.replaceState(null, '', '#' + s);
}
build(s);
window.addEventListener('resize', onResize, { passive: true });
window.addEventListener('orientationchange', onResize, { passive: true });
document.addEventListener('fullscreenchange', onResize);
// goFullscreen already reaches for the webkit entry point; without its event too, a Safari
// that DID go fullscreen would keep drawing at the old grid until something else resized it.
document.addEventListener('webkitfullscreenchange', onResize);
window.addEventListener('hashchange', function () {
var ns = seedFromHash();
if (ns !== null && ns !== seed) build(ns); // same reason: navigating to #0 is a real move
});
window.addEventListener('pointerdown', goFullscreen, { passive: true });
window.addEventListener('keydown', function (e) {
if (!e.metaKey && !e.ctrlKey && !e.altKey) goFullscreen();
});
/* The keys. `hooks` is how control.js reaches back into main without importing it — it owns
* the input, main owns the city and the canvas, and neither has to know the other's shape. */
if (CC.Control && CC.Control.attach) {
CC.Control.attach(window, document, canvas, {
city: function () { return city; },
now: function () { return simT; },
fullscreen: goFullscreen,
reseed: function () {
var ns = (Math.random() * 4294967296) >>> 0;
if (window.history && history.replaceState) history.replaceState(null, '', '#' + ns);
build(ns);
}
});
/* Pointer lock is a mouse-look, and a mouse-look nobody asked for is a trap: it is only
* requested on a real click, which is also the gesture that goes fullscreen. */
window.addEventListener('pointerdown', function () {
if (CC.Control.requestLook) CC.Control.requestLook();
}, { passive: true });
}
running = true;
last = nowMs();
window.requestAnimationFrame(tick);
}
if (HAS_DOM) {
if (document.readyState === 'loading')
document.addEventListener('DOMContentLoaded', boot);
else boot();
}
/* `cam` is read-only introspection, not an API: it exists so the walk can be PROVEN — driven
* for hundreds of frames offline and checked for pace and for clipping — rather than trusted. */
var Main = { boot: boot, layout: layout, build: build,
get seed() { return seed; }, get cols() { return cols; }, get rows() { return rows; },
get cam() { return cam; } };
CC.Main = Main;
if (typeof module !== 'undefined') module.exports = Main;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

459
src/raycast.js Normal file
View file

@ -0,0 +1,459 @@
/* CyberCity raycaster — voxel-space (heightmap) march at character resolution.
*
* One march per screen COLUMN, front to back, carrying a running silhouette row. Everything the
* frame needs falls out of that single loop: occlusion, stepped rooftops, the slot of sky, and the
* floor, which is nothing more special than terrain of height 0.
*
* Camera model is PLANAR, not cylindrical: dir = forward + right*s, left un-normalised, so the
* march parameter `w` IS the perpendicular (forward-axis) distance and the vertical projection
* needs no cosine fix-up. Straight building edges stay straight and the frame has no barrel bow.
* Radial distance — what fog and the elements' depth test want — is w*|dir|, and |dir| is a
* per-column constant.
*/
(function (CC) {
'use strict';
var P = CC.P, poke = CC.poke, hash2 = CC.hash2, vnoise = CC.vnoise;
var G_COLON = CC.g(':');
/* city.js can emit 58+46 for a landmark. The far-cutoff below must never UNDER-estimate this or
* a tower is dropped from the skyline the instant a nearer roof lifts the silhouette. */
var HMAX = 108;
/* Hard ceiling per column so a degenerate ray can never stall a frame. Never reached in
* practice: the silhouette cutoff (see the end of the march) ends the average column after ~45
* cells and the worst measured column at 146, out of the ~220 a full 125 m march would take.
* That cutoff, not a growing step, is what keeps the far march cheap — and it is exact. A
* geometric step was tried first and was both SLOWER at 400x100 (5.7 ms vs 4.0) and lossy: it
* strides over one-cell slivers of frontage and drops them out of the skyline. */
var MAXSTEP = 512;
/* ---- the record handed to CC.Surf.facade --------------------------------------------------
* city.js stores `seed` as a 0..1 float and surfaces coerces it with `|0`, which would collapse
* every building in the city onto seed 0 — one facade, repeated to the horizon. Widening it into
* a scratch record here is cheaper than reaching into either file. Memoised on the record
* pointer because a column march walks many cells of the same lot in a row.
* `hue` is the district's dominant colour and is the ONLY thing that makes a sodium quarter
* look different from a screen quarter. Dropping it here — which this record used to do —
* silently reduces the whole district system to dead code, because surfaces.js can then do
* nothing but re-roll a hue off the building seed and every district comes out identical. */
/* `h` is the height of THIS COLUMN's cell, not of the lot, and it is set after bindCell rather
* than inside it: city.js drops a lot's outer ring to a podium, so one record can front several
* different heights and the memo would hand the podium the tower's parapet. surfaces.js needs it
* to know where the wall stops — a parapet is the one piece of a facade that cannot be placed
* from u and v alone, and without it a roofline is just where the windows happen to run out. */
var SC = { seed: 0, style: 0, litRate: 0.3, accent: 0, hue: undefined, h: 0 };
var scRec = null;
function bindCell(rec) {
if (rec !== scRec) {
scRec = rec;
SC.seed = (rec.seed * 4294967296) | 0;
SC.style = rec.style | 0;
SC.litRate = rec.litRate;
SC.accent = rec.accent;
SC.hue = rec.hue;
}
return SC;
}
/* ---- signage ------------------------------------------------------------------------------
* city.js hangs a sign box on some lots and nothing else reads it. It is the brightest thing in
* the frame, so it stays small and rare — the whole box is at most 4 m across. */
var SGO = { ch: 0, col: 0, lum: 0 };
function sgset(ch, col, lum) { SGO.ch = ch; SGO.col = col; SGO.lum = lum; return SGO; }
function signPixel(rec, u, v, faceX, t) {
var s = rec.sign;
/* Anchored to the LOT, never to the hit point: a u origin derived from the camera would send
* the sign sliding along the wall as you walk. */
var u0 = (faceX ? rec.lotZ : rec.lotX) + 0.7 + s.seed * 2.2;
var du = u - u0, dv = v - s.y;
if (du < 0 || dv < 0 || du > s.w || dv > s.h) return null;
/* Dark reveal all the way round. Without it the sign fuses with the window grid behind it and
* stops reading as an object hung off the building. */
if (du < 0.22 || dv < 0.22 || s.w - du < 0.22 || s.h - dv < 0.22)
return sgset(0, P.shadow, 0);
if (s.vertical) { // blade sign: stacked characters, gapped
var seg = dv / 1.5; seg -= Math.floor(seg);
if (seg > 0.72) return sgset(0, P.shadow, 0);
}
var sd = (s.seed * 4294967296) | 0;
var h = hash2(Math.floor(du * 2.4), Math.floor(dv * 2.4), sd);
/* A slow whole-sign pulse plus tube-by-tube ageing, keyed on t and the sign's own seed alone.
* Any camera term in here and the signage boils as you walk. */
var pulse = CC.reducedMotion ? 0.93 : 0.86 + 0.14 * vnoise(t * 0.7 + s.seed * 40, 0x51);
return sgset(s.glyph, s.hue, (172 + h * 66) * (h < 0.10 ? 0.3 : 1) * pulse);
}
/* ---- the canyon the floor texture is drawn against ----------------------------------------
* surfaces.js models one street, running along +z, with its centreline at a world x. The city
* has two street directions and the walk uses both, so pick whichever one the camera is standing
* in and, for a cross street, hand floorTex its coordinates transposed — otherwise the kerbs and
* the centreline run across the view instead of away from it, and the road stops reading as a
* road at all.
* The kerb is also pulled 1.4 m in off the building line: city.js has the facades abutting the
* carriageway, and a kerb painted hard against a wall reads as a skirting board, not a street. */
var swapFloor = 0;
/* Latched across frames on purpose. A bare afx>afz comparison flips the ENTIRE floor texture
* space in one 16 ms frame the moment the heading crosses 45 deg inside an intersection —
* measured at +123% floor luminance and +18.9% of the whole frame on seed 1 frame 2176. The
* margin below makes the flip wait until the heading has clearly committed, which is the middle
* of the corner pan, where the whole image is already sliding ~2.4 columns per frame and the
* change is masked. */
var swapLatch = 0;
/* The argument object for CC.Surf.configure(), hoisted and refilled in place. It used to be an
* object literal built inside configureFor, which made it the last structural per-frame
* allocation in the whole frame path — a V8 sampling heap profile over 900 frames at 260x100
* put `render @ raycast.js` at 4.7 B/frame, and every other entry in that profile was either
* unavoidable HeapNumber boxing on a double return or the city's lazy chunk cache. The shape is
* fixed and known, so there is no reason to hand the collector a fresh one sixty times a second.
* configure() copies these into CFG, so the scratch is never retained. */
var CFGARG = { grid: 8.0, streetX: 4.0, streetPeriod: 0, half: 3.1,
horizon: 33.6, rows: 60, skyVScale: 1 };
/* One neutral-camera row, in the elevation units Surf.sky hashes on. cellAspect/2/tan(fov/2) at
* the neutral fov 1.25 is what `scale` works out to per column, so dividing the live scale back
* out gives 1.0 whenever the camera is at that fov and grows as it zooms in — which is what
* makes the star field magnify under zoom instead of being re-dealt. */
var SKY_NEUTRAL = 0.5625 / (2 * Math.tan(0.625));
function configureFor(city, camx, camz, fwx, fwz, horizon, rows, scale, cols) {
var cx = 4.0, hw = 3.1;
swapFloor = 0;
if (city && city.aveX) {
var k = Math.round(camx / city.AVE), m = Math.round(camz / city.CROSS);
var aC = 0, aW = 0, cC = 0, cW = 0, bA = 1e18, bC = 1e18, i, c, d;
for (i = k - 1; i <= k + 1; i++) {
c = city.aveX(i) + 0.5; d = camx - c; if (d < 0) d = -d;
if (d < bA) { bA = d; aC = c; aW = city.aveW(i) + 0.5; }
}
for (i = m - 1; i <= m + 1; i++) {
c = city.crossZ(i) + 0.5; d = camz - c; if (d < 0) d = -d;
if (d < bC) { bC = d; cC = c; cW = city.crossW(i) + 0.5; }
}
/* Standing in an intersection both are true, so the tiebreak is which way we are looking. */
var onAve = bA <= aW, onCross = bC <= cW;
var afz = fwz < 0 ? -fwz : fwz, afx = fwx < 0 ? -fwx : fwx;
var want;
if (onCross && !onAve) want = 1;
else if (!onCross) want = 0;
else want = swapLatch ? (afz > afx * 1.35 ? 0 : 1) // 1.35 either way = a dead band the
: (afx > afz * 1.35 ? 1 : 0); // heading cannot chatter across
swapLatch = want;
if (want) { swapFloor = 1; cx = cC; hw = cW; }
else { cx = aC; hw = aW; }
hw = hw - 1.4; if (hw < 1.6) hw = 1.6;
}
/* streetPeriod 0 disables the wrap: we know the real centreline, and a wrapped copy of the
* road markings would surface on pavements and down alleys where there is no road. */
CFGARG.grid = 8.0; CFGARG.streetX = cx; CFGARG.streetPeriod = 0; CFGARG.half = hw;
CFGARG.horizon = horizon; CFGARG.rows = rows;
/* Surf.sky hashes its vertical on an ELEVATION, and only the caster knows the projection that
* turns a screen row into one. A guard for the degenerate case: a caller that hands us a zero
* or absent scale must not put a NaN into every sky cell in the frame. */
CFGARG.skyVScale = (scale > 0 && cols > 0) ? (SKY_NEUTRAL * cols) / scale : 1;
CC.Surf.configure(CFGARG);
loadCrossings(city, camx, camz);
}
/* ---- where the cross streets cut the one we are standing in --------------------------------
* surfaces.js draws the junction — the crossing, the stop line, the box hatch, and the fact that
* the kerb STOPS — and it has no city to ask where a junction is, so the world pass loads them.
* They are handed over in the axis floorTex reads as wz, which is the transposed one when the
* camera has committed to a cross street: get that wrong and every crossing in the frame is
* painted down the road instead of across it.
*
* Written straight into the config's fixed-length arrays. Eight is comfortably more than the
* ~125 m of visible street can hold at a 26 m pitch, and allocating a fresh list per frame in
* the one function the whole world pass runs through is exactly the kind of garbage this
* renderer is built to avoid. */
function loadCrossings(city, camx, camz) {
var cf = CC.Surf.cfg;
if (!city || !city.aveX) { cf.xn = 0; return; }
/* Along the street we are ON, the streets that CROSS it are the other family. */
var along = swapFloor ? camx : camz; // the coordinate floorTex sees as wz
var pitch = swapFloor ? city.AVE : city.CROSS;
var n = 0, i, k0 = Math.round(along / pitch);
/* One behind, six ahead: the frame only shows what is in front, and a junction just behind the
* camera still owns the kerb the camera is standing next to. */
for (i = k0 - 1; i <= k0 + 6 && n < 8; i++) {
cf.xc[n] = (swapFloor ? city.aveX(i) : city.crossZ(i)) + 0.5;
/* Same 1.4 m inset the kerb takes, for the same reason: city.js abuts the facades to the
* carriageway and a junction mouth measured to the building line swallows both pavements. */
var w = (swapFloor ? city.aveW(i) : city.crossW(i)) + 0.5 - 1.4;
cf.xw[n] = w < 1.6 ? 1.6 : w;
if (n === 0) cf.xz0 = cf.xc[0];
n++;
}
cf.xn = n;
/* The pitch is published with them so floorTex can INDEX the nearest entry instead of scanning
* all of them: it asks this question once per floor cell, which is twenty thousand times a
* frame, and city.js's jitter is bounded well under half a block so the arithmetic guess is
* never more than one slot out. */
cf.xpitch = pitch;
}
/* ---- floor by inverse projection ----------------------------------------------------------
* Every floor row gets its OWN distance. Painting a span of rows from one marched sample would
* stretch metres of tarmac across rows that are tens of metres apart in world space. */
function floorRow(frame, i, r, rowC, ox, oz, dx, dz, len, horizon, scale, eyeY, t) {
var Surf = CC.Surf, den = rowC - horizon;
/* The row the horizon line falls on looks at tarmac an unbounded distance away. Black, but a
* large FINITE depth rather than Infinity — Infinity is reserved for sky, and an element that
* depth-tests against it would punch through the road. */
if (den < 1e-3) { poke(frame, i, 0, P.shadow, 0, 1e6, 2); mirA[r] = 0; return; }
var w = eyeY * scale / den, d = w * len;
var px = ox + dx * w, pz = oz + dz * w;
var o = swapFloor ? Surf.floorTex(pz, px, d, t) : Surf.floorTex(px, pz, d, t);
poke(frame, i, o.ch, o.col, Surf.fog(o.lum, d), d, 2);
/* Parked for the reflect pass at the end of the column. It cannot run here: the wall this
* cell is going to mirror has not been painted yet. */
mirA[r] = o.mir; ripA[r] = o.rip; wchA[r] = o.wch;
}
/* ---- reflections ---------------------------------------------------------------------------
* A puddle mirroring a sign is the defining image of this genre and it cannot be faked from
* inside surfaces.js, which has no frame and no camera: the old wet-road code invented a
* plausible hue per strip and the result never matched the wall standing over it. So the water
* is decided there and the COLOUR is fetched here, once the column above is finished.
*
* THE MIRROR IS THE HORIZON ROW. A point at height h and forward distance D lands on row
* `horizon - (h - eyeY)*scale/D`, and its reflection in the ground plane lands on
* `horizon + (h + eyeY)*scale/D`. Those are not quite reflections of each other about the
* horizon — the difference is 2*eyeY*scale/D, which is to say the cheap mirror shows the world
* 3.4 m taller than it is. On a thirty-metre wall that is a tenth of its height and nothing the
* eye can catch; in exchange the reflection is anchored exactly at the horizon, which is where
* every reflection anyone has ever seen is anchored, and it follows cam.horizon so it stays
* anchored when the camera pitches.
*
* Scratch is per COLUMN and lives for the length of one march, so the whole pass costs three
* floats per row and no allocation after the first frame at a given size.
*/
var mirA = new Float32Array(0), ripA = new Float32Array(0), wchA = new Uint8Array(0);
function scratch(rows) {
if (mirA.length === rows) return;
mirA = new Float32Array(rows); ripA = new Float32Array(rows); wchA = new Uint8Array(rows);
}
function reflectColumn(frame, x, cols, rows, horizon) {
var Surf = CC.Surf;
var r0 = horizon < 0 ? 0 : (horizon | 0);
for (var r = r0; r < rows; r++) {
var m = mirA[r];
if (m < 0.06) continue;
var i = r * cols + x;
if (frame.kind[i] !== 2) continue; // something took the cell after the floor did
var sr = Math.floor(2 * horizon - r - 0.5 + ripA[r]);
if (sr < 0 || sr >= r) continue; // above the frame, or not actually above the cell
var j = sr * cols + x;
var sl = frame.lum[j];
/* YOU SEE REFLECTIONS OF LIGHTS, not of dim structure, and this threshold is the whole
* difference between a wet street and a grey one. The world pass carries tens of thousands
* of cells of spandrel and mullion at lum 8-40.
*
* THE INVERSION THAT ORIGINALLY JUSTIFIED THE THRESHOLD IS GONE, and saying so is the point
* of this paragraph. It used to read: core.js prints slate at 2.00 and white at 1.15, so a
* reflection of a dead concrete panel at lum 30 comes back out of the print BRIGHTER than the
* amber kerb it is lying next to — which was true (slate lum 30 printed v 80 against the
* kerb's v 96-126, and white lum 30 printed v 112, over the kerb). On the current table slate
* is 0.60, white is 0.30 and amber is 0.50: slate at lum 30 prints v 51, white v 31, and the
* kerb prints v 137-179. Nothing dim outranks anything lit any more; the print stopped doing
* this file's argument for it.
*
* The threshold stays, because the OTHER half was never about the curve. Reflecting
* everything turned the road into a pale grey mirror of the building's own shadows — measured
* at 44% of the floor's lit energy in white, which is a COVERAGE fact: there are simply more
* dim structural cells above a puddle than lit ones, whatever they print at. Reflecting only
* what is actually emitting turns it into a black road with the signage lying in it, which is
* the picture. The numbers 55 and 118 are now conservative rather than forced, and lowering
* them is a legitimate experiment that has to be measured on white's share of the floor.
*
* Two figures, because there are two mechanisms here. Standing water is a mirror and will
* show anything lit. Dry tarmac — mir sitting at its 0.13 bounce floor — only shows a source
* bright enough to LIGHT it, which is a sign or a lit window and nothing else.
*
* A dark wall over water leaves the water dark. That is not a gap, it is the answer. */
if (sl < (m > 0.22 ? 55 : 118) || frame.ch[j] === 0) continue;
/* A reflection is a fraction of its source and it is attenuated by the distance to the
* WATER, not to the wall: the puddle is the thing being looked at. Both terms already
* carry their own fog, which is why this reads as depth rather than as a decal.
*
* THE FRACTION IS LARGE, and THE PRINT-CURVE HALF OF THAT ARGUMENT NO LONGER HOLDS. It read:
* core.js prints amber through a gain of 0.19 with a knee at 0.055, so an amber cell does not
* clear the knee until lum 74, and a reflection at a quarter of its source renders a sign at
* 200 as lum 50, which prints BLACK. Every number in that sentence has moved — amber is at
* gain 0.50 and KNEE is 0.075, so amber's knee is at lum 38 and it is over the visibility
* floor from lum 10. The worked example now comes out the other way round: a sign at 200
* reflected at a quarter is lum 50, and lum 50 prints v 98, which is not black but a legible
* reflection. The refit did not just brighten the sums, it removed the failure mode this
* fraction was sized to dodge.
*
* The fraction is kept at 0.30-0.90 anyway, on the physics alone, which is what the old
* comment listed second: water at the grazing angle a street is seen at reflects most of what
* hits it. Note what that means for anyone tuning it — the floor is now taste and geometry,
* not a cliff. A quarter would no longer give a dry road; it would give a dimmer wet one. */
var add = Surf.fog(sl * (0.30 + 0.60 * m), frame.dist[i]);
if (add < 5) continue;
var own = frame.lum[i];
if (add > own) {
/* Water takes its colour from what is above it — that is the whole point, and it is why
* this branch overwrites the swatch instead of blending toward it. Blending two palette
* indices is not a thing this renderer can do; picking the brighter of the two sources is. */
/* The glyph for a cell the floor left black comes from surfaces.js, because it has to be
* keyed on WORLD position: chosen here, off the column and the row, it would re-roll every
* frame and the water would boil while the puddle stood still. G_COLON is only the
* belt-and-braces answer for a floor row that never ran floorTex at all. */
var ch = frame.ch[i];
if (ch === 0) ch = wchA[r] || G_COLON;
poke(frame, i, ch, frame.col[j], add + own * 0.3 > 255 ? 255 : add + own * 0.3,
frame.dist[i], 2);
} else if (frame.ch[i] !== 0) {
/* Damp tarmac that is already carrying its own tone just gets a little of the glow. */
poke(frame, i, frame.ch[i], frame.col[i], own + add * 0.45, frame.dist[i], 2);
}
}
}
/* ---- the pass ------------------------------------------------------------------------------ */
function render(frame, cam, city) {
var Surf = CC.Surf;
if (!Surf) throw new Error('CC.Cast needs surfaces.js loaded first');
var cols = frame.cols, rows = frame.rows;
/* Grid size is never assumed: horizon and fov arrive on the camera, everything else is
* derived from cols/rows. */
var horizon = cam.horizon !== undefined ? cam.horizon : rows * 0.56;
var fov = cam.fov || 1.25;
var eyeY = cam.eyeY !== undefined ? cam.eyeY : 1.7;
var halfPlane = Math.tan(fov * 0.5);
/* fov and scale over-specify the camera. A character cell is about half as wide as it is
* tall, so the moment the horizontal fov is fixed, the vertical rows-per-metre that keeps a
* square metre square on screen is fixed with it — one free parameter, not two. The harness's
* rows*0.9 corresponds to a 92 degree fov at 200x60 and 102 at 400x100, so honouring it
* literally flattens the canyon further the wider the grid gets, and the height of the walls
* is the entire subject. fov wins; the vertical scale is reconciled to it. cam.scaleY is the
* escape hatch for a caller that really does want a different vertical zoom. */
var cellA = cam.cellAspect || 0.5625; // 9x16 cell, as tools/topng.py draws
var scale = cam.scaleY !== undefined ? cam.scaleY : (cols * cellA) / (2 * halfPlane);
var t = cam.t || 0;
var ox = cam.x, oz = cam.z, yaw = cam.yaw || 0;
var fwx = Math.sin(yaw), fwz = Math.cos(yaw); // yaw 0 faces +z, as city.camera assumes
var rgx = Math.cos(yaw), rgz = -Math.sin(yaw);
/* Past the end of the fog ramp fog() returns 0, so marching further is work that can only
* produce black — and the weather MOVES that end, so it is asked for rather than assumed.
* beginFrame also syncs surfaces.js's once-per-frame weather cache, which every per-cell call
* below reads, so it has to happen before the first of them. */
var FAR = Surf.beginFrame ? Surf.beginFrame(t) : Surf.FOG_END;
scratch(rows);
configureFor(city, ox, oz, fwx, fwz, horizon, rows, scale, cols);
/* Stars are fixed to the world, not to the view; without this they ride the camera round.
*
* What Surf.sky is keyed on has to be an ANGLE, and the old `skyOff = (yaw/fov)*cols` added to
* a raw column index was not one. It is the bearing measured in units of "one column at the
* CURRENT fov", so the unit itself changed the moment the wheel was touched: zooming did not
* magnify the star field, it re-dealt it. One 0.045 notch off control.js's zoom re-rolled
* 291 of 298 lit sky cells at seed 3 with the camera not having moved a millimetre, and
* skyOff alone slid 12 columns per notch near yaw +-pi/2.
*
* So the index is the column's true world BEARING, yaw + atan(sp), on a quantisation pinned to
* the neutral fov rather than the live one. A first attempt at this used the linear bearing
* yaw + fov*(x/cols - 0.5), and it was still wrong for the same reason in miniature: the
* linear form is exact only at the frame edges, and its error in the middle scales with fov,
* which walked the field about three columns across control.js's 1.02..1.52 range. atan is the
* exact inverse of the sp the ray was built from, so it removes the dependence outright rather
* than shrinking it. It costs one atan per COLUMN — not per cell — which is 260 a frame.
*
* Math.floor rather than |0 because |0 truncates toward zero, which maps -0.5 and +0.5 onto
* the same index and prints one duplicated column of sky wherever the bearing crosses zero —
* and with the bearing now centred on the view axis, that crossing is on screen. */
var skyK = cols / 1.25; // index units per radian; one column at fov 1.25
for (var x = 0; x < cols; x++) {
var sp = (2 * (x + 0.5) / cols - 1) * halfPlane;
/* This column's world bearing, quantised for Surf.sky. Hoisted out of the sky loop below
* because it is a property of the column, not of the row. */
var skyX = Math.floor((yaw + Math.atan(sp)) * skyK);
var dx = fwx + rgx * sp, dz = fwz + rgz * sp;
var len = Math.sqrt(1 + sp * sp); // w * len == radial distance
var wFar = FAR / len;
var cx = Math.floor(ox), cz = Math.floor(oz);
var sX = dx > 0 ? 1 : -1, sZ = dz > 0 ? 1 : -1;
var adx = dx === 0 ? 1e30 : Math.abs(1 / dx), adz = dz === 0 ? 1e30 : Math.abs(1 / dz);
var mX = (dx > 0 ? (cx + 1 - ox) : (ox - cx)) * adx;
var mZ = (dz > 0 ? (cz + 1 - oz) : (oz - cz)) * adz;
var sil = rows; // rows [sil, rows-1] are painted; sil==0 means the column is done
var w = 0, faceX = 1, steps = 0;
while (sil > 0 && steps++ < MAXSTEP) {
/* Cell-exact traversal, which is what hands us the entry distance and the crossed face
* for free — no back-projection, no bisection, and no chance of striding over a one-cell
* sliver of frontage and opening a hole in the wall. */
if (mX < mZ) { w = mX; mX += adx; cx += sX; faceX = 1; }
else { w = mZ; mZ += adz; cz += sZ; faceX = 0; }
if (w > wFar) break;
var h = city ? city.height(cx, cz) : 0;
if (h <= 0) continue;
var topRow = horizon - (h - eyeY) * scale / w;
if (topRow > sil - 0.5) continue; // wholly behind what is already painted
var r0 = Math.ceil(topRow - 0.5); if (r0 < 0) r0 = 0;
var dist = w * len;
var grF = horizon + eyeY * scale / w; // screen row of the wall's base
/* u runs along the face that was actually crossed, taken at the hit point in WORLD
* coordinates. This is the whole ballgame: derive u from anything camera-relative and the
* windows slide sideways down the wall as you walk instead of translating with it. */
var u = faceX ? (oz + dz * w) : (ox + dx * w);
var rec = city.cell(cx, cz);
var sc = rec ? bindCell(rec) : null;
if (sc) sc.h = h;
var sign = rec && rec.sign;
for (var r = sil - 1; r >= r0; r--) {
var rowC = r + 0.5, i = r * cols + x;
if (rowC > grF) {
/* Below the wall's base: street in FRONT of the building, at its own distance. */
floorRow(frame, i, r, rowC, ox, oz, dx, dz, len, horizon, scale, eyeY, t);
continue;
}
mirA[r] = 0; // wall, not water: nothing here reflects anything
var v = eyeY + (horizon - rowC) * w / scale;
var o = Surf.facade(u, v, sc, dist, t);
var ch = o.ch, cl = o.col, lm = o.lum, sg;
if (sign && (sg = signPixel(rec, u, v, faceX, t))) { ch = sg.ch; cl = sg.col; lm = sg.lum; }
poke(frame, i, ch, cl, Surf.fog(lm, dist), dist, 1);
}
sil = r0;
/* Nothing beyond this distance can clear the silhouette even at the city's tallest, so the
* rest of the march is provably invisible. In a canyon this ends most columns early. */
var room = horizon - sil + 0.5;
if (room > 0.5) {
var wCut = (HMAX - eyeY) * scale / room;
if (wCut < wFar) wFar = wCut;
}
}
/* Whatever the march never reached: distant road below the horizon, sky above it. */
for (var q = sil - 1; q >= 0; q--) {
var j = q * cols + x, qc = q + 0.5;
if (qc > horizon) {
floorRow(frame, j, q, qc, ox, oz, dx, dz, len, horizon, scale, eyeY, t);
} else {
var s = Surf.sky(skyX, q, t);
poke(frame, j, s.ch, s.col, s.lum, Infinity, 0);
}
}
/* The column is complete, so the water can now be told what it is standing under. */
reflectColumn(frame, x, cols, rows, horizon);
}
return frame;
}
var Cast = { render: render, HMAX: HMAX };
CC.Cast = Cast;
if (typeof module !== 'undefined') module.exports = Cast;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

244
src/render_canvas.js Normal file
View file

@ -0,0 +1,244 @@
/* CyberCity canvas renderer — glyph atlas, one drawImage per lit cell, then bloom.
*
* This is the ONLY module that touches the DOM or a 2D context. Everything above it produced a
* frame of typed arrays; everything here is about getting those ~13000 cells onto glass at 60 Hz
* and then putting the light back into them.
*
* BLOOM IS NOT DECORATION. The art direction is 55%+ pure black with a thin scatter of very bright
* glyphs; drawn flat, that reads as a text dump. The halo is what makes a sodium lamp look like it
* is emitting rather than printed, and it is the only thing that fuses the dim mullion glyphs into
* the massed slab a facade is supposed to be. The offline reference renderer (tools/topng.py) bakes
* the same two-radius glow, so this pass exists to keep the browser honest against it.
*/
(function (CC) {
'use strict';
var PALETTE = CC.PALETTE, GLYPHS = CC.GLYPHS;
var NG = GLYPHS.length, NP = PALETTE.length;
/* Bold, because the references read as MASS. A regular weight at 9px leaves the mullion glyphs
* too thin to fuse into a slab and the facade dissolves into a lattice. */
var FAMILY = '"Liberation Mono","DejaVu Sans Mono","Menlo","Consolas","Courier New",monospace';
/* Below this the glyph contributes less than one 8-bit level after the black background and the
* bloom composite — drawing it is pure cost. Measured: skips ~4% of cells, no visible change. */
var LUM_FLOOR = 4;
/* globalAlpha, NOT a per-lum atlas tier. Two reasons, both load-bearing:
* 1. On a pure black destination, source-over with alpha a is exactly dst = src*a — the same
* multiply the palette/lum model specifies, with no quantisation.
* 2. lum carries depth here (Surf.fog ramps it over 113 m). Tiering it into 8 or 16 steps puts
* visible contour bands across every long wall and down the whole road surface, which is the
* one gradient in the frame the eye actually tracks.
* The state change costs a few percent of the glyph pass; the banding would cost the image. */
var canvas = null, ctx = null;
var scene = null, sctx = null; // glyph pass lands here, bloom reads it
var b2 = null, b4 = null, b8 = null; // 1/2, 1/4, 1/8 downsample chain
var atlas = null, actx = null;
var cols = 0, rows = 0, dw = 0, dh = 0, W = 0, H = 0, dpr = 1;
var quality = 2;
/* Bloom radii, in device pixels, recomputed from the cell in setGrid. They are NOT constants:
* a fixed 1.2px halo is half a glyph wide at dpr 1 and a quarter of one at dpr 2, so the piece
* would look softer on a cheap monitor than on a retina one. Expressed as a fraction of the cell
* they hold the same look at every density and every column count. */
var rTight = 1, rWide = 1, rMid = 1;
var advance = 0.6; // measured monospace advance, em units
/* ctx.filter is absent on older WebKit. Probed once: assigning an unsupported value leaves the
* property at 'none', so a read-back is the only honest test. */
var HAS_FILTER = false;
function probeFilter() {
try {
var c = document.createElement('canvas').getContext('2d');
c.filter = 'blur(2px)';
HAS_FILTER = c.filter !== 'none' && c.filter !== '' && c.filter !== undefined;
} catch (e) { HAS_FILTER = false; }
}
function mkCanvas(w, h) {
var c = document.createElement('canvas');
c.width = w < 1 ? 1 : w; c.height = h < 1 ? 1 : h;
return c;
}
/* ---- glyph atlas ---------------------------------------------------------------------------
* Every glyph pre-rendered once per palette colour. A cell then costs one drawImage of an
* integer-aligned tile — no fillText in the frame loop, no per-cell fillStyle string, no shaping.
* Rebuilt only when the cell box or the font size changes, i.e. on resize, not on frame. */
function buildAtlas() {
atlas = mkCanvas(NG * dw, NP * dh);
actx = atlas.getContext('2d');
/* The advance ratio is measured, never assumed 0.6: the family that actually resolves may be a
* fallback with a different one, and guessing would leave the glyph either clipped by its cell
* or floating in it. */
actx.font = 'bold 100px ' + FAMILY;
advance = actx.measureText('M').width / 100 || 0.6;
var fontPx = dw / advance;
if (fontPx > dh * 0.98) fontPx = dh * 0.98; // never let a tall cell clip the ink vertically
actx.font = 'bold ' + fontPx.toFixed(2) + 'px ' + FAMILY;
actx.textAlign = 'center';
actx.textBaseline = 'alphabetic';
/* Centre the ink box of an ascender+descender pair rather than parking the baseline at a
* fixed fraction: with a fallback font that would drop ',' and '_' out of the bottom of the
* cell, and those two glyphs are most of the far-distance road texture. */
var m = actx.measureText('Xg');
var asc = m.actualBoundingBoxAscent || dh * 0.72;
var desc = m.actualBoundingBoxDescent || dh * 0.20;
var base = Math.round((dh - asc - desc) * 0.5 + asc);
if (base > dh - 1) base = dh - 1;
if (base < 1) base = 1;
var cx = dw * 0.5;
for (var p = 0; p < NP; p++) {
var rgb = PALETTE[p];
actx.fillStyle = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
var y = p * dh + base;
for (var gI = 1; gI < NG; gI++) // 0 is blank by contract; never drawn
actx.fillText(GLYPHS[gI], gI * dw + cx, y);
}
}
/* ---- sizing -------------------------------------------------------------------------------- */
function setGrid(nCols, nRows, cellW, cellH, devicePR) {
/* Compared AFTER the |0, not before: a caller handing in 19.0 and then 19 must not rebuild the
* atlas, which is 588 fillText calls and the most expensive thing in this file. */
var w = cellW | 0, h = cellH | 0;
var reAtlas = (w !== dw || h !== dh);
cols = nCols | 0; rows = nRows | 0;
dw = w; dh = h; dpr = devicePR || 1;
W = cols * dw; H = rows * dh;
canvas.width = W; canvas.height = H;
canvas.style.width = (W / dpr) + 'px';
canvas.style.height = (H / dpr) + 'px';
scene = mkCanvas(W, H); sctx = scene.getContext('2d', { alpha: false });
/* Bloom taps are downsampled: a half-resolution blur of the whole frame is 4x cheaper than a
* full one and the halo has no detail worth preserving anyway. The chain doubles as the
* no-ctx.filter fallback — bilinear minification IS a box blur, so even with filters missing
* these buffers come back genuinely blurred, just less smoothly. */
b2 = mkCanvas(W >> 1, H >> 1);
b4 = mkCanvas(W >> 2, H >> 2);
b8 = mkCanvas(W >> 3, H >> 3);
/* Each radius is expressed in ITS OWN buffer's pixels, so the 0.05/0.045 fractions below are
* the cell-relative full-resolution radii divided by the buffer's downsample factor. Landed on
* by matching tools/topng.py's 1.5px and 5.0px taps at its 9x16 cell, which is the render the
* art direction was signed off against. */
rTight = Math.max(0.6, dh * 0.05); // on b2 (1/2)
rWide = Math.max(0.8, dh * 0.045); // on b8 (1/8)
rMid = Math.max(0.7, dh * 0.06); // on b4 (1/4), degraded mode only
if (reAtlas || !atlas) buildAtlas();
}
function init(el) {
canvas = el;
ctx = canvas.getContext('2d', { alpha: false });
probeFilter();
return CC.Canvas;
}
function setQuality(q) { quality = q < 0 ? 0 : (q > 2 ? 2 : q | 0); }
/* ---- the glyph pass ------------------------------------------------------------------------ */
function glyphPass(f) {
var c = sctx;
c.globalCompositeOperation = 'source-over';
c.fillStyle = '#000';
c.fillRect(0, 0, W, H);
var ch = f.ch, cl = f.col, lu = f.lum;
var n = cols < f.cols ? cols : f.cols;
var r = rows < f.rows ? rows : f.rows;
var curA = -1, fc = f.cols;
for (var y = 0; y < r; y++) {
var row = y * fc, py = y * dh;
for (var x = 0; x < n; x++) {
var i = row + x, gI = ch[i];
if (gI === 0) continue;
var L = lu[i];
if (L < LUM_FLOOR) continue;
var a = L * (1 / 255);
/* Only assign when it actually moves: globalAlpha is a context state change and this loop
* runs 13k times a frame. */
if (a !== curA) { c.globalAlpha = a; curA = a; }
c.drawImage(atlas, gI * dw, cl[i] * dh, dw, dh, x * dw, py, dw, dh);
}
}
c.globalAlpha = 1;
}
/* ---- bloom ---------------------------------------------------------------------------------
* 'copy' rather than clearRect-then-draw: it replaces the destination in one op, which both
* clears the buffer and writes it, and it is what makes the fallback path free. */
function tap(dst, src, blurPx) {
var c = dst.getContext('2d');
c.imageSmoothingEnabled = true;
c.imageSmoothingQuality = 'high';
c.globalAlpha = 1;
c.globalCompositeOperation = 'copy';
if (HAS_FILTER && blurPx > 0) c.filter = 'blur(' + blurPx + 'px)';
c.drawImage(src, 0, 0, dst.width, dst.height);
if (HAS_FILTER) c.filter = 'none';
c.globalCompositeOperation = 'source-over';
return dst;
}
function composite() {
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(scene, 0, 0);
if (quality <= 0) { ctx.globalCompositeOperation = 'source-over'; return; }
/* Additive, not the alpha blend tools/topng.py uses. Light adds; blending would darken the
* glyph cores it is supposed to be haloing, and the cores are the only pure-white in the
* frame. The two alphas below are tuned so a lone lit window still reads as a point and a
* whole lit facade blooms into a slab. */
ctx.globalCompositeOperation = 'lighter';
if (quality >= 2) {
tap(b2, scene, rTight); // tight halo: gives glyphs an emissive edge
ctx.globalAlpha = 0.55;
ctx.drawImage(b2, 0, 0, W, H);
tap(b4, b2, 0); // chained, so the wide tap inherits the tight blur
tap(b8, b4, rWide); // wide haze: the canyon's ambient light
/* 0.55 / 0.85 was picked by rendering the same frame at 0.40/0.60, 0.55/0.85 and 0.70/1.05
* and looking: below this the dim mullions never lift off black and the facade goes back to
* reading as a lattice; above it the halo starts eating the glyph cores and the blacks grey
* out, which costs the negative space the whole composition is built on. */
ctx.globalAlpha = 0.85;
ctx.drawImage(b8, 0, 0, W, H);
} else {
/* Degraded mode: one mid tap. Keeps the piece emissive at half the bloom cost — going to
* quality 0 is a last resort because a flat frame is a different artwork. */
tap(b4, scene, rMid);
ctx.globalAlpha = 0.95;
ctx.drawImage(b4, 0, 0, W, H);
}
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
}
function draw(f) {
if (!ctx || !atlas) return;
glyphPass(f);
composite();
}
CC.Canvas = {
init: init, setGrid: setGrid, setQuality: setQuality, draw: draw,
get cellAspect() { return dh ? dw / dh : 0.5625; },
get quality() { return quality; },
get hasFilter() { return HAS_FILTER; },
FAMILY: FAMILY, LUM_FLOOR: LUM_FLOOR
};
if (typeof module !== 'undefined') module.exports = CC.Canvas;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

1390
src/surfaces.js Normal file

File diff suppressed because it is too large Load diff

227
src/weather_state.js Normal file
View file

@ -0,0 +1,227 @@
/* CyberCity weather director — the one place that decides what the sky is doing.
*
* WHY THIS IS A MODULE AND NOT FOUR CONSTANTS IN weather.js.
* Rain, fog, steam, lightning, the wetness of the road, the haze on the far end of the street, the
* stars in the slot between the rooftops and whether a pedestrian is carrying an umbrella are all
* the SAME FACT seen from eight different files. Left to themselves each of those files picks its
* own constant and the city ends up with heavy rain falling through a clear starfield onto a dry
* road — which is precisely what it did before this file existed. So the fact lives here once and
* everything else reads it.
*
* DETERMINISM. `state(t)` is a pure function of (seed, t): a seeded sequence of segments indexed by
* segment number, exactly the way city.js indexes its route by arc length. Scrubbing to frame 9000
* offline gives the weather the browser has at frame 9000, which is the whole reason the headless
* harness is worth anything. The ONLY impurity is a deliberate one — `set()` and `cycle()`, which a
* viewer reaches through the keyboard — and it is stamped with the time it happened so the blend
* out of it is still a function of t.
*
* READING IT. Every parameter is 0..1 and every one of them is a DIRECTION, not a multiplier for
* any particular element's constants. An element that was already tuned reads `rel(name)`, which is
* that parameter divided by its value in the `rain` preset — the preset the whole build was tuned
* under before this file landed — so `rel` returns 1.0 for the look that already shipped and the
* element scales around it. That is the migration rule and it is not optional: an element that
* multiplies by the raw parameter silently re-tunes itself to 65% of what it was.
*/
(function (CC) {
'use strict';
var clamp = CC.clamp, smooth = CC.smooth, hash1 = CC.hash1;
/* Eight directions. They are deliberately NOT independent — a downpour is windy and wet and
* hides the stars, and a state that lets a viewer contradict that would only produce weather
* nobody has ever stood in. */
var KEYS = ['rain', 'wind', 'fog', 'wet', 'storm', 'haze', 'cloud', 'steam'];
/* rain wind fog wet storm haze cloud steam */
var PRESETS = [
{ name: 'clear', p: [0.00, 0.25, 0.08, 0.12, 0.00, 0.10, 0.08, 0.55] },
{ name: 'drizzle', p: [0.30, 0.35, 0.22, 0.62, 0.02, 0.26, 0.45, 0.72] },
{ name: 'rain', p: [0.65, 0.55, 0.30, 0.90, 0.12, 0.40, 0.75, 0.85] },
{ name: 'downpour', p: [1.00, 0.85, 0.36, 1.00, 0.34, 0.56, 0.95, 1.00] },
{ name: 'mist', p: [0.06, 0.15, 1.00, 0.46, 0.00, 0.95, 0.70, 0.92] },
{ name: 'storm', p: [0.85, 1.00, 0.44, 1.00, 1.00, 0.60, 1.00, 0.78] }
];
var REF_I = 2; // 'rain' — the preset the pre-weather build was tuned as
/* SIX PRESETS, FOUR LOOKS — a known and UNFIXED gap, recorded here so it is not re-derived by
* eye. Pinning each preset from t=0 and rendering seeds 3/7/42/99 at frame 1800, 400x100, the
* share of cells whose printed luminance differs by more than 10% of full scale is: clear vs
* drizzle 5.2%, downpour vs storm 7.3%, against mist vs anything at 17-21%. The per-frame
* particle noise floor is about 3%, so downpour and storm are very nearly the same picture and
* only the lightning rate tells them apart. Lit coverage over the four seeds says the same
* thing: clear 24.0%, drizzle 24.3%, rain 25.9%, downpour 26.2%, mist 22.1%, storm 26.3%.
*
* THE FIX IS NOT IN THIS TABLE, and that was measured rather than assumed. Widening the gap
* here — downpour wind 0.85 -> 0.55, fog 0.36 -> 0.42, and storm fog 0.44 -> 0.24, haze 0.60
* -> 0.38, so that the two presets disagree on wind by 45 points instead of 15 — moved the
* rendered difference from 7.3% of cells to 8.5%. That is the elements spending the whole wind
* and fog budget on things the print cannot see; until weather.js turns wind into continuously
* visible travelling structure, a bigger number here only changes what downpour looks like
* without making storm look like anything else. Widen it in the same change that gives the
* elements something to do with it, and re-run the pinned comparison above. */
/* A viewer who has just pressed a key to change the weather is owed a visible answer, but the
* transition is also the best thing in the whole cycle to watch, so it is slow enough to BE
* something: the leading edge of a downpour walking up the street. 14 s under the automatic
* schedule, 5 s when somebody asked for it, because they are watching for it. */
var TRANS = 14, TRANS_FORCED = 5;
/* Long enough that weather is a mood rather than a strobe, short enough that a two-minute look
* at the piece contains a change. */
var DUR_MIN = 78, DUR_VAR = 92;
var S = 0; // seed
var segT = [], segI = []; // segment start times and preset indices, extended on demand
var forcedI = -1, forcedAt = -1e9; // viewer override and when it was asked for
/* Not every state follows every other. Sun does not come out in the middle of a downpour; it
* dries off through rain and drizzle first. The row is the current preset, the values are the
* relative weights of what may come next (self excluded at pick time). */
var NEXT = [
/* clear -> */ [0, 5, 2, 0, 3, 0],
/* drizzle -> */ [4, 0, 5, 1, 3, 1],
/* rain -> */ [1, 5, 0, 4, 2, 3],
/* downpour -> */ [0, 2, 6, 0, 1, 4],
/* mist -> */ [4, 3, 2, 0, 0, 1],
/* storm -> */ [0, 2, 5, 3, 1, 0]
];
function pickNext(prev, n) {
var row = NEXT[prev], tot = 0, i;
for (i = 0; i < 6; i++) tot += row[i];
var r = hash1(n, S + 7717) * tot;
for (i = 0; i < 6; i++) { r -= row[i]; if (r <= 0) return i; }
return REF_I;
}
function extend(tMax) {
while (segT[segT.length - 1] <= tMax) {
var n = segT.length;
var prev = segI[n - 1];
segI.push(pickNext(prev, n));
segT.push(segT[n - 1] + DUR_MIN + hash1(n, S + 991) * DUR_VAR);
}
}
/* The live parameter block. Elements hold a reference to THIS object and read fields off it
* every frame; it is never reallocated, so nothing can end up pointing at last frame's weather. */
var W = { name: 'rain', from: 'rain', to: 'rain', blend: 1, forced: false };
for (var ki = 0; ki < KEYS.length; ki++) W[KEYS[ki]] = PRESETS[REF_I].p[ki];
function apply(a, b, f) {
var A = PRESETS[a].p, B = PRESETS[b].p;
for (var i = 0; i < KEYS.length; i++) W[KEYS[i]] = A[i] + (B[i] - A[i]) * f;
W.from = PRESETS[a].name; W.to = PRESETS[b].name; W.blend = f;
/* The name is what the frame's hint line prints, and printing the target the instant the
* blend starts would name a downpour over a dry road. It flips at the halfway point, which is
* about where the eye agrees. */
W.name = PRESETS[f < 0.5 ? a : b].name;
}
function update(dt, t) {
if (!(t >= 0)) t = 0;
extend(t + 4);
// Which scheduled segment t is in, and how far into its lead-in transition.
var k = segT.length - 1;
while (k > 0 && segT[k] > t) k--;
var cur = segI[k], prev = k > 0 ? segI[k - 1] : cur;
var into = t - segT[k];
var f = k > 0 && into < TRANS ? smooth(into / TRANS) : 1;
if (forcedI >= 0) {
/* An override does not pause the schedule underneath it — it holds until the schedule
* itself moves on, at which point the city takes its weather back. That is the difference
* between a control and a mode: nothing here has to be switched off again. */
var fi = t - forcedAt;
if (fi < 0) { forcedI = -1; } // scrubbed backwards past the keypress
else if (k > 0 && segT[k] > forcedAt) { forcedI = -1; } // schedule moved on; release
else {
apply(prev, forcedI, fi < TRANS_FORCED ? smooth(fi / TRANS_FORCED) : 1);
W.forced = true;
return W;
}
}
W.forced = false;
apply(prev, cur, f);
return W;
}
/* Reference-relative read. `rel('rain')` is 1.0 under the preset the build was tuned as, so an
* element multiplies its existing constants by it and changes nothing until the weather does.
*
* The reciprocal of the reference row is precomputed and the key is resolved through an object
* map rather than KEYS.indexOf. This is not micro-optimisation for its own sake: optics.js,
* street.js, structure.js and signage.js each call rel() several times per element per frame,
* so the old form ran a linear string scan over an eight-entry array plus a divide tens of
* thousands of times a second, on the render path, for a number that cannot change between two
* calls in the same frame. Both tables are built once at load, so this stays allocation-free. */
var KI = {}, INV_REF = [];
for (var kj = 0; kj < KEYS.length; kj++) {
KI[KEYS[kj]] = kj;
var rv = PRESETS[REF_I].p[kj];
INV_REF.push(rv > 1e-6 ? 1 / rv : 1);
}
function rel(key) {
var i = KI[key];
return i === undefined ? 1 : W[key] * INV_REF[i];
}
var Weather = {
P: W, // the live parameter block; hold this, do not copy it
KEYS: KEYS, PRESETS: PRESETS, REF: PRESETS[REF_I].p,
/* Takes the city and NOTHING ELSE. Callers used to hand this an rng and the parameter was
* never referenced — the director is a pure function of (seed, t) by design, because a
* segment schedule that depended on draw order could not be scrubbed to frame 9000 offline.
* The dead parameter is gone rather than documented, because a dead parameter is an
* invitation: the first edit that starts using it silently makes the weather depend on how
* many elements happened to init before it. If this ever needs randomness it must derive it
* from `city.seed` the way segI does below. Extra arguments from existing callers are
* ignored, which is exactly what they were already. */
init: function (city) {
S = city && city.seed !== undefined ? (city.seed | 0) : 0;
segT = [0];
/* Never open on `clear`. The first thing anyone sees should have weather in it — a dry
* still night is the one state that reads as "nothing is implemented yet".
*
* The cost of that, and of DUR_MIN/DUR_VAR being long enough to be a mood, is that the
* canonical four-frame sweep (600/3000/9000/18000) very nearly never lands on `clear`. It
* currently draws storm/storm/rain/drizzle for seed 3, rain/rain/mist/storm for 7,
* storm/storm/mist/CLEAR for 42 and downpour/downpour/drizzle/rain for 99 — one clear frame
* in sixteen, and under the hash this file shipped with it was zero in sixteen. That makes
* the reference sweep all but blind to stars, moon, aircraft and cloudbase, every one of
* which only appears in the weather the sweep cannot see. A segment runs 78-170 s
* (4700-10200 frames) and clear is about 18% of wall time, so four point samples miss it
* routinely rather than unluckily. Anything measuring elements/sky.js must add a fifth
* column at the first settled `clear` frame for its seed, which is: seed 3 -> 22084,
* seed 7 -> 26789, seed 42 -> 14911, seed 99 -> 55261. (First frame where W.name is 'clear'
* and the blend has finished. These are a function of CC.hash1, PRESETS, NEXT, DUR_MIN and
* DUR_VAR — recompute them whenever any of those moves, as the hash change that took them
* off 122069/9595/31019/57290 shows.) */
segI = [1 + ((hash1(0, S + 313) * 5) | 0)];
forcedI = -1; forcedAt = -1e9;
update(0, 0);
},
update: update,
rel: rel,
/* Viewer control. Both are no-ops offline — the headless harness never calls them, so the
* reference frame stays the frame the browser draws for an untouched keyboard. */
set: function (nameOrIdx, t) {
var i = typeof nameOrIdx === 'number' ? nameOrIdx | 0 : -1;
if (i < 0) for (var j = 0; j < PRESETS.length; j++)
if (PRESETS[j].name === nameOrIdx) { i = j; break; }
if (i < 0 || i >= PRESETS.length) return false;
forcedI = i; forcedAt = t === undefined ? 0 : t;
return true;
},
cycle: function (t, dir) {
var cur = forcedI >= 0 ? forcedI : PRESETS.map(function (p) { return p.name; }).indexOf(W.name);
if (cur < 0) cur = REF_I;
var n = (cur + (dir < 0 ? -1 : 1) + PRESETS.length) % PRESETS.length;
return Weather.set(n, t);
},
get current() { return W.name; }
};
if (CC) CC.Weather = Weather;
if (typeof module !== 'undefined') module.exports = Weather;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

1165
tools/domshim.cjs Normal file

File diff suppressed because it is too large Load diff

14
tools/exposure.py Normal file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env python3
"""The exposure metric the review was stated in: a CELL counts as black when it draws nothing
or draws below lum 40, which is where a glyph stops registering. Directly comparable to the
review's 82.6-85.5% baseline and its 54-60% target."""
import sys
tb=tl=tt=0
for src in sys.argv[1:]:
L=open(src).read().split('\n'); cols,rows=map(int,L[1].split())
for y in range(rows):
for p in L[4+y].split(' ')[:cols]:
ch,ci,lu=(int(v) for v in p.split(',')); tt+=1
if ch==0 or lu<40: tb+=1
elif lu>=110: tl+=1
print(f"cells: black(lum<40) {tb/tt*100:.1f}% lit(lum>=110) {tl/tt*100:.1f}%")

421
tools/flicker-rate.cjs Normal file
View file

@ -0,0 +1,421 @@
/* PHOTOSENSITIVITY / STEP-EDGE REGRESSION TEST for the flicker personalities in
* src/elements/signage.js — the sibling of tools/lightning-rate.cjs, same rules, different unit.
*
* node tools/flicker-rate.cjs [signage.js path] [seconds] [phases]
*
* lightning-rate.cjs measures the FRAME: it sums what the element adds over every cell, which is
* the right unit for a stroke that lights the whole viewport at once. It is the wrong unit for a
* sign. A street holds a hundred fixtures at a hundred phases and their sum is smooth however
* badly any one of them behaves, so a single tube stepping half its brightness in one frame is
* invisible to a frame-level statistic and perfectly visible to a person looking at that tube.
*
* So this measures the fixture. Two passes:
*
* 1. PERSONALITY — the real `flick()` is lifted out of the source file by brace matching and run
* directly (no copy of it lives in this tool; if the shipped function changes, the number
* changes). Each personality is sampled once per 60 Hz frame for `seconds`, at `phases`
* different values of ph, and reported as:
* - largest single-frame step, as a percentage of full scale (the multiplier is a fraction of
* the fixture's own peak brightness, so full scale is 1.0), plus the same step as a
* percentage of the value it came from — a jump from 0.43 to 0.88 is +45% of full scale and
* +105% relative, and both are worth knowing;
* - dropout rate per second and mean dropout depth, a dropout being an excursion below 0.60
* that has to climb back over 0.75 before another one can be counted;
* - the strongest spectral component between 3 and 20 Hz (Hann window, amplitude as a
* percentage of full scale) — the flash-rate danger band.
*
* 2. FIXTURE — the real `neon` element is drawn against a synthetic far wall with a FROZEN camera,
* so no cell can change for any reason except flicker, and the largest frame-to-frame change of
* any single cell's luminance is reported. That is the artifact as the eye actually receives it.
*
* THE RULES, inherited from lightning-rate.cjs: no single frame may move a fixture by more than a
* third of full scale, nothing may beat between 3 and 20 Hz above 2% of full scale, and no more
* than 3 dropouts a second. Reduced motion must additionally freeze every personality dead.
*
* EXIT CODES. 0 PASS, 1 FAIL, 2 usage error, and — new, and the same repair tools/lightning-rate.cjs
* just had — 3 NOT APPLICABLE: every rule that ran passed, but at least one check MEASURED NOTHING
* and so verified nothing. Three paths through this file could do that while still exiting 0:
*
* - `fixture()` returns null when the named element is not in CC.ELEMENTS (a rename in
* signage.js is enough), and section 2 used to `continue` past it in silence;
* - a fixture that paints no cell in any of the eight bearings printed "no fixture in view" and
* was scored as a pass, because `bad` is gated on `r.painted > 0`;
* - section 3 prints "SKIP — the bob line has moved" when the string it patches out of
* signage.js no longer matches, and skipped the entire holo scan-band test.
*
* None of those is a violation, and none of them is a verification either. They now collect in
* `notApplicable`, print as an explicit NOT MEASURED block at the end, and turn the exit code into
* 3 so a gate cannot read "we never looked" as "we looked and it was fine". A real violation still
* beats them to it: FAIL is exit 1 whatever else was skipped.
*
* The last two lines of a run are machine-readable:
* SUMMARY: live <pct>% of 255 <what> | reduced-motion <pct>% of 255
* RESULT: PASS|FAIL|NOT_APPLICABLE
* SUMMARY names the worst LIVE per-cell step (section 2) and the worst reduced-motion step
* (section 4) separately and always, because those two numbers have been confused in a report
* before: "worst per-cell frame step 0/255 on both fixtures under every sky" is section 4's
* result — reduced motion, where zero is the pass condition — and it is not section 2's, which
* on this build runs to 74.1% of 255 under storm and 94.1% under drizzle and clear (signals, a
* traffic lamp changing state, which passes on the RATE rule at 0.000-0.100 big steps/s against
* the 1.0/s limit). Quote SUMMARY's own words or say which section you are quoting.
*/
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
/* Positionals are taken from the arguments that are NOT flags, and that is a bug fix, not tidying.
* argv[2] used to be read as the source path unconditionally, so the `--sky=rain` invocation this
* file's own header prescribes resolved to <root>/--sky=rain and the tool died in readFileSync
* before it measured anything. A safety tool that cannot be run the way its documentation says to
* run it is a safety tool nobody runs, so the flag is filtered out here and again below. */
const ARGS = process.argv.slice(2).filter(function (a) { return a.indexOf('--') !== 0; });
const SRC = path.resolve(ARGS[0] || path.join(root, 'src/elements/signage.js'));
const SECS = parseFloat(ARGS[1] || '60');
const PHASES = parseInt(ARGS[2] || '24', 10);
const MAX_FRAME_STEP = 0.34; // fraction of full scale
const MAX_BAND_AMP = 0.02; // fraction of full scale, 3-20 Hz
const MAX_DROPOUTS = 3; // per second
global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined;
const CC = global.CC;
/* ---- lift flick() out of the shipped source ------------------------------------------------ */
function lift(file, name) {
const src = fs.readFileSync(file, 'utf8');
const at = src.indexOf('function ' + name + '(');
if (at < 0) throw new Error('no function ' + name + ' in ' + file);
let i = src.indexOf('{', at), depth = 0, end = -1;
for (let k = i; k < src.length; k++) {
const c = src[k];
if (c === '{') depth++;
else if (c === '}') { depth--; if (depth === 0) { end = k + 1; break; } }
}
if (end < 0) throw new Error('unbalanced braces in ' + name);
const body = src.slice(at, end);
/* The module aliases a handful of CC members at its top; hand the lifted function the same
* names so it can be run outside its IIFE without editing a character of it. */
const fn = new Function('CC', 'vnoise', 'clamp', 'hash2', body + '\nreturn ' + name + ';')(
CC, CC.vnoise, CC.clamp, CC.hash2);
return { fn: fn, text: body };
}
const lifted = lift(SRC, 'flick');
const flick = lifted.fn;
console.log(`source: ${path.relative(root, SRC)} ${SECS}s @60Hz x ${PHASES} phases`);
console.log('lifted flick():\n' + lifted.text.split('\n').map(l => ' ' + l).join('\n') + '\n');
/* ---- the personalities, as the draw loops call them ----------------------------------------- */
const KINDS = [
{ label: 'kind 0 steady tube ', kind: 0, j: 0, dead: -1 },
{ label: 'kind 1 failing starter ', kind: 1, j: 0, dead: -1 },
{ label: 'kind 2 live character ', kind: 2, j: 0, dead: -1 },
{ label: 'kind 2 DEAD character ', kind: 2, j: 3, dead: 3 },
{ label: 'kind 3 slow breath ', kind: 3, j: 0, dead: -1 },
];
const N = Math.round(SECS * 60);
const S = new Float64Array(N);
function spectrum(s) { // strongest component in 3..20 Hz, Hann windowed
const n = s.length;
let mean = 0; for (let k = 0; k < n; k++) mean += s[k]; mean /= n;
const w = new Float64Array(n);
for (let k = 0; k < n; k++) w[k] = (s[k] - mean) * 0.5 * (1 - Math.cos(2 * Math.PI * k / (n - 1)));
const b0 = Math.ceil(3 * n / 60), b1 = Math.floor(20 * n / 60);
let best = 0, bf = 0;
for (let b = b0; b <= b1; b++) {
let re = 0, im = 0;
const wstep = 2 * Math.PI * b / n;
for (let k = 0; k < n; k++) { const a = wstep * k; re += w[k] * Math.cos(a); im -= w[k] * Math.sin(a); }
const amp = 2 * Math.sqrt(re * re + im * im) / n / 0.5; // /0.5 undoes Hann coherent gain
if (amp > best) { best = amp; bf = b * 60 / n; }
}
return { amp: best, hz: bf };
}
function run(label, kind, j, dead, reduced) {
CC.reducedMotion = !!reduced;
let maxStep = 0, maxStepRel = 0, maxAt = 0, drops = 0, depthSum = 0, bigSteps = 0;
let band = { amp: 0, hz: 0 }, lo = 1e9, hi = -1e9, constAll = true;
for (let p = 0; p < PHASES; p++) {
const ph = (p + 0.5) / PHASES;
for (let k = 0; k < N; k++) S[k] = flick(kind, ph, k / 60, j, dead);
let armed = true;
for (let k = 0; k < N; k++) {
const v = S[k];
if (v < lo) lo = v; if (v > hi) hi = v;
if (k) {
const d = Math.abs(v - S[k - 1]);
if (d > maxStep) { maxStep = d; maxAt = k / 60; maxStepRel = d / Math.max(S[k - 1], 1e-9); }
if (d > MAX_FRAME_STEP) bigSteps++;
/* A dropout is a downward CROSSING, not a sample that happens to be low: a personality
* that sits at 0.10 for ever (the dead character) is one dark glyph, not ten thousand
* dropouts, and counting samples would have said the second thing. */
if (armed && v < 0.60 && S[k - 1] >= 0.60) {
armed = false; drops++;
let mn = v;
for (let q = k; q < N && S[q] < 0.75; q++) if (S[q] < mn) mn = S[q];
depthSum += 1 - mn;
} else if (!armed && v > 0.75) armed = true;
}
}
if (hi - lo > 1e-12) constAll = false;
if (!constAll) { const sp = spectrum(S); if (sp.amp > band.amp) band = sp; }
}
const secs = SECS * PHASES;
return { label, maxStep, maxStepRel, maxAt, rate: drops / secs, depth: drops ? depthSum / drops : 0,
bigRate: bigSteps / secs, band, lo, hi, constAll };
}
function report(r, checks) {
const flags = [];
if (checks) {
if (r.maxStep > MAX_FRAME_STEP) flags.push('FAIL step');
if (r.band.amp > MAX_BAND_AMP) flags.push('FAIL 3-20Hz');
if (r.rate > MAX_DROPOUTS) flags.push('FAIL dropouts');
}
console.log(
`${r.label} range ${r.lo.toFixed(3)}..${r.hi.toFixed(3)}` +
` step ${(r.maxStep * 100).toFixed(1)}% fs (${(r.maxStepRel * 100).toFixed(0)}% rel, ` +
`${r.bigRate.toFixed(3)} over-${MAX_FRAME_STEP * 100 | 0}%/s)` +
` dropouts ${r.rate.toFixed(2)}/s @ ${(r.depth * 100).toFixed(0)}% deep` +
` 3-20Hz ${(r.band.amp * 100).toFixed(2)}% fs${r.band.amp > 1e-9 ? ' @ ' + r.band.hz.toFixed(2) + 'Hz' : ''}` +
(flags.length ? ' ' + flags.join(' ') : ' ok'));
return !flags.length;
}
let ok = true;
/* Every check that could not be run, in the order it was skipped. Non-empty means the exit code is
* 3 and the run verified less than its section headings claim — see the exit-code note at the top. */
const notApplicable = [];
console.log('1. PERSONALITY — flick() multiplier, one sample per frame');
for (const K of KINDS) ok = report(run(K.label, K.kind, K.j, K.dead, false), true) && ok;
console.log('\n reduced motion (every personality must be frozen):');
for (const K of KINDS) {
const r = run(K.label, K.kind, K.j, K.dead, true);
const good = r.constAll && r.band.amp === 0;
if (!good) ok = false;
console.log(`${r.label} constant ${r.lo.toFixed(3)} ${good ? 'ok' : 'FAIL — still moving'}`);
}
CC.reducedMotion = false;
/* ---- 2. the real element, frozen camera ------------------------------------------------------
* The camera does not move, so a cell can only change because a fixture changed it, and the
* largest frame-to-frame change of any ONE cell is the artifact as the eye receives it.
*
* The verdict is per cell and on the RATE, not on the existence of a big step. A frame-wide "did
* anything jump" counter says a street of twenty junctions changes hard twice a second, which is
* true and is not a defect: a traffic light going amber is supposed to be a hard cut, and no single
* lamp does it more than about six times in its 46 s cycle. What separates a state change from a
* flicker edge is how often ONE cell does it. Expected standing values on a clean build, so a
* regression shows up against them: neon and shop spill 0.000/s, signals 0.04-0.10/s (the lamp
* cycle), holo 0.25/s (see below).
*
* Holo is the one that needs saying. The advert bobs 0.28 m on a 19 s sine, so its own character
* grid drifts across the screen raster at about a third of a grid row a second, and every crossing
* re-registers a cell of a panel that is 50% dropout by design — full-scale, and unavoidable for
* any object that moves across a character grid at all (the walking camera does far more of it than
* the bob does). That drift would also MASK a regression in the scan band, which is a real flicker
* edge, so the band is tested separately below with the bob patched out of the source.
*/
/* weather_state.js is loaded, and that is a change: without it CC.Weather is absent, rel() falls
* back to 1.0 everywhere, and signage.js's AT.gust comes out at exactly 1 — which switches the
* wind gutter OFF at its `AT.gust <= 1.02` guard. The gutter is a per-fixture luminance carrier
* that exists only in wind, so the tool that guards the 34% ceiling was measuring the one sky in
* which the newest flicker source in the file does nothing at all. It is pinned to `storm` by
* default for the same reason lightning-rate.cjs is: test the worst case, not the average one.
* `--sky=rain` reproduces the reading this tool gave before the director was wired in. */
for (const rel of ['src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js',
'src/compose.js']) {
const p = path.join(root, rel); if (fs.existsSync(p)) require(p);
}
const skyArg = process.argv.find(a => a.indexOf('--sky=') === 0);
const SKY = skyArg ? skyArg.slice(6) : 'storm';
let PIN = null;
/* The parameter block is written directly rather than through Weather.set(), because set() is a
* viewer control the schedule is entitled to revoke at the next segment boundary — see the same
* note in lightning-rate.cjs, where a pin through set() silently released after two minutes. */
function pinSky() {
if (!CC.Weather) return;
if (!PIN) {
PIN = CC.Weather.PRESETS.filter(function (q) { return q.name === SKY; })[0];
if (!PIN) { console.error('unknown sky: ' + SKY); process.exit(2); }
}
const P = CC.Weather.P, K = CC.Weather.KEYS;
for (let i = 0; i < K.length; i++) P[K[i]] = PIN.p[i];
P.name = P.from = P.to = PIN.name; P.blend = 1;
}
const edir = path.join(root, 'src/elements');
for (const fn of fs.readdirSync(edir).sort()) if (fn.endsWith('.js')) require(path.join(edir, fn));
const SEEDS = [0, 7, 42, 555];
const NAMES = ['neon', 'shopSpill', 'signals', 'holo'];
const MAX_CELL_RATE = 1.0; // big steps a second in one cell, above which it is flicker
const COLS = 200, ROWS = 60;
/* One element, one seed, eight compass bearings, 20 s each at 60 Hz. */
function fixture(name, seed, els, secsEach) {
const el = els.find(e => e.name === name);
if (!el) return null;
const f = CC.makeFrame(COLS, ROWS);
const big = new Uint32Array(f.n);
let worst = 0, worstYaw = 0, worstT = 0, painted = 0, rate = 0;
for (let yi = 0; yi < 8; yi++) {
const yaw = yi * Math.PI / 4;
/* Per bearing: a cell index is a different fixture in every direction, so the counts cannot be
* pooled across them without diluting the one view that has a sign in it. */
big.fill(0);
const cam = { x: city_.startX, z: city_.startZ, yaw: yaw, eyeY: 1.7, fov: 1.25,
horizon: ROWS * 0.56, cellAspect: 0.5625, t: 0 };
let prev = null;
const N2 = Math.round(secsEach * 60);
for (let k = 0; k < N2; k++) {
const t = k / 60;
// Every tick, exactly as main.js does it: the element reads the live P block from update().
if (CC.Weather) { CC.Weather.update(1 / 60, t); pinSky(); }
for (let i = 0; i < f.n; i++) { f.ch[i] = 1; f.col[i] = 5; f.lum[i] = 0; f.dist[i] = 1e6; f.kind[i] = 1; }
if (el.update) el.update(1 / 60, t, cam);
el.draw(f, cam, t);
const cur = Float64Array.from(f.lum);
for (let i = 0; i < f.n; i++) if (cur[i] > 0) painted++;
if (prev) {
let fw = 0;
for (let i = 0; i < f.n; i++) {
const d = Math.abs(cur[i] - prev[i]) / 255;
if (d > MAX_FRAME_STEP) big[i]++;
if (d > fw) fw = d;
}
if (fw > worst) { worst = fw; worstYaw = yaw; worstT = t; }
}
prev = cur;
}
let mx = 0; for (let i = 0; i < big.length; i++) if (big[i] > mx) mx = big[i];
if (mx / secsEach > rate) rate = mx / secsEach;
}
return { worst, rate, painted, worstYaw, worstT };
}
let city_ = null;
/* The worst LIVE per-cell step of the whole run, kept so the summary at the bottom can name it.
* Section 4's number is tracked separately and deliberately: the two get quoted as one. */
let liveWorst = 0, liveWorstWhat = 'nothing measured';
console.log('\n2. FIXTURE — real element, frozen camera, largest per-cell luminance change between frames');
for (const seed of SEEDS) {
city_ = CC.City.make(seed);
if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); }
const rng = CC.mulberry(seed ^ 0x9e3779b9);
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: COLS, rows: ROWS });
for (const name of NAMES) {
const r = fixture(name, seed, els, 20);
/* An element this tool cannot find is a hole in the coverage, not a clean bearing: `continue`
* here used to drop the whole fixture out of the run without touching `ok`. */
if (!r) {
console.log(` seed ${String(seed).padStart(3)} ${name.padEnd(10)} NOT MEASURED — no element named '${name}' in CC.ELEMENTS`);
notApplicable.push(`2. seed ${seed} ${name}: element not present, nothing measured`);
continue;
}
if (r.painted === 0)
notApplicable.push(`2. seed ${seed} ${name}: painted no cell in any of the 8 bearings, nothing measured`);
if (r.painted > 0 && r.worst > liveWorst) { liveWorst = r.worst; liveWorstWhat = `seed ${seed} ${name}, yaw ${r.worstYaw.toFixed(2)}, t=${r.worstT.toFixed(2)}s, sky '${SKY}'`; }
const bad = r.painted > 0 && r.worst > MAX_FRAME_STEP && r.rate > MAX_CELL_RATE;
if (bad) ok = false;
console.log(` seed ${String(seed).padStart(3)} ${name.padEnd(10)} cells painted ${String(r.painted).padStart(7)}` +
` worst per-cell frame step ${(r.worst * 100).toFixed(1)}% of 255` +
` busiest cell over-${MAX_FRAME_STEP * 100 | 0}% ${r.rate.toFixed(3)}/s` +
` (yaw ${r.worstYaw.toFixed(2)}, t=${r.worstT.toFixed(2)}s) ` +
(r.painted === 0 ? 'NOT MEASURED — no fixture in view' : bad ? 'FAIL' : 'ok'));
}
}
/* ---- 3. the holo scan band, with the panel's drift patched out ------------------------------- */
const HOLO_STILL_MAX = 0.10;
const bobLine = 'if (!CC.reducedMotion) hy += Math.sin(t * 0.33 + ph * 6.283) * 0.28;';
const src = fs.readFileSync(SRC, 'utf8');
console.log('\n3. HOLO SCAN BAND — same element with the 0.28 m bob deleted from the source, so the' +
'\n panel is nailed to the raster and the only thing left that can move a cell is the band');
if (src.indexOf(bobLine) < 0) {
/* A skip is not a pass. This branch used to print and leave `ok` alone, so a one-character edit
* to that line in signage.js silently deleted the scan-band test from every future run. */
console.log(' NOT MEASURED — the bob line has moved; update `bobLine` in this tool');
notApplicable.push('3. holo scan band: bob line not found in signage.js, section not run');
} else {
const tmp = path.join(require('os').tmpdir(), 'signage-nobob-' + process.pid + '.js');
fs.writeFileSync(tmp, src.replace(bobLine, ''));
const before = CC.ELEMENTS.length;
require(tmp);
const still = CC.ELEMENTS.slice(before);
for (const seed of SEEDS) {
city_ = CC.City.make(seed);
if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); }
const rng = CC.mulberry(seed ^ 0x9e3779b9);
for (const el of still) if (el.init) el.init(city_, rng, { cols: COLS, rows: ROWS });
const r = fixture('holo', seed, still, 20);
/* The patched copy has to actually register an element; if requiring it added nothing named
* holo, `fixture` returns null and this line used to throw on r.painted — a crash reads as a
* broken tool rather than as an unmeasured rule, so it is reported as the latter. */
if (!r) {
console.log(` seed ${String(seed).padStart(3)} holo (still) NOT MEASURED — the patched source registered no 'holo' element`);
notApplicable.push(`3. seed ${seed} holo (still): patched source has no holo element, nothing measured`);
continue;
}
if (r.painted === 0)
notApplicable.push(`3. seed ${seed} holo (still): no panel in view, nothing measured`);
const bad = r.painted > 0 && r.worst > HOLO_STILL_MAX;
if (bad) ok = false;
console.log(` seed ${String(seed).padStart(3)} holo (still) worst per-cell frame step ` +
`${(r.worst * 100).toFixed(1)}% of 255 busiest cell ${r.rate.toFixed(3)}/s ` +
(r.painted === 0 ? 'NOT MEASURED — no panel in view' : bad ? `FAIL (> ${HOLO_STILL_MAX * 100}%)` : 'ok'));
}
fs.unlinkSync(tmp);
}
/* ---- 4. reduced motion ----------------------------------------------------------------------
* flick() being frozen is not the whole claim. Every other moving part in the file has its own
* guard — the shop pool's breath, the signal cycle and its amber blink, the advert's bob and its
* scan sweep — and the contract says every element must damp or freeze. With the camera frozen
* too, nothing in any of these four elements may move a single cell by a single unit. */
console.log('\n4. REDUCED MOTION — frozen camera, CC.reducedMotion = true, nothing may move at all');
CC.reducedMotion = true;
let rmWorst = 0;
for (const seed of [0, 555]) {
city_ = CC.City.make(seed);
if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); }
const rng = CC.mulberry(seed ^ 0x9e3779b9);
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: COLS, rows: ROWS });
for (const name of NAMES) {
const r = fixture(name, seed, els, 12);
if (!r) {
console.log(` seed ${String(seed).padStart(3)} ${name.padEnd(10)} NOT MEASURED — no element named '${name}' in CC.ELEMENTS`);
notApplicable.push(`4. seed ${seed} ${name}: element not present, nothing measured`);
continue;
}
/* A frozen element that painted nothing is the one case where "worst step 0" is arithmetic
* about an empty set. It is the exact shape of claim this tool exists to stop being made. */
if (r.painted === 0)
notApplicable.push(`4. seed ${seed} ${name}: painted no cell, its 0/255 is an empty set`);
if (r.worst > rmWorst) rmWorst = r.worst;
const bad = r.worst > 0;
if (bad) ok = false;
console.log(` seed ${String(seed).padStart(3)} ${name.padEnd(10)} cells painted ${String(r.painted).padStart(7)}` +
` worst per-cell frame step ${(r.worst * 255).toFixed(0)}/255 ` +
(r.painted === 0 ? 'NOT MEASURED — no fixture in view' : bad ? 'FAIL — still moving' : 'ok'));
}
}
CC.reducedMotion = false;
if (notApplicable.length) {
console.log('\nNOT MEASURED (these checks verified nothing; they are not passes):');
for (const s of notApplicable) console.log(' ' + s);
}
/* Two numbers, always both, always labelled with which section they came from — section 2 is the
* live build and section 4 is reduced motion, and a report has already quoted the second as if it
* were the first. See the note at the top of this file. */
console.log(`\nSUMMARY: live worst per-cell step ${(liveWorst * 100).toFixed(1)}% of 255 (${liveWorstWhat}) | ` +
`reduced-motion worst ${(rmWorst * 255).toFixed(0)}/255`);
const verdict = !ok ? 'FAIL' : (notApplicable.length ? 'NOT_APPLICABLE' : 'PASS');
console.log(verdict === 'NOT_APPLICABLE' ? 'NOT APPLICABLE' : verdict);
console.log(`RESULT: ${verdict} ${SKY}`);
process.exit(verdict === 'PASS' ? 0 : verdict === 'FAIL' ? 1 : 3);

151
tools/headless.cjs Normal file
View file

@ -0,0 +1,151 @@
/* 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`);

188
tools/lightning-rate.cjs Normal file
View file

@ -0,0 +1,188 @@
/* PHOTOSENSITIVITY REGRESSION TEST for src/elements/weather.js's lightning.
*
* node tools/lightning-rate.cjs [seed] [seconds]
*
* Drives the real element against a synthetic uniform wall, so what comes out is the element's own
* intensity envelope with no city geometry modulating it, sampled once per 60 Hz frame. It prints
* the series across the strongest stroke in the window, the position of every local maximum, the
* gap between successive maxima in Hz, and the largest single-frame change as a fraction of the
* peak. Then it checks them against the two rules the envelope is written to.
*
* THE RULES. No two maxima closer than 0.34 s, and no single frame may move the envelope by more
* than a third of its peak. The first is the flash-rate ceiling (3 Hz, and lgEnv is built to sit at
* half of it); the second is what stops a stroke arriving as a step edge across the whole viewport.
* The envelope that shipped in the first cut failed both: two maxima 0.100 s apart — 10 Hz — and a
* single 16 ms frame carrying 100% of the amplitude.
*
* EXIT CODES, and the third one is the whole reason this paragraph exists:
*
* 0 PASS — strokes were measured and they obey both rules
* 1 FAIL — strokes were measured and one of the rules is broken
* 2 usage error — unknown sky, no lightning element
* 3 NOT APPLICABLE — the window contains no stroke at all, so NOTHING WAS MEASURED
*
* Code 3 is a bug fix. Under `--sky=mist` and `--sky=clear` weather.js scales the strike rate off
* P.storm, which is 0.00 for both, so the window is legitimately empty — and this file used to
* print "no strike in 600s" and `process.exit(0)` on the line that is now the NOT APPLICABLE
* branch, BEFORE the sky-rate census below had run. Two of the six skies therefore reported
* exactly what a clean storm reports, and any gate reading the exit code as a green light was
* being told "this sky is safe" by a run that had measured nothing whatsoever. The absence of
* strokes in those two skies is correct; a safety tool claiming to have verified it is not.
*
* Every run also prints one machine-readable last line, `RESULT: PASS|FAIL|NOT_APPLICABLE <sky>`,
* for readers that would rather grep than switch on $?. A gate that treats any non-zero as a stop
* will now stop on mist and clear, which is the honest reading: if you want "nothing to test is
* fine" you have to say so, by special-casing 3 or by matching the RESULT line.
*/
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
/* Flags are filtered out of the positionals so that `--sky=storm` on its own still means seed 1.
* Read straight off argv[2] it parsed to NaN, which flowed into CC.City.make(NaN) and produced a
* degenerate city rather than an error — the tool reported a pass on a city that is not the one
* that ships. Silent NaN is the worst failure mode a safety tool has. */
const ARGS = process.argv.slice(2).filter(function (a) { return a.indexOf('--') !== 0; });
const seed = parseInt(ARGS[0] || '1', 10);
const SECS = parseInt(ARGS[1] || '600', 10);
/* Which sky to test under. Default is `storm` and that is the point: weather.js scales both the
* strike RATE and the amplitude off P.storm, and this file used to load no weather director at
* all — so it exercised the element's REF fallback (the `rain` preset, storm 0.12) and the one
* state that can actually hurt somebody went untested. `--sky=rain` reproduces the old reading. */
const skyArg = process.argv.find(a => a.indexOf('--sky=') === 0);
const SKY = skyArg ? skyArg.slice(6) : 'storm';
global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined;
for (const rel of ['src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js',
'src/compose.js']) {
const p = path.join(root, rel); if (fs.existsSync(p)) require(p);
}
const edir = path.join(root, 'src/elements');
for (const fn of fs.readdirSync(edir).sort()) if (fn.endsWith('.js')) require(path.join(edir, fn));
const CC = global.CC;
const MIN_PEAK_GAP = 0.34; // seconds
const MAX_FRAME_STEP = 0.34; // fraction of the stroke's peak
const city = CC.City.make(seed);
const rng = CC.mulberry(seed ^ 0x9e3779b9);
/* The sky is pinned by WRITING THE PARAMETER BLOCK, not through Weather.set(). set() is a viewer
* control and the schedule is entitled to take it back — it releases the override the moment a
* segment boundary passes the timestamp, which over a ten-minute window happens within the first
* two minutes. The first version of this pin did exactly that and every sky converged on the same
* 47-stroke reading, which is the scheduled weather, not the sky asked for. A regression test
* wants the parameter held flat for the whole window, so it holds it itself.
* P is the live block every element reads, and it is never reallocated, so overwriting the eight
* fields in place after each director tick is what "this sky, for ten minutes" means. */
let PIN = null;
if (CC.Weather) {
CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635));
PIN = CC.Weather.PRESETS.filter(p => p.name === SKY)[0];
if (!PIN) { console.error('unknown sky: ' + SKY); process.exit(2); }
}
function pinSky() {
if (!PIN) return;
const P = CC.Weather.P, K = CC.Weather.KEYS;
for (let i = 0; i < K.length; i++) P[K[i]] = PIN.p[i];
P.name = P.from = P.to = PIN.name; P.blend = 1;
}
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: 200, rows: 60 });
const lg = els.find(e => e.name === 'lightning');
if (!lg) { console.error('no lightning element'); process.exit(2); }
/* A flat wall at 8 m filling the frame. Every cell is eligible, so the sum of what the element adds
* is proportional to its intensity and nothing else. */
const f = CC.makeFrame(60, 20);
const cam = { x: city.startX, z: city.startZ, yaw: 0, eyeY: 1.7, fov: 1.25,
horizon: 11.2, cellAspect: 0.5625, t: 0 };
const N = SECS * 60, S = new Float64Array(N);
for (let k = 0; k < N; k++) {
const t = k / 60;
/* The director is ticked in lockstep, exactly as main.js does it, because the element reads the
* live P block every frame and a stale one would freeze the storm ramp mid-transition. */
if (CC.Weather) { CC.Weather.update(1 / 60, t); pinSky(); }
lg.update(1 / 60, t, cam);
for (let i = 0; i < f.n; i++) { f.ch[i] = 1; f.col[i] = 5; f.lum[i] = 40; f.dist[i] = 8; f.kind[i] = 1; }
lg.draw(f, cam, t);
let sum = 0; for (let i = 0; i < f.n; i++) sum += f.lum[i] - 40;
S[k] = sum / f.n;
}
let bi = 0; for (let k = 0; k < N; k++) if (S[k] > S[bi]) bi = k;
/* An empty window is NOT a pass, and it used to exit 0 right here — see the exit-code table at the
* top. The flag is carried down instead so that the sky-rate census below still runs and still
* prints (it reports the honest zeros), and the verdict is decided once, at the bottom. */
const NOSTRIKE = S[bi] <= 0;
const a = Math.max(0, bi - 8), b = Math.min(N, bi + 84);
/* HOW OFTEN, across the WHOLE window, not just inside the one stroke printed below. The per-stroke
* envelope is only half the safety question — a stroke that is individually gentle is still a
* strobe if the next one lands a fifth of a second later — and the old version of this file could
* not see that, because it only ever looked at 1.5 s around the single strongest stroke.
*
* The measure is the guideline's own: count FLASHES (local maxima carrying at least 5% of the
* window's peak, the same threshold used below) and find the worst one-second sliding window.
* Three in a second is the ceiling; this build is written to sit at half of it. A stroke is a run
* of frames above 2% of peak, reported only so the strike RATE — which weather.js scales off
* P.storm — is visible as a number rather than inferred. */
const MAX_FLASH_HZ = 3;
const allPk = [], starts = [];
for (let k = 1; k < N - 1; k++) {
if (S[k] >= S[k - 1] && S[k] > S[k + 1] && S[k] > S[bi] * 0.05) allPk.push(k);
if (S[k] > S[bi] * 0.02 && S[k - 1] <= S[bi] * 0.02) starts.push(k);
}
let worstHz = 0, worstAt = 0;
for (let i = 0, j = 0; i < allPk.length; i++) {
while (allPk[i] - allPk[j] > 60) j++; // widest window ending at flash i, one second
if (i - j + 1 > worstHz) { worstHz = i - j + 1; worstAt = allPk[j]; }
}
const rateBad = worstHz > MAX_FLASH_HZ;
if (rateBad) { /* fall through to the report; ok is cleared below */ }
/* The verdict token on this line says `not measured` rather than `ok` when the window is empty,
* because a rate census over zero strokes is not a rate anybody checked. */
console.log(`sky '${SKY}': ${starts.length} strokes in ${SECS}s = one per ` +
`${starts.length ? (SECS / starts.length).toFixed(1) : '-'}s, ${allPk.length} flashes, ` +
`worst second holds ${worstHz} at t=${(worstAt / 60).toFixed(2)}s ` +
(NOSTRIKE ? 'not measured (no strokes in window)' : rateBad ? `FAIL (> ${MAX_FLASH_HZ} Hz)` : 'ok'));
if (NOSTRIKE) {
console.log(`no strike in ${SECS}s for seed ${seed} under '${SKY}': the envelope rules below were ` +
`NOT exercised — nothing to measure, so nothing is verified. Try another seed, or a ` +
`sky whose P.storm is non-zero (storm, rain, drizzle) if you meant to test them.`);
console.log('NOT APPLICABLE');
console.log(`RESULT: NOT_APPLICABLE ${SKY}`);
process.exit(3);
}
console.log(`seed ${seed}: strongest stroke peaks at t=${(bi / 60).toFixed(2)}s.`);
console.log('added luminance per cell, one value per 60 Hz frame:');
const ser = []; for (let k = a; k < b; k++) ser.push(S[k].toFixed(2).padStart(6));
for (let i = 0; i < ser.length; i += 12) console.log(' ' + ser.slice(i, i + 12).join(''));
const pk = [];
for (let k = a + 1; k < b - 1; k++)
if (S[k] >= S[k - 1] && S[k] > S[k + 1] && S[k] > S[bi] * 0.05) pk.push(k);
console.log('maxima above 5% of peak: ' + (pk.map(k => (k / 60).toFixed(3) + 's').join(', ') || 'one only'));
let ok = !rateBad;
for (let i = 1; i < pk.length; i++) {
const dt = (pk[i] - pk[i - 1]) / 60;
const bad = dt < MIN_PEAK_GAP;
if (bad) ok = false;
console.log(` gap ${dt.toFixed(3)}s = ${(1 / dt).toFixed(2)} Hz ${bad ? 'FAIL (< ' + MIN_PEAK_GAP + 's)' : 'ok'}`);
}
let ms = 0, msk = 0;
for (let k = a + 1; k < b; k++) { const d = Math.abs(S[k] - S[k - 1]) / S[bi]; if (d > ms) { ms = d; msk = k; } }
const stepBad = ms > MAX_FRAME_STEP;
if (stepBad) ok = false;
console.log(`largest single-frame step ${(ms * 100).toFixed(1)}% of peak at t=${(msk / 60).toFixed(3)}s ` +
(stepBad ? `FAIL (> ${MAX_FRAME_STEP * 100}%)` : 'ok'));
/* The step above is RELATIVE, which is the conservative reading and the one that gates the build,
* but on a weak sky it is relative to a peak that is itself nearly nothing. Printing the peak in
* absolute terms is what stops a 32%-of-peak step on a 6%-of-full-scale drizzle stroke being read
* as the same event as a 32% step on a storm. Full scale is 255, the whole luminance range. */
console.log(` stroke peak ${(100 * S[bi] / 255).toFixed(1)}% of full scale; that step is ` +
`${(100 * ms * S[bi] / 255).toFixed(2)}% of full scale`);
console.log(ok ? 'PASS' : 'FAIL');
console.log(`RESULT: ${ok ? 'PASS' : 'FAIL'} ${SKY}`);
process.exit(ok ? 0 : 1);

92
tools/metrics.py Normal file
View file

@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Measure a CyberCity CCFRAME dump: exposure and colour-energy split.
A cell is classified by what it ACTUALLY prints — max(r,g,b) scaled by lum — not by lum
alone, because lum lies: P.shadow at lum 255 is still only (40,50,66) while P.pure at lum
40 is (40,40,40). "black" therefore means a cell no eye would call lit.
Reads CCFRAME 1 (glyph,colour,lum) and CCFRAME 2 (glyph,colour,lum,KIND) alike. The v2
kind byte was added when the harness started dumping it and this file was not updated, so
it unpacked three fields from a four-field cell and died with a ValueError on every dump
the current tools/headless.cjs writes. Two agents worked around it with throwaway scripts
rather than fixing it; the fix is the two lines below and a kind breakdown for free.
python3 tools/metrics.py f.txt [more.txt ...]
"""
import sys, json
NAMES = ['amber','azure','ember','spring','violet','white','red','slate','warm','ice','pure','shadow']
KINDS = ['sky', 'facade', 'floor', 'element']
def load(src):
lines = open(src).read().split('\n')
cols, rows = map(int, lines[1].split())
pal = [tuple(map(int, c.split(','))) for c in lines[2].split(' ', 1)[1].split()]
glyphs = json.loads(lines[3].split(' ', 1)[1])
cells = []
for y in range(rows):
parts = lines[4 + y].split(' ')
cells.append([tuple(int(v) for v in p.split(',')) for p in parts[:cols]])
return cols, rows, pal, glyphs, cells
def main(srcs):
tot_cell = 0; blank = 0; dead = 0; mid = 0; litcell = 0
energy = [0.0]*len(NAMES); litE = [0.0]*len(NAMES)
kinds = [0]*len(KINDS); kindLit = [0]*len(KINDS)
# The two numbers core.js's EXPOSURE comment tells the reader to measure, which this file
# could not see: the muddy band v=9-119 (target under 30%) and the hot tail v>=170 (target
# 3.5-5%). They are deliberately NOT the same cut as the mid(9-59)/lit(v>=60) split above --
# that split answers "is the cell visible", these answer "is the print curve in calibration"
# -- so both are reported rather than one replacing the other. black% is kept because it is
# in every historical report, but it is pinned by `blank` and cannot detect a curve change.
muddy = 0; hot = 0; litv = []
for src in srcs:
cols, rows, pal, glyphs, cells = load(src)
for y in range(rows):
for x in range(cols):
cell = cells[y][x]
# v1 carries three fields per cell, v2 four; the fourth is the kind byte.
ch, ci, lu = cell[0], cell[1], cell[2]
kd = cell[3] if len(cell) > 3 else -1
tot_cell += 1
if 0 <= kd < len(KINDS): kinds[kd] += 1
if ch == 0 or lu == 0:
blank += 1; dead += 1
continue
if 0 <= kd < len(KINDS): kindLit[kd] += 1
r, g, b = pal[ci % len(pal)]
k = lu/255.0
# what the pixel ACTUALLY renders at — lum alone lies, because P.shadow at
# lum 255 is still only (26,30,38) while P.pure at lum 40 is (40,40,40).
v = max(r, g, b) * k
e = (r+g+b)/3.0 * k
if 9 <= v < 120: muddy += 1
if v >= 170: hot += 1
if v >= 9: litv.append(v)
if v < 9: dead += 1
elif v < 60: mid += 1
else:
litcell += 1
litE[ci % len(NAMES)] += e
energy[ci % len(NAMES)] += e
es = sum(energy) or 1.0
ls = sum(litE) or 1.0
print(f"files={len(srcs)} cells={tot_cell}")
print(f" blank {blank/tot_cell*100:.1f}% black(v<9) {dead/tot_cell*100:.1f}%"
f" mid(9-59) {mid/tot_cell*100:.1f}% lit(v>=60) {litcell/tot_cell*100:.1f}%")
litv.sort()
p90 = litv[int(0.90 * (len(litv) - 1))] if litv else 0.0
print(f" CURVE: muddy(9-119) {muddy/tot_cell*100:.1f}% [target <30]"
f" hot(v>=170) {hot/tot_cell*100:.2f}% [target 3.5-5]"
f" lit p90 {p90:.0f}")
order = sorted(range(len(NAMES)), key=lambda i: -litE[i])
print(" LIT energy: " + " ".join(f"{NAMES[i]} {litE[i]/ls*100:.1f}%" for i in order if litE[i]/ls > 0.0005))
order = sorted(range(len(NAMES)), key=lambda i: -energy[i])
print(" all energy: " + " ".join(f"{NAMES[i]} {energy[i]/es*100:.1f}%" for i in order if energy[i]/es > 0.0005))
if sum(kinds):
print(" by kind: " + " ".join(
f"{KINDS[i]} {kinds[i]/tot_cell*100:.1f}% (lit {kindLit[i]/tot_cell*100:.1f}%)"
for i in range(len(KINDS))))
if __name__ == '__main__':
main(sys.argv[1:])

37
tools/topng.py Normal file
View file

@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Render a headless CyberCity frame to a PNG, with the same bloom the canvas applies."""
import sys, json
from PIL import Image, ImageDraw, ImageFont, ImageFilter
CW, CH = 9, 16
FONT = ImageFont.truetype("/usr/share/fonts/liberation-mono-fonts/LiberationMono-Bold.ttf", 15)
def main(src, dst):
lines = open(src).read().split('\n')
assert lines[0].startswith('CCFRAME'), 'not a CCFRAME dump'
cols, rows = map(int, lines[1].split())
pal = [tuple(map(int, c.split(','))) for c in lines[2].split(' ', 1)[1].split()]
glyphs = json.loads(lines[3].split(' ', 1)[1])
im = Image.new('RGB', (cols * CW, rows * CH), (2, 3, 6))
d = ImageDraw.Draw(im)
lit = 0
for y in range(rows):
parts = lines[4 + y].split(' ')
for x in range(cols):
fld = parts[x].split(',') # CCFRAME 2 appends a kind byte; ignore it here
ch, ci, lu = int(fld[0]), int(fld[1]), int(fld[2])
if ch == 0 or lu == 0: continue
r, g, b = pal[ci % len(pal)]
k = lu / 255.0
d.text((x * CW, y * CH), glyphs[ch], font=FONT,
fill=(int(r * k), int(g * k), int(b * k)))
lit += 1
g1 = im.filter(ImageFilter.GaussianBlur(1.5))
g2 = im.filter(ImageFilter.GaussianBlur(5.0))
glow = Image.blend(g1, g2, 0.5)
im = Image.blend(im, Image.eval(glow, lambda v: min(255, int(v * 2.0))), 0.5)
im.save(dst)
print(f"{dst} {cols}x{rows} cells {lit/(cols*rows)*100:.1f}% lit")
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2])