From 574d4113e6db2870357ea152a68314052a00d0fe Mon Sep 17 00:00:00 2001 From: MiguelCarino Date: Sun, 16 Aug 2026 02:20:18 -0600 Subject: [PATCH] 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. --- .gitignore | 2 + CONTRACT.md | 68 + build.js | 241 ++ index.html | 7997 +++++++++++++++++++++++++++++++++++++ src/city.js | 641 +++ src/control.js | 693 ++++ src/core.js | 489 +++ src/elements/hud.js | 326 ++ src/elements/optics.js | 1176 ++++++ src/elements/signage.js | 1824 +++++++++ src/elements/sky.js | 954 +++++ src/elements/street.js | 1423 +++++++ src/elements/structure.js | 1297 ++++++ src/elements/weather.js | 1337 +++++++ src/main.js | 344 ++ src/raycast.js | 459 +++ src/render_canvas.js | 244 ++ src/surfaces.js | 1390 +++++++ src/weather_state.js | 227 ++ tools/domshim.cjs | 1165 ++++++ tools/exposure.py | 14 + tools/flicker-rate.cjs | 421 ++ tools/headless.cjs | 151 + tools/lightning-rate.cjs | 188 + tools/metrics.py | 92 + tools/topng.py | 37 + 26 files changed, 23200 insertions(+) create mode 100644 .gitignore create mode 100644 CONTRACT.md create mode 100644 build.js create mode 100644 index.html create mode 100644 src/city.js create mode 100644 src/control.js create mode 100644 src/core.js create mode 100644 src/elements/hud.js create mode 100644 src/elements/optics.js create mode 100644 src/elements/signage.js create mode 100644 src/elements/sky.js create mode 100644 src/elements/street.js create mode 100644 src/elements/structure.js create mode 100644 src/elements/weather.js create mode 100644 src/main.js create mode 100644 src/raycast.js create mode 100644 src/render_canvas.js create mode 100644 src/surfaces.js create mode 100644 src/weather_state.js create mode 100644 tools/domshim.cjs create mode 100644 tools/exposure.py create mode 100644 tools/flicker-rate.cjs create mode 100644 tools/headless.cjs create mode 100644 tools/lightning-rate.cjs create mode 100644 tools/metrics.py create mode 100644 tools/topng.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a60b85 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/CONTRACT.md b/CONTRACT.md new file mode 100644 index 0000000..462ee2c --- /dev/null +++ b/CONTRACT.md @@ -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 > 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. diff --git a/build.js b/build.js new file mode 100644 index 0000000..6956b44 --- /dev/null +++ b/build.js @@ -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 = ` + + + + + + +CyberCity + + + + +
click for fullscreen
+ + + +`; + +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); +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..c22f8c5 --- /dev/null +++ b/index.html @@ -0,0 +1,7997 @@ + + + + + + + +CyberCity + + + + +
click for fullscreen
+ + + diff --git a/src/city.js b/src/city.js new file mode 100644 index 0000000..eab1f88 --- /dev/null +++ b/src/city.js @@ -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; +})(); diff --git a/src/control.js b/src/control.js new file mode 100644 index 0000000..92bb4c0 --- /dev/null +++ b/src/control.js @@ -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')); diff --git a/src/core.js b/src/core.js new file mode 100644 index 0000000..26922c4 --- /dev/null +++ b/src/core.js @@ -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; diff --git a/src/elements/hud.js b/src/elements/hud.js new file mode 100644 index 0000000..6ac6d95 --- /dev/null +++ b/src/elements/hud.js @@ -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')); diff --git a/src/elements/optics.js b/src/elements/optics.js new file mode 100644 index 0000000..5456aee --- /dev/null +++ b/src/elements/optics.js @@ -0,0 +1,1176 @@ +/* CyberCity optics — the glass between the city and the eye. + * + * Nothing in this file belongs to the city. It is the last thing that happens to a frame: light + * hanging in the rain under a strong source, the wash a close lamp throws across the wall behind + * it, the far end of the street going cold in mist, the fall-off at the edge of vision, fogged + * glass, drops beaded on the lens, the flare off the hottest cells, the faint horizontal texture + * of the display, and the eye adapting to all of it. + * + * THE BUDGET, which is the whole discipline of this file. The frame is 40-55% pure black and that + * IS the look. So of the seven passes here, three cannot add a single lit cell by construction — + * they only multiply cells the city already drew — and of the four that can write a glyph, three + * write into black air alone and the fourth is rationed to twenty sources. + * + * SEVEN, not the nine this file was written with. Nothing was cut: the two edge-weighted + * multipliers (vignette, condensation) are one pass and the two whole-frame multipliers + * (scanlines, exposure) are another, because each pair was walking the same cells to apply what + * is arithmetically a single number. See sections 4 and 8. + * + * The whole file, measured against the version that shipped before it, over seeds 3/7/42/99 at + * frames 600/3000/9000 at 400x100 (exposure held out of both sides, because its free-running sine + * is at a different phase in the two builds and would swamp the comparison): lit coverage + * 59.43% -> 59.57%, +0.14 points, and mean printed luminance +0.31%. It is not evenly spread and + * it is not meant to be — mist gains +0.48 points of coverage and LOSES 0.13% of its luminance, + * because the shafts open up and the condensation takes more contrast off than they add; drizzle + * loses 0.02 points and 0.61%; a downpour gains 1.27% of luminance almost entirely from the wash + * off the near signage. Re-measure exactly this way before touching any constant below. + * + * MOST OF THESE PASSES MODULATE cells they did not create. put() only accepts a strictly nearer + * depth, so see nearer() for how that rewrite is bought without opening a hole in the depth + * buffer that a later element could fall through. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, put = CC.put, hash2 = CC.hash2, clamp = CC.clamp, vnoise = CC.vnoise, + lerp = CC.lerp, smoothstep = CC.smooth; + + var G_DOT = CC.g('.'), G_TICK = CC.g('`'), G_QUOTE = CC.g("'"), G_COLON = CC.g(':'), + G_o = CC.g('o'), G_O = CC.g('O'), G_DASH = CC.g('-'); + + /* Weather, read the ONLY sanctioned way. rel(k) is the parameter divided by its value in the + * 'rain' preset, which is the preset every constant below was tuned under, so each expression + * here is written to come out at exactly its old value when rel() is 1 — grep for `rel=1` in the + * comments. Multiplying a tuned constant by the raw P.rain instead would silently re-tune this + * whole file to 65% of what shipped. + * The guard is not defensive noise: tools/headless.cjs loads whatever modules exist so the + * harness stays useful mid-rewrite, and an optics pass that throws takes the entire frame down. */ + function rel(k) { return CC.Weather ? CC.Weather.rel(k) : 1; } + + /* How much there is in the air to catch light — the one number the volumetrics in this file all + * scale by, so a shaft, the wash off a headlamp and the halo on the lens can never disagree + * about whether the street is clear or full of water. Fog is the strong term because fog is + * suspended droplets, which is what actually scatters; haze is the weak one because it is + * mostly distance. At rel=1 this is 0.22+0.46+0.32 = 1.00 exactly. Clear air lands near 0.42 + * and mist saturates the ceiling, which is a beam five times as thick as a clear-night one. */ + function airDensity() { + return clamp(0.22 + 0.46 * rel('fog') + 0.32 * rel('haze'), 0.26, 2.40); + } + + /* A modulation pass has to rewrite a cell it did not author, and put() rejects an equal depth. + * Shaving a part in ten thousand off the existing depth satisfies the test while leaving the + * cell at effectively the same place in the queue, so a sibling element that would have drawn + * in front of it still can. + * Sky carries Infinity and has no representable nudge, so this refuses it — which is the right + * answer for the passes that WRITE A GLYPH (a shaft, a mote, a bead, a flare streak): those add + * lit cells, the backdrop is not theirs to add to, and the budget at the top of this file counts + * on them staying out of it. The passes that only multiply an existing cell need the backdrop + * and go through gainDepth() below instead. Note that a backdrop cell one of them has already + * touched carries BACKDROP_D, which is past 1e30 and so is still refused here: a glyph writer + * sees the same sky whether a gain pass has been over it or not. */ + function nearer(d) { + if (!(d < 1e30)) return -1; + var n = d - d * 1e-4; + return n < d ? n : -1; + } + + /* The depth a modulation pass writes the BACKDROP back at. + * + * Sky is stored at Infinity, which has nothing representable below it, so for as long as gain() + * went through nearer() the four whole-frame multipliers in this file — vignette, condensation, + * scanlines, exposure — could not touch one sky cell. The sky ELEMENTS could: the moon, the + * blimps, the beacons and the drones are deliberately given a large FINITE depth (~1e5) so they + * self-occlude against the world pass, and every one of those passes modulated them normally. + * Measured at 400x100 frame 600, that split 882/1123/1950/784 backdrop cells on seeds 3/7/42/99 + * away from 652/219/126/603 sky-element cells sitting in the same slot, so the corners of the + * frame carried a vignetted moon inside an unvignetted starfield and the scanline dip stopped at + * the edge of every sky object. The backdrop has to breathe with the rest of the picture. + * + * A sentinel past 1e30 rather than a small finite depth, because "past 1e30" is what the rest of + * this file and core.js's tone() already read as backdrop: mistfar's `d > 1e30` still skips it, + * tone()'s `d >= SKY_D` still prints it at the near end of the curve, nearer() still refuses it + * to glyph writers, and no element in the build draws at any depth remotely near it — so making + * the depth finite opens no hole for a later element to fall through. It is small enough for the + * part-in-ten-thousand nudge to stay representable in float32, which is what lets the second, + * third and fourth pass over the same cell keep working. */ + var BACKDROP_D = 1e34; + + function gainDepth(d) { + if (d === Infinity) return BACKDROP_D; + if (!(d < 1e35)) return -1; // NaN, and nothing else can reach here + var n = d - d * 1e-4; + return n < d ? n : -1; + } + + /* Multiply one cell's brightness in place. Cells already at zero are skipped — there is no + * such thing as a darker black — and so is any gain too small to survive the 0..255 + * quantisation, which keeps four chained passes from writing thousands of cells for nothing. */ + function gain(f, x, y, g) { + var i = y * f.cols + x, lum = f.lum[i]; + if (lum === 0) return; + var nl = (lum * g + 0.5) | 0; + if (nl === lum) return; + var d = gainDepth(f.dist[i]); + if (d < 0) return; + put(f, x, y, f.ch[i], f.col[i], nl, d, f.kind[i]); + } + + /* ===================================================================================== + * 1. Volumetric shafts + * + * There is no lamp registry to read — streetlights and signage belong to other files — so the + * sources are found in the FRAME. A column carrying several very bright chromatic cells above + * the horizon is, by construction, a sign or a lit storey, and that is exactly what throws a + * shaft down through the rain. Reading the frame also means the shaft can never disagree with + * the picture about where the light is. + * + * Three shafts, never more. They only fill cells that are already black, so a shaft can never + * dim or recolour anything the city drew — it is pure addition into empty air, and the dither + * keeps it reading as motes rather than as the grey veil that would wreck the whole aesthetic. + * ===================================================================================== */ + var SHAFTS = 3; + + var shaft = { + name: 'lightshafts', + layer: 78, // before every modulation pass: the shafts are in the world, not on the lens + + init: function (city, rng) { + this.seed = ((rng() * 4294967296) | 0) ^ 0x5A17; + this.primed = false; + this.found = 0; + this.cols = 0; + // Per-column detection scratch. Sized on first draw and only ever regrown, never per frame. + this.score = null; this.smooth = null; this.srcY = null; this.srcC = null; this.hits = null; + // Live shaft slots, eased frame to frame so a sign passing behind a pillar fades out + // instead of blinking off. + this.sx = new Float32Array(SHAFTS); + this.sy = new Float32Array(SHAFTS); + this.sc = new Uint8Array(SHAFTS); + this.ss = new Float32Array(SHAFTS); + this.pkX = new Int32Array(SHAFTS); + this.pkY = new Int32Array(SHAFTS); + this.pkC = new Uint8Array(SHAFTS); + this.pkS = new Float32Array(SHAFTS); + this.tilt = new Float32Array(SHAFTS); + for (var i = 0; i < SHAFTS; i++) this.tilt[i] = (rng() - 0.5) * 0.62; + }, + + /* The easing lives HERE, on the simulation tick, and not in draw(). main.js runs a fixed-step + * accumulator: update() is called at a constant 1/60 s while draw() is called once per rendered + * frame at whatever rate the panel does, so easing where the frame is drawn made a shaft slide + * and fade twice as fast on a 120 Hz screen as on a 60 Hz one — the exact class of bug the + * accumulator exists to prevent. The targets are the ones the previous draw detected, which is + * one tick of lag on a quantity whose own time constant is a third of a second. + * Nothing is allocated and nothing is drawn; the frame is not even visible from here. */ + update: function (dt) { + if (!this.primed) return; // no detection has run yet: nothing to ease toward + var d = dt > 0.25 ? 0.25 : dt; + var eP = 1 - Math.exp(-d * 6.0); // position + var eS = 1 - Math.exp(-d * 2.2); // strength + var found = this.found; + for (var s = 0; s < SHAFTS; s++) { + var tgt = s < found ? clamp((this.pkS[s] - 150) / 420, 0, 1) : 0; + if (s < found) { + var dxs = this.pkX[s] - this.sx[s]; + // A jump of more than a few columns is a different source, not the same one moving. + if (this.ss[s] < 0.06 || dxs > 14 || dxs < -14) { + this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s]; + } else { + this.sx[s] += dxs * eP; + this.sy[s] += (this.pkY[s] - this.sy[s]) * eP; + } + this.sc[s] = this.pkC[s]; + } + this.ss[s] += (tgt - this.ss[s]) * eS; + } + }, + + sizeTo: function (cols) { + if (this.cols === cols) return; + this.cols = cols; + // Allocation on RESIZE only, which is a DOM event, not a frame. There is no honest way to + // size these at init(): the element interface hands init a city, not a viewport. + this.score = new Float32Array(cols); + this.smooth = new Float32Array(cols); + this.srcY = new Int32Array(cols); + this.srcC = new Uint8Array(cols); + this.hits = new Uint8Array(cols); + }, + + /* Sources are chromatic and bright. Slate, white and shadow are structure and pavement — + * a kerb catching a highlight is not a lamp and must not grow a beam. */ + isSource: function (c) { + return c !== P.slate && c !== P.white && c !== P.shadow && c !== P.pure; + }, + + detect: function (f, hz) { + var cols = f.cols, rows = f.rows, x, y, i; + var score = this.score, srcY = this.srcY, srcC = this.srcC, hits = this.hits; + for (x = 0; x < cols; x++) { score[x] = 0; srcY[x] = -1; srcC[x] = 0; hits[x] = 0; } + + var yEnd = (hz + rows * 0.12) | 0; + if (yEnd > rows - 1) yEnd = rows - 1; + for (y = 0; y <= yEnd; y++) { + for (x = 0; x < cols; x++) { + i = y * cols + x; + var l = f.lum[i]; + if (l < 150) continue; + var c = f.col[i]; + if (!this.isSource(c)) continue; + score[x] += l - 150; + if (hits[x] < 255) hits[x]++; + // The shaft hangs below the source, so the anchor is the LOWEST bright row, not the + // brightest: a beam that starts at the middle of a blade sign reads as a mistake. + if (y > srcY[x]) { srcY[x] = y; srcC[x] = c; } + } + } + + /* A sign is several columns wide and a single hot column is a lit window, which is far too + * small to throw a visible beam. Smoothing over +-2 columns is what discriminates them. */ + var sm = this.smooth; + for (x = 0; x < cols; x++) { + var a = 0, n = 0; + for (i = x - 2; i <= x + 2; i++) if (i >= 0 && i < cols) { a += score[i]; n++; } + sm[x] = a / n; + } + + var found = 0, k, best, bv; + for (k = 0; k < SHAFTS; k++) { + best = -1; bv = 170; // ~6 bright cells across the window; below that + for (x = 0; x < cols; x++) if (sm[x] > bv) { bv = sm[x]; best = x; } + if (best < 0) break; // nothing left worth a beam + // The smoothed peak can land a column or two off the actual glyphs, which would leave the + // anchor row unset. Snap back onto the hottest real column inside the window. + var pick = best, pv = -1; + for (i = best - 2; i <= best + 2; i++) + if (i >= 0 && i < cols && srcY[i] >= 0 && score[i] > pv) { pv = score[i]; pick = i; } + if (srcY[pick] < 0 || hits[pick] < 3) { sm[best] = 0; k--; continue; } + this.pkX[found] = pick; this.pkY[found] = srcY[pick]; + this.pkC[found] = srcC[pick]; this.pkS[found] = bv; + found++; + for (i = best - 9; i <= best + 9; i++) if (i >= 0 && i < cols) sm[i] = 0; + } + + // Sorted by column so slot i keeps tracking the same physical source between frames; an + // unsorted assignment makes shafts swap places and strobe. + for (k = 1; k < found; k++) { + var jx = this.pkX[k], jy = this.pkY[k], jc = this.pkC[k], js = this.pkS[k], j = k - 1; + while (j >= 0 && this.pkX[j] > jx) { + this.pkX[j + 1] = this.pkX[j]; this.pkY[j + 1] = this.pkY[j]; + this.pkC[j + 1] = this.pkC[j]; this.pkS[j + 1] = this.pkS[j]; j--; + } + this.pkX[j + 1] = jx; this.pkY[j + 1] = jy; this.pkC[j + 1] = jc; this.pkS[j + 1] = js; + } + return found; + }, + + draw: function (f, cam, t) { + var cols = f.cols, rows = f.rows; + this.sizeTo(cols); + var hz = cam && cam.horizon !== undefined ? cam.horizon : rows * 0.56; + var found = this.detect(f, hz); + /* Handed to update(), which owns the easing. draw() only ever READS the eased slots. */ + this.found = found; + + var s, i, x, y; + /* The very first frame has nothing to ease from, and a shaft easing up out of nothing over + * half a second means the piece opens on a street whose lamps have no beams. So the first + * detection lands directly on the slots and every later one is eased in update(). Note this + * is genuinely the FIRST frame now: while tools/headless.cjs drew once at the end of a + * replay, every offline frame took this branch and no offline frame ever showed an eased + * shaft — the easing below existed only in the browser. */ + if (!this.primed) { + this.primed = true; + for (s = 0; s < SHAFTS; s++) { + this.ss[s] = s < found ? clamp((this.pkS[s] - 150) / 420, 0, 1) : 0; + if (s < found) { + this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s]; this.sc[s] = this.pkC[s]; + } + } + } + + /* A beam is only as visible as the air it is crossing. On a clear night there is nothing + * between the lamp and the eye and the shaft is barely a suggestion round the glyphs; in + * mist the same lamp fills the street. Three separate terms move, and they have to move + * together or the beam changes shape instead of changing density: how far it reaches, how + * wide it spreads, and how solid it is at the core. All three are 1.0 at rel=1. */ + var air = airDensity(); + var reach = 0.80 + 0.20 * air; // length: the least sensitive, or a clear night loses the beam + var spread = 0.66 + 0.34 * air; // half-width + var dense = 0.35 + 0.65 * air; // alpha, and therefore very nearly the cell count + /* And the beam's own brightness, which is the term that decides whether it reads at all: + * the shafts print in the SOURCE's swatch, and the source is usually amber, whose print + * weight is the most held-down in the table (0.19). At the old flat lum a mist beam landed + * at 17/255 on screen, which the bloom smeared into nothing. */ + var glow = 0.45 + 0.55 * air; + /* Rain crossing the beam. The rain is already in the frame — weather.js drew it thirty + * layers ago — so the light does not need to invent a drop, it needs to find the one that + * is there and make it brighter than its neighbours outside the beam. That contrast IS the + * volumetric read, and it costs no coverage at all. */ + var wet = clamp(0.55 * rel('rain') + 0.45 * rel('steam'), 0, 1.6); + + for (s = 0; s < SHAFTS; s++) { + var str = this.ss[s]; + if (str < 0.07) continue; + + var x0 = this.sx[s], y0 = this.sy[s], hue = this.sc[s], tilt = this.tilt[s]; + var L = (8 + 10 * str) * reach; + // Rain drifting through the beam. Frozen to a constant under reduced motion — a shaft + // that pulses is the single most distracting thing this file can do. + var moving = !CC.reducedMotion; + + for (var k = 1; k <= L; k++) { + y = (y0 + k) | 0; + if (y >= rows) break; + if (y < 0) continue; + var fall = 1 - k / L; + /* Only down to 30% at the far end, not to zero. A shaft that fades out along its length + * as fast as it widens dies inside six rows and reads as dust round the lamp; keeping a + * floor under it is what makes the beam reach the ground, which is the whole point. */ + var along = 0.30 + 0.70 * fall; + var hw = (0.62 + k * 0.22) * spread; + var cxr = x0 + k * tilt; + // Minus t, not plus: the sampling point has to travel DOWN the beam for the thickenings + // to read as rain falling through it rather than as smoke rising out of the street. + var breathe = moving ? 0.70 + 0.44 * vnoise(k * 0.42 - t * 1.7 + s * 13.7, this.seed) + : 0.90; + var xa = Math.ceil(cxr - hw), xb = Math.floor(cxr + hw); + for (x = xa; x <= xb; x++) { + if (x < 0 || x >= cols) continue; + var dn = (x - cxr) / hw; + var e2 = 1 - dn * dn; + if (e2 <= 0) continue; + // sqrt, not the parabola it is derived from: squared, the cross-section is under the + // 0.06 floor everywhere but dead centre and a full-strength shaft lands three cells + // in the whole frame — measured, not guessed. + var a = str * along * Math.sqrt(e2) * breathe * dense; + if (a < 0.06) continue; + i = y * cols + x; + /* Something is already here. If it is faint and it is an ELEMENT — rain, sleet, + * steam, a mote — then it is airborne water inside the cone and it lights up; that is + * the one case where a shaft is allowed to touch a cell it did not author. The lum + * ceiling is the guard that keeps this to the air: a lamp, a sign or a car at 130+ is + * a source in its own right and a beam crossing it must not make it hotter. */ + if (f.ch[i] !== 0 && f.lum[i] > 4) { + if (f.kind[i] === 3 && f.lum[i] < 130 && wet > 0.05) + gain(f, x, y, 1 + a * 0.85 * wet); + continue; + } + /* Dither welded to the shaft's own seed: a solid cone is a veil, and a cone that + * re-rolls every frame is static. The pattern is fixed; only `a` breathes. + * Scaled past 1 on purpose, so the beam's core column is continuous while its edges + * stay scattered. A uniformly sampled cone at this density is not a shaft, it is + * confetti — coherence down the middle is the entire read. */ + if (hash2(x, y * 3 + s * 97, this.seed) > a * 1.15) continue; + var d = nearer(f.dist[i]); + if (d < 0) continue; + /* Thick air also changes the GLYPH, not just the value. A colon is two marks in the + * cell where a backtick is one, so the beam gains body in mist by covering more of + * the cell rather than by turning up a number the print curve would only crush. */ + put(f, x, y, a > 0.62 && air > 1.25 ? G_COLON : (a > 0.46 ? G_QUOTE : G_TICK), + hue, (7 + a * 17) * glow, d, 3); + } + } + } + } + }; + + /* ===================================================================================== + * 2. The wash off a bright thing that is CLOSE. + * + * A headlamp swinging through an intersection does not only light its own cells: it drags a + * wedge of light across the facade behind it, and the wedge arrives before the lamp does and + * leaves after it. The cars themselves belong to street.js and this file may not touch them, so + * the pass works the way a real lens does — over the FINISHED frame, reading dist and col. Any + * bright near thing qualifies: a headlamp, a shopfront two metres away, a blade sign at the + * corner. That is not a compromise, it is the honest generalisation. + * + * This pass is PURE GAIN. It never writes a glyph, so it cannot cost a single cell of coverage + * and cannot recolour anything; all it does is decide that some cells the city already drew are + * standing in somebody's light. The wedge leans in the direction the source is travelling, + * which costs nothing to know: the eased position lags the detected one, and that lag IS the + * screen velocity. + * ===================================================================================== */ + var WASH = 2; // two at once. Three sources this near is a fairground, not a street + var W_NEAR = 26; // metres. Past this a lamp is scenery and lights nothing but itself + var W_ON = 70, W_FULL = 320; // tile energy for a wash to start, and for it to reach full strength + + var wash = { + name: 'lightwash', + layer: 79, // still in the world: this is light on surfaces, not dirt on glass + + init: function (city, rng) { + // Small seed, varied additively — see the note in weather.js about hash2 and large seeds. + this.seed = (rng() * 30011) | 0; + this.cols = 0; this.rows = 0; this.tw = 0; this.th = 0; + this.te = null; this.tx = null; this.ty = null; // tile energy and its centroid + this.tc = null; this.tl = null; this.td = null; // hue, lum and depth of the tile's peak + this.found = 0; this.primed = false; + this.pkX = new Float32Array(WASH); this.pkY = new Float32Array(WASH); + this.pkS = new Float32Array(WASH); this.pkD = new Float32Array(WASH); + this.pkC = new Uint8Array(WASH); + this.sx = new Float32Array(WASH); this.sy = new Float32Array(WASH); + this.ss = new Float32Array(WASH); this.sd = new Float32Array(WASH); + this.sc = new Uint8Array(WASH); + this.lead = new Float32Array(WASH); + }, + + /* Same division of labour as the shafts: draw() detects into pk*, update() eases into s*. + * The easing has to run on the fixed simulation tick or the wedge crosses a facade at twice + * the speed on a 120 Hz panel. */ + update: function (dt) { + if (!this.primed) return; + var d = dt > 0.25 ? 0.25 : dt; + var eP = 1 - Math.exp(-d * 7.0), eS = 1 - Math.exp(-d * 2.6); + var found = this.found; + for (var s = 0; s < WASH; s++) { + var tgt = s < found ? clamp((this.pkS[s] - W_ON) / (W_FULL - W_ON), 0, 1) : 0; + if (s < found) { + var dxs = this.pkX[s] - this.sx[s]; + // Beyond a slot's tracking window this is a different lamp, not the same one moving. + if (this.ss[s] < 0.05 || dxs > 20 || dxs < -20) { + this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s]; this.lead[s] = 0; + } else { + this.sx[s] += dxs * eP; + this.sy[s] += (this.pkY[s] - this.sy[s]) * eP; + /* The wedge leans ahead of the lamp by its own lag. A parked sign has zero lag and + * gets a symmetric pool; something crossing the frame gets a wedge that runs ahead + * of it, which is what makes a pass read as a sweep rather than as a lamp with a + * glow stuck to it. */ + this.lead[s] += (clamp(dxs * 1.7, -10, 10) - this.lead[s]) * eP; + } + this.sc[s] = this.pkC[s]; this.sd[s] = this.pkD[s]; + } + this.ss[s] += (tgt - this.ss[s]) * eS; + } + }, + + sizeTo: function (cols, rows) { + if (this.cols === cols && this.rows === rows) return; + this.cols = cols; this.rows = rows; + // Resize-time allocation only; a tile is 6x3 cells, which is about the size of a car at + // fifteen metres and small enough that one shopfront does not swallow the whole frame. + this.tw = Math.ceil(cols / 6); this.th = Math.ceil(rows / 3); + var n = this.tw * this.th; + this.te = new Float32Array(n); this.tx = new Float32Array(n); this.ty = new Float32Array(n); + this.tc = new Uint8Array(n); this.tl = new Uint8Array(n); this.td = new Float32Array(n); + }, + + detect: function (f) { + var cols = f.cols, rows = f.rows, tw = this.tw; + var te = this.te, tx = this.tx, ty = this.ty, tc = this.tc, tl = this.tl, td = this.td; + var n = tw * this.th, i, x, y; + for (i = 0; i < n; i++) { te[i] = 0; tx[i] = 0; ty[i] = 0; tc[i] = 0; tl[i] = 0; td[i] = 0; } + + for (y = 0; y < rows; y++) { + var ry = ((y / 3) | 0) * tw; + for (x = 0; x < cols; x++) { + i = y * cols + x; + var l = f.lum[i]; + if (l < 150) continue; + var c = f.col[i]; + // Structure is not light. Same test the shafts use, and for the same reason: a kerb + // catching a highlight must not start washing the wall behind it. + if (c === P.slate || c === P.white || c === P.shadow) continue; + var dd = f.dist[i]; + if (!(dd < W_NEAR)) continue; + /* Squared fall-off with distance, so the wash is dominated by whatever is genuinely + * close. Linear weighting handed the whole frame to the parade of shopfronts at + * fifteen metres, which is exactly the thing that is NOT a passing light. */ + var w = 1 - dd / W_NEAR; w *= w; + var e = (l - 150) * w; + var ti = ry + ((x / 6) | 0); + te[ti] += e; tx[ti] += x * e; ty[ti] += y * e; + if (l > tl[ti]) { tl[ti] = l; tc[ti] = c; td[ti] = dd; } + } + } + + var found = 0, k, best, bv, tj; + for (k = 0; k < WASH; k++) { + best = -1; bv = W_ON; + for (i = 0; i < n; i++) if (te[i] > bv) { bv = te[i]; best = i; } + if (best < 0) break; + this.pkX[found] = tx[best] / te[best]; + this.pkY[found] = ty[best] / te[best]; + this.pkC[found] = tc[best]; this.pkD[found] = td[best]; this.pkS[found] = bv; + found++; + // Suppress the neighbourhood, or a wide sign wins both slots and the second wash sits + // on top of the first. + var bx = best % tw, by = (best / tw) | 0; + for (var oy = -2; oy <= 2; oy++) + for (var ox = -3; ox <= 3; ox++) { + var nx = bx + ox, ny = by + oy; + if (nx < 0 || ny < 0 || nx >= tw || ny >= this.th) continue; + te[ny * tw + nx] = 0; + } + } + // Sorted by column, so a slot keeps tracking the same physical lamp between frames. + for (k = 1; k < found; k++) { + var jx = this.pkX[k], jy = this.pkY[k], jc = this.pkC[k], js = this.pkS[k], jd = this.pkD[k]; + tj = k - 1; + while (tj >= 0 && this.pkX[tj] > jx) { + this.pkX[tj + 1] = this.pkX[tj]; this.pkY[tj + 1] = this.pkY[tj]; + this.pkC[tj + 1] = this.pkC[tj]; this.pkS[tj + 1] = this.pkS[tj]; + this.pkD[tj + 1] = this.pkD[tj]; tj--; + } + this.pkX[tj + 1] = jx; this.pkY[tj + 1] = jy; this.pkC[tj + 1] = jc; + this.pkS[tj + 1] = js; this.pkD[tj + 1] = jd; + } + return found; + }, + + draw: function (f, cam, t) { + var cols = f.cols, rows = f.rows; + this.sizeTo(cols, rows); + var found = this.detect(f); + this.found = found; + + var s, x, y, i; + // As with the shafts: the first frame has nothing to ease from, so it lands directly and the + // piece opens with the wash already on the wall instead of half a second of bare facade. + // this.lead is the eased position's LAG, so it is identically zero on this branch — which is + // why no offline frame rendered before tools/headless.cjs drew every tick has ever shown the + // wedge leaning, however fast the source was crossing. + if (!this.primed) { + this.primed = true; + for (s = 0; s < WASH; s++) { + this.ss[s] = s < found ? clamp((this.pkS[s] - W_ON) / (W_FULL - W_ON), 0, 1) : 0; + if (s < found) { + this.sx[s] = this.pkX[s]; this.sy[s] = this.pkY[s]; + this.sc[s] = this.pkC[s]; this.sd[s] = this.pkD[s]; + } + } + } + + /* Thick air spreads the wash and lifts it; on a clear night a headlamp lights the wall and + * almost nothing else. 1.0 at rel=1, as everywhere in this file. */ + var air = airDensity(); + var reach = 0.78 + 0.22 * air; + var amp0 = 0.52 * (0.72 + 0.28 * air); + /* The air inside the wedge, and the only part of this pass that can cost coverage. It is + * held to the inner half of the wedge and dithered against a fixed screen pattern, so what + * lands is a scatter of motes in the beam rather than a disc of fog — measured at 40-90 + * cells in a 400x100 frame, against the 500-odd cells the gain half of the pass touches. + * Nothing at all in clear air: with no water in it there is nothing there to light. */ + var motes = clamp((air - 0.85) * 0.55, 0, 0.42); + var S = this.seed; + + for (s = 0; s < WASH; s++) { + var str = this.ss[s]; + if (str < 0.06) continue; + var cx = this.sx[s], cy = this.sy[s], srcD = this.sd[s], hue = this.sc[s]; + // Under reduced motion the wedge stops leaning about; the pool stays, the sweep does not. + var lead = CC.reducedMotion ? this.lead[s] * 0.25 : this.lead[s]; + var rx = (8 + 10 * str) * reach, ry = (2.4 + 2.6 * str) * reach; + var amp = amp0 * str; + var skew = 1 + (lead < 0 ? -lead : lead) / rx * 1.6; + var ya = Math.ceil(cy - ry), yb = Math.floor(cy + ry); + if (ya < 0) ya = 0; if (yb > rows - 1) yb = rows - 1; + for (y = ya; y <= yb; y++) { + var dy = (y - cy) / ry; + var room = 1 - dy * dy; + if (room <= 0) continue; + var xa = Math.ceil(cx - rx * skew), xb = Math.floor(cx + rx * skew); + if (xa < 0) xa = 0; if (xb > cols - 1) xb = cols - 1; + for (x = xa; x <= xb; x++) { + var dx = (x - cx) / rx; + // The wedge is longer on the side the lamp is heading for and clipped short behind. + if (dx * lead > 0) dx /= skew; + var r2 = dx * dx + dy * dy; + if (r2 >= 1) continue; + i = y * cols + x; + var fall = 1 - r2; fall *= fall; + if (f.lum[i] === 0) { + /* Empty air inside the wedge. This is the only part of the pass that can add a + * cell, so it is confined to the core of the wedge and thrown away by a fixed + * screen dither — a continuous disc here would be exactly the veil of fog this + * project has already had once. */ + if (motes < 0.01 || fall < 0.30) continue; + if (hash2(x, y * 5 + s * 131, S) > motes * fall) continue; + var dm = nearer(f.dist[i]); + if (dm < 0) continue; // sky keeps its Infinity, see nearer() + put(f, x, y, fall > 0.62 ? G_QUOTE : G_TICK, hue, 6 + 16 * fall * amp, dm, 3); + continue; + } + /* Only what is BEHIND the lamp is in its light. Without this the wash lands on the + * rain between the lamp and the eye and the whole effect reads as a smear on the + * glass rather than as a beam landing on a wall. */ + if (f.dist[i] < srcD * 0.72) continue; + gain(f, x, y, 1 + amp * fall); + } + } + } + } + }; + + /* ===================================================================================== + * 3. The far field goes cold in mist. + * + * Water in the air scatters the short wavelengths back at you and swallows the long ones, so + * the far end of a misty street loses its sodium first: the lamps at the end of the block are + * blue-white long before they are dim. This pass says exactly that and nothing more — it moves + * a warm cell's colour INDEX to slate, which is the swatch this palette already keeps for cold + * distance, and invents no new colour at all. + * + * The lum is rescaled by the ratio of the two swatches' print weights, so the swap costs the + * frame no energy: it is a hue change, not a brightening. Reading CC.EXPOSURE rather than + * hard-coding 0.19/2.00 matters — those weights are refitted whenever the surfaces change, and + * a copy of them here would silently become a brightening pass the day somebody refits. + * ===================================================================================== */ + var mistfar = { + name: 'mistfar', + layer: 80, + + init: function (city, rng) { this.seed = (rng() * 30011) | 0; }, + + draw: function (f) { + /* Nothing at all until the air is genuinely thick — at rel=1 this is zero and the pass + * returns on its first line, which is what keeps it off eleven frames in twelve. */ + var str = clamp((rel('fog') - 1.30) / 1.70, 0, 1); + if (str < 0.02) return; + var EX = CC.EXPOSURE, kS = EX[P.slate]; + var cols = f.cols, rows = f.rows, S = this.seed, x, y, i; + /* WHERE the far field starts is itself a function of the fog, and by a long way — measured + * on seed 7 in full mist, only 39 lit warm cells in a 400x100 frame are past 32 m at all, + * because Surf.fog has already taken everything behind them. A "far field" fixed at 32 m + * therefore repaints nothing precisely when the effect is supposed to be at its strongest. + * In mist the distance goes cold at twelve metres, which is also how mist looks. */ + var D0 = 30 - 18 * str, DR = 60 - 30 * str; + for (y = 0; y < rows; y++) + for (x = 0; x < cols; x++) { + i = y * cols + x; + var l = f.lum[i]; + if (l === 0 || f.ch[i] === 0) continue; + var c = f.col[i]; + // Only the warm half of the palette has anything to lose. Azure and ice are already the + // colour mist would turn them, and slate is the destination. + if (c !== P.amber && c !== P.warm && c !== P.ember && c !== P.spring) continue; + var d = f.dist[i]; + if (!(d > D0) || d > 1e30) continue; + /* A fraction of the cells, not all of them, and the fraction grows with depth. A solid + * repaint of the far field turns the end of the street into one flat slab; leaving warm + * cells scattered through it is what still reads as sodium seen THROUGH something. */ + var p = clamp((d - D0) / DR, 0, 1) * str * 0.78; + /* The dither is keyed to the SCREEN cell, not to the world, which is deliberate: a + * pattern keyed to world position would swim across the picture as the viewer walks, + * and there is no world identity to key to here anyway — a post pass sees a screen. + * What moves as the camera moves is only p, the density, so the far field thickens and + * thins with the depth of what is behind it instead of crawling. */ + if (hash2(x, y, S) > p) continue; + var nl = (l * EX[c] / kS + 0.5) | 0; + if (nl < 1) continue; // it would print as a hole; leave the warm cell alone + var dd = nearer(d); + if (dd < 0) continue; + put(f, x, y, f.ch[i], P.slate, nl, dd, f.kind[i]); + } + } + }; + + /* ===================================================================================== + * 4. The fall-off at the edge of vision, and the glass fogging over it. + * + * TWO EFFECTS, ONE WALK, and the fusion is the point rather than a micro-optimisation. + * + * The vignette is corner fall-off. Its map is a pure function of the viewport, so it is built + * once per size and then read. The shape is deliberately weak at the mid-edges (~3%) and only + * real in the corners (~32%): a vignette strong enough to see as a ring reads as a lens fault, + * whereas this one just keeps the eye off the four places where the raycaster's frustum is + * least honest. + * + * The condensation is the glass itself fogging, and only in real fog — the one term in this + * file that is pure subtraction. Mist does not put light on a lens, it takes contrast off one, + * in slow soft patches that sit still while the city moves behind them. The pattern is + * therefore built ONCE per viewport and never re-rolled: condensation that crawls is a + * screensaver, condensation that sits there is a window. It is weighted to the edges of the + * frame because that is where a real one survives — the middle of any glass anybody is looking + * through gets wiped, by a hand, a blower or the heat of whatever is behind it. + * + * WHY THEY ARE ONE PASS. They are both edge-weighted scalar multipliers over the whole frame + * with nothing between them in the layer order, so run separately they cost two full-frame + * traversals and two read-modify-writes of the same cell to apply what is arithmetically one + * number. Measured over the canonical sweep, condensation on its own reached 12-17% of the + * frame at mean |dV| 3.5-5.2 — real, but the same shape and the same order of magnitude as the + * vignette that had just walked the identical cells. Folding the fog term into the vignette's + * own multiplier keeps the weather (the patches are still there, still only in mist) and pays + * for it once. The condensation map stays lazily allocated: most weather never asks for it, and + * a cols*rows Float32Array for a term that is switched off is a page per viewport spent on + * nothing. + * ===================================================================================== */ + /* Two-dimensional value noise, built from the same hash the rest of the file uses so the patch + * pattern is a pure function of the seed. Only ever called from build(), never per frame. */ + function vn2(x, y, s) { + var xi = Math.floor(x), yi = Math.floor(y); + var fx = smoothstep(x - xi), fy = smoothstep(y - yi); + var a = lerp(hash2(xi, yi, s), hash2(xi + 1, yi, s), fx); + var b = lerp(hash2(xi, yi + 1, s), hash2(xi + 1, yi + 1, s), fx); + return a + (b - a) * fy; + } + + var vignette = { + name: 'vignette', + layer: 92, + + /* One rng draw, and it is the one the condensation patches used to take when they were their + * own element at layer 93. Every element in this file shares one stream, so the COUNT and the + * ORDER of draws here is load-bearing: take one fewer and lensrain, lensbloom and the + * exposure phases all shift onto somebody else's numbers and the offline reference frames + * stop matching the browser. */ + init: function (city, rng) { + this.seed = (rng() * 30011) | 0; + this.w = 0; this.h = 0; this.map = null; this.cond = null; + }, + + build: function (cols, rows) { + if (this.w === cols && this.h === rows) return; + this.w = cols; this.h = rows; + this.map = new Float32Array(cols * rows); // resize-time only, see shaft.sizeTo + this.cond = null; // rebuilt on demand at the new size + for (var y = 0; y < rows; y++) { + var ny = (y + 0.5) / rows * 2 - 1; + for (var x = 0; x < cols; x++) { + var nx = (x + 0.5) / cols * 2 - 1; + var r = Math.sqrt(nx * nx + ny * ny) * 0.70710678; // 0 at centre, 1 at a corner + var k = clamp((r - 0.52) / 0.48, 0, 1); + this.map[y * cols + x] = 1 - 0.32 * k * k; + } + } + }, + + buildCond: function (cols, rows) { + if (this.cond) return; + this.cond = new Float32Array(cols * rows); // first mist at this size only, never per frame + var S = this.seed; + for (var y = 0; y < rows; y++) { + var ny = (y + 0.5) / rows * 2 - 1; + for (var x = 0; x < cols; x++) { + var nx = (x + 0.5) / cols * 2 - 1; + var r = Math.sqrt(nx * nx + ny * ny) * 0.70710678; + // Two octaves: broad patches with a finer break-up on top, or the edges of the patches + // read as a shape rather than as weather. + var v = vn2(x * 0.055, y * 0.10, S) * 0.68 + vn2(x * 0.16, y * 0.30, S + 41) * 0.32; + v = clamp((v - 0.34) / 0.52, 0, 1); + // Stored as the DEPTH of the dip, so the per-frame strength can scale it directly. + this.cond[y * cols + x] = v * v * clamp((r - 0.30) / 0.62, 0, 1) * 0.30; + } + } + }, + + draw: function (f) { + this.build(f.cols, f.rows); + /* No fog term at all until the air is properly wet. At rel=1 this is 0 and the term costs + * one compare for the whole frame; it is a mist effect and has no business in ordinary rain. */ + var str = clamp((rel('fog') - 1.55) / 1.45, 0, 1); + var cond = null; + if (str >= 0.02) { this.buildCond(f.cols, f.rows); cond = this.cond; } + var map = this.map, cols = f.cols, rows = f.rows, i = 0; + for (var y = 0; y < rows; y++) + for (var x = 0; x < cols; x++, i++) { + var g = map[i]; + if (cond) g *= 1 - cond[i] * str; + if (g > 0.995) continue; // the whole middle of the frame, untouched + gain(f, x, y, g); + } + } + }; + + /* ===================================================================================== + * 6. Rain beading on the lens. + * + * A drop is not a bright dot; it is a small bad lens. Each bead drags the cell behind and below + * it into its own cell and softens both, so a bead only announces itself when it crosses + * something lit — which is precisely when a real one does. Over black it leaves the faintest + * catch-light, and that is all. + * + * Positions are normalised, so a resize moves the drops with the frame instead of stranding + * them off-screen or forcing a reallocation. + * + * HOW MANY there are is the weather's business, and the count is a RATCHET, not a mirror of + * P.rain: glass that has been rained on stays rained on. It fills fast when it starts (12 s) + * and clears at the speed water actually leaves a vertical surface (a minute and a half), which + * is why a drizzle that follows a downpour still looks like the downpour just ended. The + * boundary drop fades in and out over its last unit of count rather than popping, so the + * ratchet never shows a seam. + * ===================================================================================== */ + var BEADS = 14; // allocated once; `want` decides how many are drawn + + var beads = { + name: 'lensrain', + layer: 94, + + init: function (city, rng) { + var s = ((rng() * 4294967296) | 0) ^ 0x0F71C5; + this.rnd = CC.mulberry(s); + this.n = BEADS; + this.nx = new Float32Array(this.n); + this.ny = new Float32Array(this.n); + this.r = new Float32Array(this.n); + this.age = new Float32Array(this.n); + this.life = new Float32Array(this.n); + // 9 was the measured ceiling before more than ten drops read as a dirty lens rather than a + // wet one, and 9 is exactly what the reference preset still asks for — see want(). + this.want = this.target(); + for (var i = 0; i < this.n; i++) { + this.spawn(i); + this.age[i] = this.rnd() * this.life[i]; // staggered, or every drop renews at once + } + }, + + // 9 at rel=1 — the count the lens was tuned with. A dry night keeps four old drops, a + // downpour beads the whole viewport. + target: function () { return clamp(9 * (0.45 + 0.55 * rel('rain')), 3.2, BEADS); }, + + spawn: function (i) { + var R = this.rnd; + this.nx[i] = 0.04 + R() * 0.92; + // Slight upper bias: the lens is vertical, so the lower half is where drops have already + // run off. It also keeps them off the road, which is meant to be the darkest thing in frame. + this.ny[i] = 0.03 + R() * R() * 0.94; + // Heavier rain beads fatter drops, and a fat drop is the only kind that creeps. + this.r[i] = (0.5 + R() * R() * 1.1) * (0.86 + 0.14 * rel('rain')); + this.age[i] = 0; + this.life[i] = 9 + R() * 17; + }, + + update: function (dt) { + var d = dt > 0.25 ? 0.25 : dt; + var tgt = this.target(); + // The asymmetry IS the effect: water arrives quickly and leaves slowly. + var e = 1 - Math.exp(-d / (tgt > this.want ? 12 : 90)); + this.want += (tgt - this.want) * e; + if (CC.reducedMotion) return; // frozen glass; the drops are simply already there + for (var i = 0; i < this.n; i++) { + this.age[i] += dt; + // Only the fat ones have the mass to creep, and even they take a minute to cross a frame. + if (this.r[i] > 1.0) this.ny[i] += dt * 0.006; + if (this.age[i] > this.life[i] || this.ny[i] > 0.99) this.spawn(i); + } + }, + + cell: function (f, x, y, str) { + var cols = f.cols, rows = f.rows; + if (x < 0 || y < 0 || x >= cols || y >= rows) return; + var i = y * cols + x; + var d = nearer(f.dist[i]); + if (d < 0) return; // sky: a drop against the empty slot has nothing to bend + var la = f.lum[i], ca = f.col[i]; + var jy = y + 1 < rows ? y + 1 : y - 1; + var j = jy * cols + x; + var lb = f.lum[j], cb = f.col[j]; + var out = (la * 0.42 + lb * 0.44) * str; + var top = la > lb ? la : lb; + if (out < 4.5) { + if (str < 0.9) return; // the tail of a drop over black is nothing at all + put(f, x, y, G_DOT, P.ice, 10 + top * 0.08, d, 3); + return; + } + var hue = la >= lb ? ca : cb; + // Water beads a strong source towards white-blue before it beads it towards its own hue. + if (top > 118) { hue = P.ice; out *= 0.74; } + put(f, x, y, out > 46 ? G_O : (out > 16 ? G_o : G_COLON), hue, out, d, 3); + }, + + draw: function (f) { + var cols = f.cols, rows = f.rows; + // Priming here, not in init(), because init() runs before the first Weather.update in some + // hosts and a want of 0 would open on a bone-dry lens in a downpour. + if (!(this.want > 0)) this.want = this.target(); + var want = this.want; + for (var i = 0; i < this.n; i++) { + // The last drop in the count is a partial one and fades rather than pops. + var edge = want - i; + if (edge <= 0) break; + var str = edge < 1 ? edge : 1; + var x = (this.nx[i] * cols) | 0, y = (this.ny[i] * rows) | 0; + this.cell(f, x, y, str); + // A drop elongates downward under its own weight once it is big enough to. + if (this.r[i] > 1.05) this.cell(f, x, y + 1, 0.62 * str); + } + } + }; + + /* ===================================================================================== + * 7. Lens bloom — the halo, and the streak off the very hottest cells. + * + * Two things a real lens does with a light it cannot quite contain, and they are two ends of + * one mechanism, so they are one pass: + * + * the HALO is scatter inside the glass, it is a gain on the cells immediately around a source + * and therefore costs no coverage at all, and it grows with haze because haze is what puts + * the scattering medium in front of the lens in the first place; + * + * the STREAK is the anamorphic one — a horizontal flare off the brightest handful of cells + * only. It is the single loudest thing in this file, so it is rationed to eight sources that + * have to be local peaks, it writes only into cells nothing else wanted, and it leans with + * the pan: the smear on wet glass runs the way the world is sliding, which is the way the + * camera is turning. + * + * Both are anchored to lum >= 175 BEFORE the print curve, which is where the sources actually + * are: signage, headlamps, the hot core of a shopfront. At eight sources the halo was a private + * joke — 56 cells in a 400x100 frame, which is not a property of the lens, it is a coincidence. + * Twenty is enough for the frame to read as being seen THROUGH something and still small enough + * that the streaks stay countable. + * ===================================================================================== */ + var BSRC = 20; + + var lensbloom = { + name: 'lensbloom', + layer: 95, + + init: function (city, rng) { + this.seed = (rng() * 30011) | 0; + this.bx = new Int32Array(BSRC); this.by = new Int32Array(BSRC); + this.bl = new Int32Array(BSRC); this.bc = new Uint8Array(BSRC); + this.n = 0; + // Pan tracking. The smear DIRECTION is the camera's own turn rate and stays that way even + // now that weather.js exports CC.Wind: a streak across a lens is drawn by the lens moving, + // not by the weather, and reaching for the wind vector here would smear the glass sideways + // while the camera was standing still. rel('wind') is read further down, for the streak's + // LENGTH, because wind is what puts the water on the glass in the first place — that is the + // one part of this effect the sky has any say in. + this.yaw = 0; this.panned = false; this.pan = 0; + }, + + update: function (dt, t, cam) { + if (!cam) return; + var y = cam.yaw || 0; + if (!this.panned) { this.yaw = y; this.panned = true; return; } + var d = y - this.yaw; + // Yaw is unwrapped by whoever owns the camera, so a lap of the block can hand us +-2pi. + while (d > 3.14159265) d -= 6.28318531; + while (d < -3.14159265) d += 6.28318531; + this.yaw = y; + var rate = dt > 1e-4 ? d / dt : 0; + // Eased hard: the smear must not flicker on one frame of camera jitter. + var e = 1 - Math.exp(-(dt > 0.25 ? 0.25 : dt) * 3.0); + this.pan += (clamp(rate * 1.1, -1, 1) - this.pan) * e; + }, + + draw: function (f) { + var cols = f.cols, rows = f.rows, x, y, i, k; + var haze = rel('haze'), windy = rel('wind'); + // 0.32 at rel=1. The halo is the safe half of this pass and carries most of the read. + var halo = clamp(0.14 + 0.18 * haze, 0.10, 0.46); + /* The streak's length. Wind is in it because wind is what puts the water ON the glass that + * the flare smears through; the pan supplies the direction and a little more length. */ + var pan = CC.reducedMotion ? this.pan * 0.3 : this.pan; + var reach = 2.2 + 1.5 * haze + 1.2 * windy * (0.4 + 0.6 * (pan < 0 ? -pan : pan)); + var TH = 175; + + // ---- pick the sources: local peaks only, brightest first, at most BSRC of them. + var n = 0, bl = this.bl, bx = this.bx, by = this.by, bc = this.bc; + for (y = 1; y < rows - 1; y++) + for (x = 1; x < cols - 1; x++) { + i = y * cols + x; + var l = f.lum[i]; + if (l < TH) continue; + var c = f.col[i]; + if (c === P.slate || c === P.shadow) continue; // concrete does not flare + /* Local peak, or one blade sign fills all eight slots and the other seven lights in + * the frame get nothing. >= on one side and > on the other breaks ties along a run of + * equal cells so exactly one of them wins. */ + if (f.lum[i - 1] > l || f.lum[i + 1] >= l) continue; + if (f.lum[i - cols] > l || f.lum[i + cols] >= l) continue; + if (n < BSRC) { + k = n++; + } else { + // Full: replace the weakest, and only if this one beats it. + var worst = 0; + for (k = 1; k < BSRC; k++) if (bl[k] < bl[worst]) worst = k; + if (bl[worst] >= l) continue; + k = worst; + } + bx[k] = x; by[k] = y; bl[k] = l; bc[k] = c; + } + this.n = n; + + for (k = 0; k < n; k++) { + var sx = bx[k], sy = by[k], hue = bc[k]; + var s = clamp((bl[k] - TH) / 70, 0.30, 1); + + // ---- halo: gain on the ring around the source. Orthogonal neighbours get the full + // scatter, diagonals about half, which is what keeps the halo round rather than square. + var g1 = 1 + halo * s, g2 = 1 + halo * s * 0.45; + gain(f, sx - 1, sy, g1); gain(f, sx + 1, sy, g1); + gain(f, sx, sy - 1, g1); gain(f, sx, sy + 1, g1); + gain(f, sx - 1, sy - 1, g2); gain(f, sx + 1, sy - 1, g2); + gain(f, sx - 1, sy + 1, g2); gain(f, sx + 1, sy + 1, g2); + + // ---- streak: horizontal only, and longer on the side the world is sliding towards. + for (var side = -1; side <= 1; side += 2) { + var len = reach * s * (side * pan > 0 ? 1.45 : 0.75); + var L = len | 0; + for (var j = 1; j <= L; j++) { + x = sx + side * j; + if (x < 0 || x >= cols) break; + i = sy * cols + x; + var a = (1 - j / (len + 0.6)); + a *= a; + var lum = bl[k] * a * 0.30; + if (lum < 6) break; + // Only into cells that have nothing brighter to say. A flare that overwrites the + // glyph next to it eats the sign it came from. + if (f.ch[i] !== 0 && f.lum[i] > lum) continue; + var d = nearer(f.dist[i]); + if (d < 0) continue; + put(f, x, sy, j < 2 ? G_DASH : G_TICK, hue, lum, d, 3); + } + } + } + } + }; + + /* ===================================================================================== + * 8. The display, and the eye in front of it — scanlines and exposure in one walk. + * + * THE SCANLINES are two terms. A fixed every-other-row dip, which is the display itself and + * never moves, and one very broad bar rolling once every ~25 seconds at a third of that depth. + * The bar is the part that is easy to overdo: at 2.6% it is invisible as an object and only + * registers as the frame being faintly alive. + * + * WHY THE TWO ARE ONE PASS. The scanline factor is per-ROW and the exposure factor is per-FRAME, + * so their product is per-row too, and nothing in the build draws between layer 96 and layer 98. + * Kept apart they walked the whole frame twice and read-modify-wrote every cell twice to apply + * one number per row. Multiplied together first, the row factor is computed once for the row and + * the frame is touched once. ANYONE ADDING AN ELEMENT AT LAYER 97 has to split them again, which + * is the one thing this fusion assumes. + * + * The exposure measurement now happens BEFORE the scanline dip is applied rather than after it, + * which is the only behavioural difference and it cancels: the adaptation below is a RATIO of two + * lagged copies of that measurement, so a near-constant ~1.5% scale on both terms divides out. + * + * THE BREATHE is unchanged in shape: two incommensurate sines so the loop never closes audibly. + * It is the one effect meant to be felt and never seen, and its amplitude is down a third to + * make room for the term below without the two of them ever summing past the +-4.6% the frame + * was built to tolerate. + * + * THE ADAPTATION is new and it is a response, not an oscillation. It measures the frame's own + * energy and keeps two lagged copies of it: a FAST one, which is roughly the retina, and a SLOW + * one, which is the adapted state the retina is being compared against. The printed gain is the + * ratio of the two. Stand still and they converge, the ratio is 1 and the pass does nothing at + * all. Walk out of a dark block into a lit parade and the fast term jumps while the slow one is + * still in the dark, so the frame is pulled DOWN for a second or two and then released as the + * eye catches up — which is what walking into a bright street actually feels like. Walking into + * the dark does the same in reverse, and more slowly, because dark adaptation is slower than + * light adaptation in the eye as well. + * + * WHY IT CANNOT PUMP. The fast term's time constant is half a second, which is four times the + * length of the longest lightning stroke in weather.js, so the biggest transient this city can + * produce moves it by a few percent. The exponent is a fractional power, so even a doubling of + * scene energy asks for well under a stop. And the whole thing is clamped: nothing this pass + * does can move the frame by more than the CLAMP below, ever. + * + * WHERE IT IS MEASURED. In draw(), because that is the only place the frame exists — and then + * integrated in update(), on the fixed tick, so the adaptation takes the same time in seconds + * whatever the panel is doing. That is one tick of lag on a quantity whose own time constant is + * half a second. The very first draw seeds BOTH filters from the same measurement, so the frame + * the viewer opens on is the fully-adapted one and the piece never fades up out of a start-up + * transient; everything after it is history. + * + * KNOWN-BUG NOTE. This element is not the source of the reduced-motion breathing report. Before + * this rewrite it returned on its first line under CC.reducedMotion and contributed nothing at + * all; measured over 5 s of wall clock at three seeds, the frame's mean-luminance sigma was + * 20.7%/21.4%/8.9% in normal motion against 6.1%/1.7%/2.9% under reduced motion, i.e. the frame + * already breathed far LESS with reduced motion on. It still does: the sines stay off there and + * the adaptation, which is a stabiliser, is the only term left. + * + * HOW TO MEASURE THIS PASS, because the obvious way reports zero and a review has already been + * misled by it. The measurement this element integrates can only be taken in draw(), so a + * harness that replays update() and calls draw() once leaves this.meas at -1 for the entire + * replay, update() returning on its first line and `adapt` pinned at exactly 1. That is what + * tools/headless.cjs used to do, and it is why every palette share and every luminance + * histogram this project published before the harness was fixed was taken with this pass + * switched off; the fix was to draw every tick, not to touch anything here, because measuring + * in draw and integrating on the fixed tick is what main.js actually does. A still-frame census + * run the old way measures the breathe alone: mean |dV| 1.0-1.9 over the canonical sweep, + * nothing moving by 10, which reads as a pass that does nothing. Replayed the way main.js runs + * it, `adapt` sits between 0.93 and 1.10 at 400x100 and swings 6.9%/8.7%/15.1% over four + * seconds on seeds 42/3/99, reaching its clamp. At seed 42 frame 3180 that is the whole frame's + * printed mean moving 2.9% with no single cell moving by 10, which is exactly the signature of + * an exposure change and exactly what a per-cell threshold cannot see: you cannot detect a fade + * by asking whether any one cell jumped. + * + * AND WHAT THAT COSTS THE READER OF A SINGLE OFFLINE FRAME. `adapt` is a full-frame multiplier + * with a history, so the frame at (seed, tick) now carries whatever gain the walk up to that + * tick earned — near 1.00 on a steady block, down at the 0.88 clamp a second after stepping out + * into a lit parade. Two frames of the same seed a few hundred ticks apart are no longer at the + * same exposure, and a threshold census (black%, hot%) will move by more than the geometry did. + * That is the honest picture and not a defect, but anything fitting a curve to a single frame + * has to know it is fitting to that frame's adaptation as well. + * ===================================================================================== */ + var exposure = { + name: 'exposure', + layer: 96, // truly last: this is the gain on everything above it, scanlines included + + /* Three rng draws in this order because that is what the two elements this one replaces took + * between them — scanlines' phase at layer 96, then the two breathe phases at layer 98. One + * shared stream feeds every element, so changing the count or the order here re-rolls nothing + * in this file (it is last) but would still move the reference frames off the browser's. */ + init: function (city, rng) { + this.phase = rng(); + this.p0 = rng() * 6.2831853; + this.p1 = rng() * 6.2831853; + this.rows = 0; + this.g = null; // per-row multiplier: scanline dip x this frame's exposure + this.meas = -1; // scene energy, written by draw() and read by update() + this.fast = -1; this.slow = -1; + this.adapt = 1; // the gain update() has settled on; draw() only reads it + }, + + update: function (dt) { + if (this.meas < 0) return; // no frame has been measured yet + var d = dt > 0.25 ? 0.25 : dt; + this.fast += (this.meas - this.fast) * (1 - Math.exp(-d / 0.5)); + /* Light adaptation in about two and a half seconds, dark adaptation in five. Both are far + * slower than anything in the frame moves, which is the whole defence against pumping. */ + var tau = this.meas > this.slow ? 2.5 : 5.0; + this.slow += (this.fast - this.slow) * (1 - Math.exp(-d / tau)); + var f = this.fast, s = this.slow; + if (!(f > 0.01) || !(s > 0.01)) { this.adapt = 1; return; } + /* Thick air is a low-contrast world with nothing much to adapt to, and a viewer in mist who + * walks past a lit window should not have the whole street dip. k is 0.34 at rel=1. */ + var k = clamp(0.34 - 0.09 * (airDensity() - 1), 0.16, 0.44); + if (CC.reducedMotion) k *= 0.5; + var e = Math.pow(s / f, k); + var lo = CC.reducedMotion ? 0.94 : 0.88, hi = CC.reducedMotion ? 1.05 : 1.11; + this.adapt = e < lo ? lo : (e > hi ? hi : e); + }, + + draw: function (f, cam, t) { + /* The measurement is deliberately over EVERY cell, not over the lit ones: the share of the + * frame that is black is exactly what changes when you walk into a bright block, and a mean + * taken over lit cells only would report the same number for a dark street with one sign in + * it as for a street that is all sign. This is also the whole of the "place" term — where + * you are standing is not a coordinate, it is how much light is arriving. */ + var n = f.n, lum = f.lum, ch = f.ch, sum = 0, i; + for (i = 0; i < n; i++) if (ch[i] !== 0) sum += lum[i]; + this.meas = sum / n; + if (this.fast < 0) { this.fast = this.meas; this.slow = this.meas; } + + var e = this.adapt; + // The free-running breathe, which reduced motion switches off exactly as it always did. + if (!CC.reducedMotion) + e *= 1 + 0.020 * Math.sin(t * 0.61 + this.p0) + 0.011 * Math.sin(t * 0.233 + this.p1); + + var cols = f.cols, rows = f.rows, x, y; + if (this.rows !== rows) { this.rows = rows; this.g = new Float32Array(rows); } + var g = this.g; + // Frozen roll under reduced motion; the static line texture stays, because it does not move. + var ph = CC.reducedMotion ? this.phase : this.phase + t * 0.040; + /* The whole modulation for a row, resolved before a single cell is touched: the display's + * every-other-row dip, the slow bar, and the eye's gain on top of all of it. */ + for (y = 0; y < rows; y++) { + var bar = 0.5 + 0.5 * Math.cos((y / rows * 1.6 - ph) * 6.2831853); + g[y] = (1 - 0.070 * (y & 1)) * (1 - 0.026 * bar) * e; + } + for (y = 0; y < rows; y++) { + var gy = g[y]; + if (gy > 0.9975 && gy < 1.0025) continue; // this row is already what it should be + for (x = 0; x < cols; x++) gain(f, x, y, gy); + } + } + }; + + var LIST = [shaft, wash, mistfar, vignette, beads, lensbloom, exposure]; + for (var q = 0; q < LIST.length; q++) CC.ELEMENTS.push(LIST[q]); + if (typeof module !== 'undefined') module.exports = LIST; +})(typeof CC !== 'undefined' ? CC : require('../core.js')); diff --git a/src/elements/signage.js b/src/elements/signage.js new file mode 100644 index 0000000..7cc8af6 --- /dev/null +++ b/src/elements/signage.js @@ -0,0 +1,1824 @@ +/* CyberCity signage — everything the street lights itself with. + * + * Four ambient systems, four ELEMENTS entries: shop-window spill on the pavement, neon mounted on + * facades, traffic signals at the junctions, holographic adverts hung mid-canyon. + * + * Placement is NOT a spawn list. The walk is endless, so every fixture is a pure function of the + * world cell (or of the street-lattice index) it hangs on: nothing is allocated, nothing is + * recycled, and scrubbing time backwards puts every sign back exactly where it was. The cost of + * that is a bounded scan of the cells around the camera each frame, which is why every scan below + * rejects on the cheap forward-distance dot product before it touches a hash or the heightmap. + * + * THE VOCABULARY. `neon` used to have two shapes — a stack of characters down a corner and a row + * of them over a door — which is not a city, it is a texture applied to one. It now has twelve + * STYLES, each with its own construction, its own animation and its own way of failing, chosen per + * lot by a weighted roll off the district so a concrete quarter is full of half-dead boards and the + * arcade strip is full of chase borders and character blocks. They are listed at S_TUBE below. + * The one that carries the most weight in the references is S_BLOCK, the stacked square clusters + * that read as a language: it is the difference between "signs" and "this city has writing on it". + * + * HOW BIG A SIGN ACTUALLY IS, which is the thing that decides whether any of that vocabulary + * reaches the viewer. Instrumented over the canonical sweep (seeds 3/7/42/99 x frames + * 600/3000/9000/18000 at 400x100, through the real harness — the frame checksum of the + * instrumented render matches tools/headless.cjs cell for cell): 125 fixtures land, 7.8 a frame, + * 281 cells a frame, 0.70% of the picture. The MEDIAN fixture is 3.1 screen columns wide at 30 m + * and 72% of them are under 8 columns. All twelve styles appear, and most of them had nowhere to + * happen, in two separate ways that were both being blamed on the constructions: + * + * 1. THE GRID WAS FINER THAN THE SCREEN. A fixture's character grid is fixed in the world at up + * to 9 columns, and the shader is point-sampled once per screen column, so at 3 columns two + * grid columns in three are never asked about — 52% of all fixtures had a grid at least twice + * as fine as their own footprint. Which columns survived was a function of where the board's + * edge fell between two cells, so a hollow tube printed as an L, a chase border lost a side, + * and a character block lost the gaps that made it characters. board() now coarsens the drawn + * grid to what the screen can sample (52% -> 11% undersampled) while shade() keeps every + * letterform, brightness jitter and screen-noise lookup indexed in the WORLD grid, so the + * construction gets coarser on approach and the writing does not reshuffle. + * 2. BELOW A CERTAIN SIZE THERE IS NO CONSTRUCTION, only its ink — four or five loose marks in + * the two pillar hues, drawn from the same glyph bank the window lattice behind them is drawn + * from, at the wall's own brightness. So under MIN_C x MIN_R a fixture crossfades into its own + * MASS: the case fills the cells the construction leaves dark and everything converges on one + * level, which is what a real sign reduces to at distance and the one property shared by every + * style the craft review found legible. Measured on the printed frame as the largest connected + * run of the fixture's own cells at v>=60: median 10 -> 12 cells, mean 15.7 -> 18.5, and the + * styles that read worst gained most (chase 8 -> 16, screen 4 -> 10, block 8 -> 13, tube + * 11 -> 13.5) while the ones that already read are untouched by construction (marquee 9 -> 10). + * The crossfade is over two cells of span rather than a threshold, because the quantity it + * keys on is one the walk changes continuously; and since the mass level is a constant, the + * blend can only REDUCE a cell's temporal amplitude — measured, tools/flicker-rate.cjs returns + * exactly the same worst per-cell step for `neon` before and after, 15.3/13.3/17.3/19.6% on + * seeds 0/7/42/555, on 15% more painted cells. + * + * The bill for both: 281 -> 337 cells a frame, 0.70% -> 0.84% of the picture, almost all of it + * dark case rather than light. Over the same 16 frames the printed palette does not move — amber + * 22.59% -> 22.58% of lit energy, azure 24.91% -> 24.88%, black 44.02% -> 43.98%. + * + * WHAT A SIGN LIGHTS. A sign is a light source, and until this pass it lit nothing — it was a + * bright decal on a wall that stayed exactly as dark as the wall next door. Every fixture now + * casts (castGlow), and the cast is deliberately a MODULATION of cells that are already painted + * rather than new marks: the wall it is bolted to, the pavement under it, the awning over the + * stall in front, the rain falling through it and the near edge of whoever is walking past all + * arrive in the frame before layer 30 does, so lighting them costs energy and almost no coverage. + * That is the whole trick, and it is why the budget below barely moved for the largest visible + * change in the file. + * + * WET REFLECTION. As the road wets, every fixture smears down it toward the viewer (wetSmear) at + * the fixture's own screen column, in the fixture's own colour. surfaces.js owns the road's general + * wetness and its anonymous streaking; this owns the reflection OF A NAMED SIGN, which is the one + * thing a generic road texture cannot know about. + * + * PHOTOSENSITIVITY IS A CEILING, NOT A PREFERENCE. Nothing here flashes above 3 Hz and no cell may + * move more than a third of full scale in one frame. Every travelling crest in this file is a + * smoothstep PLATEAU rather than a threshold, for the reason spelled out at the holo scan band; the + * one deliberate strobe (S_FAIL) is a 2.2 Hz sine of amplitude 0.28, whose worst frame is 6.4% of + * full scale; the ticker changes GLYPH and not luminance, so its 2 Hz step is a shape change and + * not a luminance edge at all. + * + * tools/flicker-rate.cjs is the judge and it says PASS, but read what it actually covers: part 1 + * lifts flick() out of this file, and part 2 drives the real elements over four seeds and eight + * bearings. Neither one knows the styles exist. So each style was ALSO forced city-wide on its own + * and measured — worst per-cell frame step, and the strongest 3-20 Hz component of the forty + * busiest cells over 24 s, Hann windowed exactly the way the tool does it: + * + * tube 23.1%/1.47% blade 23.9%/1.45% chase 17.6%/0.29% wipe 25.1%/1.45% + * ticker 0.0%/0.00% block 22.7%/1.46% flap 2.7%/0.32% fail 3.1%/0.04% + * backlit 0.0%/0.00% arrow 3.9%/0.28% screen 1.2%/0.03% marquee 27.5%/1.78% + * + * Every one is inside the 34% step and 2% band limits. The 3.79 Hz line the lit styles all carry is + * flick()'s failing starter and nothing else — it is the same line part 1 reports at 1.06% on the + * multiplier. Three of those numbers are the record of a bug this pass introduced and fixed, and + * the fixes are written up where they live: the visibility cut in board(), the smear gate under it, + * and the screen's black level. Compared like for like against the file this replaced, on the same + * measurement: worst per-cell step 18.8% against 26.3%, strongest 3-20 Hz 1.14% against 1.75%. + * + * Coverage budget, measured by rendering seeds 3/7/42/99 at frames 600/3000/9000 at 400x100 with + * the four elements drawn and again with them skipped — the same process and the same rng draw + * either way, or the elements downstream re-roll and a third of the frame changes for reasons that + * have nothing to do with signage: signage owns 1.74% of cells (the file it replaces: 1.05%) and + * adds 0.29 points of lit coverage (0.33). It touches two thirds again as many cells for LESS new + * light, which is the cast doing exactly what it was built to do. Lit energy over those twelve + * frames with signage in: amber 27.4%, azure 24.0% against 27.6%/23.7% without it — the two pillars + * level and unmoved — ember 2.0%, spring 0.7%, violet under 0.05%. That is the whole point: the + * references are 54-60% pure black and signage is the one thing in frame allowed to be truly + * bright, so it has to stay small or it stops reading as bright at all. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, g = CC.g, hash2 = CC.hash2, vnoise = CC.vnoise, clamp = CC.clamp, put = CC.put; + + var G_HASH = g('#'), G_8 = g('8'), G_0 = g('0'), G_O = g('O'), G_oo = g('o'), + G_X = g('X'), G_Z = g('Z'), G_EQ = g('='), G_COLON = g(':'), G_DOT = g('.'), + G_QUOTE = g("'"), G_DASH = g('-'), G_COMMA = g(','); + /* The second bank, for the styles that need a letterform rather than a lamp: the dense square + * glyphs a character block is built out of, the arrow head, the tube's vertical leg. */ + var G_PIPE = g('|'), G_V = g('V'), G_M = g('M'), G_W = g('W'), G_N = g('N'), + G_H = g('H'), G_U = g('U'), G_K = g('K'), G_Y = g('Y'), G_Q = g('Q'), + G_AT = g('@'), G_PCT = g('%'), G_PLUS = g('+'), G_STAR = g('*'), G_SEMI = g(';'); + + /* Blocky only. A neon tube at this resolution is a solid mark; anything with holes in it + * (& $ ? %) dithers into noise and stops reading as a lit object. */ + var NEON_G = [G_HASH, G_8, G_0, G_X, G_O, G_Z, G_EQ], NEON_N = 7; + var HOLO_G = [G_COLON, G_DASH, G_EQ, G_oo, G_Z, G_X], HOLO_N = 6; + var SPILL_G = [G_DOT, G_COLON, G_QUOTE, G_COMMA], SPILL_N = 4; + /* A character block is read by its MASS, not by which glyph it is: every entry here fills most + * of its cell, so a 2x2 cluster of them prints as one dense square with a bit of internal + * structure, which is exactly how a CJK signboard reads across a street. Anything lighter than + * these (o, :, -) breaks the cluster back into separate marks and the read is gone. */ + var BLOCK_G = [G_HASH, G_8, G_M, G_W, G_N, G_H, G_U, G_K, G_Y, G_X, G_Q, G_0, G_AT], BLOCK_N = 13; + /* The ticker is text you cannot resolve, so it wants VARIETY of width rather than mass. */ + var TICK_G = [G_EQ, G_DASH, G_COLON, G_PLUS, G_STAR, G_X, G_Z, G_oo, G_PCT, G_SEMI], TICK_N = 10; + /* A luminance ramp, dark to bright. The screen style picks its glyph by how bright the cell + * came out, which is the oldest trick in ASCII rendering and the reason a slow noise field + * reads as video rather than as a rectangle of static. */ + var SCREEN_G = [G_DOT, G_COLON, G_oo, G_O, G_8, G_HASH], SCREEN_N = 6; + + /* surfaces.js is loaded before the elements directory in every path that matters, but a + * standalone `require` of this file has no CC.Surf at all. Bind late, once. */ + var _fog = null; + function passthrough(l) { return l; } + function fog(l, d) { + if (!_fog) _fog = (CC.Surf && CC.Surf.fog) || passthrough; + return _fog(l, d); + } + + /* ---- weather ------------------------------------------------------------------------------- + * rel(k) is the parameter divided by its value in the 'rain' preset, which is the preset every + * constant in this file was tuned under, so each expression below is written to come out at + * exactly 1.0 when rel() is 1 and the element renders the look that shipped. Multiplying by the + * raw P.rain instead would silently re-tune the whole file to 65% of itself. + * The guard is not defensive noise, but the reason it used to give here is no longer true and a + * stale reason is worse than none. This comment claimed tools/flicker-rate.cjs deliberately does + * NOT load weather_state.js, so the photosensitivity numbers were taken with CC.Weather absent. + * That stopped being true when the director was wired in: flicker-rate.cjs and lightning-rate.cjs + * both require src/weather_state.js now and PIN a preset (storm by default, --sky=... to choose), + * for the reason flicker-rate.cjs writes out at its own load line — with CC.Weather absent every + * rel() is 1, AT.gust comes out at exactly 1, and that trips the `AT.gust <= 1.02` guard which + * switches the wind gutter off, so the tool guarding the 34% ceiling was measuring the one sky in + * which the newest flicker source in this file does nothing at all. Anyone quoting "measured with + * the weather absent" is quoting a run that no longer exists. + * What the fallback still buys is tools/headless.cjs's promise to render whatever subset of src + * exists: on a half-written tree with no weather module, `CC.Weather.rel(k)` would throw on the + * first sign of the first frame, and instead every rel() returns 1 and this file draws the 'rain' + * reference look it was tuned under. */ + function rel(k) { return CC.Weather ? CC.Weather.rel(k) : 1; } + + /* One object, filled once per element draw. Fog eats a sign's own luminance and hands it back as + * halo — that is what fog IS, light taken off the source and smeared over everything near it — + * so `dim` and `halo` move in opposite directions off the same parameter and a mist night is + * soft glowing blobs where a clear night is hard bright marks. */ + var AT = { dim: 1, halo: 1, wet: 1, gust: 1 }; + function airPrep() { + var f = rel('fog'), h = rel('haze'); + AT.dim = clamp(1 - 0.17 * (f - 1) - 0.11 * (h - 1), 0.46, 1.14); + AT.halo = clamp(1 + 0.42 * (f - 1) + 0.26 * (h - 1), 0.72, 2.10); + AT.wet = clamp(rel('wet'), 0, 1.30); + AT.gust = clamp(1 + 0.60 * (rel('wind') - 1), 0.55, 1.90); + } + + /* The wind gutter. A tube in a gale does not strobe, it BREATHES badly: the whole fixture sags + * and comes back, together, because what is moving is the supply and not the glass. + * + * It is applied to the fixture's peak ONCE, outside flick(), and that separation is deliberate. + * flick()'s failing-starter personality already sits at 32.5% of full scale in its worst frame, + * measured; deepening THAT by the gust would push it over the 34% ceiling in a storm, which is + * the one thing this file may not do. A separate 1.1 Hz carrier at 0.26 depth costs 0.6% of full + * scale a frame at the strongest wind in the presets and cannot interact with the starter at all. + * Frozen flat under reduced motion, like everything else here. */ + function gutter(t, ph) { + if (CC.reducedMotion || AT.gust <= 1.02) return 1; + /* THE CARRIER IS THE CITY'S WIND, not a private noise. weather.js publishes one gust envelope + * that the rain slant, the litter, the banners and the washing all ride; a sign sagging on its + * own 1.1 Hz noise sagged while the rain was falling straight, which reads as two unrelated + * weathers on one screen. CC.Wind.mult is that envelope with a mean of 1, remapped here to + * 0..1 across the range it actually occupies. + * + * The private noise is not deleted, it is demoted to a third of the signal: every fixture in + * the street dropping by exactly the same fraction on exactly the same frame is its own kind + * of wrong, and the residue is what gives each one its own slack in the supply. + * + * Both terms stay inside 0..1, so the depth of the gutter is bounded exactly as it was before + * and tools/flicker-rate.cjs's 0.6%-of-full-scale reading still holds. */ + var shared = CC.Wind ? clamp((CC.Wind.mult - 0.70) / 0.60, 0, 1) + : vnoise(t * 1.1, 0x4C1); + return 1 - 0.26 * (AT.gust - 1) * + (0.65 * shared + 0.35 * vnoise(t * 1.1 + ph * 23, 0x4C1)); + } + + /* ---- projection ---------------------------------------------------------------------------- + * Must agree with raycast.js cell for cell or an element floats off its wall. Same planar + * camera, same `scale` derivation (cam.scaleY is the escape hatch, not cam.scale — the harness + * sets cam.scale to something the raycaster ignores), same radial distance w*|dir| so the depth + * test in CC.put compares like with like. */ + var CO = { cols: 0, rows: 0, horizon: 0, hp: 0, scale: 1, eyeY: 1.7, + ox: 0, oz: 0, fwx: 0, fwz: 1, rgx: 1, rgz: 0 }; + var VP = { x: 0, y: 0, w: 0, dist: 0 }; + + function setCam(frame, cam) { + CO.cols = frame.cols; CO.rows = frame.rows; + CO.horizon = cam.horizon !== undefined ? cam.horizon : frame.rows * 0.56; + CO.hp = Math.tan((cam.fov || 1.25) * 0.5); + CO.scale = cam.scaleY !== undefined ? cam.scaleY + : (frame.cols * (cam.cellAspect || 0.5625)) / (2 * CO.hp); + CO.eyeY = cam.eyeY !== undefined ? cam.eyeY : 1.7; + CO.ox = cam.x; CO.oz = cam.z; + var yaw = cam.yaw || 0; + CO.fwx = Math.sin(yaw); CO.fwz = Math.cos(yaw); + CO.rgx = Math.cos(yaw); CO.rgz = -Math.sin(yaw); + } + + function project(px, py, pz) { + var rx = px - CO.ox, rz = pz - CO.oz; + var w = rx * CO.fwx + rz * CO.fwz; + if (w < 0.6) return false; // at or behind the lens + var sp = (rx * CO.rgx + rz * CO.rgz) / w; + /* Generous horizontal margin: a wide sign whose CENTRE is off-screen can still have half of + * itself in view, and clipping it here would make it vanish a beat early at the frame edge. */ + if (sp < -CO.hp * 2 || sp > CO.hp * 2) return false; + VP.x = (sp / CO.hp + 1) * 0.5 * CO.cols - 0.5; + VP.y = CO.horizon - (py - CO.eyeY) * CO.scale / w; + VP.w = w; + VP.dist = w * Math.sqrt(1 + sp * sp); + return true; + } + + /* The same projection with no horizontal cull and its own output slot, because a board is drawn + * from its two END points and one of them being off the side of the frame is not a reason to + * drop the sign — it is the normal case for anything close. The cull is done once, on the + * fixture's centre, by project() above. */ + var VA = { x: 0, y: 0, w: 0, dist: 0 }, VB = { x: 0, y: 0, w: 0, dist: 0 }; + function projInto(px, py, pz, O) { + var rx = px - CO.ox, rz = pz - CO.oz; + var w = rx * CO.fwx + rz * CO.fwz; + if (w < 0.9) return false; + var sp = (rx * CO.rgx + rz * CO.rgz) / w; + O.x = (sp / CO.hp + 1) * 0.5 * CO.cols - 0.5; + O.y = CO.horizon - (py - CO.eyeY) * CO.scale / w; + O.w = w; + O.dist = w * Math.sqrt(1 + sp * sp); + return true; + } + + /* Metres-across at distance w, converted to screen columns. Signs are sized in the world and + * then clamped in cells, because a 0.4 m neon tube two metres from the eye is thirty columns + * wide and a thirty-column bar of pure amber owns the entire frame. */ + function colsFor(m, w) { return (m / w / CO.hp) * CO.cols * 0.5; } + + /* A modulation pass has to rewrite a cell it did not author, and put() rejects an equal depth. + * Shaving a part in ten thousand off the existing depth satisfies the test while leaving the + * cell at effectively the same place in the queue. Sky carries Infinity, which has no + * representable nudge and is how the rest of the pipeline recognises sky, so it is refused. */ + function nearer(d) { + if (!(d < 1e30)) return -1; + var n = d - d * 1e-4; + return n < d ? n : -1; + } + + /* ---- the wall the fixture hangs on ---------------------------------------------------------- + * A cell is a candidate only if it is built AND at least one of its four sides opens onto + * street/alley/plaza. The dominant axis is tried first: that is the face turned towards the + * camera, and mounting on the other one puts the sign inside the block. */ + var FACE = { nx: 0, nz: 0, fx: 0, fz: 0 }; + function faceOf(city, gx, gz, rx, rz) { + var xFirst = (rx < 0 ? -rx : rx) > (rz < 0 ? -rz : rz); + var i, nx, nz; + for (i = 0; i < 2; i++) { + if ((i === 0) === xFirst) { + nx = rx > 0 ? -1 : 1; nz = 0; + } else { + nx = 0; nz = rz > 0 ? -1 : 1; + } + if (city.height(gx + nx, gz + nz) <= 0) { + FACE.nx = nx; FACE.nz = nz; + FACE.fx = gx + 0.5 + nx * 0.5; FACE.fz = gz + 0.5 + nz * 0.5; + return true; + } + } + return false; + } + + /* ---- flicker personalities ------------------------------------------------------------------ + * Four, because a street where every tube behaves the same reads as a texture rather than as a + * hundred separate failing objects. `j` is the character index down the sign so personality 2 + * can kill one glyph and only that glyph. Nothing here takes a camera term: a flicker keyed on + * anything the walk changes makes the whole street boil as you move. + * + * tools/flicker-rate.cjs LIFTS THIS FUNCTION out of the source file by brace matching and runs + * it with nothing but (CC, vnoise, clamp, hash2) in scope. Do not reach out of it for a module + * helper: the measurement stops working and nothing tells you. */ + function flick(kind, ph, t, j, dead) { + if (kind === 2 && j === dead) return 0.10; + if (CC.reducedMotion) return 0.88; + if (kind === 0) return 1; + if (kind === 1) { + /* A failing starter, NOT a strobe — and, since this line, not a step edge either. + * + * The cut before this one selected between two branches at b < 0.26. That reads as + * continuous and is not: the low branch tops out at 0.30 + 0.5*0.26 = 0.430 and the high + * branch opens at 0.84 + 0.16*0.26 = 0.882, so every crossing moved the tube 0.45 — 45% of + * full scale — inside one 16 ms frame. Measured on that function: 50.3% worst frame, +135% + * of the value it left, and a step over a third of full scale about twice a second. + * + * Two things were wrong, and CROSSFADING the branches only fixes one of them. + * + * The crossfade (below) removes the discontinuity, but a smoothstep 0.12 of noise-range + * wide is not a ramp at 5.6 noise units a second: value noise moves up to 0.14 of its range + * per frame there, so the window was crossed in one or two frames and the worst frame still + * measured 49.0%. Widening the window is the obvious lever and it is the wrong one — it + * turns the strike into a dimmer, which is exactly what this personality must not be. + * + * The second fault is the carrier. Round 2 halved 11.3 to 5.6 and reported the DROPOUT rate, + * 1.0 a second, as the rate — but the modulation itself is at the noise rate, and 5.6 Hz is + * inside the 3-20 Hz flash band this piece is built to stay out of. A DFT of the multiplier + * found a coherent line sitting right on 5.60 Hz at 3.2% of full scale, and it stayed there + * at every crossfade width, because it is the noise's own node grid and no amount of + * smoothing the transfer curve moves it. Halving again to 2.8 puts the carrier under the + * ceiling and takes the strike's per-frame travel with it. + * + * Both together, measured by tools/flicker-rate.cjs, which lifts this exact function out of + * this file and samples it at 60 Hz over 90 s x 12 phases: worst frame 32.5% of full scale + * (was 50.3%), never over a third, strongest 3-20 Hz component 0.81% (was 3.2% at 5.60 Hz). + * The crossfade window is centred on the old 0.26 threshold and slowing the noise does not + * move it, so the mean multiplier is 0.832 against the old 0.828: over 64 frames across four + * seeds the whole element's summed luminance moved +1.5%, on 1.6% of the frame, and the + * exposure the lead set is where he set it. + * + * It still reads as a starter: the tube gutters every two seconds or so — 0.48 dropouts a + * second at 63% mean depth, floor 0.30, so it is never actually out, it just fails to + * strike — and comes back in four to six frames, which is a snap and not a fade. + * + * The other three personalities are audited by the same tool: 0 (steady) and 2 (steady, one + * dead character) do not move at all, and 3 is a 0.13 Hz breath whose worst frame is 0.2%. */ + var b = vnoise(t * 2.8 + ph * 17, 0x8117); + var w = CC.smooth(clamp((b - 0.20) / 0.12, 0, 1)); + return (0.30 + 0.5 * b) * (1 - w) + (0.84 + 0.16 * b) * w; + } + if (kind === 2) return 0.97; + return 0.66 + 0.34 * (0.5 + 0.5 * Math.sin(t * 0.8 + ph * 6.283)); + } + + /* A travelling crest, and the ONLY shape allowed to travel in this file. `d` is the signed + * distance to the crest in whatever parameter it runs along, measured the short way round the + * wrap; the answer is a flat-topped plateau `hold` wide falling to nothing by `hold + soft`. + * + * It is a profile rather than a test for the reason written out at the holo scan band: a hard + * `Math.abs(d) < w` edge on a smooth sweep jumps every cell it crosses the full height of the + * boost inside one frame, which on a bright sign cell is over 200 of 255 — the largest artefact + * this file has ever shipped, invisible to every frame-level statistic because it is one cell + * wide, and perfectly visible to somebody looking at that cell. Measuring the short way round + * the wrap matters just as much: a crest that teleports from the end of the sign back to the + * start is the same step edge in a different costume. */ + function crest(d, hold, soft) { + d -= Math.floor(d); + if (d > 0.5) d = 1 - d; + return CC.smooth(clamp((hold + soft - d) / soft, 0, 1)); + } + + /* ---- decorrelated per-cell hashes ------------------------------------------------------------ + * hash2 folds its salt in as s*(2^31-1), which modulo 2^32 is nothing but (s&1)*2^31 - s. Two + * salts differing by a small XOR therefore differ by a small CONSTANT inside the mixer, and the + * avalanche does not hide it. Conditioning on one such hash landing in its low tail — exactly + * what "is there a sign on this cell" does — drags every sibling hash into ITS low tail, and a + * census of 360k cells came back 100% amber: one hue, one sign type, one flicker, city-wide. + * So the varying term is the COORDINATE, which enters through a large odd multiplier and + * decorrelates cleanly (measured: flat quartiles). Offsets stay under 5e6 because hash2 + * multiplies by 6.7e8 in double precision and the product must stay inside 2^53. + * The same trap is waiting for anyone who derives two decisions from one cell here. + * There are ten slots and the styles below want more than ten independent decisions per lot; + * the extra streams come from OFFSETTING THE COORDINATE (hk(gx + 7, gz - 3, ...)), which is the + * same escape and for the same reason — never from a second salt. */ + var HKX = [0, 104729, 611953, 1999993, 3391993, 4796027, 7919, 2750159, 4256233, 1299709]; + var HKZ = [0, 4256233, 1299709, 4796027, 611953, 2750159, 3391993, 104729, 7919, 1999993]; + function hk(a, b, salt, i) { return hash2(a + HKX[i], b + HKZ[i], salt); } + + function neonHue(r) { + /* Two pillars carry it, two accents garnish it, and there is NO violet here. A violet tube + * bloomed into exactly the hot magenta the references are built to avoid — it was, by some + * distance, the loudest object in any frame that contained one. Violet survives in this file + * on the holo panels alone, which is what "screens and signage only" actually buys you: a + * dim translucent projection can carry it, a saturated glass tube on a near wall cannot. */ + return r < 0.34 ? P.amber : r < 0.68 ? P.azure : r < 0.80 ? P.warm + : r < 0.90 ? P.ember : P.spring; + } + + /* ============================================================================================= + * THE SIGN STYLES + * Twelve constructions. Each is a shader over the fixture's own character grid — see shade() — + * plus a geometry rule in setupSign() and a weight per district in STYLE_W. + * ========================================================================================== */ + var S_TUBE = 0, // hollow rectangle of tube, one corner segment out + S_BLADE = 1, // vertical banner projecting PERPENDICULAR from the facade, read edge-on + S_CHASE = 2, // lamps running round a marquee border + S_WIPE = 3, // a bar of light travelling across the face + S_TICKER = 4, // a band of scrolling glyph noise: text you cannot quite make out + S_BLOCK = 5, // stacked square character clusters — the CJK signboard read + S_FLAP = 6, // split-flap segments flicking between states + S_FAIL = 7, // one segment dead, one segment strobing under the safety ceiling + S_BACKLIT = 8, // a dark panel that lights the WALL rather than the street + S_ARROW = 9, // chevrons pulsing down toward a doorway + S_SCREEN = 10, // a slow luminance field that reads as video from across the street + S_MARQUEE = 11, // the plain row of letters over the door — the baseline this file shipped + S_N = 12; + + /* Weights by district id, in the order city.js declares them: sodium, screen, concrete, ember, + * spring, arcade. This table is the whole reason a district reads as a place rather than as a + * hue: the concrete quarter is where signs go to die (S_FAIL, S_BACKLIT, and very little that + * moves), the screen district is screens and tickers, and the arcade strip is the only place + * that can afford a chase border on every second building. */ + var STYLE_W = [ + /* TUBE BLADE CHASE WIPE TICK BLOK FLAP FAIL BACK ARRW SCRN MARQ */ + /* sodium */ [ 6, 3, 3, 2, 1, 4, 2, 3, 2, 3, 1, 5], + /* screen */ [ 2, 3, 2, 4, 5, 3, 3, 1, 3, 1, 6, 2], + /* concrete*/ [ 3, 1, 1, 1, 1, 2, 2, 6, 5, 2, 1, 3], + /* ember */ [ 4, 2, 2, 1, 1, 2, 2, 5, 2, 5, 1, 3], + /* spring */ [ 3, 3, 2, 2, 2, 3, 4, 2, 3, 2, 2, 3], + /* arcade */ [ 3, 5, 6, 4, 4, 6, 3, 2, 2, 4, 5, 2] + ]; + + /* HOW MUCH SCREEN A CONSTRUCTION NEEDS BEFORE IT IS A CONSTRUCTION, in cells across and cells + * up, per style. These are not taste: they are the size at which the style's own parts stop + * being separable. A hollow tube needs two legs and something between them (4 across, 3 up); a + * chase border needs four sides; a character block needs two cells of ink and one of gap; a + * marquee needs three letters to read as writing; an arrow needs the chevrons to stack. Below + * these the fixture is drawn as its own MASS instead — see BD.lod in board(). That is what the + * eye gets from a real sign a hundred metres away, and the alternative measured over the sweep + * is a handful of loose marks in the facade's own glyphs and the facade's own hues, which is + * exactly what the craft review found the small styles printing as. */ + var MIN_C = [4, 1, 4, 3, 3, 5, 3, 3, 3, 2, 3, 3]; + var MIN_R = [3, 4, 3, 2, 2, 2, 2, 2, 2, 4, 2, 2]; + + /* The nearest grid size at or below n that holds a whole number of block characters, 2 ink and + * 1 gap each: 2, 5, 8, 11. Never below one character, or the block style has nothing to draw. */ + function blockGrid(n) { + var k = ((n + 1) / 3) | 0; + return (k < 1 ? 1 : k) * 3 - 1; + } + + function pickStyle(did, r) { + var w = STYLE_W[did] || STYLE_W[0], tot = 0, i; + for (i = 0; i < S_N; i++) tot += w[i]; + var x = r * tot; + for (i = 0; i < S_N; i++) { x -= w[i]; if (x <= 0) return i; } + return S_MARQUEE; + } + + /* The fixture currently being drawn. One object, filled by setupSign and read by shade, board, + * castGlow and wetSmear — the draw path allocates nothing, and a per-sign closure over these + * values would allocate twelve of them a frame. */ + /* ncW/nrW are the fixture's character grid in the WORLD, fixed for its life; nc/nr are the grid + * the SCREEN can actually sample this frame, which is never finer — see board(). gs/rs carry the + * ratio, so a shader can index its structure in the drawn grid and its content in the world one + * and the lettering stays put while the construction coarsens. Both are 1 whenever the fixture + * is big enough to hold its own grid, and then every expression below is what it always was. */ + var BD = { + style: 0, hue: 0, sd: 0, ph: 0, kind: 0, dead: 0, dead2: 0, + gl: 0, gl2: 0, nc: 2, nr: 2, ncW: 2, nrW: 2, gs: 1, rs: 1, + bv: 0, peak: 200, halo: 0.55, dens: 1, cased: 1, lod: 0, massk: 0.82, sweep: 0, tt: 0 + }; + var SH = { g: 0, k: 0, c: 0 }; // one cell's answer out of shade() + var GEO = { ax: 0, az: 0, bx: 0, bz: 0, v0: 0, H: 0 }; + + /* Where a fixture's colour comes from. city.js already decided a hue for the sign PANEL it + * painted into this lot's wall texture, and taking it means the fixture and the panel behind it + * are the same advertisement rather than two unrelated objects that happen to overlap. Lots with + * no panel fall back to the file's own roll, which is what every sign used before this pass, so + * the palette census barely moves. */ + function signHue(rec, r, style) { + var h = (rec && rec.sign) ? rec.sign.hue : neonHue(r); + /* Violet is a SCREEN pigment here and nothing else — see neonHue. A screen or a ticker is a + * dim emissive panel and can carry it; a saturated glass tube on a near wall blooms into the + * hot magenta the whole palette exists to avoid. */ + if (h === P.violet && style !== S_SCREEN && style !== S_TICKER) h = P.azure; + /* The concrete district hands out slate and white sign panels, which are structure colours. + * A sign is a light source and a light source is never unlit concrete. */ + if (h === P.slate || h === P.white || h === P.shadow) h = r < 0.5 ? P.amber : P.azure; + return h; + } + + /* ---- the shader ------------------------------------------------------------------------------ + * (u, v) are the fixture's own surface coordinates, u along it from one end and v up from its + * foot, both 0..1 and both computed perspective-correct in board(). Everything a style needs + * beyond that is on BD. Fills SH and returns false for a cell the style leaves dark — the gaps + * are as much of the construction as the marks are, since a sign with no dark in it is a slab. + * + * All locals are declared here rather than in the branches: `var` inside a switch case is + * function-scoped anyway, and hoisting them makes that visible instead of surprising. */ + function shade(u, v, t) { + var nc = BD.nc, nr = BD.nr; + var ci = (u * nc) | 0; if (ci < 0) ci = 0; else if (ci >= nc) ci = nc - 1; + var ri = (v * nr) | 0; if (ri < 0) ri = 0; else if (ri >= nr) ri = nr - 1; + /* STRUCTURE is indexed in the drawn grid (ci, ri) and CONTENT in the world grid (cw, rw). + * The distinction only exists when board() had to coarsen the grid to what the screen can + * sample, and it is what keeps that coarsening from re-rolling the sign: which columns are + * border and which are gap has to follow the cells that exist, while which letterform sits in + * a column, how bright it is and what a screen is showing must stay a property of the fixture + * or the whole board reshuffles at the two or three distances where a column becomes + * affordable. gs and rs are 1 for an unclamped fixture, so cw === ci and rw === ri and every + * line below reduces to exactly what it computed before this split existed. */ + var cw = BD.gs > 1 ? (ci * BD.gs) | 0 : ci; + var rw = BD.rs > 1 ? (ri * BD.rs) | 0 : ri; + var edge, quad, pl, pi, p, k, j, ff, st, fr, d, lv, a, b, bi, ix, iy, pk, cs; + SH.c = BD.hue; + + switch (BD.style) { + + case S_TUBE: + /* The classic bar sign: a hollow rectangle of tube with the name floating inside it. */ + edge = (ci === 0 || ci === nc - 1 || ri === 0 || ri === nr - 1); + if (!edge) { + if (nr < 5 || ri !== (nr >> 1) || (ci & 1)) return false; + SH.g = (cw & 2) ? BD.gl : BD.gl2; + SH.k = 0.60 * flick(BD.kind, BD.ph, t, cw, BD.dead2); + return true; + } + /* One corner segment is out. A rectangle of tube fails at a corner — that is where the + * bend is and where the electrode sits — and a rectangle with three corners is instantly + * read as a broken sign, where a uniformly dim one is just read as a distant one. */ + quad = (ci * 2 >= nc ? 1 : 0) + (ri * 2 >= nr ? 2 : 0); + SH.g = (ri === 0 || ri === nr - 1) ? BD.gl : G_PIPE; + SH.k = quad === (BD.dead & 3) ? 0.09 + : (0.86 + 0.14 * hk(cw, rw, BD.sd, 3)) * flick(BD.kind, BD.ph, t, 0, -1); + return true; + + case S_BLADE: + /* A stack of characters down a banner that stands out from the wall. Same construction the + * file has always had; what changed is where it hangs — see setupSign. */ + k = v * nr; + j = k | 0; ff = k - j; + if (ff > 0.66) return false; // the gap between stacked characters + j = BD.rs > 1 ? (j * BD.rs) | 0 : j; // the character, in the world grid + SH.g = hk(j, cw, BD.sd, 2) < 0.55 ? BD.gl : BD.gl2; + SH.k = (0.86 + 0.20 * hk(j, cw, BD.sd, 1)) * flick(BD.kind, BD.ph, t, j, BD.dead); + return true; + + case S_CHASE: + /* Lamps running round the border at a fixed rate, letters holding steady inside it. The + * crest is 0.10 of the perimeter wide with a 0.09 falloff and laps in 4.5 s, so a given lamp + * takes about 0.4 s to come up: 4% of full scale a frame at the very worst. */ + edge = (ci === 0 || ci === nc - 1 || ri === 0 || ri === nr - 1); + if (edge) { + pl = 2 * (nc + nr) - 4; if (pl < 1) pl = 1; + if (ri === 0) pi = ci; + else if (ci === nc - 1) pi = (nc - 1) + ri; + else if (ri === nr - 1) pi = (nc - 1) + (nr - 1) + (nc - 1 - ci); + else pi = 2 * (nc - 1) + (nr - 1) + (nr - 1 - ri); + p = crest(pi / pl - BD.sweep, 0.10, 0.09); + SH.g = p > 0.34 ? G_O : G_oo; + SH.k = 0.26 + 0.86 * p; + return true; + } + if (nr < 3 || ri !== (nr >> 1)) return false; + if ((ci & 3) === 3) return false; // inter-letter dark inside the border + SH.g = hk(cw, 0, BD.sd, 2) < 0.55 ? BD.gl : BD.gl2; + SH.k = 0.74 * flick(BD.kind, BD.ph, t, cw, BD.dead); + return true; + + case S_WIPE: + /* A bar of light crossing the face of an otherwise dull board — the cheapest animation a + * real sign has and the one that reads from furthest away. */ + k = u * nc; + j = k | 0; ff = k - j; + if (ff > 0.68) return false; + SH.g = hk(cw, rw, BD.sd, 2) < 0.55 ? BD.gl : BD.gl2; + SH.k = (0.30 + 0.68 * crest(u - BD.sweep, 0.08, 0.13)) * + flick(BD.kind, BD.ph, t, cw, BD.dead); + return true; + + case S_TICKER: + /* Text you cannot quite read, and the reason it is safe: the GLYPH scrolls, the luminance + * does not. Nothing in this branch takes t except the integer step, so the per-cell + * luminance is dead flat over time and the eye still gets a band of moving characters at + * 2 Hz. Put a blank in TICK_G and that stops being true — a space scrolling past a cell is + * a full-scale on/off edge twice a second, which is the exact artefact this file spent two + * rounds of measurement removing. */ + if (nr > 2 && (ri === 0 || ri === nr - 1)) { + SH.g = G_DASH; SH.k = 0.22; return true; // the case around the display + } + st = CC.reducedMotion ? 0 : (BD.tt * 2.0) | 0; + SH.g = TICK_G[((hk(cw + st, rw, BD.sd, 4) * 1361) | 0) % TICK_N]; + SH.k = 0.52 + 0.44 * hk(cw, rw, BD.sd, 5); + return true; + + case S_BLOCK: + /* Stacked square character clusters: a 2-cell block of dense glyphs, a gap, the next block. + * This is the signboard read the references lean on hardest and the single strongest cue in + * the file that the city has a written language — which is exactly why the block's ink + * pattern is a fixed function of its index and never of t. Writing that changes shape is + * not writing. */ + if (BD.bv) { + if (ri % 3 === 2) return false; // the gap between stacked characters + bi = (ri / 3) | 0; ix = ci; iy = ri % 3; + } else { + if (ci % 3 === 2) return false; + bi = (ci / 3) | 0; ix = ci % 3; iy = ri; + } + /* The character a block shows is a property of the fixture, not of how far away you are + * standing, so the block index is lifted into the world grid exactly like every other + * content index in this shader. */ + bi = BD.bv ? (BD.rs > 1 ? (bi * BD.rs) | 0 : bi) : (BD.gs > 1 ? (bi * BD.gs) | 0 : bi); + pk = hk(bi * 4 + ix, iy, BD.sd + 41, 8); + if (pk < 0.15) return false; // the counter inside the character + cs = hk(bi, 0, BD.sd + 7, 7); + SH.g = BLOCK_G[(((cs * 977 + pk * 131) | 0) % BLOCK_N)]; + SH.k = (0.82 + 0.18 * pk) * flick(BD.kind, BD.ph, t, bi, BD.dead); + return true; + + case S_FLAP: + /* A split-flap board. Each character holds a state for about a second and then turns over, + * and the turn is a DIP: the flap is edge-on to the street for the moment it is moving, so + * the cell darkens, the glyph changes at the bottom of the dip where nobody can see the + * change, and it comes back. The dip is measured to the flip instant the short way round, + * so there is no wrap edge — the same rule as crest(). */ + p = hk(cw, rw, BD.sd, 6); + k = BD.tt * 0.55 + p * 7; + st = k | 0; fr = k - st; + d = fr < 0.5 ? fr : 1 - fr; + SH.g = TICK_G[((hk(st + cw * 5, rw, BD.sd, 4) * 1361) | 0) % TICK_N]; + /* The dip is WIDE on purpose, and the rate is low on purpose, and both numbers are the + * answer to a measurement rather than to taste. At 0.85 flips a second through a dip 0.14 + * of a period wide this is a narrow pulse train, and a narrow pulse train is a comb: the + * fourth harmonic landed at 3.42 Hz carrying 5.75% of full scale, three times the 2% the + * flash band allows, even though nothing in it moved more than 9% in any one frame. Half a + * flip a second through a dip that occupies more than half the cycle is almost a raised + * cosine, and its content above 3 Hz measures 0.32%. */ + SH.k = 0.94 - 0.52 * CC.smooth(clamp((0.28 - d) / 0.28, 0, 1)); + return true; + + case S_FAIL: + /* The sign nobody has come to fix: one row of segments dead, one column of them strobing. + * 2.2 Hz is under the 3 Hz ceiling and the amplitude is 0.28, so the worst frame moves the + * cell 0.28 * 2 * pi * 2.2 / 60 = 6.4% of full scale. That is a fault, not a flash. */ + if (ri === BD.dead2 % nr) { SH.g = BD.gl2; SH.k = 0.07; return true; } + if (ci === BD.dead % nc) { + SH.g = BD.gl; + SH.k = CC.reducedMotion ? 0.56 + : 0.42 + 0.28 * (0.5 + 0.5 * Math.sin(BD.tt * 13.82 + BD.ph * 6.283)); + return true; + } + k = u * nc; j = k | 0; ff = k - j; + if (ff > 0.70) return false; + SH.g = hk(cw, rw, BD.sd, 2) < 0.55 ? BD.gl : BD.gl2; + SH.k = 0.80 + 0.14 * hk(cw, rw, BD.sd, 1); + return true; + + case S_BACKLIT: + /* A sign that is not the light source: an opaque panel with the tubes behind it, so what + * you actually see is the WALL around it glowing and the panel itself as a dark shape with + * a rim. All the energy is in BD.halo — see setupSign — and this branch is only here to + * put a hole in the middle of it. */ + edge = (ci === 0 || ci === nc - 1 || ri === 0 || ri === nr - 1); + if (edge) { SH.g = BD.gl; SH.k = 0.42 + 0.12 * hk(cw, rw, BD.sd, 3); return true; } + SH.c = P.shadow; + SH.g = G_HASH; SH.k = 0.34; + return true; + + case S_ARROW: + /* Chevrons pointing down at a doorway, with the pulse running down them. One chevron per + * grid row, 3.3 s a pulse: this is the slowest animation in the file and the most legible, + * because what moves is a POSITION and not a brightness. */ + p = crest((nr - 1 - ri) / nr - BD.sweep, 0.09, 0.16); + SH.g = ri === nr - 1 ? G_EQ : G_V; // a bar at the head, chevrons under it + SH.k = 0.24 + 0.82 * p; + return true; + + case S_SCREEN: + /* Something is playing on it. Two slow value-noise fields crossed — one running along the + * screen, one up it — give luminance regions that grow and drift rather than a field of + * static, and picking the glyph off the LEVEL rather than off a hash is what turns that + * into a picture: bright regions print dense, dark ones print sparse, exactly the way an + * ASCII conversion of a video frame does. + * At 0.45 units a second the field moves at most 1.1% of its range in a frame, so a screen + * on a near wall is the calmest object in this file despite never repeating. */ + a = vnoise(BD.tt * 0.45 + cw * 0.83 + BD.ph * 9, BD.sd + 101); + b = vnoise(BD.tt * 0.37 + rw * 1.29 + BD.ph * 5, BD.sd + 211); + lv = clamp(a * 0.66 + b * 0.52 - 0.13, 0, 1); + /* The black in the picture is DARK, not absent. `if (lv < 0.07) return false` was the + * obvious way to write it and it is a moving threshold on a moving field: every cell the + * picture faded through it stopped being drawn, and with two panels overlapping — which is + * common, they are the most numerous style in the screen district — the cell behind flashed + * through the hole. Forced to one style city-wide and measured, that cut was a 36.1% single + * frame step; without it the same panels measure 1.2%. A screen is an object: its black + * cells still print as its black cells, and the floor in board() keeps them occluding. */ + j = (lv * SCREEN_N) | 0; if (j >= SCREEN_N) j = SCREEN_N - 1; + SH.g = SCREEN_G[j]; + SH.k = 0.16 + 0.90 * lv * lv; + return true; + + default: + /* S_MARQUEE — a short row of glyph blocks over the door, the shape this file shipped with + * and still the right answer for most buildings. */ + k = u * nc; + j = k | 0; ff = k - j; + if (ff > 0.62) return false; // inter-letter dark, so it reads as writing + SH.g = hk(cw, rw, BD.sd, 2) < 0.55 ? BD.gl : BD.gl2; + SH.k = (0.84 + 0.22 * hk(cw, rw, BD.sd, 1)) * flick(BD.kind, BD.ph, t, cw, BD.dead); + return true; + } + } + + /* ---- what a sign lights ---------------------------------------------------------------------- + * The cast, and the reason it is a modulation and not a mark: everything a street sign actually + * illuminates — the wall it is bolted to, the pavement under it, the underside of the awning + * over the stall in front of it, the rain falling through it, the near edge of whoever is + * walking past — has ALREADY BEEN PAINTED by the time layer 30 runs. Lighting those cells costs + * energy and almost no coverage, which is the only way an effect this large fits in a frame that + * is 43% pure black on purpose. + * + * Two rules keep it honest. Only cells that already carry ink are lit, because light falls on + * surfaces and there is no surface in an empty cell. And only cells at roughly the sign's own + * depth are lit: something twenty metres in front of the sign is not being lit BY it, and + * without that test a fixture glowing behind a near corner lights up the corner. + * + * The colour crossfades rather than switching: near the source the surface takes the sign's hue + * outright, further out it keeps its own and only gets brighter, which is what a coloured light + * on a coloured surface does and what stops a halo reading as a decal. */ + function castGlow(frame, cx, cy, rx, ry, hue, amt, dist) { + if (amt < 0.03 || rx < 0.5 || ry < 0.5) return; + var cols = CO.cols, rows = CO.rows; + var xa = Math.floor(cx - rx), xb = Math.ceil(cx + rx); + var ya = Math.floor(cy - ry), yb = Math.ceil(cy + ry); + if (xa < 0) xa = 0; if (xb > cols - 1) xb = cols - 1; + if (ya < 0) ya = 0; if (yb > rows - 1) yb = rows - 1; + if (xb < xa || yb < ya) return; + var dNear = dist * 0.55, dFar = dist * 1.5; + var x, y, dx, dy, rr, i, l0, nd, k, add; + for (y = ya; y <= yb; y++) { + dy = (y + 0.5 - cy) / ry; + if (dy < -1 || dy > 1) continue; + for (x = xa; x <= xb; x++) { + dx = (x + 0.5 - cx) / rx; + rr = dx * dx + dy * dy; + if (rr > 1) continue; + i = y * cols + x; + if (frame.ch[i] === 0) continue; // nothing there to light + l0 = frame.lum[i]; + if (l0 === 0) continue; + if (!(frame.dist[i] > dNear && frame.dist[i] < dFar)) continue; + k = 1 - Math.sqrt(rr); k *= k; + add = fog(amt * k * 104, frame.dist[i]); + if (add < 3) continue; + nd = nearer(frame.dist[i]); + if (nd < 0) continue; + put(frame, x, y, frame.ch[i], k > 0.44 ? hue : frame.col[i], l0 + add, nd, + frame.kind[i]); + } + } + } + + /* Is any part of this fixture in front of what the world pass already put there? Sampled on the + * board's own centre row at three points across it, because one sample lands in the gap between + * two raindrops as often as it lands on the wall. 0.86 of the board's depth is the slack: the + * wall the sign is bolted to is a few tens of centimetres behind it and must NOT count as an + * occluder, while a building on the near side of the street is at a fraction of the distance. */ + function boardVisible(frame, xL, xR, cy, dist) { + var cols = CO.cols, y = Math.round(cy); + if (y < 0) y = 0; else if (y > CO.rows - 1) y = CO.rows - 1; + var lim = dist * 0.86, q, x; + for (q = 0; q < 3; q++) { + x = Math.round(xL + (xR - xL) * (0.1 + 0.4 * q)); + if (x < 0 || x > cols - 1) continue; + if (!(frame.dist[y * cols + x] < lim)) return true; + } + return false; + } + + /* ---- what a sign leaves on the road ---------------------------------------------------------- + * The single highest-value effect in a rain-slicked street, and it belongs here because it is + * made of the sign's colour and the sign's brightness, which nothing else in the build knows. + * surfaces.js owns the road's own wetness — the anonymous streaking that says "this tarmac is + * wet" — and this owns the reflection of a NAMED fixture: one column, at the sign's own screen + * column, dragged toward the viewer. + * + * A mirror image in a horizontal plane lands in the same screen column as its source, so the + * smear is vertical and no sideways term is needed or wanted. It runs from the foot of the wall + * toward the eye and dies out on the way, because the further from the source the more of the + * road's own texture is mixed into it. Every value here is static in t: a reflection that + * shimmers is a reflection that flickers, and this file does not flicker. */ + function wetSmear(frame, cx, w, hue, peak, sd) { + if (AT.wet < 0.22 || peak < 20) return; + var cols = CO.cols, rows = CO.rows, horizon = CO.horizon; + var x = Math.round(cx); + if (x < 0 || x > cols - 1 || w < 1.6 || w > 44) return; + var sp = (2 * (x + 0.5) / cols - 1) * CO.hp, len = Math.sqrt(1 + sp * sp); + var r0 = Math.floor(horizon + CO.eyeY * CO.scale / w); + var lo = Math.floor(horizon) + 1; if (r0 < lo) r0 = lo; + /* How far toward the eye the image is dragged. A damp road holds a short blurred copy that + * dies a third of the way out; a flooded one pulls it two thirds of the way to your feet. */ + var wEnd = w * (0.60 - 0.30 * AT.wet); if (wEnd < 1.1) wEnd = 1.1; + var r1 = Math.ceil(horizon + CO.eyeY * CO.scale / wEnd); + if (r1 > rows - 1) r1 = rows - 1; + var d = w - wEnd; if (d < 0.2) return; + var r, den, wf, q, fall, dth, lum, dd; + for (r = r0; r <= r1; r++) { + den = r + 0.5 - horizon; + if (den < 0.4) continue; + wf = CO.eyeY * CO.scale / den; + q = (w - wf) / d; + if (q < 0) q = 0; else if (q > 1) continue; + fall = (1 - q) * (1 - q); + dth = hk(x, r, sd, 5); + if (dth > 0.26 + 0.62 * fall * AT.wet) continue; + dd = wf * len; + lum = fog(peak * 0.50 * fall * AT.wet * AT.dim, dd); + if (lum < 5) continue; + /* One column wandering by a cell, keyed on the row so it is a stable ripple and not a + * per-frame jitter, and 0.6% nearer than the tarmac it lies on because the road at this + * exact distance was painted by the raycaster and the coin flip has to be settled. */ + put(frame, x + ((hk(x, r >> 1, sd, 6) * 2.6) | 0) - 1, r, + dth < 0.11 ? G_QUOTE : G_COLON, hue, lum, dd * 0.994); + } + } + + /* ============================================================================================= + * 1. SHOP WINDOW SPILL — layer 28 + * The warm pool a lit shopfront throws onto the wet pavement in front of it. Drawn first of the + * four so a sign or a signal always wins the cell. + * ========================================================================================== */ + var SP = { salt: 0 }; + + /* surfaces.js decides which ground-floor units are open from hash2(floor(u/2.55),0,sd^0x7E31), + * with sd the building seed widened the way raycast.js widens it. Re-deriving that here is the + * whole reason the spill lands under a lit window instead of under a shutter. If surfaces ever + * re-rolls that test this degrades to spill in a merely plausible place, never to a crash. */ + function shopOpen(rec, u) { + var sd = (rec.seed * 4294967296) | 0; + return hash2(Math.floor(u / 2.55), 0, sd ^ 0x7E31) < 0.40; + } + + CC.ELEMENTS.push({ + name: 'shopSpill', + layer: 28, + + /* The interface hands `city` to init but not to draw, so park it on the element rather than + * in a module-level singleton a second City instance would silently share. */ + init: function (city, rng) { + this.city = city; + SP.salt = (rng() * 2147483647) | 0; + }, + + update: function () {}, + + draw: function (frame, cam, t) { + var city = this.city; + if (!city) return; + setCam(frame, cam); + airPrep(); + + var R = 25; // past this the pool is under two rows and reads as grime + var gx0 = Math.floor(CO.ox - R), gx1 = Math.floor(CO.ox + R); + var gz0 = Math.floor(CO.oz - R), gz1 = Math.floor(CO.oz + R); + var rows = CO.rows, cols = CO.cols, horizon = CO.horizon; + var drawn = 0, gx, gz; + + /* Every cell, not every other one: a stride over world cells aliases against the wall, + * whose frontage is a single column of constant gx, so half the time a whole facade is + * skipped and the other half it is fully covered. The pools are broken apart by a hash + * below instead — a continuous wash along the kerb reads as a painted stripe. */ + for (gz = gz0; gz <= gz1; gz++) { + for (gx = gx0; gx <= gx1; gx++) { + if (drawn > 16) return; + var rx = gx + 0.5 - CO.ox, rz = gz + 0.5 - CO.oz; + var w = rx * CO.fwx + rz * CO.fwz; + if (w < 1.2 || w > R) continue; + var side = rx * CO.rgx + rz * CO.rgz, lim = w * CO.hp + 2.5; + if (side > lim || side < -lim) continue; + if (hk(gx, gz, SP.salt, 6) > 0.62) continue; // one pool per few metres, not a wash + if (city.height(gx, gz) <= 0) continue; + if (!faceOf(city, gx, gz, rx, rz)) continue; + + var rec = city.cell(gx, gz); + if (!rec) continue; + var nx = FACE.nx, nz = FACE.nz; + /* u is the world coordinate ALONG the wall — the same one raycast.js hands the facade + * texture, so the unit boundaries agree. */ + var u = nx ? FACE.fz : FACE.fx; + if (!shopOpen(rec, u)) continue; + + if (!project(FACE.fx + nx * 0.5, 0.1, FACE.fz + nz * 0.5)) continue; + var span = colsFor(0.75, VP.w); + var xa = Math.floor(VP.x - span), xb = Math.ceil(VP.x + span); + if (xa < 0) xa = 0; if (xb > cols - 1) xb = cols - 1; + if (xb < xa) continue; + + var hs = hk(gx, gz, SP.salt, 1); + /* The pool's colour comes from the sign over the door when there is one. A shopfront + * and its sign are lit by the same tubes, and pooling generic warm under an azure + * fixture was the one place in this file where two systems disagreed about what colour + * a shop is. Most units keep the interior warm: the light on the pavement is mostly + * what is on INSIDE, and a street where every pool matches its sign is a lighting rig, + * not a street. */ + var hue = (rec.sign && hs < 0.58) ? signHue(rec, hs, S_MARQUEE) + : (hs < 0.74 ? P.warm : (hs < 0.93 ? P.amber : P.ice)); + var depth = 1.15 + hs * 0.75; + var peak = 74 + hk(gx, gz, SP.salt, 2) * 46; + /* The pool breathes with whatever is on inside. Tiny amplitude — this is a reflection, + * and a reflection that pulses harder than its source stops being one. */ + if (!CC.reducedMotion) peak *= 0.90 + 0.10 * vnoise(t * 0.5 + hs * 30, SP.salt); + /* Wet pavement holds the pool; dry pavement scatters it. Exactly 1.0 at the preset the + * pool was tuned under, so this changes nothing until the weather does. */ + peak *= clamp(0.68 + 0.32 * AT.wet, 0.60, 1.16) * AT.dim; + /* Counts pools that landed, not pools considered: a parade of shopfronts hidden behind + * the near block must not spend the budget the visible kerb needs. */ + var hit = 0; + + var planeX = FACE.fx, planeZ = FACE.fz; + /* The pool only ever occupies the band of rows looking at pavement between the wall and + * `depth` metres out. Deriving that band up front turns a full-column march into three + * or four rows; the margin covers the face being a plane rather than a sphere, so a + * column at the edge of the span still finds its ground. */ + var wLo = w - depth - 1.2; if (wLo < 0.9) wLo = 0.9; + var rTop = Math.floor(horizon + CO.eyeY * CO.scale / (w + 1.2)); + var rBot = Math.ceil(horizon + CO.eyeY * CO.scale / wLo); + if (rTop < Math.floor(horizon) + 1) rTop = Math.floor(horizon) + 1; + if (rBot > rows - 1) rBot = rows - 1; + var a0 = (nx ? FACE.fz : FACE.fx) - 0.5, a1 = a0 + 1; + + for (var x = xa; x <= xb; x++) { + var sp = (2 * (x + 0.5) / cols - 1) * CO.hp; + var dx = CO.fwx + CO.rgx * sp, dz = CO.fwz + CO.rgz * sp; + var len = Math.sqrt(1 + sp * sp); + /* Each row is inverse-projected on its own — a pool painted from one sample would + * stretch metres of pavement across rows that are metres apart in world space. */ + for (var r = rTop; r <= rBot; r++) { + var den = r + 0.5 - horizon; + if (den < 0.4) continue; + var wf = CO.eyeY * CO.scale / den; + var px = CO.ox + dx * wf, pz = CO.oz + dz * wf; + var out = (px - planeX) * nx + (pz - planeZ) * nz; + if (out < 0.04 || out > depth) continue; + var along = nx ? pz : px; + if (along < a0 || along > a1) continue; + var k = 1 - out / depth; + var dith = hk(Math.floor(px * 3.1), Math.floor(pz * 3.1), SP.salt, 3); + if (dith > 0.30 + k * 0.20) continue; // brighter near the glass means denser too + var lum = fog(peak * k * k * (0.6 + 0.8 * dith), wf * len); + if (lum < 5) continue; + /* 0.6% depth bias: the pool is a decal on tarmac the raycaster already painted at + * this exact distance, and without it, which one wins is a floating-point coin flip. */ + if (put(frame, x, r, SPILL_G[((dith * 977) | 0) % SPILL_N], hue, lum, + wf * len * 0.994)) hit = 1; + } + } + drawn += hit; + } + } + } + }); + + /* ============================================================================================= + * 2. FACADE NEON — layer 30 + * Twelve sign styles bolted to the walls, each one lighting what is around it and smearing down + * the wet road in front of it. city.js already paints a flat sign PANEL into the wall texture; + * these are the fixtures that stand proud of it, mounted off the face so they occlude the facade + * honestly instead of by fiat. + * ========================================================================================== */ + var NE = { salt: 0 }; + var SIGN_CAP = 14; // fixtures that may LAND in one frame; bounds cost and coverage together + /* The screen area, in cells, at which a fixture starts thinning out instead of growing. A 2 m + * board eight metres away is 70 columns of solid neon, which is the entire frame's light budget + * in one object; past this the dither takes cells away as fast as the perspective adds them, so + * a sign you walk up to gets BIGGER and SPARSER rather than turning into a wall of colour. The + * dropout is keyed in the fixture's own grid, never in screen space, so it does not crawl as you + * approach. */ + var AREA_T = 108; + + /* Everything about one fixture, derived from its cell. Fills BD and GEO; no allocation. */ + function setupSign(gx, gz, bh, rec, t) { + var nx = FACE.nx, nz = FACE.nz; + var tx = nz, tz = -nx; // unit vector ALONG the wall; the faces are axis-aligned + var r1 = hk(gx, gz, NE.salt, 1), r2 = hk(gx, gz, NE.salt, 2), r3 = hk(gx, gz, NE.salt, 3); + var r4 = hk(gx, gz, NE.salt, 4), r9 = hk(gx, gz, NE.salt, 9); + var style = pickStyle(rec ? rec.did : 0, hk(gx, gz, NE.salt, 5)); + var W, H, v0, L, blade = 0, vert = 0; + + /* A blade needs wall to hang off. Falling back to the marquee rather than to nothing keeps the + * low industrial pockets — which is most of the ember district — from being the only unsigned + * streets in the city. The vertical signboard makes the same decision for itself below, since + * it has a horizontal version to fall back to and the blade does not. */ + if (style === S_BLADE && bh < 15) style = S_MARQUEE; + + switch (style) { + case S_BLADE: + /* Perpendicular to the facade, which is the whole point of a blade: walking down the street + * it is a bright board, and looking straight at the wall it collapses to a line. board() + * handles that collapse by projecting both ends rather than assuming a width. */ + blade = 1; + L = 0.85 + r2 * 0.80; + H = 3.4 + r3 * 4.6; + if (H > bh - 6) H = bh - 6; + if (H < 2.2) H = 2.2; + v0 = 5.0 + r9 * (bh - H - 7 > 0 ? bh - H - 7 : 0); + W = L; + break; + case S_BLOCK: + /* Tall buildings get the vertical signboard — characters stacked one above the other down + * the corner, which is the single most recognisable shape in the reference set. Everything + * else gets the horizontal fascia version of the same construction. */ + vert = (bh > 19 && r2 < 0.66) ? 1 : 0; + if (vert) { + W = 0.95; H = 2.9 + r3 * 3.4; + if (H > bh - 8) H = bh - 8; + if (H < 2.0) { vert = 0; } + } + if (vert) v0 = 4.6 + r9 * (bh - H - 8 > 0 ? bh - H - 8 : 0); + else { W = 1.9 + r3 * 0.9; H = 1.05; v0 = 3.0 + r9 * 1.9; } + break; + case S_TUBE: W = 1.7 + r3 * 0.9; H = 0.95 + r2 * 0.80; v0 = 2.95 + r9 * 1.7; break; + case S_ARROW: W = 0.70; H = 1.9 + r3 * 0.9; v0 = 2.45 + r9 * 0.7; break; + case S_SCREEN: W = 1.5 + r3 * 1.1; H = 1.05 + r2 * 0.9; v0 = 3.1 + r9 * 2.6; break; + case S_TICKER: W = 2.0 + r3 * 0.9; H = 0.60; v0 = 3.2 + r9 * 1.6; break; + case S_CHASE: W = 1.8 + r3 * 0.8; H = 0.95 + r2 * 0.5; v0 = 3.0 + r9 * 1.5; break; + case S_FLAP: W = 1.5 + r3 * 0.8; H = 0.70 + r2 * 0.4; v0 = 3.0 + r9 * 1.5; break; + case S_BACKLIT: W = 1.5 + r3 * 1.0; H = 0.95 + r2 * 0.7; v0 = 3.2 + r9 * 2.2; break; + default: W = 1.6 + r3 * 0.9; H = 0.62 + r2 * 0.5; v0 = 3.1 + r9 * 1.4; break; + } + + var cx = FACE.fx, cz = FACE.fz; + if (blade) { + GEO.ax = cx + nx * 0.18; GEO.az = cz + nz * 0.18; + GEO.bx = cx + nx * (0.18 + L); GEO.bz = cz + nz * (0.18 + L); + } else { + /* 0.30 m proud of the face, and off-centre on its own cell by up to 15 cm so a run of + * signed lots does not print as a dotted line of perfectly spaced boards. */ + var off = (r4 - 0.5) * 0.30; + GEO.ax = cx + nx * 0.30 + tx * (off - W * 0.5); + GEO.az = cz + nz * 0.30 + tz * (off - W * 0.5); + GEO.bx = cx + nx * 0.30 + tx * (off + W * 0.5); + GEO.bz = cz + nz * 0.30 + tz * (off + W * 0.5); + } + GEO.v0 = v0; GEO.H = H; + + /* The character grid, in the WORLD and fixed for the life of the fixture: walking towards a + * sign enlarges its lettering instead of re-rolling it, which is the same rule the holo panel + * follows and for the same reason. */ + BD.ncW = Math.round(W / 0.30); if (BD.ncW < 2) BD.ncW = 2; else if (BD.ncW > 9) BD.ncW = 9; + BD.nrW = Math.round(H / 0.34); if (BD.nrW < 2) BD.nrW = 2; else if (BD.nrW > 14) BD.nrW = 14; + BD.bv = vert; + if (style === S_BLOCK) { + /* Blocks are 2 grid cells of ink and 1 of gap, so the grid has to be a whole number of + * them or the last character comes out clipped. */ + var nch; + if (vert) { + BD.ncW = 2; + nch = Math.round(H / 1.02); if (nch < 2) nch = 2; else if (nch > 6) nch = 6; + BD.nrW = nch * 3 - 1; + } else { + nch = Math.round(W / 0.92); if (nch < 2) nch = 2; else if (nch > 4) nch = 4; + BD.ncW = nch * 3 - 1; BD.nrW = 2; + } + } + if (style === S_ARROW) { BD.ncW = 2; BD.nrW = Math.round(H / 0.42); if (BD.nrW < 3) BD.nrW = 3; } + /* Until board() measures the fixture on screen, the drawn grid IS the world grid: setupSign is + * the only writer of these and a shader must never see a stale pair from the fixture before. */ + BD.nc = BD.ncW; BD.nr = BD.nrW; BD.gs = 1; BD.rs = 1; + + BD.style = style; + BD.hue = signHue(rec, r1, style); + BD.kind = (hk(gx, gz, NE.salt, 6) * 4) | 0; + BD.ph = hk(gx, gz, NE.salt, 7); + BD.gl = NEON_G[(r3 * NEON_N) | 0]; + /* A sign is a WORD. Rolling a fresh glyph per character turned every board into a column of + * static, so each fixture gets exactly two letterforms and alternates between them; the eye + * reads that as lettering it cannot quite make out. */ + BD.gl2 = NEON_G[(hk(gx, gz, NE.salt, 8) * NEON_N) | 0]; + /* Which segment is out is a fact about the FIXTURE, so it is rolled against the world grid and + * taken modulo the drawn one where it is used. Rolling it against the drawn grid would move the + * dead tube to another column every time the sign gained a column on approach. */ + BD.dead = (hk(gx + 7, gz - 3, NE.salt, 0) * BD.ncW) | 0; + BD.dead2 = (hk(gx - 5, gz + 11, NE.salt, 0) * BD.nrW) | 0; + /* Small, and varied additively: hash2 is exact in imul now, but every seed in this file stays + * inside a few tens of thousands so that the vnoise streams below cannot collide by rounding. */ + BD.sd = (hk(gx + 13, gz + 17, NE.salt, 2) * 30011) | 0; + BD.tt = CC.reducedMotion ? BD.ph * 31 : t; + + /* Every fixture is boxed — see the case in board(). The flag exists because the backlit panel + * already IS a case with a rim round it, and a second one under it only darkens its own + * interior for nothing. */ + BD.cased = style === S_BACKLIT ? 0 : 1; + /* The level the fixture collapses to when it is too small to have parts. It carries the + * fixture's own flicker personality and nothing else — a distant sign that guttered per + * character would be twinkling, and twinkle at this size is indistinguishable from the + * lattice noise the mass exists to separate itself from. j is off the end of the grid on + * purpose so personality 2's dead character cannot be the one cell the whole fixture is. */ + BD.massk = 0.82 * flick(BD.kind, BD.ph, t, -1, -2); + + var peak = 178 + hk(gx + 3, gz - 5, NE.salt, 1) * 66; + BD.halo = 0.50; + if (style === S_SCREEN) { peak *= 0.80; BD.halo = 0.70; } + else if (style === S_BACKLIT) { peak *= 0.50; BD.halo = 1.70; } + else if (style === S_TICKER) { peak *= 0.86; BD.halo = 0.42; } + else if (style === S_BLOCK) BD.halo = 0.62; + BD.peak = peak * gutter(t, BD.ph); + + /* Sweep rates, one field because no style has two travelling crests. Every one of them laps + * in three to five seconds: what the eye reads is the MOVEMENT, and a crest that laps faster + * than that stops being a lamp running round a border and becomes a flicker. */ + var rate = style === S_CHASE ? 0.22 : (style === S_WIPE ? 0.26 : 0.30); + BD.sweep = CC.reducedMotion ? BD.ph : (BD.ph + t * rate) % 1; + } + + /* Rasterise the fixture described by BD and GEO. Returns 1 if anything landed. + * + * The board is a rectangle in the world standing on the segment (ax,az)-(bx,bz) — along the wall + * for a fascia, out along the normal for a blade — so one routine draws both and a blade + * foreshortens correctly instead of being faked. Both ends are projected and the interior is + * interpolated PERSPECTIVE-CORRECT: 1/w is what is linear in screen x, so the depth of a column + * is 1/lerp(1/wL, 1/wR) and the surface coordinate is (s/wR) over that same sum. Interpolating u + * linearly instead puts the lettering of a near sign visibly off-centre. */ + function board(frame, t) { + if (!projInto(GEO.ax, GEO.v0, GEO.az, VA)) return 0; + if (!projInto(GEO.bx, GEO.v0, GEO.bz, VB)) return 0; + var cols = CO.cols, rows = CO.rows; + var xL, xR, wL, wR; + if (VA.x <= VB.x) { xL = VA.x; wL = VA.w; xR = VB.x; wR = VB.w; } + else { xL = VB.x; wL = VB.w; xR = VA.x; wR = VA.w; } + /* A blade seen edge-on is a LINE, not nothing — that instant is when a blade sign is most + * itself — so a board narrower than a column is widened to one rather than dropped. */ + var span = xR - xL; + if (span < 0.9) { var mid = (xL + xR) * 0.5; xL = mid - 0.45; xR = mid + 0.45; span = 0.9; } + if (xR < 0 || xL > cols - 1) return 0; + + var wMid = 2 / (1 / wL + 1 / wR); + var hRows = GEO.H * CO.scale / wMid; + var cxs = (xL + xR) * 0.5; + var cys = CO.horizon - (GEO.v0 + GEO.H * 0.5 - CO.eyeY) * CO.scale / wMid; + var spC = (2 * (cxs + 0.5) / cols - 1) * CO.hp; + var distMid = wMid * Math.sqrt(1 + spC * spC); + + var xa = Math.floor(xL), xb = Math.ceil(xR); + if (xa < 0) xa = 0; if (xb > cols - 1) xb = cols - 1; + if (xb < xa) return 0; + + /* ---- the grid the screen can actually sample -------------------------------------------- + * A fixture's character grid is fixed in the world — up to 9 columns of lettering — and the + * shader is point-sampled once per screen column. Over the canonical sweep the median fixture + * covers 3.1 columns at 30 m while carrying 7 grid columns, and 52% of all fixtures have a + * grid at least twice as fine as the screen: for those, one grid column in two is never asked + * about, and WHICH ones are skipped is a function of where the board's edge happens to fall + * between two cells. That is the whole reason the constructions do not read. A hollow tube + * loses one leg and prints as an L; a chase border loses a side; a character block loses the + * gap that separates two characters and prints as the same lattice the window texture behind + * it is made of. Nothing was wrong with the constructions — half of every construction was + * being sampled away, and the half that survived changed as the viewer walked. + * + * Coarsening the grid to what the screen can carry is the standard answer to that (it is a + * mip level, and the alternative — supersampling every cell — is a draw-path allocation and + * four times the shader cost for an object 3 cells wide). STRUCTURE then follows the cells + * that exist, so a tube always has two legs and a border always has four sides, at any size. + * CONTENT does not follow it: gs/rs carry the ratio and shade() lifts every letterform, + * brightness jitter and screen-noise lookup back into the world grid, so approaching a sign + * does not reshuffle what it says. Both ratios are 1 for any fixture big enough to hold its + * own grid, and that fixture renders exactly what it rendered before. */ + var sgc = Math.round(span); if (sgc < 2) sgc = 2; + var sgr = Math.round(hRows); if (sgr < 2) sgr = 2; + BD.nc = BD.ncW < sgc ? BD.ncW : sgc; + BD.nr = BD.nrW < sgr ? BD.nrW : sgr; + if (BD.style === S_BLOCK) { + /* A block character is two grid cells of ink and one of gap, so a grid that is not a whole + * number of them clips the last character in half — the same rule setupSign follows when it + * builds the world grid, applied again to the coarsened one. */ + if (BD.bv) BD.nr = blockGrid(BD.nr); else BD.nc = blockGrid(BD.nc); + } + BD.gs = BD.nc > 0 ? BD.ncW / BD.nc : 1; + BD.rs = BD.nr > 0 ? BD.nrW / BD.nr : 1; + + /* ---- and when even that is too small ------------------------------------------------------ + * Coarsening the grid makes a construction survivable; it cannot make it EXIST. 72% of the + * fixtures in the sweep are under 8 columns and half are under 3, and at 3 columns a hollow + * rectangle, a chase border and a video screen are the same object: four or five loose marks + * in the two pillar hues, drawn out of the same glyph bank the window lattice behind them is + * drawn from, at the wall's own brightness. That is the finding, and no amount of care inside + * the shader answers it, because the parts being drawn are smaller than a cell. + * + * So below MIN_C x MIN_R the fixture stops being a construction and becomes its own MASS: a + * contiguous block of the sign's colour at one level, which is what a real sign reduces to at + * distance and — per the review's own census of what does and does not read — the single + * property shared by every style that survives. lod crossfades it in over two cells of span + * rather than switching, for the reason every travelling shape in this file is a plateau: a + * threshold on a quantity the walk changes puts a full-scale step on every cell of a fixture + * in one frame, and this quantity changes with every step the viewer takes. Since the mass + * level is a constant, the blend can only ever REDUCE a cell's temporal amplitude — the + * chase's crest, the screen's field and the fail's strobe all shrink toward flat as lod goes + * up, so nothing here can push a style past the envelope it was measured at. */ + var mnc = MIN_C[BD.style], mnr = MIN_R[BD.style]; + if (BD.style === S_BLOCK && BD.bv) { mnc = 2; mnr = 5; } + var dfc = (mnc - span) * 0.5, dfr = (mnr - hRows) * 0.5; + if (dfr > dfc) dfc = dfr; + BD.lod = BD.cased ? CC.smooth(clamp(dfc, 0, 1)) : 0; + + /* Thinning, not clamping — see AREA_T. */ + var area = (xb - xa + 1) * (hRows < 1 ? 1 : hRows); + BD.dens = area > AREA_T ? AREA_T / area : 1; + if (BD.dens < 0.24) BD.dens = 0.24; + + /* The cast goes down FIRST and the board over the top of it. The board carries a 0.4% depth + * bias — it stands 0.3 m proud of its wall, so it is genuinely nearer — and the halo is only + * a part in ten thousand nearer than whatever it landed on, so the sign can never be eaten by + * its own glow. Reverse the order and it is, at every grazing angle where the standoff stops + * separating the two depths. + * + * Which is why the visibility of the fixture has to be settled BEFORE anything is drawn: the + * board finds out it is behind a wall one put() at a time, and by then the halo has already + * gone down. Three samples across the board's own row, and any one of them seeing past the + * board's depth is enough — a sign half hidden by a corner still lights the corner. */ + var vis = boardVisible(frame, xL, xR, cys, distMid); + if (vis) { + /* The halo's reach is deliberately mean. At span*0.85 + 2.2 it was a 52x30 ellipse on a near + * fixture — six hundred cells of somebody else's facade repainted in the sign's hue, which + * is not a sign lighting a wall, it is a sign eating one. Half that radius still puts a + * clear pool of colour around every fixture and leaves the facade underneath legible. */ + var gr = span * 0.55 + 1.8; if (gr > 15) gr = 15; + var gy = hRows * 0.55 + 1.4; if (gy > 9) gy = 9; + /* A dim fixture casts a dim pool: the halo is a fraction of the source and not a constant, + * or a ticker at 0.86 peak lights the street as hard as a marquee at full. */ + castGlow(frame, cxs, cys, gr, gy, BD.hue, + BD.halo * AT.halo * clamp(BD.peak / 210, 0.40, 1.20), distMid); + } + + var hit = 0, x, r, s, iw, w, u, sp, len, dist, yBot, yTop, vspan, r0, r1, v, lum; + for (x = xa; x <= xb; x++) { + s = (x + 0.5 - xL) / span; + if (s < 0) s = 0; else if (s > 1) s = 1; + iw = (1 - s) / wL + s / wR; + w = 1 / iw; + u = (s / wR) / iw; + sp = (2 * (x + 0.5) / cols - 1) * CO.hp; + len = Math.sqrt(1 + sp * sp); + dist = w * len * 0.996; + yBot = CO.horizon - (GEO.v0 - CO.eyeY) * CO.scale / w; + yTop = yBot - GEO.H * CO.scale / w; + vspan = yBot - yTop; + if (vspan < 0.4) vspan = 0.4; + r0 = Math.ceil(yTop); r1 = Math.floor(yBot); + if (r0 < 0) r0 = 0; if (r1 > rows - 1) r1 = rows - 1; + if (r1 < r0) continue; + for (r = r0; r <= r1; r++) { + v = (yBot - (r + 0.5)) / vspan; + if (v < 0) v = 0; else if (v > 1) v = 1; + /* Thinned in the fixture's own grid at three times its resolution, so the holes stay put + * on the sign as you walk towards it instead of crawling across it. */ + if (BD.dens < 1 && hk((u * BD.ncW * 3) | 0, (v * BD.nrW * 3) | 0, BD.sd, 4) > BD.dens) continue; + if (!shade(u, v, t)) { + /* THE CASE. A sign is an object bolted to a wall, not a stencil cut into one, and until + * this line the cells a construction leaves dark showed the facade straight through — + * so a fixture arrived as a handful of loose marks scattered across the window lattice, + * in the lattice's own glyphs and the lattice's own two hues. That is the whole of why + * the small styles do not read: at the median fixture, 3 screen columns at 30 m, there + * is no construction left to see, only its ink, and its ink is indistinguishable from + * lit windows. The one style everybody agrees reads — the marquee — is the one whose + * ink happens to be contiguous. + * + * The case fixes that for every style at once and costs no light: it is the sign's own + * dark box, at a tenth of its brightness in the shadow swatch, filling exactly the cells + * the construction does not. What it buys is a SILHOUETTE — the lattice stops dead at + * the fixture's edge — and a silhouette is the cue that says object rather than + * lit-window-cluster. It writes dark cells over bright wall, so it takes lit coverage + * away rather than adding any, which is the only kind of legibility this frame budget + * can afford. + * + * It goes down at the board's own depth, so it occludes honestly, and it is static: no + * cell of it moves at any rate, and it can only ever make the fixture's total energy + * smaller. */ + if (!BD.cased) continue; + SH.c = BD.hue; + /* The case takes the fixture's own two letterforms rather than one filler glyph: the + * box of a sign is lit by the tubes bolted to it, and a flat field of one character + * reads as a texture swatch where an alternation reads as an object. The parity is + * taken in the WORLD grid, so it holds still on the sign as the viewer walks instead of + * crawling across it a cell at a time the way a screen-space parity would. */ + SH.g = ((((u * BD.ncW) | 0) + ((v * BD.nrW) | 0)) & 1) ? BD.gl : BD.gl2; + SH.k = 0.10; + } + /* Toward the fixture's mass as it gets too small to have parts — see BD.lod. */ + if (BD.lod > 0) SH.k += (BD.massk - SH.k) * BD.lod; + lum = fog(BD.peak * SH.k * AT.dim, dist); + /* A sign OCCLUDES whether or not it is lit, and the floor here is what enforces that. + * `if (lum < 5) continue` looks like a harmless saving and is a photosensitivity bug: a + * fixture guttering across that threshold stops writing its cells for a frame, and every + * cell of it that happened to be in front of a brighter fixture behind flips to that + * fixture's value and back. Measured with the styles forced one at a time, that hole was + * a 56% single-frame step on the wipe and 36% on the screen — by some way the worst + * artefact in the file, and invisible in the aggregate because it needs two fixtures to + * overlap. A dark cell is a dark cell; a hole is a flash. */ + if (lum < 4) lum = 4; + if (put(frame, x, r, SH.g, SH.c, lum, dist)) hit = 1; + } + } + /* Gated on VISIBILITY and not on `hit`, for exactly the reason above: `hit` is false for a + * frame whenever the fixture is mid-dropout, and a reflection that blinks out with the + * flicker of its source is a 90% step on every cell of the smear. The image in the road is + * the sign's steady brightness — water does not strobe. */ + if (vis) wetSmear(frame, cxs, wMid, BD.hue, BD.peak, BD.sd); + return hit; + } + + CC.ELEMENTS.push({ + name: 'neon', + layer: 30, + + init: function (city, rng) { + this.city = city; + NE.salt = (rng() * 2147483647) | 0; + }, + + update: function () {}, + + draw: function (frame, cam, t) { + var city = this.city; + if (!city) return; + setCam(frame, cam); + airPrep(); + + var R = 58; + var gx0 = Math.floor(CO.ox - R), gx1 = Math.floor(CO.ox + R); + var gz0 = Math.floor(CO.oz - R), gz1 = Math.floor(CO.oz + R); + var drawn = 0, gx, gz; + + /* Stride 1 for the same reason the spill uses it: a wall's frontage is one column of + * constant gx, and any stride at all makes whether a facade carries signage depend on the + * parity of the camera's own cell. */ + for (gz = gz0; gz <= gz1; gz++) { + for (gx = gx0; gx <= gx1; gx++) { + /* The cap counts fixtures that actually reached the frame, not fixtures considered. + * Counting attempts lets a row of signs hidden behind the near block spend the whole + * budget and leave the visible street bare. */ + if (drawn > SIGN_CAP) return; + var rx = gx + 0.5 - CO.ox, rz = gz + 0.5 - CO.oz; + var w = rx * CO.fwx + rz * CO.fwz; + if (w < 2.2 || w > R) continue; + var side = rx * CO.rgx + rz * CO.rgz, lim = w * CO.hp + 3; + if (side > lim || side < -lim) continue; + + /* Cheap rejection FIRST — most cells die here, before a heightmap lookup. */ + if (hk(gx, gz, NE.salt, 0) > 0.105) continue; + var bh = city.height(gx, gz); + if (bh < 6) continue; + if (!faceOf(city, gx, gz, rx, rz)) continue; + /* The record is only worth building once the cell is certainly a signed facade: cell() + * is chunk-cached, but the first call for a chunk builds 256 of them. */ + var rec = city.cell(gx, gz); + if (!rec) continue; + + setupSign(gx, gz, bh, rec, t); + drawn += board(frame, t); + } + } + } + }); + + /* ============================================================================================= + * 3. TRAFFIC SIGNALS — layer 31 + * One head each side of a junction, four metres up. Three lamps, one of them alight. This is the + * only element that is allowed pure saturated red, and it is two cells of it. + * ========================================================================================== */ + var TS = { salt: 0 }; + var LAMP_V = [4.30, 4.66, 5.02]; // green low, amber, red high, as they are hung + var LAMP_C = [P.spring, P.amber, P.red]; + var CYCLE = 46; + + CC.ELEMENTS.push({ + name: 'signals', + layer: 31, + + init: function (city, rng) { + this.city = city; + TS.salt = (rng() * 2147483647) | 0; + }, + + update: function () {}, + + draw: function (frame, cam, t) { + var city = this.city; + if (!city || !city.aveX) return; + setCam(frame, cam); + airPrep(); + + var R = 62; + var k0 = Math.round((CO.ox - R) / city.AVE), k1 = Math.round((CO.ox + R) / city.AVE); + var m0 = Math.round((CO.oz - R) / city.CROSS), m1 = Math.round((CO.oz + R) / city.CROSS); + var k, m, s; + + for (k = k0; k <= k1; k++) { + var aw = city.aveW(k); + if (aw < 3) continue; // an alley mouth gets no signal head + var ix = city.aveX(k) + 0.5; + for (m = m0; m <= m1; m++) { + var cw = city.crossW(m); + if (cw < 2) continue; + var iz = city.crossZ(m) + 0.5; + + /* Phase is per junction and never per frame, so the lights keep time through a scrub + * and two heads at the same crossing always agree with each other. */ + var phase = hk(k, m, TS.salt, 1) * CYCLE; + var u = CC.reducedMotion ? phase : (t + phase) % CYCLE; + if (u < 0) u += CYCLE; + var on = u < 21 ? 0 : (u < 25 ? 1 : 2); + /* The amber is the only lamp that blinks; a steady frame of it looks like a dead pixel + * rather than the four seconds of warning it is. 9 rad/s is 1.43 Hz — under the ceiling, + * and a sine rather than a square, so its worst frame moves the lamp 0.45*9/60 = 6.8% of + * full scale. The lamp CHANGES, on the other hand, are hard cuts of most of full scale, + * and are meant to be: a traffic light is the one object here that is supposed to snap. + * They cost a given cell about six steps per 46 s cycle, which is what tells them apart + * from a flicker edge — see the rate column in tools/flicker-rate.cjs. */ + var blink = (on === 1 && !CC.reducedMotion) ? (0.55 + 0.45 * Math.sin(u * 9)) : 1; + + var zs = hk(k, m, TS.salt, 2) < 0.5 ? -1 : 1; + for (s = -1; s <= 1; s += 2) { + /* aw/cw are half-widths in CELLS, so the carriageway reaches aw + 0.5 either side of + * the centreline. Hanging the head at aw + 1.1 put every one of them a metre inside + * the corner building, where the height test then silently dropped it. */ + var hx = ix + s * (aw - 0.2), hz = iz + zs * (cw + 0.9); + if (city.height(hx, hz) > 0) continue; // the corner got eaten by a plaza or a lot + var lit = 0, lw = 0, lx = 0; + for (var li = 0; li < 3; li++) { + if (!project(hx, LAMP_V[li], hz)) break; + var near = VP.dist < 21; + if (li !== on && !near) continue; // far off, only the burning lamp survives + var lum = li === on ? fog(236 * blink * AT.dim, VP.dist) : fog(15, VP.dist); + if (lum < 5) continue; + put(frame, Math.round(VP.x), Math.round(VP.y), + li === on ? G_O : G_oo, li === on ? LAMP_C[li] : P.shadow, lum, VP.dist); + if (li === on) { lw = VP.w; lx = VP.x; } + lit++; + } + /* The head's own body, one cell under the bottom lamp, only when it is close enough + * for the lamps to have separated into their own rows. */ + if (lit && VP.dist < 15 && project(hx, 4.05, hz)) + put(frame, Math.round(VP.x), Math.round(VP.y), G_EQ, P.shadow, + fog(20, VP.dist), VP.dist); + /* A stop lamp on a wet road is the most reliably reflected object in a night street — + * it is the brightest saturated thing at the lowest height. Same smear the signs use, + * at a third of the strength: the head is two cells and its reflection may not become + * the larger object. */ + if (lw > 0) wetSmear(frame, lx, lw, LAMP_C[on], 96, TS.salt & 0x7fff); + } + } + } + } + }); + + /* ============================================================================================= + * 4. HOLOGRAPHIC ADVERTS — layer 33 + * Hung over the carriageway, camera-facing because a hologram has no back. Interlaced and heavily + * dropped out: a holo you can't see the sky through is just a billboard. + * ========================================================================================== */ + var HO = { salt: 0 }; + var HZ = 30; // metres between advert slots down an avenue + /* How much of a character row the vertical resample below spends crossfading between the two + * rows a screen row straddles — see the long note in the draw loop. Away from that window the + * cell shows exactly one character row and prints exactly what it always printed; inside it the + * two are mixed, which is what removes the pop and also what costs coverage, since a cell is lit + * if EITHER row lights it and the advert is 50% dropout by design. + * + * The width is set by LOOKING, not by the step, because over the whole range 0.25..1.00 the + * measured worst per-cell frame step only moves between 3.5% and 4.3% of full scale — the scan + * band's own 2.7-3.1% dominates it either way, so the step buys nothing above about 0.3. What + * does change is the picture: at 0.6 and above a line of copy is visibly DOUBLED for most of the + * bob's travel, a bright row with a dim ghost of the next row under it (seed 99, camera frozen at + * frame 2990, frames 3247-3256, rendered and looked at). That is the failure the brief names — + * a holo that shimmers permanently is worse than one that pops rarely. At 0.30 the ghost is gone, + * the panel reads as the single clean row it always did, and the row change still arrives cell by + * cell at matched luminance instead of as a whole row swapping in one frame. */ + var HXF = 0.30; + + CC.ELEMENTS.push({ + name: 'holo', + layer: 33, + + init: function (city, rng) { + this.city = city; + HO.salt = (rng() * 2147483647) | 0; + }, + + update: function () {}, + + draw: function (frame, cam, t) { + var city = this.city; + if (!city || !city.aveX) return; + setCam(frame, cam); + airPrep(); + + /* Only the camera's own avenue and its immediate neighbours. An advert hung over an + * avenue two blocks away is behind thirty metres of building in a canyon this deep: it can + * never be seen, but it can still spend the per-frame budget. */ + var kn = Math.round(CO.ox / city.AVE), k0 = kn - 1, k1 = kn + 1; + var j0 = Math.floor((CO.oz - 30) / HZ), j1 = Math.floor((CO.oz + 105) / HZ); + var rows = CO.rows, cols = CO.cols, drawn = 0, k, j; + + for (k = k0; k <= k1; k++) { + var aw = city.aveW(k); + if (aw < 3) continue; // needs a canyon wide enough to hang in + var ax = city.aveX(k) + 0.5; + for (j = j0; j <= j1; j++) { + if (drawn > 1) return; // two panels in one frame is already a crowded sky + if (hk(k, j, HO.salt, 0) > 0.42) continue; + + var hx = ax + (hk(k, j, HO.salt, 1) - 0.5) * aw * 1.1; + var hz = j * HZ + hk(k, j, HO.salt, 2) * (HZ - 6); + var hy = 5.4 + hk(k, j, HO.salt, 3) * 4.6; // between the facades, not above them + var ph = hk(k, j, HO.salt, 4); + if (!CC.reducedMotion) hy += Math.sin(t * 0.33 + ph * 6.283) * 0.28; + + if (!project(hx, hy, hz)) continue; + var d = VP.dist; + /* Under ~18 m one advert is half the frame. Fading it out instead of popping it lets + * the viewer walk under it and watch it dissolve overhead, which is the nicer read + * anyway. */ + if (d < 17) continue; + var near = d < 34 ? clamp((d - 17) / 17, 0, 1) : 1; + /* A projection is made of the air it is projected into, so fog takes it faster than it + * takes a glass tube — but it is also the one object that gets a halo out of the murk + * rather than only losing to it. Exactly 1.0 at the preset the panel was tuned under. */ + near *= clamp(AT.dim * 0.92 + 0.08 * AT.halo, 0.42, 1.12); + /* AND THE FAR END, which the panel never had. 335 is the brightest value any cell of this + * shader can carry — the dropout keeps h2 at or under 0.50, so the copy tops out at + * 72 + 0.50*250 = 197, and the scan band multiplies that by at most 1.7 — so if that + * cannot clear the luminance floor after fog, no cell of this panel can, at any phase of + * its scan. Measured over eight seeds x 3000 frames at 400x100, that is exactly the + * 120 m+ band where the panel's brightest printed cell is already 0: nothing visible is + * being removed. What IS being removed is a panel that draws nothing and yet reaches + * `drawn` below, which is the same defect the k range at the top of this loop was + * narrowed to fix — an advert nobody can see spending the two-panel budget. */ + if (fog(335 * near, d) < 5) continue; + + var W = 3.4 + hk(k, j, HO.salt, 5) * 3.0; + var H = 2.2 + hk(k, j, HO.salt, 6) * 2.2; + var hw = colsFor(W * 0.5, VP.w); + var hh = H * 0.5 * CO.scale / VP.w; + if (hw < 0.8 || hh < 0.6) continue; + + /* The panel's own extent, kept UNCLAMPED — every index below is measured from it. + * Indexing off the clamped bounds instead welded the copy to the VIEWPORT: the moment a + * panel touched a frame edge, (x - xa) and (y - ya) jumped and the whole layout re-rolled + * frame by frame, and the edge stroke was drawn along the screen border instead of along + * the advert. That happens on every panel in the last seconds before the 17 m cull, + * which is exactly when it is biggest. */ + var pL = VP.x - hw, pT = VP.y - hh; + var xa0 = Math.floor(pL), xb0 = Math.ceil(VP.x + hw); + var ya0 = Math.floor(pT), yb0 = Math.ceil(VP.y + hh); + var xa = xa0 < 0 ? 0 : xa0, xb = xb0 > cols - 1 ? cols - 1 : xb0; + var ya = ya0 < 0 ? 0 : ya0, yb = yb0 > rows - 1 ? rows - 1 : yb0; + if (xb < xa || yb < ya) continue; + + /* The advert's own character grid, ~0.30 m a cell and fixed for the life of the panel + * because W and H are. Copy is laid out in THIS grid, never in screen cells, so walking + * towards a panel enlarges its lettering instead of re-rolling it — near, one grid cell + * covers the two or three screen cells that make a letter read as a letter. */ + var NC = Math.round(W / 0.30); if (NC < 4) NC = 4; + var NR = Math.round(H / 0.30); if (NR < 3) NR = 3; + + var hr = hk(k, j, HO.salt, 7); + /* Weighted hard toward the pillars. One advert is a hundred-odd cells, so a green or + * violet panel does not read as a garnish the way a green window does — it swings the + * whole frame's colour balance on its own. Azure leads, ice backs it, and the two + * accents are there to be caught once in a while and not to be expected. */ + var hue = hr < 0.54 ? P.azure : (hr < 0.86 ? P.ice : (hr < 0.94 ? P.violet : P.spring)); + /* The scan band is what sells it as projected rather than printed. Frozen under reduced + * motion, which leaves a static band — still legible as a screen, just not moving. + * 0.30 Hz, so the band itself is nowhere near the flash band; what mattered was its + * EDGE, see the profile below. */ + var sweep = CC.reducedMotion ? ph : (ph + t * 0.30) % 1; + var cover = 0; + + /* ---- the vertical resample, and the pop it exists to delete ------------------------ + * The panel bobs 0.28 m on a 19 s sine, so pT — and nothing else about the panel, since + * hy does not enter VP.w or VP.dist — creeps down the screen raster and back. Until this + * block the copy was point-sampled out of that creep: `ri = (gv * NR) | 0` picked ONE + * character row per screen row, and every time gv*NR crossed an integer the screen row + * swapped which row of the advert it was showing. The advert is 50% dropout by design and + * its rows are independent hashes, so that swap lands a lit cell on what was a hole and a + * hole on what was lit: measured by tools/flicker-rate.cjs part 2, up to 98.8% of full + * scale in one frame in clear air (52.5% in mist, which only damps it), at 0.20-0.25 + * crossings a second. Part 3 of the same tool deletes the bob line from the source and the + * worst step collapses to 1.6-3.1%, which is the scan band and nothing else — so the bob + * was the whole of it. It PASSES the tool, because 0.25 Hz is nowhere near the 3 Hz + * photosensitivity ceiling; it was the largest single-cell discontinuity in the build + * anyway, and no statistic in the repo could see it because it is one cell wide. + * + * Neither of the other two obvious fixes works. Quantising the bob to whole cells makes + * the teleport rarer and not smaller — it is still a full-scale step on every cell of the + * panel at once, which is worse. Dithering the crossing over several frames spreads it + * into exactly the high-frequency noise the whole file is built to avoid. What is left is + * to stop point-sampling: reconstruct each screen row from the TWO character rows it + * straddles, and CROSSFADE between them across a window HXF of a character row wide + * centred on the boundary the old code stepped over. The two weights sum to 1 everywhere, + * so the advert's integrated brightness is unchanged; outside the window one weight is + * exactly 1 and the cell prints exactly what it printed before; inside it the cell walks + * from one row's value to the other's instead of jumping. + * + * The travel rate is what makes a window that narrow enough: the bob's peak speed in + * character rows is 0.28*0.33 * NR/H, and NR = round(H/0.30) fixes NR/H at 3.33, so it is + * 0.31 character rows a second AT ANY DISTANCE — the scale and the depth cancel out of the + * expression entirely. A smoothstep of width HXF therefore moves a weight by at most + * 1.5*0.0051/HXF = 0.026 per frame at HXF 0.30, which on the brightest cell the shader can + * paint is under 3% of full scale. + * + * MEASURED ON THE WHOLE ELEMENT, by running tools/flicker-rate.cjs part 2 against this file + * and against a reconstruction of the point-sampled code it replaced — a reconstruction and + * not the historical file, which this tree keeps no history of, so it reverts exactly the + * four things described above and nothing else: point-sampled ri with the clamp, the row + * loop back inside ya..yb with no margin, the stroke pinned to `y === Math.floor(pT)`, and + * no lineOnly. Reverting the resample alone still measures 86-98% and reverting the stroke + * alone 44.7-80.4%, so those are two independent full-scale faults and not one fault seen + * twice — which is why both halves of this block have to stay. + * Over the tool's own four seeds and + * all six skies the worst per-cell frame step goes 45.9-98.0% -> 2.4-3.9%, and the rate + * that decides the verdict goes 0.100-0.350 big steps a second -> 0.000 in every sky. Both + * low ends are mist, which damps the panel and everything else; clear is the worst sky and + * the one to quote, 86.3-98.0% before. There is ONE exception to the after range, it is not + * this expression's, and it is written out below. Over + * a 24-seed sweep in clear air (3001 + 137k) it goes min 45.5 / median 89.0 / p90 98.8 / + * max 100.0% -> min 2.0 / median 3.9 / p90 3.9 / max 4.3%. Part 3's bob-deleted panel + * reads 2.0-3.1% under the same skies, so the moving panel now sits at the still panel's + * own floor, which is the definition of the bob no longer popping. The previous revision + * of this paragraph quoted "2.7-3.9% ... over four seeds and six skies", which is the + * range with seed 42 left out of it, and 51-98% for the old code where the reconstruction + * measures 86-98 — quote the outlier or the next reader believes a bound that does not + * hold. + * + * AND THE TRADE WAS CHECKED, because it is the one this fix could plausibly have made and + * NEITHER number the tool prints can see it: a crossfade that shimmered permanently would + * improve both the worst step and the over-34%/s rate while making the panel worse. So the + * per-cell 3-20 Hz band — part 1's statistic, Hann-windowed, applied to the fixture instead + * of to flick() — was measured over every painted cell, eight bearings, 20 s, in clear and + * in storm: worst cell 1.24-2.44% of full scale before against 0.24-0.41% after, and three + * cells over part 1's own 2% ceiling before (clear, seed 7) against none after. The mean + * absolute frame-to-frame change over painted cells FELL in the same runs, 0.071-0.126% -> + * 0.051-0.088%. The panel moves LESS on average, not more, so nothing was traded: the + * crossfade did not spread the pop into a shimmer, it removed it. + * + * THE ONE RESIDUAL, and it belongs to the print floor rather than to the resample: seed 42, + * yaw 0, t=3.033 s, cell (101,25) at 200x60 steps 42 -> 5 in a single frame, 14.5% of full + * scale (11.4-14.5% across the five non-mist skies, 3.1% in mist), on 1 seed in the 28 + * measured and at 0.000 big steps a second. Two panels overlap there: a near one at 48 m + * whose top stroke is crossfading onto an INTERLACED row at ew ~ 0.11, and a far one at + * 93 m directly behind it. The near stroke's whole value on a lineOnly row is 74*ew*near + * (band does not multiply a stroke), and the bob walks ew through the `lum < 5` floor + * further down this loop: at ew 0.1086 that is 8.89, which fogs to 4 and is dropped, and + * one frame later ew 0.1111 gives 9.09, which fogs to 5 and prints. On the frame it prints + * it takes the depth slot and hides a 42-lum copy cell of the panel behind. + * So the panel that MOVED changed by one unit and a different panel lost forty: a hard + * threshold plus an occlusion, which no amount of resampling touches. The fix for it is to + * make a hologram composite as light rather than as a surface — never darken a cell it + * lands on — and that is a change to how this element meets the entire world pass, with a + * real coverage risk against bright facades, so it is recorded here for whoever owns that + * decision instead of being slipped in under a bob fix. + * + * The GLYPH still switches, at the instant the two contributions cross, and that is + * deliberate: a glyph change at equal luminance is a shape change and not a luminance + * edge, which is the same licence the ticker's 2 Hz scroll runs on. + * + * The panel's top and bottom rows fall out of the same machinery for free. A character row + * outside 0..NR-1 simply contributes nothing, so the leading row fades in over the + * crossing instead of switching on — where the old code clamped ri and printed the edge + * row at full strength right up to the frame it vanished. */ + var NRi = NR / (2 * hh); // character rows per screen row; constant per panel + var pB = pT + 2 * hh; + var edged = hh > 1.2, laced = hh > 1.6; + /* One row of margin each side: the row just outside the old bounds is exactly the one the + * crossfades are fading in, and clipping it back to the old bounds would put the switch + * edge back at the panel's rim, which is where it is most visible. */ + var yLo = ya - 1; if (yLo < 0) yLo = 0; + var yHi = yb + 1; if (yHi > rows - 1) yHi = rows - 1; + var y, yc, ew, eT, eB, gv, band, gr, mA, mB, wA, wB, lwA, lwB, lwMax, lineOnly; + var x, gu, cb, val, best, gsel, h2, vv, lum; + + for (y = yLo; y <= yHi; y++) { + yc = y + 0.5; + /* The top and bottom strokes are the panel's only continuous lines and they used to be + * nailed to `y === Math.floor(pT)`, which is a cell index and therefore teleports a + * whole stroke one row every time the bob crosses a boundary — 74 of 255 arriving on one + * row and leaving another in a single frame. Spread over the two rows the stroke + * straddles, with weights that sum to 1, it slides instead. */ + ew = 0; + if (edged) { + eT = 1 - (yc > pT ? yc - pT : pT - yc); + eB = 1 - (yc > pB ? yc - pB : pB - yc); + ew = eT > eB ? eT : eB; + if (ew < 0) ew = 0; + } + /* Interlace, in SCREEN rows. A projection you cannot see the street through is a + * billboard, and a billboard hanging in the air with nothing holding it up looks like + * a bug. Screen rows and not panel rows: the missing lines are the display's, so they + * hold still while the panel drifts across them, and there is no rate at which the + * comb can beat against the panel's own grid. */ + if (ew <= 0 && (y & 1) === 1 && laced) continue; + /* AND AN INTERLACED ROW THAT IS ONLY IN THE FRAME BECAUSE THE STROKE REACHED IT CARRIES + * THE STROKE AND NOTHING ELSE. This one line is most of the 98.8% pop. The old code + * pinned the stroke to `y === Math.floor(pT)`, so a bob crossing flipped an odd row from + * skipped to drawn and an even row from stroke to copy — and copy is up to 322 against + * the stroke's 74, so a cell went from black to 247 in one frame (probed at seed 0, yaw + * 4.71, t=11.617, cell 58,23). Resampling the copy does not touch that: it is the row's + * ROLE changing, not its content. An odd row that only ever carries a stroke whose + * weight starts at zero can only ever fade in. */ + lineOnly = laced && (y & 1) === 1; + gv = (yc - pT) / (2 * hh); + /* The band's PROFILE, and it is a profile rather than a test for the same reason the + * neon starter is a crossfade rather than a threshold. `Math.abs(gv - sweep) < 0.14` + * put a hard edge on a smooth sweep: every cell the edge passed over jumped the full + * 0.7 of the boost in one frame, which on a bright panel cell is 225 of 255 — the + * largest single-frame change anywhere in this file, measured at 92% of full scale + * happening 0.95 times a second per panel, worse than the neon step that started this + * audit and hidden from every frame-level statistic because it is one cell wide. + * A plateau inside 0.10 falling to nothing by 0.20 keeps the same integrated boost + * (2*(0.10 + 0.10/2)*0.7 = 0.21 against the old 2*0.14*0.7 = 0.196, so the panel's + * exposure does not move) and the same tight bright line, at 6.6% of full scale a + * frame. The distance is measured the short way round the wrap: at 0.30 Hz the sweep + * crosses 1 back to 0 every 3.3 s, and a band that teleports from the bottom of the + * panel to the top is the same step edge in a different costume. */ + band = 1 + 0.7 * crest(gv - sweep, 0.10, 0.10); + /* The two character rows this screen row straddles. gr is the row centre measured in + * character rows with the half-row offset already taken out, so gr - mA - 0.5 is the + * signed distance to the boundary between them and the crossfade is centred there: at + * the character row's own centre one weight is 1 and the resample is a no-op, and only + * within HXF of the boundary do both rows contribute. A tap off either end of the copy + * is simply absent, which is what fades the panel's first and last row in and out. */ + gr = (yc - pT) * NRi - 0.5; + mA = Math.floor(gr); + mB = mA + 1; + wB = CC.smooth(clamp((gr - mA - 0.5) / HXF + 0.5, 0, 1)); + wA = 1 - wB; + if (mA < 0 || mA >= NR) wA = 0; + if (mB < 0 || mB >= NR) wB = 0; + if (lineOnly) { wA = 0; wB = 0; } + if (wA <= 0 && wB <= 0 && ew <= 0) continue; + /* Ragged right margin: each line stops somewhere different, which is what makes a + * block of dropout read as lines of copy instead of as noise. It is a property of the + * character row, so each tap carries its own and the scan runs to the longer of the + * two — a line whose neighbour is longer now fades out along its own end rather than + * being cut off at a hard column. */ + lwA = wA > 0 ? 0.42 + 0.58 * hk(mA, j * 31 + k, HO.salt, 8) : 0; + lwB = wB > 0 ? 0.42 + 0.58 * hk(mB, j * 31 + k, HO.salt, 8) : 0; + lwMax = ew > 0 ? 1 : (lwA > lwB ? lwA : lwB); + for (x = xa; x <= xb; x++) { + gu = (x + 0.5 - pL) / (2 * hw); + if (gu > lwMax) break; + cb = (gu * NC) | 0; + if (cb < 0) cb = 0; else if (cb >= NC) cb = NC - 1; + val = 0; best = 0; gsel = G_DASH; + if (wA > 0 && gu <= lwA) { + h2 = hk(cb + j * 13, mA + k * 7, HO.salt, 9); + if (h2 <= 0.50) { + vv = wA * (72 + h2 * 250); + val += vv; + if (vv > best) { best = vv; gsel = HOLO_G[((h2 * 1361) | 0) % HOLO_N]; } + } + } + if (wB > 0 && gu <= lwB) { + h2 = hk(cb + j * 13, mB + k * 7, HO.salt, 9); + if (h2 <= 0.50) { + vv = wB * (72 + h2 * 250); + val += vv; + if (vv > best) { best = vv; gsel = HOLO_G[((h2 * 1361) | 0) % HOLO_N]; } + } + } + val *= band; best *= band; + /* The top and bottom edges are the only continuous strokes on the panel. Without + * them the dropout above reads as glyphs scattered in mid-air rather than as an + * object with a boundary; with them it snaps into a rectangle immediately. Dashed, + * so the frame stays a hint. + * + * The stroke TAKES THE ROW OVER in proportion to ew rather than adding to it, and + * that is not cosmetic. At ew = 1 the row is exactly what it always was — dashes on + * the even character columns and nothing else — so the panel's brightness and cell + * count at rest are unchanged. Adding instead was measured and rejected: it made the + * two boundary rows carry copy AND stroke, and the extra light was enough to push a + * panel 114 m down the avenue over the lum floor for the first time. That panel then + * counted against `drawn`, and the two-panel budget it consumed belonged to a panel + * 23 m away — so a fixture nobody could see switched a big near advert on and off + * bodily, at seed 3, frames 1221/1341/1536. A crossfade cannot do that because at + * full weight it adds nothing. */ + if (ew > 0) { + val *= 1 - ew; best *= 1 - ew; + if ((cb & 1) === 0) { + vv = 74 * ew; + val += vv; + if (vv > best) { best = vv; gsel = G_DASH; } + } + } + if (val <= 0) continue; + lum = fog(val * near, d); + /* LANDING IS A DEPTH FACT, NOT A BRIGHTNESS ONE, and `drawn` below counts landings. + * Counting only cells that actually printed made the two-panel budget hinge on one + * cell of the panel clearing the luminance floor this frame, which for a panel in + * the 110-120 m band — where the brightest printed cell is 5 to 14 — is a coin the + * scan band tosses several times a second. Frozen camera, seed 3, frame 1217: a panel + * at 114 m flipped its landing every few frames and each flip handed or withdrew the + * budget of a 700-cell advert 23 m away, which switched that advert on and off + * bodily. `cover` records that a cell of this panel was in front of what the world + * pass had already put there, whether or not it was bright enough to print, so an + * occluded panel still costs nothing and a dim one stops blinking the budget. */ + if (lum < 5) { + if (!cover && d < frame.dist[y * cols + x]) cover = 1; + continue; + } + if (put(frame, x, y, gsel, hue, lum, d)) cover = 1; + } + } + drawn += cover; + } + } + } + }); + +})(typeof CC !== 'undefined' ? CC : require('../core.js')); diff --git a/src/elements/sky.js b/src/elements/sky.js new file mode 100644 index 0000000..184adcf --- /dev/null +++ b/src/elements/sky.js @@ -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')); diff --git a/src/elements/street.js b/src/elements/street.js new file mode 100644 index 0000000..937e0d3 --- /dev/null +++ b/src/elements/street.js @@ -0,0 +1,1423 @@ +/* CyberCity street life — the pavement layer: people, ground traffic across the intersections, + * a cat, food stalls, and the litter the wind pushes around. + * + * DESIGN NOTE, because it governs every draw call below: this batch is mostly SUBTRACTIVE. + * The reference frames are ~60% pure black and the road is already the darkest thing in them, so + * a person or a car drawn as a lit shape would be the brightest object on screen and would wreck + * the balance. Instead they are drawn as black cut-outs at their true depth — CC.put writes + * ch=0/lum=0 and stamps `dist`, which punches the shape out of the lit shopfront band behind it — + * and each one carries only a couple of genuinely lit cells: a rim of sodium on a head, a pair of + * headlamps, an eye-shine. That is how the references read, and it means the whole batch costs + * almost nothing against the black budget. + * + * Everything is world-anchored. Agents hold world (x,z) and a world velocity, so turning a corner + * leaves them behind on the street they belong to instead of dragging them round with the view. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, g = CC.g, hash2 = CC.hash2, clamp = CC.clamp, vnoise = CC.vnoise, put = CC.put; + + /* Resolved once — g() is a string lookup and these are hit thousands of times a frame. */ + var G_DOT = g('.'), G_COMMA = g(','), G_COLON = g(':'), G_SEMI = g(';'), G_QUOTE = g("'"), + G_TICK = g('`'), G_DASH = g('-'), G_UNDER = g('_'), G_EQ = g('='), G_PIPE = g('|'), + G_HASH = g('#'), G_8 = g('8'), G_0 = g('0'), G_X = g('X'), G_o = g('o'), G_M = g('M'), + G_W = g('W'), G_CARET = g('^'), G_STAR = g('*'); + + /* Blocky only. Anything with holes in it dithers instead of massing at this cell size. */ + var FILL = [G_8, G_0, G_HASH, G_M, G_W, G_X], FILL_N = FILL.length; + var PAPER = [G_QUOTE, G_TICK, G_COMMA, G_DOT, G_DASH, G_UNDER, G_COLON, G_SEMI], + PAPER_N = PAPER.length; + + /* ---- the weather, and the two ways of reading it --------------------------------------------- + * CC.Weather.P is a LIVE object — held, never copied, or an element ends up drawing last + * minute's sky. Two readings, and which one to use is not a matter of taste: + * + * wrel(k) the parameter divided by its value under the 'rain' preset, which is the preset + * this whole file was tuned under. A constant that already existed and already looked + * right is scaled by wrel(), so it reproduces its shipped value exactly and only + * moves when the weather does. Multiplying such a constant by the RAW parameter would + * silently re-tune it to 65% of what it was. + * wp().x the raw 0..1 direction, for behaviour that is NEW and has no shipped value to + * preserve — how far a downpour thins the pavement, how many umbrellas are up. + * + * The fallback block is the 'rain' preset itself, so a harness that never loaded the director + * renders the frame the director's reference preset would have produced. */ + var W_STILL = { rain: 0.65, wind: 0.55, fog: 0.30, wet: 0.90, storm: 0.12, haze: 0.40, + cloud: 0.75, steam: 0.85 }; + function wp() { return CC.Weather ? CC.Weather.P : W_STILL; } + function wrel(k) { return CC.Weather ? CC.Weather.rel(k) : 1; } + /* 0 on autopilot, easing to 1 while a human drives. Read, never written. */ + function ctrlBlend() { return CC.Control ? CC.Control.blend : 0; } + + /* ---- camera basis --------------------------------------------------------------------------- + * Duplicated from raycast.js rather than reached for, because elements are handed `cam` and + * nothing else. The projection MUST match the caster exactly or a pedestrian stands beside the + * kerb it is meant to be standing on: planar camera, so `w` is the forward-axis distance and the + * radial distance the depth test wants is w*sqrt(1+sp*sp). */ + var CX = 0, CZ = 0, FWX = 0, FWZ = 1, RGX = 1, RGZ = 0, HP = 0.7, EYE = 1.7; + var COLS = 0, ROWS = 0, HOR = 0, SCALE = 1, CPM = 1; + + function camBasis(cam) { + var yaw = cam.yaw || 0; + FWX = Math.sin(yaw); FWZ = Math.cos(yaw); + RGX = Math.cos(yaw); RGZ = -Math.sin(yaw); + CX = cam.x; CZ = cam.z; + HP = Math.tan((cam.fov || 1.25) * 0.5); + EYE = cam.eyeY !== undefined ? cam.eyeY : 1.7; + } + /* Split out from camScreen so that update(), which is handed a camera and no frame, can still ask + * the questions draw() asks — specifically how large a figure is about to print. A cull written + * against a screen-space budget has to compute that budget the same way the drawing code does or + * the two disagree at exactly the moment it matters. */ + function camScreenAt(cam, cols, rows) { + camBasis(cam); + COLS = cols; ROWS = rows; + HOR = cam.horizon !== undefined ? cam.horizon : ROWS * 0.56; + /* Once the horizontal fov and the cell aspect are fixed so is the vertical scale — same + * reconciliation the caster does. Reading cam.scale instead would tilt every element off the + * world by the ratio between the two. */ + SCALE = cam.scaleY !== undefined ? cam.scaleY + : (COLS * (cam.cellAspect || 0.5625)) / (2 * HP); + CPM = COLS * 0.5 / HP; // screen columns per metre of lateral offset, times 1/w + } + function camScreen(frame, cam) { camScreenAt(cam, frame.cols, frame.rows); } + + var PJ = { ok: 0, w: 0, sp: 0, x: 0, dist: 0 }; + /* Module scratch: the caller must read what it needs out of PJ before projecting anything else. + * The car body, which projects a nose and a tail, is the one place that matters. */ + function project(px, pz) { + var dx = px - CX, dz = pz - CZ; + var w = dx * FWX + dz * FWZ; + /* Behind the eye, or so close that sp explodes and the shape smears across the whole frame. */ + if (w < 0.45) { PJ.ok = 0; return PJ; } + var sp = (dx * RGX + dz * RGZ) / w; + PJ.ok = 1; PJ.w = w; PJ.sp = sp; + PJ.x = (sp / HP + 1) * COLS * 0.5 - 0.5; + PJ.dist = w * Math.sqrt(1 + sp * sp); + return PJ; + } + function rowOf(y, w) { return HOR - (y - EYE) * SCALE / w; } + + /* Depth of the TARMAC at a screen row. Anything drawn below an object's base — a pool of spill, + * a reflection — lies on road that is NEARER than the object casting it, so handing CC.put the + * object's own distance loses the depth test every time and the mark silently never appears. + * This was drawn wrong first and the stall spill and the car's tail reflection were both + * invisible; that is the reason this function exists. */ + function roadDist(row, sp) { + var den = row - HOR; + if (den < 0.5) return 1e6; + return (EYE * SCALE / den) * Math.sqrt(1 + sp * sp); + } + + /* The world pass has already fogged its own cells. Fogging here too keeps a figure at 50 m as + * dim as the wall it stands against; skipping it makes the far half of the street brighter than + * the buildings around it, which inverts the depth cue the whole palette rests on. */ + function fg(lum, dist) { + var S = CC.Surf; + return S ? S.fog(lum, dist) : lum; + } + + /* Depth ties LOSE in CC.put (it wants a strict improvement), and a figure's feet stand on tarmac + * at almost exactly the figure's own distance. Biasing an element a few centimetres toward the + * eye is what stops the bottom row of every silhouette dropping out. */ + function near(d) { return d * 0.994; } + /* A second bias step, for anything that sits on the FRONT FACE of a shape this file has already + * stamped at near(): a rim light on a silhouette, a headlamp on a car, a cat's eye. Without it + * the detail ties with its own body and CC.put throws it away — every element in this file was + * drawing its silhouette and losing all its lit cells, which is exactly as visible as drawing + * nothing at all. */ + function nearer(d) { return d * 0.982; } + + /* ---- which corridor the camera is standing in ----------------------------------------------- + * Mirrors raycast.configureFor. Avenues run along +z, cross streets along +x; standing in an + * intersection both are true, so the tiebreak is which way the camera is looking. Street life is + * laid out in corridor space (along, lateral) and only then converted to world, because "on the + * pavement" is a statement about the corridor, not about x or z. */ + var COR = { axis: 0, ctr: 0, half: 3.5, along: 0, dir: 1 }; + function corridor(city, cam) { + if (!city || !city.aveX) { // no city loaded: assume the harness's canyon + COR.axis = 0; COR.ctr = 0.5; COR.half = 3.5; + COR.along = cam.z; COR.dir = FWZ < 0 ? -1 : 1; + return COR; + } + var k = Math.round(cam.x / city.AVE), m = Math.round(cam.z / 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 = cam.x - 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 = cam.z - c; if (d < 0) d = -d; + if (d < bC) { bC = d; cC = c; cW = city.crossW(i) + 0.5; } + } + var afz = FWZ < 0 ? -FWZ : FWZ, afx = FWX < 0 ? -FWX : FWX; + if (bC <= cW && (bA > aW || afx > afz)) { + COR.axis = 1; COR.ctr = cC; COR.half = cW; COR.along = cam.x; COR.dir = FWX < 0 ? -1 : 1; + } else { + COR.axis = 0; COR.ctr = aC; COR.half = aW; COR.along = cam.z; COR.dir = FWZ < 0 ? -1 : 1; + } + return COR; + } + function worldX(a, l) { return COR.axis ? a : COR.ctr + l; } + function worldZ(a, l) { return COR.axis ? COR.ctr + l : a; } + + /* The kerb sits 1.4 m in off the building line (raycast.configureFor), so the pavement is that + * 1.4 m strip. A 3 m alley has no such strip, hence the floor at half the corridor width. */ + function kerbL() { + var p = COR.half - 1.4; + return p < COR.half * 0.5 ? COR.half * 0.5 : p; + } + + /* Vertical run of one shape in one column. rTop/rBot are float screen rows, top first. */ + function bar(f, x, rTop, rBot, ch, col, lum, dist) { + var r0 = Math.round(rTop), r1 = Math.round(rBot); + if (r1 < r0) r1 = r0; + if (r0 < 0) r0 = 0; + if (r1 > ROWS - 1) r1 = ROWS - 1; + for (var r = r0; r <= r1; r++) put(f, x, r, ch, col, lum, dist); + } + + /* ============================================================================================= + * FOOD STALLS — layer 18 + * The one genuinely emissive thing down here, so it is built the way the references build every + * lit surface: ONE massed horizontal slab (the counter) with dark above and below it, never a + * scatter of bright dots. Steam is the only part that moves. + * ============================================================================================ */ + /* Four slots, not two. A stall now spawns at 66–90 m instead of 16–58 (see update), so it spends + * the first half-minute of its life as a smudge in the fog and only the last twenty seconds as + * the massed slab it exists to be — and a route that jogs onto a parallel avenue kills it on the + * way in. With two slots the street went minutes at a time with no lit counter anywhere near it: + * measured over 50 s of walk, stall energy fell to a twentieth. Four put it back to 0.9x the old + * average on a straight run, and they are staggered far enough apart that the street is still a + * street that happens to have a stall on it rather than one lined with them. */ + var stalls = null, STALL_N = 4, PUFF_N = 5; + + CC.ELEMENTS.push({ + name: 'foodstalls', + layer: 18, + init: function (city, rng) { + this.city = city; + this.seed = (rng() * 2147483647) | 0; + stalls = new Array(STALL_N); + for (var i = 0; i < STALL_N; i++) + stalls[i] = { x: 0, z: 0, side: 1, n: i * 37 + 1, live: 0, hue: P.amber, + w: 1.8, tall: 2.2 }; + }, + /* Stalls are static furniture; update() only recycles the ones the walk has left behind. */ + update: function (dt, t, cam) { + camBasis(cam); + corridor(this.city, cam); + var S = this.seed, kl = kerbL(), i; + for (i = 0; i < STALL_N; i++) { + var s = stalls[i]; + if (s.live) { + var p = project(s.x, s.z); + /* The retirement range has to sit PAST the spawn range below, or a stall born at 80 m + * fails this test on its very next update and re-rolls itself every frame without ever + * being drawn. */ + var sl = COR.axis ? s.z - COR.ctr : s.x - COR.ctr; + if (sl < 0) sl = -sl; + /* Retired the moment the walk jogs onto a parallel avenue: the stall is then out in the + * middle of somebody else's block and can never come back into view, but the projection + * test alone keeps it alive for another twenty seconds while its slot — one of only four + * — sits dead. Freeing it immediately is what keeps a stall in the pipeline on a route + * that turns often. */ + if (p.ok && p.w < 96 && p.sp < HP * 2.4 && p.sp > -HP * 2.4 && sl < COR.half + 3) continue; + s.live = 0; + } + s.n++; + var h1 = hash2(i, s.n, S), h2 = hash2(i, s.n, S ^ 0x5A1), h3 = hash2(i, s.n, S ^ 0x9B); + /* Spawned at 66–90 m, which is BEYOND the far end of the draw below, so a stall is never + * seen arriving. It used to spawn at 16–58 m: at 16 m a lit amber counter is thirteen + * columns of lum 186 and it simply materialised in the middle of the frame. Now the fog + * hands it over — 34 lum and a column and a half at 90 m — and the walk takes half a + * minute to bring it up to the massed slab it exists to be. */ + var a = COR.along + COR.dir * (66 + h1 * 24); + s.side = h2 < 0.5 ? -1 : 1; + var l = s.side * (kl + 0.25 + h3 * 0.55); + s.x = worldX(a, l); s.z = worldZ(a, l); + s.w = 1.5 + h1 * 1.3; + s.tall = 2.05 + h2 * 0.45; + /* Amber strip light or a warm fry counter, and nothing else — a stall in an accent colour + * reads as signage rather than as food. */ + s.hue = h3 < 0.55 ? P.amber : P.warm; + s.live = 1; + } + }, + draw: function (frame, cam, t) { + camScreen(frame, cam); + var S = this.seed, i, j, x; + for (i = 0; i < STALL_N; i++) { + var s = stalls[i]; + if (!s.live) continue; + var p = project(s.x, s.z); + /* Drawn all the way out past the spawn range so the reveal belongs to the fog and not to + * this cull: a hard cut-off anywhere inside the spawn range is just the pop again, moved. */ + if (!p.ok || p.dist > 96) continue; + /* Copied out of PJ before anything else projects — it is one shared scratch record. */ + var w = p.w, cx = p.x, dist = p.dist, sp = p.sp, d = near(dist); + var hw = s.w * 0.5 * CPM / w; // half width, in screen columns + if (hw < 0.5) hw = 0.5; + var x0 = Math.round(cx - hw), x1 = Math.round(cx + hw); + if (x1 < 0 || x0 > COLS - 1) continue; + + /* rowOf climbs the screen as y climbs, so every pair below is (top, bottom). */ + var rGnd = rowOf(0, w); + var rCtT = rowOf(1.36, w), rCtB = rowOf(0.98, w); + var rTop = rowOf(s.tall, w), rEave = rowOf(s.tall - 0.28, w); + var lit = fg(196 + hash2(i, s.n, S ^ 0x3) * 46, dist); + var dim = fg(30, dist); + + /* Columns per metre ACROSS this stall at its own depth. The texture below is hashed on a + * world offset from the stall's centre, not on the screen column: hashing on x welded the + * canopy dashes, the counter fill, the lum jitter and the trestle legs to the VIEWPORT, so + * the whole surface re-rolled as the stall slid across the frame — a stall that swims is + * the loudest thing on a quiet street. One third of a metre per bin, which is a plank at + * arm's length and about a column at the far end of the draw. */ + var cpm = CPM / w; + for (x = x0; x <= x1; x++) { + if (x < 0 || x > COLS - 1) continue; + var hx = hash2(Math.floor((x - cx) / cpm * 3), s.n, S ^ 0x71); + /* Canopy drawn as a dark slab with only a thin lit underside. The dark half is what + * keeps the counter reading as a slot of light and not a bar floating in the air. */ + bar(frame, x, rTop, rEave, hx < 0.55 ? G_EQ : 0, P.shadow, hx < 0.55 ? dim * 0.6 : 0, d); + bar(frame, x, rEave + 1, rCtT - 1, 0, P.shadow, 0, d); // shadowed interior + bar(frame, x, rCtT, rCtB, FILL[(hx * FILL_N) | 0], s.hue, lit * (0.82 + hx * 0.30), d); + bar(frame, x, rCtB + 1, rGnd, hx < 0.30 ? G_PIPE : 0, P.shadow, + hx < 0.30 ? dim * 0.5 : 0, d); // trestle legs + } + /* The burner: one ember cell in the dark above the counter. It is the only accent colour + * this element is allowed and it is deliberately a single cell. */ + if (dist < 40) { + var bl = fg(150, dist); + if (bl >= 5) + put(frame, Math.round(cx + (hash2(i, s.n, S ^ 0xE) - 0.5) * hw), + Math.round(rCtT - 1), G_o, P.ember, bl, nearer(dist)); + } + /* Spill on the wet tarmac in front. Smeared ALONG the view, one column per row, because a + * reflection on a road streaks toward the eye — that vertical drag is the whole reason a + * street reads as wet. Dimmed hard: it must stay a fraction of the counter above it. + * Its LENGTH now follows the road: wrel('wet') is 1.0 under the preset this was tuned as, + * so a rainy street keeps exactly the four rows it always had and a dry one gets two. */ + if (dist < 40) { + var wetS = wrel('wet'); + var spn = 2 + ((wetS * 2.2) | 0); if (spn > 5) spn = 5; + var rp0 = Math.round(rGnd) + 1; + for (j = 0; j < spn; j++) { + var rr = rp0 + j, rd = roadDist(rr, sp); + var sl = fg(58 * (1 - j * 0.22) * (0.55 + 0.45 * wetS), rd); + if (sl < 5) continue; + put(frame, Math.round(cx - s.side * (j * 0.6)), rr, + j < 2 ? G_COLON : G_QUOTE, s.hue, sl, near(rd)); + } + } + + /* Steam. Derived from t and a fixed per-puff phase rather than integrated, so scrubbing + * time lands on the same frame every time and there is no state to drift. */ + var rate = CC.reducedMotion ? 0.05 : 0.42; + for (j = 0; j < PUFF_N; j++) { + var ph = hash2(j, s.n, S ^ 0xC0FE); + var age = (t * rate + ph) % 1; + /* Wind pushes the plume sideways as it rises, keyed on the stall's own seed so two + * stalls never breathe in step. */ + var drift = (vnoise(t * 0.5 + ph * 20, S ^ 0x1D) - 0.5) * age * 2.6; + var fade = (1 - age) * (1 - age); + var sl2 = fg(50 * fade, dist); + if (sl2 < 6) continue; + /* ONE cell per puff. A dense plume is a grey veil, which is the single failure this + * whole art direction exists to prevent. */ + put(frame, Math.round(cx + drift * CPM / w * 0.6), + Math.round(rowOf(s.tall + 0.15 + age * 3.4, w)), + age < 0.35 ? G_QUOTE : G_TICK, P.slate, sl2, near(dist)); + } + } + } + }); + + /* ============================================================================================= + * PEDESTRIANS — layer 20 + * + * A walker is still a black cut-out with a lit top edge, because that is the only thing that + * reads against a black road. What is new is that the cut-out has a SHAPE. Every figure draws an + * ARCHETYPE at spawn and the archetype is spent on the SILHOUETTE, not on colour: most of this + * crowd stands between six and twenty rows tall, where a coat's COLOUR is one cell and a coat's + * HEM is four. So a long coat widens toward the ankle, a hood peaks where a face would be, a + * courier's pack breaks one shoulder square, a brim runs wider than the head, a skirt narrows to + * two legs, and an umbrella puts an arc over the lot. Each archetype also carries its own stride + * frequency, bob and pace — a costume without its own walk is a sticker, and fourteen identical + * gaits was exactly the tell. + * + * The body stays NEAR-BLACK. The lit cells on a figure are the rim (sodium off the lamp + * standards, azure where the frontage behind them is screenlight), the phone, and AT MOST ONE + * accent — LED piping down a technical shell, a courier's reflective strip, a cigarette, a lit + * takeaway bag. Roughly one figure in six carries an accent at all. Two coloured things on one + * silhouette and it stops being a person in the dark. + * ============================================================================================ */ + + /* The costume table. Built once at load and held BY REFERENCE on each walker, so an archetype + * costs no per-frame lookup and no allocation. Every measurement below is in "shoulder + * half-widths" across and in body fractions down, 0 at the crown and 1 at the sole, so a costume + * is the same shape at 3 m and at 60 m. + * w relative spawn weight + * hem how far the hem flares past the shoulder line + * hemTop where that flare starts and where it ends — a coat reaches the ankle, a skirt the knee + * hemBot + * legTop below this the silhouette narrows to legW: a narrow base, which is what reads as a + * skirt and heels rather than as trousers + * legW half-width of the legs + * brim a hat brim, wider than the shoulders, sitting just under the crown + * pack a square courier pack, ONE side only + * bag a shoulder bag or a case, one side, at hip height + * hood the crown reads as a peak and carries no face + * umb may own an umbrella — a pack or a hood is already this figure's answer to rain + * tallB metres of extra height + * stride stride frequency multiplier + * bob head bob amplitude, metres + * spd walking pace multiplier + * accP chance this archetype carries its accent at all + * acc 1 LED piping 2 reflective strip 3 cigarette 4 something carried and lit + */ + var ARCH = [ + { name: 'plain', w: 0.17, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, tallB: 0.00, + stride: 1.00, bob: 0.035, spd: 1.00, accP: 0.06, acc: 3 }, + { name: 'coat', w: 0.17, hem: 0.70, hemTop: 0.46, hemBot: 0.97, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, tallB: 0.00, + stride: 0.86, bob: 0.028, spd: 0.96, accP: 0.10, acc: 3 }, + { name: 'hood', w: 0.15, hem: 0.26, hemTop: 0.58, hemBot: 0.92, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.00, bag: 0.00, hood: 1, umb: 0, tallB: 0.00, + stride: 0.96, bob: 0.024, spd: 1.08, accP: 0.14, acc: 1 }, + { name: 'skirt', w: 0.12, hem: 0.34, hemTop: 0.50, hemBot: 0.76, legTop: 0.76, legW: 0.19, + brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, tallB: 0.00, + stride: 1.24, bob: 0.052, spd: 1.02, accP: 0.10, acc: 4 }, + { name: 'courier', w: 0.10, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.55, bag: 0.00, hood: 0, umb: 0, tallB: 0.00, + stride: 1.14, bob: 0.030, spd: 1.30, accP: 0.34, acc: 2 }, + /* The one figure allowed a narrow accent down its own seam, and it is 6% of the crowd. */ + { name: 'shell', w: 0.06, hem: 0.16, hemTop: 0.55, hemBot: 0.95, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, tallB: 0.14, + stride: 0.98, bob: 0.032, spd: 1.04, accP: 0.78, acc: 1 }, + { name: 'hat', w: 0.09, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, + brim: 0.55, pack: 0.00, bag: 0.00, hood: 0, umb: 1, tallB: 0.00, + stride: 0.92, bob: 0.026, spd: 0.94, accP: 0.06, acc: 3 }, + { name: 'bagger', w: 0.14, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, + brim: 0.00, pack: 0.00, bag: 0.60, hood: 0, umb: 1, tallB: 0.00, + stride: 1.00, bob: 0.034, spd: 0.97, accP: 0.18, acc: 4 } + ]; + var ARCH_TOT = 0; + (function () { + /* `ext` is how far past the shoulder line this costume can possibly reach, so the column loop + * knows where to stop without testing every accessory on every column of every figure. */ + for (var i = 0; i < ARCH.length; i++) { + var A = ARCH[i], e = A.hem; + if (A.brim > e) e = A.brim; + if (A.pack > e) e = A.pack; + if (A.bag > e) e = A.bag; + A.ext = e; + ARCH_TOT += A.w; A.acc0 = ARCH_TOT; + } + })(); + function archPick(h) { + var r = h * ARCH_TOT, i; + for (i = 0; i < ARCH.length - 1; i++) if (r < ARCH[i].acc0) return ARCH[i]; + return ARCH[ARCH.length - 1]; + } + + /* The pool is allocated at the maximum and only a PREFIX of it is ever live, the same shape the + * rain uses, and for the same reason: a crowd is measured against the frame it is drawn in. A + * 400x100 window is three and a third times the cells of the reference 200x60 and shows a walker + * at three times the detail, so a world-fixed population that reads as a crowd there reads as a + * scatter. NOT linear in cells, though — unlike a rain streak, a figure's screen FOOTPRINT is + * already a fixed fraction of the frame at any grid size, so scaling linearly would multiply the + * cut-out area by the same factor as the count and black the picture out. The square root adds + * people without adding that much occlusion. */ + var peds = null, PED_MAX = 52, PED_AT_REF = 20, REF_CELLS = 200 * 60; + + function pedWant(cells) { + var n = PED_AT_REF * Math.sqrt(cells / REF_CELLS); + /* Rain empties a pavement. NEW behaviour, so it reads the raw 0..1 direction rather than + * wrel(): there is no shipped value here to preserve, and rain=1 meaning "downpour" is exactly + * what the number is for. Three in five stay out in the worst of it, and disproportionately + * many of those are the ones who own an umbrella. */ + n *= 1 - 0.38 * wp().rain; + n = n | 0; + return n > PED_MAX ? PED_MAX : (n < 4 ? 4 : n); + } + + /* ---- how much of the frame one walker blacks out ------------------------------------------- + * THE NUMBER THIS FILE'S WORST TRANSIENT IS MEASURED IN, so it is computed here once and used + * both by the draw (which builds the box) and by the retirement in update() (which decides the + * box is too big). Two different formulas for the same box is how the cull came to let through + * exactly the case it existed to catch. + * + * A pedestrian is a BLACK CUT-OUT — see the design note at the top — so its area is not a matter + * of taste, it is the whole-frame luminance it removes. Every other visual property of a figure + * can be eased; this one cannot, because there is no such thing as a half-drawn hole. */ + function pedShoulder(w) { + var shw = 0.24 * CPM / w; // half a SHOULDER width, in columns + return shw < 0.45 ? 0.45 : shw; + } + function pedCover(p, pr) { + var xw = pedShoulder(pr.w) * (1 + p.A.ext); + /* Clipped to the frame, deliberately: a figure that is half off the left edge blacks out half + * as much picture, and it is the picture that this budget is about. That clip is also what + * lets somebody walk right past your shoulder — the case that reads best — while stopping + * somebody walking into your face. */ + var x0 = pr.x - xw, x1 = pr.x + xw; + if (x0 < 0) x0 = 0; + if (x1 > COLS - 1) x1 = COLS - 1; + if (x1 <= x0) return 0; + var rr = (p.tall + p.A.tallB) * SCALE / pr.w; // head to feet, in screen rows + if (rr > ROWS) rr = ROWS; + return (x1 - x0) * rr / (COLS * ROWS); + } + /* THE BUDGET, and the one number in this file that is a safety limit rather than a look. + * + * The projection has a singularity at the eye and the near cull in project() sits right on top of + * it: a walker at 0.46 m is 585 rows tall and 250 columns wide, i.e. a black slab over the whole + * frame, and the next tick deletes it. Measured over seeds 3/7/42/99 x 300 s at 400x100 that + * happened ten times, and the worst of them moved the whole frame's mean printed luminance by + * 8.0% of full scale in one 16 ms frame with 32% of the cells changing by more than a tenth — + * far and away the largest luminance step the piece can produce, and invisible to both safety + * tools because neither of them looks at area. + * + * Retiring on a screen-area budget rather than on a distance is what makes this correct at every + * grid size and every fov, and it is also kinder than a distance would be: a slim figure and one + * clipped by the frame edge may both come far closer than a coat walking straight at you, which + * is the case that has to go. 3.5% of the frame is the largest cut-out the rest of the build + * already produces routinely at the LATERAL cull, so nothing here introduces a transient the + * piece did not already have — it only stops the ones an order of magnitude past it. */ + var PED_COVER_MAX = 0.035; + + /* How busy the frontage is at a spot on the pavement, and what colour it throws. The city + * already knows both: a lot with a sign on it and a high litRate is a shopfront parade, a + * concrete lot with neither is a dead wall. Asking it is the difference between a crowd that + * stands outside the shops and a sprinkle spread evenly along a street that is not even. + * Returns roughly 0.34 (blank wall) .. 2.0 (a lit parade under signage). */ + var FF_HUE = 0; + function footfall(city, a, l) { + FF_HUE = P.amber; + if (!city || !city.cell) return 1; + /* Sampled 2.2 m PAST the walker, i.e. inside the frontage. The pavement itself is street and + * carries no building record, so sampling where the figure stands always returns null. */ + var ll = l + (l < 0 ? -2.2 : 2.2); + var c = city.cell(worldX(a, ll), worldZ(a, ll)); + if (!c) return 0.62; // a gap in the frontage — an alley mouth or a plaza, not a parade + FF_HUE = c.hue; + return 0.34 + c.litRate * 2.4 + (c.sign ? 0.55 : 0); + } + + function pedSpawn(p, i, S, fresh, city) { + p.n++; + var n = p.n; + /* One independent draw per decision. Sharing a hash between two of them welds them together, + * and the shipped version of this function did exactly that twice: reusing the crossing draw + * for the rim colour made every crosser amber. Additive offsets, never XOR — the house rule + * for seeding hash2. */ + var h1 = hash2(i, n, S + 101), h2 = hash2(i, n, S + 211), h3 = hash2(i, n, S + 307), + h4 = hash2(i, n, S + 401), h5 = hash2(i, n, S + 503), h6 = hash2(i, n, S + 601), + h7 = hash2(i, n, S + 701), h8 = hash2(i, n, S + 809), h9 = hash2(i, n, S + 907), + h10 = hash2(i, n, S + 1013), h11 = hash2(i, n, S + 1117), h12 = hash2(i, n, S + 1223), + h13 = hash2(i, n, S + 1301), h14 = hash2(i, n, S + 1409); + var rain = wp().rain; + var kl = kerbL(), band = COR.half - kl - 0.6; + if (band < 0.2) band = 0.2; + var side = h2 < 0.5 ? -1 : 1; + var A = archPick(h4); + var a, l, ki; + + /* WHERE. Three candidate spots down the street, and the busiest frontage wins. */ + var l0 = side * (kl + 0.2 + h3 * band); + var bestA = COR.along + COR.dir * 58, bestF = -1, bestH = P.amber; + for (ki = 0; ki < 3; ki++) { + var hk = hash2(i, n * 4 + ki, S + 1361); + /* The first fill spreads over the whole visible street; every later respawn arrives from + * BEYOND the draw cull below, so a walker is always handed to the frame by the fog at two + * rows and thirty lum rather than switching on at full contrast in the middle of it. */ + var ak = COR.along + COR.dir * (fresh ? 5 + hk * 42 : 52 + hk * 16); + var ff = footfall(city, ak, l0); + if (ff > bestF) { bestF = ff; bestA = ak; bestH = FF_HUE; } + } + /* And if even the best of the three has nothing worth walking past, this slot sits the next + * second or two out and asks again. That is what actually thins the pavement on a dead block — + * picking the best spot alone only slides the same crowd along it. The first fill is exempt, + * or the street starts empty and takes half a minute to populate. */ + /* The wait deliberately shares h6 with the threshold. Given that the test failed, h6 is + * conditioned HIGH — the fussier the draw, the emptier the frontage it just turned down — so + * a genuinely dead block keeps its slot idle for longer than a marginal one does, for free. */ + if (!fresh && bestF < 0.55 + h6 * 0.80) { + p.live = 0; p.wait = 0.5 + h6 * 2.4; + return; + } + + var sp = (0.95 + h1 * 0.55) * A.spd; + /* Nobody strolls in a downpour, and nobody sprints in one either at this camera distance — + * they shorten up and get on with it. The hunch below is the visible half of the same fact. */ + sp *= 1 - 0.16 * rain; + p.shelter = 0; + /* How many of them are standing still under something. It grows with the rain because that is + * what rain does to a pavement, but it is capped low on purpose: a sheltering figure has no + * velocity, so it is one that will never walk into the near field, and a share much past a + * quarter empties the foreground and stacks the whole crowd at one depth. */ + var shP = 0.05 + 0.22 * rain; + if (h7 < 0.28) { + /* A quarter of them cross the carriageway. On a 13 m boulevard the pavements sit at the very + * edge of a 92-degree view and a figure standing on one is out of frame until it is 8 m + * away, so without crossers the middle of the street — most of the lower frame — never has + * anybody in it at all. + * A crosser has to start near enough to still be crossing when it matters, so it cannot be + * hidden by distance the way the pavement walkers are. It is hidden by the BUILDING instead: + * 1.2 m in behind the frontage, where the facade the raycaster already painted wins the + * depth test, so the figure walks out from the wall rather than appearing in the road. */ + p.cross = 1; p.goSide = side; + a = COR.along + COR.dir * (fresh ? 7 + h1 * 22 : 15 + h1 * 17); + l = -side * (COR.half + 1.2); + p.vx = COR.axis ? 0 : side * sp; + p.vz = COR.axis ? side * sp : 0; + } else if (h7 < 0.28 + shP) { + /* SHELTERING. Rain does not only thin a pavement, it moves the people who are still on it + * off the middle of it and under whatever roof is nearest — which is why this share grows + * with the rain rather than being a fixed quirk. A sheltering figure has no velocity at all: + * the walk brings the camera to it, exactly the way it brings the camera to a stall. */ + p.cross = 0; p.shelter = 1; + p.vx = 0; p.vz = 0; + a = bestA; l = side * (COR.half - 0.5); + /* Only about half of them go to a stall, and never more than a couple of metres either side + * of it. With every shelterer homing on the nearest live counter the whole group landed + * inside one 3.6 m span at one depth — twelve people shoulder to shoulder reads as a wall, + * not as a queue. The rest hold up whatever frontage they happen to be beside. */ + var sst = h13 < 0.5 && stalls ? stalls[(h13 * 2 * STALL_N) | 0] : null; + if (sst && sst.live) { + /* Better still, under the stall's own canopy. It is the one lit roof on the street, so it + * is both where anybody waiting out a downpour would actually stand and the one place on + * the pavement where a black cut-out has something bright to stand against. */ + var sa = COR.axis ? sst.x : sst.z; + var sl = (COR.axis ? sst.z : sst.x) - COR.ctr; + a = sa + (h1 - 0.5) * 3.6; + l = sl + (sl < 0 ? 0.95 : -0.95); + side = sl < 0 ? -1 : 1; + } + } else { + /* With the camera and against it, but weighted to the oncoming ones: they are what make the + * street feel used rather than swept, and they are also the only half that ever arrives — + * a walker going YOUR way at 1.2 m/s in front of a 1.6 m/s walk closes at 0.4 m/s and + * spends its whole life two rows tall at the far end of the street. */ + p.cross = 0; + a = bestA; l = l0; + var go = (h5 < 0.62 ? -1 : 1) * COR.dir; + p.vx = COR.axis ? go * sp : 0; + p.vz = COR.axis ? 0 : go * sp; + } + p.x = worldX(a, l); p.z = worldZ(a, l); + p.dodge = 0; p.dx = 0; p.dz = 0; + p.A = A; + p.tall = 1.62 + h11 * 0.22; + p.walked = 0; + p.phase = h3 * 6.283; + /* Which shoulder the nearest lamp is over. Rimming both sides makes a figure read as a + * cardboard cut-out lit from the front, which is the one thing it must not look like. For a + * sheltering figure the counter beside it IS the lamp, so the lit shoulder is the outboard + * one whatever the hash says. */ + p.side = p.shelter ? (l < 0 ? -1 : 1) : (h14 < 0.5 ? -1 : 1); + /* Rim colour follows the frontage this figure is walking past rather than a coin toss: a + * screen block throws azure onto whoever is in front of it and a sodium one throws amber, + * which is the same two-pillar rule the facades themselves obey. One in five breaks it, + * because a street has more light in it than the wall behind you. */ + var scr = bestH === P.azure; + p.rim = (h10 < 0.80 ? scr : !scr) ? P.azure : P.amber; + /* Umbrellas. Owning one is not the same as having it up — see the easing in update(). */ + p.umbOwn = A.umb && h9 < 0.62 ? 1 : 0; + p.uRate = 0.20 + h1 * 0.26; // seconds-scale, and different for every figure + /* A phone is a screen, which is the one thing violet is licensed for. Conditional on the gate, + * h12/0.18 is itself uniform on 0..1 and independent of it, so the colour needs no extra + * draw — the same trick pays for the accent below. */ + if (h12 < 0.18) { + var q = h12 / 0.18; + p.phone = q < 0.70 ? P.azure : (q < 0.88 ? P.ice : P.violet); + } else p.phone = -1; + /* THE ONE ACCENT, and only about one figure in six has one. */ + if (h8 < A.accP) { + var qa = h8 / A.accP; + p.acc = A.acc; + /* Piping leans violet rather than spring, and that is a PRINT decision, not a taste one: + * core.js gives spring an exposure weight of 1.55 against violet's 0.70, so the same lum + * prints spring more than twice as hot and a green seam was reading as the brightest thing + * on the pavement. */ + p.accHue = A.acc === 1 ? (qa < 0.34 ? P.spring : P.violet) + : A.acc === 2 ? P.ice + : A.acc === 3 ? P.ember + : (qa < 0.60 ? P.warm : P.amber); + } else { p.acc = 0; p.accHue = P.amber; } + p.live = 1; + } + + CC.ELEMENTS.push({ + name: 'pedestrians', + layer: 20, + init: function (city, rng, dims) { + this.city = city; + /* Small seed and additive offsets, per the house rule for hash2 — and the draw is still one + * rng() call, so no downstream element's stream moves. */ + this.seed = (rng() * 30011) | 0; + this.boot = 0; + this.cols = dims && dims.cols ? dims.cols : 200; + this.rows = dims && dims.rows ? dims.rows : 60; + this.cells = this.cols * this.rows; + peds = new Array(PED_MAX); + for (var i = 0; i < PED_MAX; i++) + peds[i] = { x: 0, z: 0, vx: 0, vz: 0, dx: 0, dz: 0, dodge: 0, n: i * 91, tall: 1.7, + phase: 0, cross: 0, goSide: 1, shelter: 0, side: 1, rim: P.amber, phone: -1, + acc: 0, accHue: P.amber, walked: 0, live: 0, wait: 0, + umbOwn: 0, umb: 0, uRate: 0.3, hunch: 0, A: ARCH[0] }; + }, + update: function (dt, t, cam) { + /* The full screen basis, not just camBasis, because the retirement below is written in screen + * area. The dimensions are last frame's — one frame of lag on a window resize, which is a + * frame in which nothing has moved anyway. */ + camScreenAt(cam, this.cols, this.rows); + corridor(this.city, cam); + var S = this.seed, city = this.city, i, p; + /* Deferred to the first update because init() has no camera and therefore no corridor. */ + if (!this.boot) { + this.boot = 1; + for (i = 0; i < PED_MAX; i++) pedSpawn(peds[i], i, S, 1, city); + } + var k = CC.reducedMotion ? 0.10 : 1; + var eK = CC.reducedMotion ? 0.35 : 1; + var want = pedWant(this.cells); + var rain = wp().rain, cb = ctrlBlend(); + var latX = COR.axis ? 0 : 1, latZ = COR.axis ? 1 : 0; + for (i = 0; i < PED_MAX; i++) { + p = peds[i]; + if (i >= want) { + /* The rain coming on trims the tail of the pool. Staggering the wait is what stops the + * whole tail walking back on in one block when it eases off again. */ + if (p.live) { p.live = 0; p.wait = 0.4 + (i % 7) * 0.35; } + continue; + } + if (!p.live) { + /* NOT damped by k, unlike the car and the cat below, and the difference is the rule: + * damp a timer by whatever damps the thing it feeds. What retires a walker is the CAMERA + * overtaking it, and the camera's speed is not this element's to slow — damping the + * refill too would empty the pavement for a reduced-motion viewer and leave it empty. */ + p.wait -= dt; + if (p.wait <= 0) pedSpawn(p, i, S, 0, city); + continue; + } + p.x += p.vx * dt * k; p.z += p.vz * dt * k; + p.walked += (p.vx === 0 ? (p.vz < 0 ? -p.vz : p.vz) : (p.vx < 0 ? -p.vx : p.vx)) * dt * k; + + /* Hunch and umbrella are EASED, never switched. An umbrella that appeared on the frame the + * rain crossed a threshold would be the loudest cut in the piece; over three or four + * seconds, every figure on its own rate, it reads as a street putting them up one at a + * time as the front arrives. Reduced motion slows the transition rather than freezing it, + * because a half-open umbrella frozen forever is worse than a slow one. */ + p.hunch += (rain - p.hunch) * Math.min(1, dt * 0.55 * eK); + var uT = (p.umbOwn && rain > 0.22) ? 1 : 0; + p.umb += (uT - p.umb) * Math.min(1, dt * p.uRate * eK); + if (p.umb < 0.002) p.umb = 0; + + var pr = project(p.x + p.dx, p.z + p.dz); + /* Somebody is driving, so the nearest walkers give way. Half a metre, eased in over about + * a second, only inside 7 m and only near the middle of the view — and stepping toward the + * kerb they are already nearest, which is what a person does and also what keeps this + * independent of which way the frame happens to be facing. Any more than this and the + * crowd is visibly reacting to the camera, which turns an ambient piece into a video game. + * On autopilot CC.Control.blend is 0 and none of it happens at all. */ + var dodgeT = 0; + if (cb > 0.02 && pr.ok && pr.w < 9) { + /* The test is in METRES across the camera's own path, not in screen columns. Screen + * offset was the first cut and it never fired once: sp is an angle, so at 7 m a walker + * standing a metre off the line of travel is already a third of the way to the frame + * edge and failed a "near the middle of the view" test that a 60-degree lens made + * meaningless. Multiplying by w turns it back into the question actually being asked — + * is this person about to be walked into. */ + var off = pr.sp * pr.w; + if (off < 1.3 && off > -1.3) { + var lat = COR.axis ? p.z - COR.ctr : p.x - COR.ctr; + dodgeT = (lat < 0 ? -1 : 1) * 0.55 * cb; + } + } + p.dodge += (dodgeT - p.dodge) * Math.min(1, dt * 1.5); + p.dx = latX * p.dodge; p.dz = latZ * p.dodge; + + /* The lateral cull is generous (1.8 half-fovs) so somebody stepping out of frame at the + * edge is not instantly teleported to the horizon in front of your eyes. The far cull sits + * past the 68 m respawn, or a recycled walker is retired on the same tick it is created. */ + var gone = !pr.ok || pr.w > 74 || pr.sp > HP * 1.8 || pr.sp < -HP * 1.8; + /* THE NEAR RETIREMENT, and it runs a long way ahead of project()'s w<0.45 near cull on + * purpose — see PED_COVER_MAX. That cull is still there and still correct as a guard on the + * arithmetic, but it must never be the thing that actually retires a walker: by the time a + * figure reaches it, it is a black slab over the whole frame and deleting it is the biggest + * luminance step the piece can produce. Retiring on the AREA the cut-out would black out + * instead means the figure is small when it goes, which is the only way a hole can leave + * quietly — a cut-out cannot be faded down, because it has no brightness to fade. */ + if (!gone && pedCover(p, pr) > PED_COVER_MAX) gone = 1; + /* A crosser reaches the far pavement without ever leaving the frustum, so it needs its + * own retirement test or it walks on through the buildings forever. + * + * SIGNED, against the direction it set out in, and that is a bug fix rather than a tidy-up. + * The shipped test took the ABSOLUTE lateral offset, and a crosser is deliberately born + * 1.2 m behind the frontage it walks out of — which is already further from the centreline + * than the 0.6 m the test allowed. Every crosser was therefore retired on the very first + * tick of its life, before it had moved a centimetre, and the "a third of them cross the + * carriageway" this file has always claimed simply never happened: the slot rolled again + * and came back as a pavement walker two times in three. That is also why the near field + * was empty. Crossers are the only figures that spawn inside 32 m, so they are what keeps + * anybody in the bottom half of the frame at all. */ + if (!gone && p.cross) { + var l2 = (COR.axis ? p.z - COR.ctr : p.x - COR.ctr) * p.goSide; + if (l2 > COR.half + 0.6) gone = 1; + } + if (gone) { p.live = 0; p.wait = 0; } + } + }, + draw: function (frame, cam, t) { + camScreen(frame, cam); + /* Picked up here rather than only at init so a resized window re-scales the crowd on the + * next frame instead of on the next rebuild. update() reads the same three back, because the + * near retirement is a screen-area test and it has no frame of its own to measure. */ + this.cols = frame.cols; this.rows = frame.rows; + this.cells = frame.cols * frame.rows; + var S = this.seed, i, x, q; + var wetR = wrel('wet'); + for (i = 0; i < PED_MAX; i++) { + var p = peds[i]; + if (!p.live) continue; + var pr = project(p.x + p.dx, p.z + p.dz); + /* Past the respawn distance, so a walker fades up out of the fog instead of switching on + * at the cull. The sub-cell test a few lines down retires it for good past ~90 m. */ + if (!pr.ok || pr.dist > 72) continue; + var w = pr.w, dist = pr.dist, d = near(dist), cx = pr.x, A = p.A; + /* Bob and stride are keyed on distance walked, not wall clock — they survive scrubbing and + * they stay in step with the legs instead of with the frame counter. The archetype's own + * stride multiplier is what stops eight costumes sharing one walk. */ + var st = CC.reducedMotion ? 0 : Math.sin(p.walked * 3.6 * A.stride + p.phase); + var bobA = CC.reducedMotion ? A.bob * 0.12 : A.bob; + var hunch = p.hunch; + var rFeet = rowOf(0, w); + var rHead = rowOf((p.tall + A.tallB) * (1 - hunch * 0.055) + st * bobA, w); + var tallRows = rFeet - rHead; + if (tallRows < 1.4) continue; // sub-cell: it would only salt the pavement + var shw = pedShoulder(w); // half a SHOULDER width, in columns + var xw = shw * (1 + A.ext); // ...and how far the costume reaches past it + var x0 = Math.round(cx - xw), x1 = Math.round(cx + xw); + if (x1 < 0 || x0 > COLS - 1) continue; + /* Backstop for the one tick a window resize can put between update()'s area budget and this + * box: without it a figure that was inside the budget at the old size can print as a slab + * at the new one, which is precisely the transient PED_COVER_MAX exists to prevent. Twice + * the budget, so it never fires while the two agree. Skipped rather than retired here, + * because retiring is update()'s job and it will do it on the very next tick, having by + * then been handed the new dimensions. */ + if (pedCover(p, pr) > PED_COVER_MAX * 2) continue; + /* Clamped to the frame, because the loop below walks every column between them and an + * unclamped near figure spans hundreds of columns that are not on screen. */ + if (x0 < 0) x0 = 0; + if (x1 > COLS - 1) x1 = COLS - 1; + + /* The body is a black cut-out, and the ONLY lit thing on it is the top edge of that + * cut-out: sodium from the lamp standards overhead, catching a crown and two shoulders. + * That single rule is what makes a figure read on a black road — the earlier version drew + * the silhouette alone, which is invisible everywhere the shopfronts behind it are dark, + * and that is most of the street. The rule now pays for the costumes too: because the rim + * lands on whatever the topmost occupied row of each column is, a hat brim, a coat hem and + * a courier's pack all catch the light on their own edge for free. */ + var rim = fg(70 + hash2(i, p.n, S + 5) * 44, dist); + var sTop = 0.13 + hunch * 0.06; // shoulder line, rising as the figure hunches + for (x = x0; x <= x1; x++) { + var u = (x - cx) / shw, au = u < 0 ? -u : u; + var onAcc = (u < 0 ? -1 : 1) === p.side; // the side the bag or the pack is slung on + /* v0/v1 are the top and bottom of this column as body fractions. Start empty and let + * each piece of the costume claim its own span; a column nothing claims is skipped. The + * union is deliberately taken as a single run rather than as separate pieces — at this + * cell size a gap between a bag and a hip is one cell of black inside a silhouette that + * is already black, so drawing it twice would cost and show nothing. */ + var v0 = 9, v1 = -9; + if (au <= 1.0) { + v0 = au > 0.62 ? 0.20 + hunch * 0.05 : (au > 0.34 ? sTop : 0); + /* A hood is a PEAK, and a peak is a shape, not a glyph. Sloping the crown band away + * from the centre puts the middle column one row above its neighbours, which is what + * makes the caret below read as a hood rather than as a row of carets — the first cut + * left the crown flat and printed ^^^^ across the top of every hooded figure. */ + if (A.hood && au <= 0.34) v0 = au * 0.30; + v1 = au > 0.62 ? 0.66 : (au > A.legW ? A.legTop : 1); + /* The legs parting is the whole walk cycle at this size; anything more is invisible. */ + if (au < 0.28 && tallRows > 5 && st > 0.42) v1 = 0.90; + } + if (A.hem > 0 && au > 1 && au <= 1 + A.hem) { + /* A coat is a triangle: shoulder-width at the waist, widest at the hem. So a column + * this far out is covered from the height where the flare has reached it, down. */ + q = A.hemTop + (A.hemBot - A.hemTop) * (au - 1) / A.hem; + if (q < v0) v0 = q; + if (A.hemBot > v1) v1 = A.hemBot; + } + if (A.brim > 0 && au <= 1 + A.brim) { + if (0.05 < v0) v0 = 0.05; + if (0.13 > v1) v1 = 0.13; + } + /* The pack hangs BELOW the crown and stops at the small of the back. Started at the head + * and carried to 1.8 half-widths it stopped being a pack and squared the whole figure + * off into a slab with a bump on top. */ + if (A.pack > 0 && onAcc && au > 0.50 && au <= 1 + A.pack) { + if (0.15 < v0) v0 = 0.15; + if (0.54 > v1) v1 = 0.54; + } + if (A.bag > 0 && onAcc && au > 0.60 && au <= 1 + A.bag) { + if (0.40 < v0) v0 = 0.40; + if (0.66 > v1) v1 = 0.66; + } + if (v1 < v0) continue; + var rt = rHead + v0 * tallRows, rb = rHead + v1 * tallRows; + bar(frame, x, rt, rb, 0, P.shadow, 0, d); + if (rim >= 5) { + /* A hood carries no face, so its crown is a dimmer peak rather than the bright round + * head every other archetype gets — which is the whole read at eight rows tall. + * + * THE RAMP OUTWARD USED TO END AT 0.32 AND THAT WAS THE COSTUMES' WHOLE PROBLEM. Every + * cell this loop lights is the TOP EDGE of its own column — the crown, the shoulder + * line, the top of a coat's flare, a hat brim, the lid of a pack — so all of them face + * the same lamp and none of them has any business being a third as bright as the head. + * And au>1 is not a detail: it is exactly the hem, brim, pack and bag, i.e. the only + * columns that tell one archetype from another. At 0.32 of a rim that starts at 70-114, + * amber landed at raw 22-36, and core.js prints amber at 0.19 exposure — 12 to 32 out + * of 255, one step above the black it is drawn on. The geometry was in the buffer and + * nothing was on the screen. Azure hid it: the same 0.32 prints 38-79 through azure's + * 0.34 exposure, so a screen-lit figure read and a sodium-lit one did not, which is + * why this survived being looked at. + * + * The crown stays at 1. It is the only feature a figure eight rows tall has left, and + * the review that found the 0.32 wanted it dropped to 0.55 for hierarchy — but that + * hierarchy costs half the brightness of every walker in the middle distance, which is + * most of the crowd, to model a figure that is only modelled at all when it is close. + * The hierarchy is kept the cheap way instead: the outer bands come UP to just under + * the crown rather than the crown coming down to them. */ + var rl = au < 0.34 ? (A.hood ? 0.60 : 1) : (au <= 1.0 ? 0.72 : 0.88); + /* AND THE GLYPH IS HALF THE FIX, which measuring lum alone will never show. The two + * outer bands used to be drawn with ' and ` — the two smallest marks in the table, a + * speck in the corner of a cell. A shoulder line and a coat's hem are HORIZONTAL edges + * caught from above, and at this resolution the thing that says "edge" is a mark with + * width across the cell, so they are dashes. Rendered and looked at: with the ticks the + * costume was a dotted rumour at any brightness, and the same cells as dashes are a + * shoulder and a flared hem. The crown keeps its round o, and a hood its caret, because + * those two are reading a curve rather than an edge. */ + put(frame, x, Math.round(rt), + au < 0.34 ? (A.hood ? G_CARET : G_o) : G_DASH, + p.rim, rim * rl, nearer(dist)); + } + } + if (rim < 5) continue; + + /* One shoulder is turned to the lamp, so that side gets a short CONTIGUOUS rim down the + * upper body. Contiguous matters: spaced every other row it scattered into loose ticks + * that read as grit on the pavement rather than as the lit edge of a coat. It stops at the + * waist — carried to the feet it outlines the figure and turns it into a neon sign, which + * is also why the run is capped: at 400x100 a figure at 3 m is forty rows tall and 0.42 of + * that is most of a person drawn in sodium. */ + if (tallRows > 8) { + var rx = Math.round(cx + p.side * shw), qn = (tallRows * 0.42) | 0; + if (qn > 13) qn = 13; + /* The old ramp was 0.36 down to 0.16, and 0.16 of a rim that starts at 70 is raw lum 11, + * which core.js prints as amber 3. The bottom two thirds of every lit shoulder in the + * piece were therefore drawn in a colour that does not exist on screen — the run was + * "contiguous" in the buffer and a couple of ticks long in the picture. It now starts + * near the shoulder rim's own value and fades to nothing over its whole length, which is + * what a fade is; the cap of 13 cells is what keeps it a lit edge rather than a strip + * light, and that cap was never the part that was wrong. */ + for (q = 1; q <= qn; q++) + put(frame, rx, Math.round(rHead + q), G_QUOTE, p.rim, + rim * (0.62 - 0.44 * q / qn), nearer(dist)); + } + + /* THE ACCENT — at most one per figure, and only about one figure in six carries one. */ + if (p.acc && tallRows > 4) { + if (p.acc === 1) { + /* LED piping down one seam. This is the ONE place a narrow accent is licensed to + * appear on a person, which is the reason the tall technical shell exists as an + * archetype at all: it gives the colour something to be a property OF. Dim at the top + * and fading down, so it reads as a lit seam rather than as a strip light. */ + var al = fg(52, dist); + if (al >= 5) { + var qn2 = (tallRows * 0.40) | 0; if (qn2 > 8) qn2 = 8; + var px2 = Math.round(cx - p.side * shw * 0.70); + for (q = 0; q <= qn2; q++) + put(frame, px2, Math.round(rHead + tallRows * 0.18) + q, G_PIPE, p.accHue, + al * (0.90 - 0.55 * q / (qn2 + 1)), nearer(dist)); + } + } else if (p.acc === 2) { + /* A courier's reflective strip across the pack. Ice, which is the swatch's actual job + * — a GLINT, two cells, never a surface. */ + var al2 = fg(165, dist); + if (al2 >= 5) { + var bx = Math.round(cx + p.side * shw * (1 + A.pack * 0.7)); + put(frame, bx, Math.round(rHead + tallRows * 0.30), G_DASH, P.ice, al2, nearer(dist)); + if (tallRows > 9) + put(frame, bx - p.side, Math.round(rHead + tallRows * 0.30), G_DOT, P.ice, + al2 * 0.45, nearer(dist)); + } + } else if (p.acc === 3) { + /* A cigarette. One ember cell at the mouth, breathing on the figure's own phase so no + * two pulse together, and frozen flat under reduced motion. */ + var glow = CC.reducedMotion ? 0.72 + : 0.55 + 0.45 * vnoise(t * 0.7 + p.phase * 3, S + 47); + var al3 = fg(120 * glow, dist); + if (al3 >= 5) + put(frame, Math.round(cx + p.side * shw * 0.55), + Math.round(rHead + tallRows * 0.10), G_DOT, P.ember, al3, nearer(dist)); + } else { + /* Something carried and lit — a takeaway bag, a paper lantern, a lit sign held low. + * It swings with the arm, which is why it needs the stride and not a clock. */ + var al4 = fg(128, dist); + if (al4 >= 5) { + var hx2 = Math.round(cx + p.side * shw * (0.85 + st * 0.22)); + var hy2 = Math.round(rHead + tallRows * (0.56 + st * 0.03)); + put(frame, hx2, hy2, G_STAR, p.accHue, al4, nearer(dist)); + if (tallRows > 11) + put(frame, hx2, hy2 + 1, G_DOT, p.accHue, al4 * 0.40, nearer(dist)); + } + } + } + + /* THE UMBRELLA. A shallow arc over the head, wide enough to be a roof and no wider, drawn + * as one cell per column so it never masses into a lit blob: the apex takes the light and + * the ribs fall away from it. p.umb is the open fraction, so the canopy grows out of the + * head over three or four seconds rather than appearing. */ + if (p.umb > 0.03 && tallRows > 3.5) { + var ru = shw * 2.0 * p.umb; + if (ru < 1) ru = 1; + var ruI = ru | 0; + var rApex = rHead - tallRows * (0.07 + 0.08 * p.umb); + for (q = -ruI; q <= ruI; q++) { + var f2 = q / ru; + var ul = rim * (0.46 - 0.30 * f2 * f2) * (0.5 + 0.5 * p.umb); + put(frame, Math.round(cx) + q, Math.round(rApex + f2 * f2 * tallRows * 0.17), + (q === -ruI || q === ruI) ? G_TICK : G_DASH, p.rim, ul, nearer(dist)); + } + /* The shaft, and only the stretch between the canopy and the crown: below that it runs + * inside a cut-out that is already black, so drawing it again would cost and show + * nothing. */ + bar(frame, Math.round(cx), rApex + 1, rHead - 1, 0, P.shadow, 0, nearer(dist)); + } + + /* Reflected in the wet road under the feet, smeared toward the eye. This does more work + * than the figure itself: it is the only part of a pedestrian that lands in the empty + * black road rather than in the busy band at the horizon, where a 1.7 m head seen from a + * 1.7 m eye always sits. Falls off fast — a reflection never out-reads its source. + * How far it runs is now the road's business: wrel('wet') is 1.0 under the preset this was + * tuned as, so a rainy street keeps exactly the four rows it always had, a dry one gets + * one, and an umbrella keeps a patch of road dry under itself. */ + var rn = 1 + ((wetR * 3.4) | 0); if (rn > 5) rn = 5; + var dry = 1 - 0.55 * p.umb; + for (var rj = 1; rj <= rn; rj++) { + var rr = Math.round(rFeet) + rj, rd = roadDist(rr, pr.sp); + var rl2 = fg(rim * (0.52 - rj * 0.11) * (0.55 + 0.45 * wetR) * dry, rd); + if (rl2 < 5) break; + put(frame, Math.round(cx), rr, rj < 3 ? G_QUOTE : G_DOT, p.rim, rl2, near(rd)); + } + if (p.phone >= 0 && tallRows > 3.2) { + var pl = fg(150, dist); + if (pl >= 5) + put(frame, Math.round(cx - p.side * shw * 0.6), + Math.round(rHead + tallRows * 0.40), G_DOT, p.phone, pl, nearer(dist)); + } + } + } + }); + + /* ============================================================================================= + * A CAT — layer 21 + * Dormant most of the time. The body is a cut-out that mostly disappears into the road; the + * eye-shine is the whole element, and it is two cells at most. + * ============================================================================================ */ + var cat = null; + + CC.ELEMENTS.push({ + name: 'cat', + layer: 21, + init: function (city, rng) { + this.city = city; + this.seed = (rng() * 2147483647) | 0; + cat = { x: 0, z: 0, vx: 0, vz: 0, live: 0, wait: 5, n: 0, len: 0.5, side: 1 }; + }, + update: function (dt, t, cam) { + camBasis(cam); + corridor(this.city, cam); + var S = this.seed, k = CC.reducedMotion ? 0.10 : 1, rain = wp().rain; + if (cat.live) { + cat.x += cat.vx * dt * k; cat.z += cat.vz * dt * k; + var pr = project(cat.x, cat.z); + var l = COR.axis ? cat.z - COR.ctr : cat.x - COR.ctr; + if (l < 0) l = -l; + if (!pr.ok || pr.w > 48 || l > COR.half + 0.9) { + cat.live = 0; + /* Long gaps. A cat every few seconds is a rat problem, not an atmosphere. And a cat in + * a downpour is a cat under a parked van: the gap stretches by up to two and a half + * times, which is the difference between a wet night that happens to have a cat in it + * and one that has the same cat in it as a dry one. */ + cat.wait = (19 + hash2(0, cat.n, S ^ 0x11) * 26) * (1 + 1.5 * rain); + } + return; + } + /* Damped by k, unlike the pedestrians' respawn above: what ends a cat's crossing is the + * cat's own legs, and those ARE slowed by k. Leaving the timer at full speed while the + * crossing crawls is what puts a permanent cat in a reduced-motion frame. */ + cat.wait -= dt * k; + if (cat.wait > 0) return; + cat.n++; + var h1 = hash2(1, cat.n, S), h2 = hash2(2, cat.n, S), h3 = hash2(3, cat.n, S); + cat.side = h2 < 0.5 ? -1 : 1; + /* Out at 34–42 m and 0.9 m BEHIND the building line, so the frontage the raycaster already + * painted owns those cells and the cat walks out from under it. It used to start at 9–22 m + * and half a metre in, which on any block with a gap in the frontage put a lit pair of eyes + * on screen out of nothing. */ + var a = COR.along + COR.dir * (34 + h1 * 8); + var l0 = -cat.side * (COR.half + 0.9); + cat.x = worldX(a, l0); cat.z = worldZ(a, l0); + /* It crosses the corridor, so its velocity is purely lateral. Halved from the old sprint: + * from 34 m the walk needs a few seconds to bring the crossing inside the draw, and a cat + * that has already reached the far kerb by then is a cat nobody ever sees. It also simply + * looks more like a cat — they saunter across a road and bolt only at the end. Except in the + * rain, when the saunter is the first thing to go. */ + var sp = (1.05 + h3 * 0.75) * (1 + 0.55 * rain); + cat.vx = COR.axis ? 0 : cat.side * sp; + cat.vz = COR.axis ? cat.side * sp : 0; + cat.len = 0.44 + h3 * 0.16; + cat.live = 1; + }, + draw: function (frame, cam, t) { + if (!cat || !cat.live) return; + camScreen(frame, cam); + var pr = project(cat.x, cat.z); + /* Past the 42 m end of the spawn range, so this cull never switches the eye-shine on: the + * reveal is the frontage the cat steps out from, and after that the fog. */ + if (!pr.ok || pr.dist > 46) return; + var w = pr.w, dist = pr.dist, d = near(dist), cx = pr.x; + var hw = cat.len * 0.5 * CPM / w; + if (hw < 0.5) hw = 0.5; + var rGnd = rowOf(0, w), rBack = rowOf(0.26, w); + var x, x0 = Math.round(cx - hw), x1 = Math.round(cx + hw); + for (x = x0; x <= x1; x++) bar(frame, x, rBack, rGnd, 0, P.shadow, 0, d); + /* Tail, kicked up behind: one cell, and it is what turns a smudge into an animal. */ + put(frame, Math.round(cx - cat.side * (hw + 1)), Math.round(rBack - 0.6), 0, P.shadow, 0, d); + /* Tapetum. Spring green, and the one thing in this batch licensed to be bright — two dots + * moving across a black road is the entire read. */ + var el = fg(198, dist); + if (el < 6) return; + var ex = Math.round(cx + cat.side * hw); + put(frame, ex, Math.round(rBack), G_DOT, P.spring, el, nearer(dist)); + if (hw > 2.4) + put(frame, ex - cat.side, Math.round(rBack), G_DOT, P.spring, el * 0.7, nearer(dist)); + } + }); + + /* ============================================================================================= + * GROUND TRAFFIC — layer 22 + * Cars are only ever seen crossing the intersections ahead, never coming down the camera's own + * street: the walk goes down the middle of the carriageway and a car bearing down on the eye + * would turn an ambient piece into an event. Occlusion is free — the depth test drops the body + * the moment a corner building is in front of it, so a car only exists inside the slot. + * ============================================================================================ */ + var cars = null, CAR_N = 2; + + /* An intersection 14–58 m ahead, picked by a 0..1 hash. Counted then re-walked rather than + * collected, because an element may not allocate. */ + function crossAhead(city, pick) { + if (!city || !city.aveX) return NaN; + var period = COR.axis ? city.AVE : city.CROSS; + var i0 = Math.round(COR.along / period), i, c, dd, cnt = 0, want; + for (i = i0 - 4; i <= i0 + 4; i++) { + c = (COR.axis ? city.aveX(i) : city.crossZ(i)) + 0.5; + dd = (c - COR.along) * COR.dir; + if (dd >= 14 && dd <= 58) cnt++; + } + if (!cnt) return NaN; + want = (pick * cnt) | 0; if (want >= cnt) want = cnt - 1; + for (i = i0 - 4; i <= i0 + 4; i++) { + c = (COR.axis ? city.aveX(i) : city.crossZ(i)) + 0.5; + dd = (c - COR.along) * COR.dir; + if (dd >= 14 && dd <= 58) { if (want === 0) return c; want--; } + } + return NaN; + } + function crossHalf(city, c) { + if (!city || !city.aveX) return 2.0; + var period = COR.axis ? city.AVE : city.CROSS; + var i = Math.round((c - 0.5) / period); + return (COR.axis ? city.aveW(i) : city.crossW(i)) + 0.5; + } + + CC.ELEMENTS.push({ + name: 'traffic', + layer: 22, + init: function (city, rng) { + this.city = city; + this.seed = (rng() * 2147483647) | 0; + cars = new Array(CAR_N); + for (var i = 0; i < CAR_N; i++) + cars[i] = { x: 0, z: 0, vx: 0, vz: 0, live: 0, wait: 1.5 + i * 6, n: i * 53, + len: 4.2, tall: 1.4, go: 1, tail: P.red }; + }, + update: function (dt, t, cam) { + var city = this.city; + camBasis(cam); + corridor(city, cam); + var S = this.seed, k = CC.reducedMotion ? 0.08 : 1, i; + for (i = 0; i < CAR_N; i++) { + var c = cars[i]; + if (c.live) { + c.x += c.vx * dt * k; c.z += c.vz * dt * k; + var pr = project(c.x, c.z); + var l = COR.axis ? c.z - COR.ctr : c.x - COR.ctr; + /* Retired well past the far building line — the depth test has been hiding it for + * several metres by then, so nothing pops out of existence on screen. */ + if (!pr.ok || pr.w > 70 || l * c.go > COR.half + 11) { + c.live = 0; + c.wait = 3.5 + hash2(i, c.n, S ^ 0x4D) * 11; + } + continue; + } + /* THE GAP IS DAMPED BY THE SAME k AS THE CROSSING, and that is a reduced-motion FIX, not a + * flourish. A crossing takes 26 m at 8% of 8–15 m/s, so a car that used to be on screen + * for two seconds in every eight was on it for thirty out of every eight — a headlamp at + * lum 240 and a six-cell sodium beam parked in the intersection essentially permanently, + * and the whole frame's luminance stepping up and down around it on a slow cycle it never + * has at normal speed. Motion damped without its own timer damped does not calm a frame; + * it changes what is in it. */ + c.wait -= dt * k; + if (c.wait > 0) continue; + c.n++; + var h1 = hash2(i, c.n, S), h2 = hash2(i, c.n, S ^ 0x21), h3 = hash2(i, c.n, S ^ 0x8F); + var ca = crossAhead(city, h1); + if (ca !== ca) { c.wait = 2.5; continue; } // nothing crossing in range; look again soon + var ch = crossHalf(city, ca); + c.go = h2 < 0.5 ? -1 : 1; + /* Lane offset opposed to the direction of travel, so the two slots never share a line. */ + var a = ca + (ch > 1.6 ? 0.55 + h3 * (ch - 1.2) : 0) * -c.go; + var l0 = -c.go * (COR.half + 10); + c.x = worldX(a, l0); c.z = worldZ(a, l0); + var sp = 8 + h3 * 7; + c.vx = COR.axis ? 0 : c.go * sp; + c.vz = COR.axis ? c.go * sp : 0; + c.len = 3.6 + h1 * 1.7; + c.tall = 1.25 + h2 * 0.35; + c.tail = h3 < 0.82 ? P.red : P.ember; + c.live = 1; + } + }, + draw: function (frame, cam, t) { + camScreen(frame, cam); + var i, j; + /* The road's wetness, read reference-relative: 1.0 is the preset every constant below was + * tuned under, so a rainy crossing looks exactly as it always did and only a dry or a + * drowned one moves. */ + var wetR = wrel('wet'); + for (i = 0; i < CAR_N; i++) { + var c = cars[i]; + if (!c.live) continue; + /* Nose and tail as world points, then sampled between them: the car is broadside to the + * view, so its two ends can be many metres apart in DEPTH at a near intersection and a + * single projected centre would shear the whole body. */ + var half = c.len * 0.5; + var nx = c.x + (c.vx > 0 ? half : (c.vx < 0 ? -half : 0)); + var nz = c.z + (c.vz > 0 ? half : (c.vz < 0 ? -half : 0)); + var tx = c.x * 2 - nx, tz = c.z * 2 - nz; + + /* PJ is shared scratch: read each projection out before taking the next. */ + var pn = project(nx, nz); if (!pn.ok) continue; + var xn = pn.x, wn = pn.w, dn = pn.dist; + var pt = project(tx, tz); if (!pt.ok) continue; + var xt = pt.x, wt = pt.w, dtl = pt.dist, spt = pt.sp; + if (dn > 72 && dtl > 72) continue; + + var span = xn - xt; if (span < 0) span = -span; + var ns = (span + 2) | 0; if (ns < 4) ns = 4; if (ns > 72) ns = 72; + for (j = 0; j <= ns; j++) { + var s = j / ns; + var ps = project(tx + (nx - tx) * s, tz + (nz - tz) * s); + if (!ps.ok) continue; + var sd = near(ps.dist); + var rB = rowOf(0.06, ps.w), rT = rowOf(c.tall, ps.w); + /* The cabin is set back from both ends. At this size that step is the only thing that + * says car rather than skip. */ + var cab = s > 0.28 && s < 0.74; + if (cab) rT = rowOf(c.tall + 0.34, ps.w); + bar(frame, Math.round(ps.x), rT, rB, 0, P.shadow, 0, sd); + /* THE ROOFLINE AND THE SILL, which are what turn the body from a hole in the road into a + * car. Measured over the canonical sweep the element blanked 89 to 140 cells to paint 8 + * to 10, all of them lamps: a black bar sliding across a black street with two sparks on + * it, and the step up over the cabin — the one piece of shape this thing has — printed + * nowhere at all. The pedestrians beside it have solved this since they were written; a + * cut-out is only a silhouette if SOMETHING lights its edge. + * + * Sodium, because that is what is over an intersection, and the beam this element throws + * on the tarmac a few lines down is already amber for the same reason. Kept well under + * the headlamp: a roof is a reflection and a lamp is a lamp, and if the two arrive at the + * same brightness the car stops having a front. The ends are dimmer than the cabin so the + * line reads as a roof falling away to a bonnet rather than as a bar. */ + var rfl = fg(cab ? 58 : 42, ps.dist); + if (rfl >= 5) + put(frame, Math.round(ps.x), Math.round(rT), G_DASH, P.amber, rfl, nearer(ps.dist)); + /* The sill catches the road's own sheen rather than the lamp, so it is dimmer still and + * it grows with the wet — on a dry night there is nothing down there to catch. */ + var sll = fg(30 * (0.45 + 0.55 * wetR), ps.dist); + if (sll >= 5) + put(frame, Math.round(ps.x), Math.round(rB) - 1, G_UNDER, P.amber, sll, nearer(ps.dist)); + /* Glazing: a dim azure dash along the cabin. Interior light, not a lamp. */ + if (s > 0.30 && s < 0.72 && ps.dist < 42 && (j & 1) === 0) { + var gl = fg(54, ps.dist); + if (gl >= 5) + put(frame, Math.round(ps.x), Math.round(rT + 1), G_DASH, P.azure, gl, nearer(ps.dist)); + } + } + + /* Head and tail lamps: the point of the whole element. Both are drawn as short horizontal + * SMEARS trailing the direction of travel, not as points — at 12 m/s a lamp is a streak to + * the eye, and one isolated bright cell in a black intersection reads as a stuck pixel + * rather than as something moving. Two or three cells is all it takes. */ + var back = xn > xt ? -1 : 1; // screen direction opposite the travel + var hl = fg(240, dn), tl = fg(196, dtl); + var rHl = Math.round(rowOf(0.62, wn)), rTl = Math.round(rowOf(0.78, wt)); + if (hl >= 5) { + put(frame, Math.round(xn), rHl, G_0, P.ice, hl, nearer(dn)); + put(frame, Math.round(xn) + back, rHl, G_o, P.ice, hl * 0.46, nearer(dn)); + put(frame, Math.round(xn) + back * 2, rHl, G_DOT, P.ice, hl * 0.20, nearer(dn)); + put(frame, Math.round(xn), rHl + 1, G_DOT, P.ice, hl * 0.34, nearer(dn)); + /* The bloom on a wet road. Extra CELLS, never extra lum: fg(240) is already at the top + * of the scale and the print's shoulder is what would eat any further gain, so pushing + * the number only flattens the lamp. Two dim cells either side is what a wet windscreen + * actually does to a light. */ + if (wetR > 0.80) { + var bw = hl * 0.16 * wetR; + put(frame, Math.round(xn) + back * 3, rHl, G_DOT, P.ice, bw, nearer(dn)); + put(frame, Math.round(xn) - back, rHl, G_DOT, P.ice, bw * 1.2, nearer(dn)); + } + } + if (tl >= 5) { + put(frame, Math.round(xt), rTl, G_o, c.tail, tl, nearer(dtl)); + put(frame, Math.round(xt) + back, rTl, G_DOT, c.tail, tl * 0.44, nearer(dtl)); + if (span > 8) + put(frame, Math.round(xt) - back, rTl, G_DOT, c.tail, tl * 0.34, nearer(dtl)); + } + + /* The beam on the tarmac ahead of the nose — this is the "streak" the crossing actually + * reads as. Sodium-tinted, because it is landing on a sodium-lit road, and it reaches + * further the wetter that road is: six steps under the preset this was tuned as, four on + * a dry one, where a beam has nothing to lie on. */ + if (dn < 46) { + var bn = 4 + ((wetR * 2.4) | 0); if (bn > 8) bn = 8; + var ux = c.vx === 0 ? 0 : (c.vx > 0 ? 1 : -1), uz = c.vz === 0 ? 0 : (c.vz > 0 ? 1 : -1); + for (j = 1; j <= bn; j++) { + var bp = project(nx + ux * (1.1 + j * 1.35), nz + uz * (1.1 + j * 1.35)); + if (!bp.ok) continue; + var bl = fg(120 * (1 - j / (bn + 1.5)), bp.dist); + if (bl < 5) continue; + put(frame, Math.round(bp.x), Math.round(rowOf(0.02, bp.w)), + j < 3 ? G_EQ : G_DASH, P.amber, bl, near(bp.dist)); + } + /* Tail lamps in the wet road, at the TARMAC's depth — the road under the car's skirt is + * nearer than the car, so the lamp's own distance would lose the test outright. Kept + * well under the lamp itself: a reflection that competes with its source stops looking + * like water. It runs longer as the road gets wetter, which is the one place in this + * element where the weather is meant to be legible rather than merely correct. */ + var tn = 1 + ((wetR * 2.2) | 0); if (tn > 4) tn = 4; + var rr0 = Math.round(rowOf(0, wt)) + 1; + for (j = 0; j < tn; j++) { + var rrd = roadDist(rr0 + j, spt); + var rl = fg((70 - j * 22) * (0.55 + 0.45 * wetR), rrd); + if (rl >= 5) put(frame, Math.round(xt), rr0 + j, G_QUOTE, c.tail, rl, near(rrd)); + } + } + } + } + }); + + /* ============================================================================================= + * LITTER — layer 24 + * Fourteen single cells whose job is to make the wind visible. Dim, mostly scraping the ground, + * and brightening only when one lifts far enough to catch a streetlamp. + * ============================================================================================ */ + var bits = null, BIT_N = 18; + + function bitSpawn(b, i, S, fresh) { + b.n++; + var h1 = hash2(i, b.n, S), h2 = hash2(i, b.n, S ^ 0x2F), h3 = hash2(i, b.n, S ^ 0x5C); + /* Respawned CLOSE, because the wind blows them away from the camera faster than the walk + * follows: seeded at the far cull they spent their whole life past 30 m, where fog has them + * at four or five lum and half the pool was invisible. */ + var a = COR.along + COR.dir * (fresh ? 3 + h1 * 20 : 8 + h1 * 16); + var l = (h2 * 2 - 1) * COR.half * 0.94; + b.x = worldX(a, l); b.z = worldZ(a, l); + b.lift = h3 < 0.55 ? 0.05 + h3 * 0.35 : 0.40 + h3 * 1.10; // most never leave the tarmac + b.ph = h1 * 6.283; + b.rate = 0.8 + h2 * 1.9; + b.hue = h3 < 0.62 ? P.slate : (h3 < 0.87 ? P.white : P.amber); + b.gl = PAPER[(h1 * PAPER_N) | 0]; + } + + CC.ELEMENTS.push({ + name: 'litter', + layer: 24, + init: function (city, rng) { + this.city = city; + this.seed = (rng() * 2147483647) | 0; + this.boot = 0; + bits = new Array(BIT_N); + for (var i = 0; i < BIT_N; i++) + bits[i] = { x: 0, z: 0, n: i * 17 + 3, lift: 0.2, ph: 0, rate: 1, y: 0.05, + hue: P.slate, gl: G_QUOTE }; + }, + update: function (dt, t, cam) { + camBasis(cam); + corridor(this.city, cam); + var S = this.seed, i, b; + if (!this.boot) { this.boot = 1; for (i = 0; i < BIT_N; i++) bitSpawn(bits[i], i, S, 1); } + var k = CC.reducedMotion ? 0.12 : 1; + /* One gust field for the whole street, so every scrap moves together — that shared motion is + * the only reason a handful of dots reads as wind and not as insects. Its strength is the + * wind's, read reference-relative so a rainy night blows exactly as hard as it always did + * and a still one barely stirs. */ + var wR = wrel('wind'); + /* The along-street push rides weather.js's shared gust envelope (CC.Wind.mult, mean 1 by + * construction) rather than a private vnoise. A scrap of paper skating up the street while + * the rain curtain was leaning the other way was the most visible symptom of every element + * rolling its own wind, and it is exactly what the exported vector exists to stop. + * 1.30 is the old expression's mean — (0.35 + 0.5*1.9) — so the average drift rate at the + * reference sky is unchanged; only the phase, and the fact that it is now the city's phase, + * has moved. The fallback keeps the file standing in a harness that loads no weather. + * The LATERAL swirl below keeps its own noise on purpose: it is the cross-street component, + * which is turbulence around the buildings and not the wind itself. */ + var wmult = CC.Wind ? CC.Wind.mult : (0.27 + vnoise(t * 0.31, S ^ 0x77) * 1.46); + var gust = 1.30 * wmult * (0.35 + 0.65 * wR); + var swirl = (vnoise(t * 0.24 + 11, S ^ 0x9A) - 0.5) * 1.4 * (0.35 + 0.65 * wR); + for (i = 0; i < BIT_N; i++) { + b = bits[i]; + b.ph += dt * b.rate * k; + /* Height is derived from the phase, not integrated: a scrap bouncing off an accumulated + * velocity walks out of the street after a few thousand frames of catch-up. */ + b.y = 0.04 + b.lift * (0.5 - 0.5 * Math.cos(b.ph)) * (CC.reducedMotion ? 0.3 : 1); + var along = gust * (0.6 + b.lift), lat = swirl * b.lift; + b.x += (COR.axis ? COR.dir * along : lat) * dt * k; + b.z += (COR.axis ? lat : COR.dir * along) * dt * k; + var pr = project(b.x, b.z); + if (!pr.ok || pr.w > 30 || pr.sp > HP * 1.6 || pr.sp < -HP * 1.6) bitSpawn(b, i, S, 0); + } + }, + draw: function (frame, cam, t) { + camScreen(frame, cam); + for (var i = 0; i < BIT_N; i++) { + var b = bits[i]; + var pr = project(b.x, b.z); + if (!pr.ok || pr.dist > 32) continue; + /* A lifted scrap catches the streetlight and a scraping one does not; that contrast IS the + * animation. Capped low — this must never outshine the kerb it blows past. */ + var lum = fg(18 + clamp(b.y / (b.lift + 0.05), 0, 1) * 48, pr.dist); + if (lum < 5) continue; + put(frame, Math.round(pr.x), Math.round(rowOf(b.y, pr.w)), b.gl, b.hue, lum, + near(pr.dist)); + } + } + }); + +})(typeof CC !== 'undefined' ? CC : require('../core.js')); +if (typeof module !== 'undefined') + module.exports = (typeof CC !== 'undefined' ? CC : require('../core.js')).ELEMENTS; diff --git a/src/elements/structure.js b/src/elements/structure.js new file mode 100644 index 0000000..cb6bf2c --- /dev/null +++ b/src/elements/structure.js @@ -0,0 +1,1297 @@ +/* CyberCity structure — the hardware bolted to the canyon. + * + * Seven ambient systems that all share one job: break the flat rectangle of a facade and the flat + * slot of sky with objects that have a real position in the world. Cables and skybridges cross the + * void between the walls, fire escapes hang off them, plant and masts stand on top of them, + * lanterns hang under them — and street props stand on the pavement under all of it, which is the + * one band this file used to leave completely empty. See section 7 for why that mattered. + * + * Everything here is placed by hashing a WORLD lattice index, never by hashing a camera-relative + * sample. A screen- or camera-derived placement re-rolls every frame and the whole street boils — + * the same failure surfaces.js documents for facade windows, and it is far more obvious on an + * object with a silhouette than on a texel. + * + * That rule applies to the PATTERNS ON an object exactly as much as to the object's position, and + * the first cut of this file honoured it for placement and broke it for pattern in two places: the + * skybridge window band, soffit dash and window brightness were all keyed on the screen column, and + * segment3's dash phase came from a per-call counter over drawn screen cells. Both produced a + * texture welded to the viewport that the object then slid underneath. Measured against a world + * lattice, 4-37% of a bridge's pattern cells and 21-27% of an escape's dash decisions re-rolled + * between two consecutive frames 27 mm apart; both are 0.0% now. If you add anything to this file, + * the test is: hold the world still, move the camera by a millimetre, and nothing may change that + * is not a consequence of the projection. + * + * Coverage discipline: measured against the 200x60 harness over four seeds, the whole batch costs + * between half a point and two points of lit coverage, averaging about one. Much of what it draws + * is BLACK — a bridge soffit and a mast shaft are unlit iron, and CC.put with ch 0 / lum 0 is how + * you draw an absence at a depth. Adding lit cells was never the goal; adding silhouette was. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, hash2 = CC.hash2, vnoise = CC.vnoise, put = CC.put; + + /* g() is a string-keyed lookup and these are hit thousands of times per frame. */ + var G_DASH = CC.g('-'), G_PIPE = CC.g('|'), G_SL = CC.g('/'), G_BS = CC.g('\\'), + G_EQ = CC.g('='), G_HASH = CC.g('#'), G_O = CC.g('O'), G_oo = CC.g('o'), + G_0 = CC.g('0'), G_8 = CC.g('8'), G_U = CC.g('U'), G_V = CC.g('V'), + G_Y = CC.g('Y'), G_STAR = CC.g('*'), G_PLUS = CC.g('+'), G_COLON = CC.g(':'), + G_UNDER = CC.g('_'), G_DOT = CC.g('.'), G_COMMA = CC.g(','), G_SEMI = CC.g(';'), + G_X = CC.g('X'), G_M = CC.g('M'), G_W = CC.g('W'), G_N = CC.g('N'), G_A = CC.g('A'), + G_PCT = CC.g('%'), G_AMP = CC.g('&'), G_TICK = CC.g('`'), G_QUOTE = CC.g("'"); + + var LANTERN_G = [G_oo, G_O, G_0, G_8]; + + /* ---- shared state --------------------------------------------------------------------------- + * All six elements draw off one city and one seed, so BASE is drawn from the rng ONCE PER WORLD: + * six draws would give every element a different lattice offset and, worse, would shift the + * shared rng stream under every element that inits after these six. + * + * The guard is the city object, not a `booted` boolean. A boolean is right exactly once. main.js + * calls init() again whenever the seed changes — a #hashchange, someone pasting a link — and a + * latched BASE meant the new city inherited the old city's cables, masts, escapes and lanterns + * while every other module rebuilt around them. Comparing identity keeps the once-per-world + * property (all six are handed the SAME object in one round) and still re-rolls on a real + * rebuild. Resizing is not a rebuild and never reaches here: main.js's layout() re-allocates the + * frame and leaves the elements alone, precisely so a window drag cannot reshuffle the city. */ + var CITY = null, BASE = 0, bootWorld, Surf = null; + function boot(city, rng) { + if (rng && bootWorld !== city) { bootWorld = city; BASE = (rng() * 4294967296) | 0; } + CITY = city && city.aveX ? city : null; // no street lattice, nothing here has an anchor + } + + /* ---- the view ------------------------------------------------------------------------------ + * Mirrors raycast.js exactly. The camera is PLANAR: w is the perpendicular distance and doubles + * as the projection divisor, and the radial distance the depth test wants is w*sqrt(1+sp^2). + * Deriving `scale` from fov the same way raycast does is not optional — an element projected + * with a different vertical scale detaches from the wall it is bolted to. */ + var V = { + ox: 0, oz: 0, eyeY: 1.7, fwx: 0, fwz: 1, rgx: 1, rgz: 0, + hp: 0.7265, colK: 0, colMid: 0, scale: 77, horizon: 33, cols: 0, rows: 0, far: 125, + t: 0, tt: 0 + }; + + /* ---- weather binding ------------------------------------------------------------------------ + * Read off CC.Weather.P, which is a LIVE block held by reference, once per element draw and + * cached in these three scalars — the alternative is a dozen `CC.Weather.rel('wet')` calls per + * frame, each of which walks a string array. + * + * W_WET and the rest come through rel(), which is 1.0 under the 'rain' preset the whole build + * was tuned in, so a constant multiplied by it is unchanged until the weather actually moves. + * Multiplying by the RAW parameter instead would silently re-tune this file to 65% of what it + * was on the day it shipped, which is the one migration mistake weather_state.js calls out. + * + * W_GUST is the exception and is deliberately NOT a rel(): there is no gust in the tuned preset + * to be relative to. It is a 0..1-ish magnitude and every consumer below scales its own + * displacement by it. */ + var W_WET = 1, W_GUST = 0.55, W_RAIN = 1; + + /* REDUCED MOTION, once, for everything in this file that swings. A damped amplitude is not + * enough on its own — a banner still swinging at a third of its travel is still a banner + * swinging — so the clock is stopped as well and the amplitude kept, which leaves the cloth + * leaning on a fixed gust instead of oscillating on one. W_SWAY is that amplitude factor and + * V.tt the stopped clock; every sway in the file reads both. */ + var W_SWAY = 1; + + /* THE GUST. weather.js owns the single wind vector the whole build shares — rain slant, steam + * drift, litter — and publishes the live strength of it as CC.Wind.gust, which is P.wind beaten + * by its gust envelope on the director's own 0..1 scale (up to about 1.6 on the hardest gust of + * a storm). Reading it is what puts the banners, the washing and the paper lanterns on exactly + * the same beat as the rain curtain instead of on a private one that happens to look similar. + * + * The fallback is not dead code and should stay: this file is also loaded by tools that require + * a subset of src/, and a missing wind must produce a still street rather than an exception. + * Probed every frame rather than latched at init, because CC.Wind is a live object and the + * element files load in an order this one does not get to choose. */ + function gustOf(Wm, t) { + var G = CC.Wind ? CC.Wind.gust : undefined; + if (typeof G === 'number') return G; + var base = Wm ? Wm.P.wind : 0.55; + return base * (0.70 + 0.66 * vnoise(t * 0.27, 0x51D)); + } + + function view(f, cam, t) { + if (!Surf) Surf = CC.Surf; + var fov = cam.fov || 1.25, hp = Math.tan(fov * 0.5); + var cellA = cam.cellAspect || 0.5625; + V.cols = f.cols; V.rows = f.rows; V.hp = hp; + V.colK = f.cols * 0.5 / hp; V.colMid = f.cols * 0.5; + V.scale = cam.scaleY !== undefined ? cam.scaleY : (f.cols * cellA) / (2 * hp); + V.horizon = cam.horizon !== undefined ? cam.horizon : f.rows * 0.56; + V.eyeY = cam.eyeY !== undefined ? cam.eyeY : 1.7; + var yaw = cam.yaw || 0; + V.fwx = Math.sin(yaw); V.fwz = Math.cos(yaw); + V.rgx = Math.cos(yaw); V.rgz = -Math.sin(yaw); + V.ox = cam.x; V.oz = cam.z; + V.far = Surf ? Surf.FOG_END : 125; + V.t = t; + V.tt = CC.reducedMotion ? 0 : t; + var Wm = CC.Weather; + W_WET = Wm ? Wm.rel('wet') : 1; + W_RAIN = Wm ? Wm.rel('rain') : 1; + W_GUST = gustOf(Wm, t); + W_SWAY = CC.reducedMotion ? 0.38 : 1; + } + + /* Continuous cell coordinates: column i covers [i, i+1), row i has its centre at i+0.5, which is + * the convention raycast.js paints against. Floor, never |0 — |0 truncates -0.4 to 0 and would + * smear anything just off the top-left corner back onto the frame. */ + var PJ = { x: 0, y: 0, d: 0 }; + function project(px, py, pz) { + var rx = px - V.ox, rz = pz - V.oz; + var w = rx * V.fwx + rz * V.fwz; + if (w < 0.4) return false; // at or behind the eye plane + var sp = (rx * V.rgx + rz * V.rgz) / w; + PJ.d = w * Math.sqrt(1 + sp * sp); + PJ.x = sp * V.colK + V.colMid; + PJ.y = V.horizon - (py - V.eyeY) * V.scale / w; + return PJ.d < V.far; + } + + /* The only write. Fog is applied here because raycast.js already fogged the world pass; an + * unfogged mast at 90 m would read nearer than the tower it stands on. A cell fogged to nothing + * still gets written: it is unlit iron in front of something, and that occlusion is the point. */ + function emit(f, x, y, ch, col, lum, d) { + if (x < 0 || y < 0 || x >= V.cols || y >= V.rows) return; + if (lum > 0 && Surf) { lum = Surf.fog(lum, d); if (lum <= 0) ch = 0; } + put(f, x, y, ch, col, lum, d, 3); + } + + /* The same write for a LAMP rather than a surface, and the difference is not a licence — it is + * the physics. Surf.fog models a surface that stops reaching you: multiply by k^1.5 and crush + * the tail, so an 80 m parapet correctly goes to black. A point source is the other case: an + * aerial obstruction light is built to be seen from further than this city is deep, and fogging + * it as though it were concrete is why the mast element measured 4.5 cells a frame with NOT ONE + * of them over v=60 across the whole canonical sweep — the beacons were arithmetically present + * and printed as nothing. The floor keeps 42% of the lamp's own luminance at any range, which + * is a lamp dimmed by weather rather than a lamp deleted by it, and it is applied to exactly + * two cells per mast and nothing else in this file. */ + function emitLamp(f, x, y, ch, col, lum, d) { + if (x < 0 || y < 0 || x >= V.cols || y >= V.rows) return; + var l = Surf ? Surf.fog(lum, d) : lum, fl = lum * 0.42; + put(f, x, y, ch, col, l < fl ? fl : l, d, 3); + } + + /* ---- straight world segment --------------------------------------------------------------- + * Sample count comes from the segment's PROJECTED length, so a rail two metres away and the same + * rail at sixty cost the same number of distinct cells. `dash` draws one distinct cell in N: + * ironwork drawn continuously turns into the grey lattice the art direction exists to prevent. + * + * THE DASH PHASE COMES FROM THE WORLD. It used to come from a running counter over drawn screen + * cells — `if (dash > 1 && (k++ % dash)) continue;` — with k reset at the top of every call. That + * counter is indexed by the screen, so the instant a sub-cell camera step pushed the segment's + * first sample across a column boundary the whole run re-phased and every drawn cell in it + * jumped one place along. Fire escapes were the worst of it: measured at 200x60, consecutive + * frames 27 mm apart re-rolled 15%, 61%, 35%, 45% of the escapes' cells. Nothing was moving in + * the world; the pattern was simply being re-dealt sixty times a second. + * + * The replacement counts TICKS along the segment in world units, so a tick belongs to a point on + * the ironwork and stays with it. The one subtlety is the tick pitch. A pitch fixed in metres + * looks right at one distance only — it goes solid at range and turns into three lonely cells up + * close — so the pitch tracks the projected density, but QUANTISED TO A POWER OF TWO of ticks + * per metre. That quantisation is the whole trick: it holds a segment's pattern rigid across a + * 1.4x change of distance, which at walking pace is several seconds, and when it does change it + * changes once, cleanly, instead of dithering every frame. `anchor` puts the lattice origin in + * the world rather than at the segment's own end, so a stack of landings on one wall does not + * come out with every flight starting on the same tread. */ + var TICK_MIN = 0.03125, TICK_MAX = 64; + function segment3(f, x0, y0, z0, x1, y1, z1, ch, col, lum, dash) { + var okA = project(x0, y0, z0), ax = PJ.x, ay = PJ.y; + var okB = project(x1, y1, z1), bx = PJ.x, by = PJ.y; + if (!okA && !okB) return; + var n, span; + if (okA && okB) { + var dx = bx - ax, dy = by - ay; + if (dx < 0) dx = -dx; if (dy < 0) dy = -dy; + span = dx > dy ? dx : dy; // Chebyshev length: how many cells this covers + /* Three samples per cell, not the 1.35 this used to run at. 1.35 does not guarantee a sample + * lands in every cell the line passes through, so a tenth of the cells were simply missed — + * and WHICH tenth changed as the phase drifted, which looked exactly like the dash bug and + * partly was it. Oversampling costs projections, not writes: the duplicate-cell test below + * throws the extra samples away before they reach emit(). */ + n = (span * 3 + 2) | 0; + if (n > 480) n = 480; + } else { n = 48; span = 24; } // one end is behind us; sample generously + var wl = 0, tpm = 0, anchor = 0; + if (dash > 1) { + var wdx = x1 - x0, wdy = y1 - y0, wdz = z1 - z0; + wl = Math.sqrt(wdx * wdx + wdy * wdy + wdz * wdz); + if (wl < 1e-4) wl = 1e-4; + /* Ticks per metre, from the CELL count and never from the sample count: one tick is meant to + * be about one screen cell, so that a run of `dash` ticks reads as one gap and one mark. */ + tpm = Math.pow(2, Math.round(Math.log(span / wl) / Math.LN2)); + if (!(tpm >= TICK_MIN)) tpm = TICK_MIN; else if (tpm > TICK_MAX) tpm = TICK_MAX; + anchor = x0 * 0.37 + y0 * 1.13 + z0 * 0.71; + } + var lx = -9999, ly = -9999, i, u, cx, cy; + for (i = 0; i <= n; i++) { + u = i / n; + if (!project(x0 + (x1 - x0) * u, y0 + (y1 - y0) * u, z0 + (z1 - z0) * u)) { lx = -9999; continue; } + cx = Math.floor(PJ.x); cy = Math.floor(PJ.y); + if (cx === lx && cy === ly) continue; + lx = cx; ly = cy; + if (dash > 1 && (Math.floor((anchor + u * wl) * tpm) % dash)) continue; + emit(f, cx, cy, ch, col, lum, PJ.d); + } + } + + /* ---- street geometry ------------------------------------------------------------------------ + * axis 0 = avenue (runs along +z, so a span crosses in x); axis 1 = cross street (spans z). + * city.js puts street cells at |g - centre| <= halfWidth, so the wall faces sit at centre-hw and + * centre+hw+1 — the +1 is the far edge of the last street cell, and getting it wrong buries an + * anchor a metre inside the building. */ + var SPAN = { c0: 0, c1: 0, mid: 0, w: 0 }; + function streetSpan(axis, idx) { + var c, h; + if (axis) { c = CITY.crossZ(idx); h = CITY.crossW(idx); } + else { c = CITY.aveX(idx); h = CITY.aveW(idx); } + SPAN.c0 = c - h; SPAN.c1 = c + h + 1; + SPAN.mid = c + 0.5; SPAN.w = SPAN.c1 - SPAN.c0; + } + function wx(axis, along, cross) { return axis ? along : cross; } + function wz(axis, along, cross) { return axis ? cross : along; } + + /* Height of the building a span anchors into. Callers pass a `cross` half a metre BEHIND the + * wall face, so the probe can never land on the street cell itself and report a hole. + * Three probes, tallest wins: the frontage is broken by alleys, courtyards and vacant lots + * every few metres, and a single probe dropped roughly half of all spans on the floor — the + * street ended up with no cables at all for fifty metres at a time. A four-metre gap in the + * frontage does not stop a wire being strung from the masonry either side of it. */ + function anchorH(axis, along, cross) { + var a = CITY.height(wx(axis, along, cross), wz(axis, along, cross)); + var b = CITY.height(wx(axis, along - 2.5, cross), wz(axis, along - 2.5, cross)); + var c = CITY.height(wx(axis, along + 2.5, cross), wz(axis, along + 2.5, cross)); + if (b > a) a = b; + return c > a ? c : a; + } + + /* Cheap reject for a whole span before its sample loop runs. Generous lateral margin: the ends + * of a span can be on screen while its midpoint is not. + * + * `near` is the same allowance one axis over, and it defaults to a metre only because most of + * this file hangs its objects overhead, where a span whose MIDPOINT is a metre away is entirely + * past the top of the frame. Street props are the exception and pass their own: a prop is four + * metres long, so its midpoint goes behind the eye plane while half of it is still filling a + * third of the screen, and a test on the midpoint alone deleted it in one frame. Objects that + * survive this test still get clipped exactly, per span, by clipNear() below. */ + function spanVisible(axis, along, cross, near) { + var px = wx(axis, along, cross), pz = wz(axis, along, cross); + var rx = px - V.ox, rz = pz - V.oz; + var w = rx * V.fwx + rz * V.fwz; + if (w < (near === undefined ? 1 : near) || w > V.far) return 0; + var s = rx * V.rgx + rz * V.rgz, lim = w * V.hp + 14; + if (s < -lim || s > lim) return 0; + return w; + } + + /* Index windows either side of the camera. AVE is 30 m and CROSS 26, so these cover the fog + * range in both directions without walking indices that can only produce black. */ + function idxLo(axis) { + return Math.round((axis ? V.oz : V.ox) / (axis ? CITY.CROSS : CITY.AVE)) - (axis ? 5 : 3); + } + function idxHi(axis) { + return Math.round((axis ? V.oz : V.ox) / (axis ? CITY.CROSS : CITY.AVE)) + (axis ? 5 : 3); + } + function alongLo(axis, pitch) { return Math.floor(((axis ? V.ox : V.oz) - V.far) / pitch); } + function alongHi(axis, pitch) { return Math.floor(((axis ? V.ox : V.oz) + V.far) / pitch); } + + /* ============================================================================================ + * 1. SKYBRIDGES — layer 20 + * A tube crossing the canyon overhead. Rare on purpose: one in frame is an event, two is a + * theme park. Drawn as its near face only — the far face is behind it and never resolves at + * this resolution — with a dark soffit that occludes the skyline behind it. + * ========================================================================================== */ + function drawBridges(f) { + if (!CITY) return; + var axis, idx, n, r, along, hA, hB, y, thick, near, hue, sd, w, cnt, i, u, cross; + var rt, rb, r0, r1, row, cx, dd, lit, lastCx, cw, band; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + if (SPAN.w < 5) continue; // an alley cannot carry a bridge + for (n = alongLo(axis, 34); n <= alongHi(axis, 34); n++) { + if (hash2(idx, n, BASE ^ 0x5B12) > 0.46) continue; + along = n * 34 + hash2(idx, n, BASE ^ 0x5B13) * 24; + w = spanVisible(axis, along, SPAN.mid); + if (!w) continue; + hA = anchorH(axis, along, SPAN.c0 - 0.5); + hB = anchorH(axis, along, SPAN.c1 + 0.5); + if (hA < 15 || hB < 15) continue; // needs two buildings, not two shopfronts + sd = BASE ^ (idx * 131 + n * 7919); + y = 9 + hash2(idx, n, BASE ^ 0x5B14) * 14; + r = (hA < hB ? hA : hB) - 3.2; + if (y > r) y = r; + /* Under about 7 m it stops reading as a bridge and starts reading as an awning; the + * eye is at 1.7 and needs to be looking clearly UP at the thing. */ + if (y < 7.5) continue; + thick = 2.3 + hash2(idx, n, BASE ^ 0x5B15) * 1.3; + /* The face we can actually see. Picking the wrong one puts the bridge a few metres out + * of place, which is enough for its shadow edge to disagree with the towers it lands on. */ + near = ((axis ? V.ox : V.oz) < along) ? along - 1.7 : along + 1.7; + r = hash2(idx, n, BASE ^ 0x5B16); + hue = r < 0.55 ? P.azure : (r < 0.90 ? P.amber : P.warm); + + cnt = (SPAN.w * 210 / w) | 0; + if (cnt < 10) cnt = 10; if (cnt > 260) cnt = 260; + lastCx = -99999; + for (i = 0; i <= cnt; i++) { + u = i / cnt; + cross = SPAN.c0 + SPAN.w * u; + if (!project(wx(axis, near, cross), y + thick, wz(axis, near, cross))) continue; + rt = PJ.y; cx = Math.floor(PJ.x); dd = PJ.d; + /* Duplicate screen columns, dropped the way segment3 drops them. At 210 samples per + * projected column the span hits the same cx three or four times running, and each + * repeat was a fresh CC.put at a slightly different depth — so which of them won a + * cell flipped as the camera moved, on top of everything below. */ + if (cx === lastCx) continue; + lastCx = cx; + if (!project(wx(axis, near, cross), y, wz(axis, near, cross))) continue; + rb = PJ.y; + r0 = Math.floor(rt); r1 = Math.floor(rb); + if (r1 < r0) r1 = r0; + if (r1 - r0 > 24) r1 = r0 + 24; // a bridge overhead can fill the screen + /* THE PATTERN IS KEYED ON THE BRIDGE, NEVER ON THE VIEWPORT. + * Every one of these three used to read `cx`, the SCREEN COLUMN — the soffit dash, the + * window band and the band's own brightness hash. A pattern keyed on a screen column + * is welded to the frame, not to the object: the bridge slides across the screen and + * the stripes stay where they are, so the windows crawl along the tube and the soffit + * dashes swim through it. Measured against the world lattice below, 34% of a bridge's + * pattern cells re-rolled between two consecutive frames 27 mm apart. + * `cw` is the distance ALONG THE SPAN in units of 0.625 m, offset by the bridge's own + * seed so neighbouring bridges do not line up. 1.6 units per metre is chosen so one + * unit stays wider than one screen column out to ~60 m, past which fog has the bridge + * anyway: finer than that and the pattern aliases against the column grid, which is + * the same bug wearing a different hat. */ + cw = Math.floor(cross * 1.6) + (sd & 3); + band = cw & 3; + for (row = r0; row <= r1; row++) { + if (row === r0) { emit(f, cx, row, G_EQ, P.slate, 34, dd); continue; } + if (row === r1 && r1 > r0) { // soffit: deck lights, otherwise black mass + /* DECK LIGHTS, and they are what makes the bridge pay for itself. Measured over + * the canonical sweep, this element punched out 8.4 already-visible cells a frame + * and put back 1.1 — a black tube crossing the one part of the frame that has any + * sky in it, contributing nothing but the hole. A tube that big in a city like + * this has lights under it. One every eight units of span, which is five metres, + * so a canyon-width bridge carries three or four: a run, not a strip. + * Amber because a light under a deck is a sodium lamp, and because amber is a + * pillar and this is one of the few places up in the slot that can carry one. + * Half a period off the window band so the two patterns stay legibly separate. */ + if (!(cw & 7)) emit(f, cx, row, G_oo, P.amber, 150, dd); + else emit(f, cx, row, band === 2 ? G_DASH : 0, P.slate, band === 2 ? 15 : 0, dd); + continue; + } + /* One window band, one unit of span in four. The rest of the tube is dark: a lit + * strip that reads as a strip is worth more than a lit rectangle that reads as a + * sign. */ + /* row - r0 and not row: the second argument of the hash has to be an offset from the + * TUBE, because the tube's absolute screen row changes every time the camera takes a + * step and a hash keyed on it re-rolls the window brightness with it. Same bug as + * the column, one axis over, and it survived the first pass at this fix. */ + lit = (row === r0 + 1) && band === 0; + if (lit) emit(f, cx, row, G_8, hue, 150 + hash2(cw, row - r0, sd) * 62, dd); + else emit(f, cx, row, 0, P.shadow, 0, dd); + } + } + } + } + } + } + + /* ============================================================================================ + * 2. ROOFTOP PLANT — layer 21 + * Air handling units and satellite dishes. These only ever resolve on buildings 40 m out and + * further: a near roof projects far above the top of the frame. Their whole job is to stop the + * mid-distance skyline being a row of clean parapets. + * + * PLACED ALONG THE STREET FRONTAGE, for exactly the reason section 3 gives for the masts, and + * this element learned it the expensive way. It used to walk a world lattice over the whole + * city, which sounds more general and is strictly worse: raycast.js paints walls and never roof + * surfaces, so a box standing five metres back from the parapet is hidden behind its own + * building's front wall — that wall is nearer, projects higher, and wins the depth test. Only + * the front metre or two of any roof is ever on the silhouette. Measured over the canonical + * sweep the lattice version put 6.6 cells a frame into the picture, of which NOT ONE printed + * over v=60: an element slot spent on hidden geometry. The frontage walk enumerates the strip + * that is actually visible, and it is welded to the world in exactly the same way — a lattice + * along the street rather than across the city. + * ========================================================================================== */ + function drawPlant(f) { + if (!CITY) return; + var axis, idx, n, side, r, along, cross, px, pz, w, h, top, wide, tall; + var x0, y0, x1, y1, cx0, cx1, ry0, ry1, col, row, dd, lum; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + for (n = alongLo(axis, 9); n <= alongHi(axis, 9); n++) { + for (side = 0; side < 2; side++) { + r = hash2(idx * 2 + side, n, BASE + 0x7A0F); + if (r > 0.30) continue; // hash first: height() is the expensive part + along = n * 9 + hash2(idx * 2 + side, n, BASE + 0x7A10) * 7; + /* 1.4 m back from the wall face, which is far enough that the box stands ON the roof + * rather than floating off the front of it and near enough to stay on the silhouette. */ + cross = side ? SPAN.c1 + 1.4 : SPAN.c0 - 1.4; + w = spanVisible(axis, along, cross); + if (!w || w < 14) continue; // nearer than that, the roof is off the top + px = wx(axis, along, cross); pz = wz(axis, along, cross); + h = CITY.height(px, pz); + if (h < 7) continue; + + if (r < 0.08) { + /* Dish. 'U' is the only glyph in the table that reads as a tilted parabola; the stem + * below it is what stops it looking like a stray letter on the skyline. */ + if (!project(px, h + 1.5, pz)) continue; + dd = PJ.d; col = Math.floor(PJ.x); row = Math.floor(PJ.y); + emit(f, col, row, G_U, hash2(idx * 2 + side, n, BASE + 0x7A12) < 0.7 ? P.slate : P.white, 52, dd); + emit(f, col, row + 1, G_COLON, P.slate, 26, dd); + continue; + } + /* Plant box. Two rows at most — measured against the harness, a third row of housing + * turns a skyline accent into a second parapet. */ + top = h + 1.1 + r * 2.9; + wide = 1.5 + r * 3.8; + if (!project(px - wide * 0.5, top, pz)) continue; + x0 = PJ.x; y0 = PJ.y; dd = PJ.d; + if (!project(px + wide * 0.5, h, pz)) continue; + x1 = PJ.x; y1 = PJ.y; + cx0 = Math.floor(x0); cx1 = Math.floor(x1); + if (cx1 < cx0) { tall = cx0; cx0 = cx1; cx1 = tall; } + if (cx1 - cx0 > 9) cx1 = cx0 + 9; + ry0 = Math.floor(y0); ry1 = Math.floor(y1); + if (ry1 > ry0 + 2) ry1 = ry0 + 2; + for (row = ry0; row <= ry1; row++) { + lum = row === ry0 ? 46 : 28; // only the top deck catches the skyglow + for (col = cx0; col <= cx1; col++) + emit(f, col, row, row === ry0 ? G_EQ : G_HASH, P.slate, lum, dd); + } + } + } + } + } + } + + /* ============================================================================================ + * 3. MASTS AND AERIAL LAMPS — layer 22 + * The only place red is allowed to lead, and it is three or four cells of it in the whole frame. + * Lamps carry their own phase so a skyline of them never pulses in unison. + * + * Placed along the street FRONTAGE rather than on a lattice over the roofs, which is not a + * stylistic choice: raycast.js paints walls and never roof surfaces, so a mast standing back + * from the parapet is hidden behind its own building's front wall — that wall is nearer, so it + * projects higher and wins the depth test. Only the front metre of a roof is ever on the + * silhouette, and that is exactly what the frontage walk enumerates. + * ========================================================================================== */ + function drawMasts(f) { + if (!CITY) return; + var axis, idx, n, side, r, along, cross, h, mh, col, row, rowTop, dd, k, ph, blink; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + for (n = alongLo(axis, 15); n <= alongHi(axis, 15); n++) { + for (side = 0; side < 2; side++) { + r = hash2(idx * 2 + side, n, BASE ^ 0x2E10); + if (r > 0.30) continue; + along = n * 15 + hash2(idx * 2 + side, n, BASE ^ 0x2E11) * 11; + /* A metre back from the face so the mast stands ON the roof; any further and its foot + * disappears behind the parapet it is supposed to be bolted to. */ + cross = side ? SPAN.c1 + 1.0 : SPAN.c0 - 1.0; + if (!spanVisible(axis, along, cross)) continue; + h = CITY.height(wx(axis, along, cross), wz(axis, along, cross)); + /* 11 m, down from 14. Not a loosening for its own sake: a mast can only enter the + * frame at all beyond about fifty metres, because a nearer roofline projects above the + * top of it — (h - eye) * scale / d has to fall under `horizon` before the mast's own + * FOOT is on screen — and out there fog has most of what it draws. Dropping the gate + * by three metres brings the 25-40 m band into play, which is the only part of the + * street where a mast is not already half fog. Below about ten metres it stops being a + * mast on a building and becomes a flagpole on a shop. */ + if (h < 11) continue; + + mh = 3.5 + r * 26 + (h > 55 ? 9 : 0); // landmarks carry the tall ones + if (!project(wx(axis, along, cross), h + mh, wz(axis, along, cross))) continue; + col = Math.floor(PJ.x); rowTop = Math.floor(PJ.y); dd = PJ.d; + if (rowTop >= V.rows) continue; // whole mast below the roofline we can see + if (!project(wx(axis, along, cross), h, wz(axis, along, cross))) continue; + row = Math.floor(PJ.y); + if (row - rowTop > 30) row = rowTop + 30; + + /* Shaft, dashed. A solid column of '|' at this scale reads as a lit edge rather than + * as a wire frame against the sky. */ + for (k = rowTop + 1; k <= row; k++) + if (!((k - rowTop) & 1) || (k - rowTop) < 3) + emit(f, col, k, G_PIPE, P.slate, 26, dd); + /* A third of them are lattice aerials rather than plain poles: two stub arms, no more. */ + if (hash2(idx * 2 + side, n, BASE ^ 0x2E13) < 0.34 && row - rowTop > 4) { + k = rowTop + 2; + emit(f, col - 1, k, G_DASH, P.slate, 22, dd); + emit(f, col + 1, k, G_DASH, P.slate, 22, dd); + emit(f, col, rowTop + 1, G_Y, P.slate, 30, dd); + } + ph = V.t * 0.55 + hash2(idx * 2 + side, n, BASE ^ 0x2E14); + blink = CC.reducedMotion ? 0.72 : ((ph - Math.floor(ph)) < 0.34 ? 1 : 0.16); + emitLamp(f, col, rowTop, blink > 0.5 ? G_STAR : G_PLUS, P.red, 78 + 150 * blink, dd); + /* Tall masts carry a second lamp partway down; that pair is what makes height read. */ + if (mh > 22 && row - rowTop > 12) + emitLamp(f, col, rowTop + ((row - rowTop) >> 1), G_PLUS, P.red, 40 + 90 * blink, dd); + } + } + } + } + } + + /* ============================================================================================ + * 4. FIRE ESCAPES — layer 23 + * Hung 0.42 m proud of the wall, which is both true of real ironwork and what keeps the whole + * assembly strictly nearer than the facade so it passes the depth test instead of z-fighting it. + * Landings and stair flights only: the balustrades and the rail returns are sub-cell at every + * distance this thing survives to, and drawing them cost 40% more coverage for no read at all. + * + * The zig-zag is spent only on walls we see enough of. A canyon wall running away from the + * camera foreshortens the along-wall axis into pure depth, so a 3.3 m flight lands as a single + * unbroken diagonal twenty-five rows tall — a scratch across the frame, not a staircase. Below + * five columns of projected width the flights are dropped and the landings alone remain, which + * reads as balcony ledges: correct for that viewing angle and a tenth of the cells. + * ========================================================================================== */ + function drawEscapes(f) { + if (!CITY) return; + var axis, idx, n, side, r, along, plane, h, top, y, lev, wdt, dd, dir, a0, a1, lum, pw, flights; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + for (n = alongLo(axis, 11); n <= alongHi(axis, 11); n++) { + for (side = 0; side < 2; side++) { + r = hash2(idx * 2 + side, n, BASE ^ 0x3E5C); + if (r > 0.18) continue; + along = n * 11 + hash2(idx * 2 + side, n, BASE ^ 0x3E5D) * 7.5; + dd = spanVisible(axis, along, side ? SPAN.c1 : SPAN.c0); + if (!dd) continue; + h = anchorH(axis, along, side ? SPAN.c1 + 0.5 : SPAN.c0 - 0.5); + if (h < 12) continue; + plane = side ? SPAN.c1 - 0.42 : SPAN.c0 + 0.42; + top = h - 1.7; if (top > 21) top = 21; + wdt = 1.15 + r * 2.2; // half-width along the wall + /* Fog crushes anything past ~70 m to nothing, and drawing an invisible lattice is + * still 80 cells of work per escape. */ + /* Nearer than about twelve metres a single 3.3 m flight is twenty-odd rows tall and + * all you get is a fragment of one diagonal; past seventy fog has crushed it to + * nothing and the eighty cells of work go straight in the bin. */ + if (dd > 74 || dd < 12) continue; + + a0 = along - wdt; a1 = along + wdt; + if (!project(wx(axis, a0, plane), 8, wz(axis, a0, plane))) continue; + pw = PJ.x; + if (!project(wx(axis, a1, plane), 8, wz(axis, a1, plane))) continue; + pw = PJ.x - pw; if (pw < 0) pw = -pw; + if (pw < 2.2) continue; // edge-on: nothing here would read at all + flights = pw >= 5; + lev = 0; + for (y = 2.9; y < top; y += 3.3, lev++) { + /* One landing per escape is lit from inside — a door left open. This is the only + * warm cell in the whole element and it is what stops the escape reading as dirt. */ + lum = (lev === 1 && r < 0.06) ? 62 : 33; + segment3(f, wx(axis, a0, plane), y, wz(axis, a0, plane), + wx(axis, a1, plane), y, wz(axis, a1, plane), + G_EQ, (lev === 1 && r < 0.06) ? P.amber : P.slate, lum, 3); + if (!flights || y + 3.3 >= top) continue; + /* The zig-zag. Flights alternate direction, which is the whole silhouette of a fire + * escape and reads even when the landings have fogged out. Drawn every other cell: + * a solid diagonal is a scratch, a broken one is a run of treads. */ + dir = (lev & 1) ? 1 : -1; + segment3(f, wx(axis, along - wdt * dir, plane), y, wz(axis, along - wdt * dir, plane), + wx(axis, along + wdt * dir, plane), y + 3.3, wz(axis, along + wdt * dir, plane), + dir > 0 ? G_SL : G_BS, P.slate, 24, 2); + } + } + } + } + } + } + + /* ============================================================================================ + * 5. CABLES — layer 24 + * Power and tram feed strung wall to wall. The sag is a parabola, not a true catenary: over a + * span this short the two differ by well under a character cell, and the parabola costs one + * multiply. Cables are drawn as an unbroken run — the one thing in this file that must not be + * dashed, because a dashed wire stops being a wire. + * ========================================================================================== */ + function drawCableRun(f, axis, along, c0, c1, yA, yB, sag, col, lum, w) { + var cnt = ((c1 - c0) * 220 / w) | 0; + if (cnt < 12) cnt = 12; if (cnt > 300) cnt = 300; + var lx = -9999, ly = -9999, i, u, cross, y, cx, cy, dy, ch, k; + for (i = 0; i <= cnt; i++) { + u = i / cnt; + cross = c0 + (c1 - c0) * u; + y = yA + (yB - yA) * u - sag * 4 * u * (1 - u); + if (!project(wx(axis, along, cross), y, wz(axis, along, cross))) { lx = -9999; continue; } + cx = Math.floor(PJ.x); cy = Math.floor(PJ.y); + if (cx === lx && cy === ly) continue; + if (lx === -9999) ch = G_DASH; + else { + dy = cy - ly; + /* Near the anchors the wire climbs faster than one row per column; those rows have to be + * bridged or the cable arrives at the wall in pieces. */ + if (dy > 1 || dy < -1) { + for (k = ly + (dy > 0 ? 1 : -1); k !== cy; k += (dy > 0 ? 1 : -1)) + emit(f, cx, k, G_PIPE, col, lum, PJ.d); + ch = G_PIPE; + } else ch = dy === 0 ? G_DASH : (dy > 0 ? G_BS : G_SL); + } + emit(f, cx, cy, ch, col, lum, PJ.d); + lx = cx; ly = cy; + } + } + + function drawCables(f) { + if (!CITY) return; + var axis, idx, n, r, along, hA, hB, yA, yB, sag, w, tram, lum; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + /* One span in four, every 26 m. Two visible cables read as a canyon that is wired; five + * read as scaffolding, and at 200x60 they were costing more coverage than every other + * element in this file put together. */ + for (n = alongLo(axis, 26); n <= alongHi(axis, 26); n++) { + r = hash2(idx, n, BASE ^ 0x1CAB); + if (r > 0.26) continue; + along = n * 26 + hash2(idx, n, BASE ^ 0x1CAC) * 18; + w = spanVisible(axis, along, SPAN.mid); + if (!w) continue; + hA = anchorH(axis, along, SPAN.c0 - 0.5); + hB = anchorH(axis, along, SPAN.c1 + 0.5); + if (hA < 8 || hB < 8) continue; + yA = 6.5 + hash2(idx, n, BASE ^ 0x1CAD) * 6.5; + /* The two ends differ by barely a metre and the sag is 8-15% of the span. Both numbers + * are picked against each other, not from a catalogue: at the first attempt the ends + * could disagree by 1.7 m, which at 15 m out is seven screen rows of tilt against four + * of sag — every cable in the city came out a straight diagonal ramp and the whole + * point of hanging them was lost. */ + yB = yA + (hash2(idx, n, BASE ^ 0x1CAE) - 0.5) * 1.2; + if (yA > hA - 1.4) yA = hA - 1.4; + if (yB > hB - 1.4) yB = hB - 1.4; + if (yA < 5 || yB < 5) continue; + sag = SPAN.w * (0.075 + hash2(idx, n, BASE ^ 0x1CAF) * 0.075); + /* Brighter than a real wire deserves. At lum 25 a fogged cable was arithmetically + * present and visually absent — slate at 19/255 does not survive the bloom pass. */ + tram = r < 0.10; + lum = tram ? 62 : 44; + drawCableRun(f, axis, along, SPAN.c0, SPAN.c1, yA, yB, sag, P.slate, lum, w); + /* A tram feed is a pair — contact wire and catenary — and only close enough to resolve + * as two. Doubling every span would double the cheapest element into the dearest. */ + if (tram && w < 46) + drawCableRun(f, axis, along, SPAN.c0, SPAN.c1, yA - 1.15, yB - 1.15, + sag * 0.55, P.slate, 34, w); + } + } + } + } + + /* ============================================================================================ + * 6. LANTERNS AND PENNANTS — layer 26 + * Strung low over the street. The cord is deliberately NOT drawn: at night an unlit cord is + * invisible and the lanterns float, which is both what the reference frames show and about + * eight cells per string instead of eighty. + * ========================================================================================== */ + function drawLanterns(f) { + if (!CITY) return; + var axis, idx, n, r, along, hA, hB, y, sag, w, cnt, i, u, cross, yy, hue, sd, flick, lum; + var col, row, dd, pennant, swing, ph; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + for (n = alongLo(axis, 14); n <= alongHi(axis, 14); n++) { + r = hash2(idx, n, BASE ^ 0x4A17); + if (r > 0.46) continue; + along = n * 14 + hash2(idx, n, BASE ^ 0x4A18) * 10; + w = spanVisible(axis, along, SPAN.mid); + if (!w) continue; + hA = anchorH(axis, along, SPAN.c0 - 0.5); + hB = anchorH(axis, along, SPAN.c1 + 0.5); + if (hA < 6 || hB < 6) continue; + y = 4.6 + hash2(idx, n, BASE ^ 0x4A19) * 1.9; + sag = 0.30 + r * 1.4; + sd = BASE ^ (idx * 613 + n * 4099); + /* Own hash, not the existence roll: keying hue off `r` ties the colour to how likely the + * string was, and every rare string in the city comes out the same colour. Paper red is + * the one place ember leads, and it stays a minority even here. */ + hue = (r = hash2(idx, n, BASE ^ 0x4A1B)) < 0.26 ? P.ember : (r < 0.40 ? P.warm : P.amber); + pennant = hash2(idx, n, BASE ^ 0x4A1A) < 0.34; + cnt = (SPAN.w / 1.9) | 0; if (cnt < 4) cnt = 4; + /* Wind. The string is strung ACROSS the canyon, so a wind blowing down it pushes the + * lanterns ALONG the street — that is why the displacement goes into `along` and not + * into `cross`, which would only make the string longer and shorter. The lift is the + * other half of it: a lantern that swings sideways without rising reads as a slider on + * a rail. Both scale off the one gust magnitude the whole file shares, so the paper + * lanterns, the banners and the washing all move on the same weather. */ + swing = W_GUST * (0.34 + r * 0.30) * W_SWAY; + for (i = 0; i < cnt; i++) { + u = (i + 0.5) / cnt; + cross = SPAN.c0 + SPAN.w * u; + yy = y - sag * 4 * u * (1 - u); + /* Neighbours on one cord swing very nearly together — i * 0.22 is a lag along the + * string, not eight independent pendulums, which is what a cord physically does. */ + ph = Math.sin(V.tt * 1.25 + (sd & 31) * 0.19 + i * 0.22); + yy += swing * 0.13 * (ph > 0 ? ph : -ph); + if (!project(wx(axis, along + swing * ph, cross), yy, + wz(axis, along + swing * ph, cross))) continue; + col = Math.floor(PJ.x); row = Math.floor(PJ.y); dd = PJ.d; + /* Paper lanterns breathe rather than flicker; keyed on the string seed and t alone so + * they cannot boil as the camera walks past. */ + flick = CC.reducedMotion ? 0.94 + : 0.80 + 0.24 * vnoise(V.t * 1.7 + i * 0.7 + (sd & 255) * 0.13, 0x4A1); + lum = (168 + hash2(i, n, sd) * 60) * flick; + emit(f, col, row, LANTERN_G[(hash2(i, 0, sd) * 4) | 0], hue, lum, dd); + if (pennant && (i & 1)) + emit(f, col, row + 1, G_V, hue, lum * 0.26, dd); + } + } + } + } + } + + /* ============================================================================================ + * 7. STREET PROPS — layer 19 + * + * The complaint this element answers is specific: the canyon was over-furnished at the roofline + * and empty at eye level. Everything above was bolted on at 8-25 m — bridges, cables, masts, + * lanterns — and the first two metres of the street, which is the part a walking viewer is + * actually standing in, carried nothing but tarmac and the shopfront band behind it. + * + * HOW A PROP EARNS ITS CELLS. Almost all of these are drawn the way street.js draws a person: + * as a hole. CC.put with ch 0 / lum 0 at the prop's depth punches its silhouette out of the lit + * facade behind it, which costs no light at all and reads immediately, because the shopfronts + * ARE the light down here. On top of that hole each prop gets between one and a dozen genuinely + * lit cells — a vending machine's face, a warm sliver under a half-shut shutter, the glow coming + * up out of a stairwell. That split is the whole budget story: the group adds silhouette almost + * for free and buys its lit coverage back one small light source at a time. + * + * DRAW ORDER INSIDE A PROP. Lit detail first, dark mass second, and the mass is pushed 5 cm + * further from the street so it is unambiguously behind. CC.put wants a STRICT improvement in + * depth, so a carcass drawn at the same plane as the face it surrounds would lose ties — but + * "the same plane" is only true to the precision of two different sample positions along the + * prop, and where the carcass won a column by a millimetre it swallowed the lit cell. The 5 cm + * makes the ordering a fact about the geometry rather than a fact about rounding. + * + * PLACEMENT is a world lattice per side of each corridor, hashed exactly as everything else in + * this file is: walk it and a prop stays welded to its lot. A prop needs a frontage to belong to, + * so a lot with no building on it (anchorH under 3 m) is skipped — a call box standing alone in + * a vacant lot reads as a bug, not as a call box. + * ========================================================================================== */ + var K_VEND = 0, K_SHUTTER = 1, K_BOLLARD = 2, K_CRATES = 3, K_AC = 4, + K_BANNER = 5, K_CALLBOX = 6, K_LADDER = 7, K_PLANTER = 8, K_HOARD = 9, K_SCAFF = 10, + K_SHELTER = 11, K_NEWSBOX = 12, K_STAIR = 13, K_WASH = 14; + + /* The deal. Repeated slots are the weights, and they are weighted by what each prop is FOR: + * refuse and vending are the two things a real street has every few doors, the light sources are + * common because they are the reason this element exists, and the big assemblies — scaffolding, + * a bus shelter, a hoarding — get one slot each because two of them in one frame is a set. + * + * THREE KINDS WERE CUT, and the census that cut them is the argument. Over the canonical sweep + * (4 seeds x 4 frames at 400x100, every prop diffed against the frame it drew into): the bicycle + * came out at a MEDIAN OF SEVEN CELLS in a 2x5 box and a best-in-sweep of 33, which is a diagonal + * scratch of slate '/' whose slope argues with the perspective around it; the wall dish at six + * cells in 5x3 and a best of 11; the pavement grate turned up ONCE in sixteen frames, thirteen + * cells of lum-22 slate lying flat on tarmac. None of the three put a single cell over v=60 in + * the whole sweep. They were detail at a scale this renderer does not have, and cells spent on + * them are cells not spent on silhouette. + * + * Their four slots went to the two kinds the same census says do read: the vending machine (10 + * instances, 108 cells per frame over v=60 — on its own the best small light source in the + * build) and the half-shut shutter (534 cells at 36x20 in the median, whose amber slat ribs are + * unmistakable at street level), plus one to the call box, which is the only other prop that + * pairs a dark cabinet with a lit panel and keeps a run of vending machines from becoming a + * row of vending machines. The news box stays: 22 cells is small, but it is a chest-high box + * with a lit ember face and it is the only ember at eye level. */ + var KIND = new Uint8Array([ + K_VEND, K_VEND, K_VEND, K_VEND, K_VEND, + K_CRATES, K_CRATES, K_CRATES, + K_SHUTTER, K_SHUTTER, + K_BOLLARD, K_BOLLARD, + K_AC, K_AC, + K_CALLBOX, K_CALLBOX, + K_PLANTER, K_NEWSBOX, + K_LADDER, K_BANNER, + K_STAIR, K_SHELTER, K_HOARD, K_WASH, K_SCAFF + ]); + + var STY_FLAT = 0, STY_RIB = 1, STY_MESH = 2; + + /* NEAR-PLANE CLIP OF A PANEL'S SPAN. + * This is the fix for the worst pop in the build. panel() used to bail on the WHOLE panel the + * instant one of its two ends failed to project, and project() fails at w < 0.4 — the eye plane. + * A 4.2 m hoarding walked past at arm's length has its trailing end behind that plane while the + * rest of it still covers a third of the screen, and almost every prop is mostly a black + * occluder plate, so the frame lost a plate the size of a wall between one frame and the next. + * Measured at seed 3, 400x100: at t=68.750 s streetprops owned 4664 cells (11.7% of the frame) + * and at t=68.767 s it owned 110, and the whole-frame printed mean stepped 16.94% -> 20.79% of + * full scale in that single frame. + * + * Note what it was NOT: nothing was culled by spanVisible, and both frames drew the same thirty + * props. The object did not leave; one of its corners crossed the eye plane. + * + * The cure is to clip the span rather than drop it. Both w (forward distance) and s (lateral + * offset) are AFFINE in u along a straight world span, so "in front of the eye plane" is one + * linear inequality and the surviving interval is exact — no iteration, no allocation. The panel + * now walks off the edge of the frame over the two seconds the geometry says it should take, + * instead of switching off. 0.42 rather than 0.40 so the endpoint projection below cannot fail + * on the rounding of the same comparison. */ + var CLIP = { u0: 0, u1: 1 }; + function clipNear(axis, a0, a1, cross) { + var rx = wx(axis, a0, cross) - V.ox, rz = wz(axis, a0, cross) - V.oz; + var g0 = rx * V.fwx + rz * V.fwz - 0.42; + rx = wx(axis, a1, cross) - V.ox; rz = wz(axis, a1, cross) - V.oz; + var g1 = rx * V.fwx + rz * V.fwz - 0.42; + if (g0 < 0 && g1 < 0) return false; // the whole span is behind us + CLIP.u0 = 0; CLIP.u1 = 1; + if (g0 < 0) CLIP.u0 = g0 / (g0 - g1); + else if (g1 < 0) CLIP.u1 = g0 / (g0 - g1); + return true; + } + + /* One flat panel standing in the world: a0..a1 along the street, y0..y1 in height, at a fixed + * distance `cross` from the corridor centre. Drawn ONE SAMPLE PER SCREEN COLUMN, so a crate at + * three metres and the same crate at forty cost the same number of writes. + * + * The column is the loop variable and the world point is solved for, rather than the other way + * round. Marching uniformly along the span and taking whatever column each sample lands in is + * the obvious way to write this and it fails exactly where it matters most: the projection is a + * Möbius map, its screen density goes as 1/w^2, and once the span is allowed to reach the eye + * plane the two ends differ in density by a factor of thirty or more. A uniform march then + * leaves multi-column gaps in the near end of a black plate — holes in a silhouette, which read + * as tearing. Inverting sp(u) = (s0 + ds*u)/(w0 + dw*u) for the column centre costs one divide + * and lands exactly one sample in every column the panel covers, at any distance. + * + * The pattern lattice is the panel's own: `a` is a world coordinate and `row - r0` is an offset + * from the panel's top edge, so neither re-rolls when the camera takes a step. Keying either on + * the screen is the bug the skybridge comment above documents at length, and it is even louder + * on a two-metre object than on a bridge. */ + function panel(f, axis, a0, a1, cross, y0, y1, ch, col, lum, jit, sty, sd) { + if (!clipNear(axis, a0, a1, cross)) return; + var b0 = a0 + (a1 - a0) * CLIP.u0, b1 = a0 + (a1 - a0) * CLIP.u1; + var rx = wx(axis, b0, cross) - V.ox, rz = wz(axis, b0, cross) - V.oz; + var w0 = rx * V.fwx + rz * V.fwz, s0 = rx * V.rgx + rz * V.rgz; + rx = wx(axis, b1, cross) - V.ox; rz = wz(axis, b1, cross) - V.oz; + var w1 = rx * V.fwx + rz * V.fwz, s1 = rx * V.rgx + rz * V.rgz; + var dw = w1 - w0, ds = s1 - s0; + var xa = s0 / w0 * V.colK + V.colMid, xb = s1 / w1 * V.colK + V.colMid; + var j0 = Math.floor(xa < xb ? xa : xb), j1 = Math.floor(xa < xb ? xb : xa); + if (j1 < 0 || j0 >= V.cols) return; + if (j0 < 0) j0 = 0; + if (j1 > V.cols - 1) j1 = V.cols - 1; + var j, sp, den, u, a, rt, rb, r0, r1, row, dd, lat, l, tmp, pat, fade; + for (j = j0; j <= j1; j++) { + sp = (j + 0.5 - V.colMid) / V.colK; + den = sp * dw - ds; + /* A panel that projects into a single column has no gradient to invert; take its middle. */ + u = (den > 1e-9 || den < -1e-9) ? (s0 - sp * w0) / den : 0.5; + if (u < 0) u = 0; else if (u > 1) u = 1; + a = b0 + (b1 - b0) * u; + if (!project(wx(axis, a, cross), y1, wz(axis, a, cross))) continue; + rt = PJ.y; dd = PJ.d; + /* THE APPROACH DISSOLVE, and it is here because the camera genuinely walks THROUGH these + * things. A kerb prop stands at wallC + 1.55 m and the walk runs about a metre and a half + * off the wall, so the two planes are the same plane to within a few centimetres several + * times a minute. Clipping alone is honest about that and unwatchable: at seed 3 f2738 the + * scaffold netting the camera is 0.49 m from covered the ENTIRE frame in a dotted veil. + * A fade cannot be done in luminance, because most of a prop is a black occluder plate and + * a black plate has no brightness to take away. It is done in COVERAGE instead: each cell + * keeps a fixed random rank on the panel's own lattice, and the panel drops the cells whose + * rank is above the fade. Cells then leave ONE AT A TIME as the viewer closes the last two + * metres, so there is no frame where anything steps, and the near end of a long panel + * dissolves before its far end, which is the way an object you are walking into should go. + * 3.0 m is where a prop on the walk line starts to be a wall rather than an object, and by + * 1.2 m it is closer than the eye can focus. */ + fade = (dd - 1.2) * 0.5556; + if (fade <= 0) continue; + if (fade > 1) fade = 1; + if (!project(wx(axis, a, cross), y0, wz(axis, a, cross))) continue; + rb = PJ.y; + r0 = Math.floor(rt); r1 = Math.floor(rb); + if (r1 < r0) { tmp = r0; r0 = r1; r1 = tmp; } + /* The pattern's row origin is the panel's OWN top edge, captured before the frame clip + * below moves it. Keyed on the clipped r0 the rib and mesh phases re-roll the moment a near + * panel's top leaves the screen, which is the viewport-welded pattern this file spends four + * paragraphs on elsewhere, in the one place it is largest on screen. */ + pat = r0; + /* CLIP TO THE FRAME. Capping the raw run at N rows from its top looks like the same thing + * and is not: a prop close enough for its top edge to leave the screen has a hugely negative + * r0, so `r1 = r0 + N` cut the run off ABOVE the first visible row and the whole prop + * silently disappeared exactly when it was largest. The frame clip is also the whole write + * budget — at most rows+2 cells per column — so the fixed 60-row cap that used to follow it + * is not just redundant, it is wrong on any frame taller than sixty: it sliced the bottom + * off a near prop with a horizontal edge that has no business being there. */ + if (r0 < -1) r0 = -1; + if (r1 > V.rows) r1 = V.rows; + lat = Math.floor(a * 4.7) + (sd & 15); + for (row = r0; row <= r1; row++) { + /* The rank is drawn on the panel's lattice, never on the screen: a rank keyed on the cell + * would re-roll every frame and the dissolve would boil instead of erode. Additive salt — + * see street.js:467; an XOR of the seed is data-dependent and correlates with the jitter + * hash two lines below, which shares its two coordinates. */ + if (fade < 1 && hash2(lat, row - pat, sd + 0x51) > fade) continue; + l = lum; + if (sty === STY_RIB) { if ((row - pat) & 1) l *= 0.32; } + else if (sty === STY_MESH && ((lat + row - pat) & 1)) continue; + if (jit) l += hash2(lat, row - pat, sd) * jit; + emit(f, j, row, ch, col, l, dd); + } + } + } + + /* One cell at one world point. `bias` pulls the write a fraction toward the eye, and every mark + * that lies ON THE PAVEMENT needs it: the tarmac under a prop is at very nearly the prop's own + * depth, CC.put wants a strict improvement, and a spill pool drawn at the road's exact distance + * loses every tie and is simply never seen. street.js hit this first and calls it near(). */ + function pcell(f, axis, a, cross, y, ch, col, lum, bias) { + if (!project(wx(axis, a, cross), y, wz(axis, a, cross))) return; + emit(f, Math.floor(PJ.x), Math.floor(PJ.y), ch, col, lum, PJ.d * bias); + } + + /* ---- the props themselves -------------------------------------------------------------------- + * Each takes the corridor axis, its position along the street, the plane of the building face, + * the sign that points from that face toward the street centre, its own seed and its distance. + * `wp` is the prop face (0.45 m proud of the wall, which is both true of a real machine and what + * keeps it strictly nearer than the facade), `kp` the kerb, `bp` the back plane the dark mass + * goes on. */ + function propVend(f, axis, a, wp, kp, inw, sd, dd) { + var q = hash2(1, 0, sd); + /* A vending machine is the best small light source this genre has, so it is allowed to be one + * of the two pillars nearly every time; spring is the one in five that makes a row of them + * read as different machines rather than one machine repeated. */ + var hue = q < 0.44 ? P.azure : (q < 0.82 ? P.amber : P.spring); + panel(f, axis, a - 0.44, a + 0.44, wp, 0.60, 1.74, G_8, hue, 92, 58, STY_FLAT, sd); + panel(f, axis, a - 0.58, a + 0.58, wp - inw * 0.05, 0, 2.04, 0, P.shadow, 0, 0, STY_FLAT, sd); + // The top edge is the only part of the carcass that catches the street lamp above it. + panel(f, axis, a - 0.58, a + 0.58, wp - inw * 0.05, 1.98, 2.06, G_EQ, P.slate, 40, 0, STY_FLAT, sd); + /* The pool of its own light on the wet pavement. This is what makes the machine a LAMP rather + * than a bright rectangle, and it is three cells. Wet weather doubles it, which is the cheapest + * weather cue in the file. */ + var wl = 26 + 30 * W_WET; + pcell(f, axis, a - 0.30, wp + inw * 0.55, 0.02, G_COMMA, hue, wl, 0.985); + pcell(f, axis, a, wp + inw * 0.75, 0.02, G_COLON, hue, wl * 1.2, 0.985); + pcell(f, axis, a + 0.30, wp + inw * 0.55, 0.02, G_DOT, hue, wl, 0.985); + } + + function propShutter(f, axis, a, wp, kp, inw, sd, dd) { + /* Half down: corrugation above, and under it the sliver of the shop that is still open. The + * sliver is the point — a fully shut shutter is a dark rectangle and there are enough of those + * already. */ + /* The sliver is 30 cm and meshed, and both numbers are the difference between a shop that is + * still open and a light box: walk past this at six metres and the panel projects forty rows + * tall, so a warm slab the full width of the opening was the brightest object in the frame and + * put warm — a support swatch, capped at 8% of lit energy — over the two pillars on its own. */ + panel(f, axis, a - 1.30, a + 1.30, wp, 0.18, 0.48, G_UNDER, P.warm, 76, 30, STY_MESH, sd); + panel(f, axis, a - 1.35, a + 1.35, wp - inw * 0.05, 0, 1.16, 0, P.shadow, 0, 0, STY_FLAT, sd); + panel(f, axis, a - 1.40, a + 1.40, wp, 1.16, 2.72, G_EQ, P.slate, 30, 10, STY_RIB, sd); + // The bottom rail of the shutter itself, which is the line that says "half down". + panel(f, axis, a - 1.40, a + 1.40, wp + inw * 0.03, 1.16, 1.24, G_DASH, P.slate, 54, 0, STY_FLAT, sd); + pcell(f, axis, a, wp + inw * 0.6, 0.02, G_COLON, P.warm, 30 + 26 * W_WET, 0.985); + } + + function propBollard(f, axis, a, wp, kp, inw, sd, dd) { + /* Four posts on the kerb. A row is what reads; one post is a stray mark. */ + var i, aa; + for (i = 0; i < 4; i++) { + aa = a - 1.65 + i * 1.1; + segment3(f, wx(axis, aa, kp), 0.02, wz(axis, aa, kp), + wx(axis, aa, kp), 0.86, wz(axis, aa, kp), G_PIPE, P.slate, 34, 1); + // The reflective band, which is the only reason a bollard is visible at night. + pcell(f, axis, aa, kp, 0.90, G_oo, P.white, 74, 1); + } + } + + function propCrates(f, axis, a, wp, kp, inw, sd, dd) { + /* Refuse against the wall: two stacks of crates and a heap of sacks beside them. Pure + * silhouette apart from the top edges — this is mass, and mass is what the bottom of a wall + * needs. + * + * TWO STACKS AND NOT ONE. It was a single 1 m box of '#' with one lit edge along the top, and + * at the near end of its range that is 250-odd cells of uniform hatch in a rectangle: read as + * a patch of wall texture rather than as an object, because nothing inside it says where one + * thing ends and the next begins. The break costs one extra panel and one extra lit edge. The + * edges are slate, deliberately: this is structure catching the street lamp, not a light, and + * the two heights are what makes the silhouette say "stacked". */ + var hL = 1.26, hR = 0.94 + hash2(3, 0, sd) * 0.22; + panel(f, axis, a - 0.85, a - 0.34, wp - inw * 0.05, 0, hL, G_HASH, P.shadow, 16, 8, STY_FLAT, sd); + panel(f, axis, a - 0.85, a - 0.34, wp, hL - 0.08, hL + 0.02, G_EQ, P.slate, 44, 0, STY_FLAT, sd); + panel(f, axis, a - 0.34, a + 0.15, wp - inw * 0.05, 0, hR, G_HASH, P.shadow, 14, 8, STY_FLAT, sd); + panel(f, axis, a - 0.34, a + 0.15, wp, hR - 0.08, hR + 0.02, G_EQ, P.slate, 36, 0, STY_FLAT, sd); + panel(f, axis, a + 0.15, a + 0.92, wp - inw * 0.05, 0, 0.62, G_oo, P.shadow, 14, 8, STY_FLAT, sd); + /* The odd crate left on top of the taller stack, with its own edge so it reads as a separate + * box rather than as the stack having grown. */ + if (hash2(4, 0, sd) < 0.4) { + panel(f, axis, a - 0.78, a - 0.40, wp + inw * 0.10, hL, hL + 0.44, G_HASH, P.shadow, 15, 8, STY_FLAT, sd); + panel(f, axis, a - 0.78, a - 0.40, wp + inw * 0.10, hL + 0.36, hL + 0.46, G_EQ, P.slate, 38, 0, STY_FLAT, sd); + } + } + + function propAC(f, axis, a, wp, kp, inw, sd, dd) { + /* An air-conditioning unit at head height and above, which is the one prop here that furnishes + * the wall BETWEEN the shopfront band and the fire escapes. */ + panel(f, axis, a - 0.40, a + 0.40, wp + inw * 0.15, 3.22, 3.68, G_EQ, P.slate, 32, 0, STY_RIB, sd); + panel(f, axis, a - 0.46, a + 0.46, wp + inw * 0.10, 3.05, 3.86, G_HASH, P.slate, 22, 10, STY_FLAT, sd); + /* The drip. One cell, falling on the unit's own phase, and the ROLL PER CYCLE is what makes it + * weather: a dry night drips now and then, a wet one runs steadily. Frozen under reduced + * motion rather than slowed — a single cell teleporting down a wall is exactly the kind of + * motion the flag exists to remove. */ + if (!CC.reducedMotion) { + var ph = V.t * 0.62 + (sd & 31) * 0.19, k = Math.floor(ph), fr = ph - k; + if (hash2(k, 0, sd + 11) < 0.22 + 0.46 * W_WET) + pcell(f, axis, a + 0.12, wp + inw * 0.18, 3.02 - fr * fr * 3.0, G_QUOTE, P.ice, 96, 1); + } + // The stain it has made under itself, which is only visible when the pavement is wet. + if (W_WET > 0.5) + pcell(f, axis, a + 0.12, wp + inw * 0.35, 0.02, G_COMMA, P.ice, 16 + 18 * W_WET, 0.985); + } + + function propBanner(f, axis, a, wp, kp, inw, sd, dd) { + /* Cloth on a bracket, and the best wind gauge in the frame: the sway is the whole prop. + * Amplitude grows down the cloth, because that is how a hung banner moves and because a slab + * translating sideways as one piece reads as a sprite sliding rather than as fabric. */ + var q = hash2(6, 0, sd); + var hue = q < 0.44 ? P.ember : (q < 0.84 ? P.amber : P.violet); + var p = wp + inw * 0.42, i, y, s, amp = W_GUST * 0.40 * W_SWAY, ph = (sd & 63) * 0.11; + segment3(f, wx(axis, a, wp - inw * 0.3), 4.02, wz(axis, a, wp - inw * 0.3), + wx(axis, a, p), 4.02, wz(axis, a, p), G_DASH, P.slate, 32, 1); + for (i = 0; i < 9; i++) { + y = 3.92 - i * 0.20; + /* i/8 squared, so the top stays pinned to its bracket and the hem does the travelling. */ + s = amp * (i / 8) * (i / 8) * Math.sin(V.tt * 1.45 + ph + i * 0.30); + segment3(f, wx(axis, a - 0.26 + s, p), y, wz(axis, a - 0.26 + s, p), + wx(axis, a + 0.26 + s, p), y, wz(axis, a + 0.26 + s, p), + i === 8 ? G_V : G_8, hue, i === 8 ? 46 : 62 + hash2(i, 0, sd) * 40, 1); + } + } + + function propCallbox(f, axis, a, wp, kp, inw, sd, dd) { + /* A call box: a dark cabinet with one lit panel in it. The lamp on top is the tell — a box + * with a small steady light beside a much bigger dark shape reads as public infrastructure. */ + panel(f, axis, a - 0.26, a + 0.26, wp, 1.48, 2.06, G_8, P.azure, 104, 40, STY_FLAT, sd); + panel(f, axis, a - 0.40, a + 0.40, wp - inw * 0.05, 0, 2.28, 0, P.shadow, 0, 0, STY_FLAT, sd); + panel(f, axis, a - 0.40, a + 0.40, wp - inw * 0.05, 2.22, 2.30, G_EQ, P.slate, 38, 0, STY_FLAT, sd); + var ph = V.t * 0.31 + (sd & 15) * 0.21; ph -= Math.floor(ph); + pcell(f, axis, a, wp, 2.42, G_oo, P.ember, + CC.reducedMotion ? 96 : (ph < 0.5 ? 150 : 44), 1); + pcell(f, axis, a, wp + inw * 0.5, 0.02, G_COLON, P.azure, 18 + 20 * W_WET, 0.985); + } + + function propLadder(f, axis, a, wp, kp, inw, sd, dd) { + /* A ladder left against the wall. Rails plus rungs, all dashed: solid ironwork at this cell + * size reads as a lit edge, which is the note the fire escapes above are drawn to. */ + var p = wp + inw * 0.08, i, y, top = 4.6 + hash2(7, 0, sd) * 1.6; + segment3(f, wx(axis, a - 0.26, p), 0.1, wz(axis, a - 0.26, p), + wx(axis, a - 0.26, p), top, wz(axis, a - 0.26, p), G_PIPE, P.slate, 30, 1); + segment3(f, wx(axis, a + 0.26, p), 0.1, wz(axis, a + 0.26, p), + wx(axis, a + 0.26, p), top, wz(axis, a + 0.26, p), G_PIPE, P.slate, 30, 1); + for (y = 0.45; y < top; y += 0.52) + segment3(f, wx(axis, a - 0.26, p), y, wz(axis, a - 0.26, p), + wx(axis, a + 0.26, p), y, wz(axis, a + 0.26, p), G_DASH, P.slate, 26, 1); + } + + function propPlanter(f, axis, a, wp, kp, inw, sd, dd) { + /* The one place spring is allowed down here, and it is six cells of it. Foliage is scattered on + * the planter's own lattice rather than filled, or a street tree comes out as a green slab. */ + panel(f, axis, a - 0.70, a + 0.70, kp, 0, 0.54, G_HASH, P.slate, 24, 8, STY_FLAT, sd); + panel(f, axis, a - 0.70, a + 0.70, kp, 0.50, 0.58, G_EQ, P.slate, 46, 0, STY_FLAT, sd); + var i, aa, y; + for (i = 0; i < 7; i++) { + aa = a - 0.55 + hash2(i, 1, sd) * 1.1; + y = 0.62 + hash2(i, 2, sd) * 0.72; + pcell(f, axis, aa, kp + inw * (hash2(i, 3, sd) - 0.5) * 0.3, y, + hash2(i, 4, sd) < 0.5 ? G_AMP : G_PCT, P.spring, 34 + hash2(i, 5, sd) * 30, 1); + } + } + + function propHoard(f, axis, a, wp, kp, inw, sd, dd) { + /* A construction hoarding: a long flat nothing at the kerb whose entire job is to hide the + * shopfront band behind it and carry one blinking lamp. A dark mass that big is a gift to a + * frame that is 43% black — it is the black, placed on purpose. */ + panel(f, axis, a - 2.1, a + 2.1, kp, 0, 2.16, 0, P.shadow, 0, 0, STY_FLAT, sd); + panel(f, axis, a - 2.1, a + 2.1, kp, 2.10, 2.18, G_EQ, P.slate, 36, 0, STY_FLAT, sd); + // Hazard stripes, dashed rather than drawn: a solid band of ember at the kerb is a sign. + panel(f, axis, a - 2.0, a + 2.0, kp + inw * 0.02, 1.72, 1.88, G_SL, P.ember, 30, 12, STY_MESH, sd); + var ph = V.t * 1.05 + (sd & 31) * 0.13; ph -= Math.floor(ph); + pcell(f, axis, a + 1.9, kp, 2.34, G_0, P.amber, + CC.reducedMotion ? 110 : (ph < 0.34 ? 208 : 30), 1); + pcell(f, axis, a + 1.9, kp + inw * 0.4, 0.02, G_COLON, P.amber, + (CC.reducedMotion ? 22 : (ph < 0.34 ? 44 : 8)) * (0.6 + W_WET * 0.8), 0.985); + } + + function propScaff(f, axis, a, wp, kp, inw, sd, dd) { + /* Scaffolding, which is the one prop here that reaches all the way up into the territory the + * fire escapes own — and that is the point of it: it ties the empty pavement to the crowded + * roofline instead of leaving them two unrelated bands. */ + var p = wp + inw * 0.55, i, y, aa, top = 6.4 + hash2(8, 0, sd) * 3.4; + for (i = 0; i < 3; i++) { + aa = a - 1.9 + i * 1.85; + segment3(f, wx(axis, aa, p), 0.05, wz(axis, aa, p), + wx(axis, aa, p), top, wz(axis, aa, p), G_PIPE, P.slate, 30, 2); + } + for (y = 2.3; y < top; y += 2.4) { + segment3(f, wx(axis, a - 1.9, p), y, wz(axis, a - 1.9, p), + wx(axis, a + 1.8, p), y, wz(axis, a + 1.8, p), G_EQ, P.slate, 34, 2); + // One brace per lift, alternating, which is what stops it reading as a plain grid. + segment3(f, wx(axis, a - 1.9, p), y - 2.4, wz(axis, a - 1.9, p), + wx(axis, a - 0.05, p), y, wz(axis, a - 0.05, p), G_SL, P.slate, 22, 3); + } + /* The debris netting on the bottom lift, meshed so it is a veil rather than a wall. */ + panel(f, axis, a - 1.9, a + 1.8, p + inw * 0.06, 0.1, 2.3, G_COLON, P.slate, 18, 6, STY_MESH, sd); + } + + function propShelter(f, axis, a, wp, kp, inw, sd, dd) { + /* A bus shelter: a roof, two posts, a bench and one back-lit advertising panel. The panel is + * doing all the work — a lit rectangle at knee-to-shoulder height with a dark roof over it is + * the single most legible object this element draws. */ + /* Stood ON the kerb, not past it: the shelter is the widest thing this element puts on the + * pavement and a quarter of a metre further out was enough to have it standing in the road on + * a narrow corridor. */ + var p = kp; + panel(f, axis, a - 1.05, a - 0.05, p, 0.55, 2.10, G_8, P.azure, 96, 46, STY_FLAT, sd); + panel(f, axis, a - 1.05, a - 0.05, p - inw * 0.05, 0, 2.20, 0, P.shadow, 0, 0, STY_FLAT, sd); + panel(f, axis, a - 1.75, a + 1.75, p, 2.28, 2.44, G_EQ, P.slate, 38, 0, STY_FLAT, sd); + segment3(f, wx(axis, a + 1.70, p), 0.05, wz(axis, a + 1.70, p), + wx(axis, a + 1.70, p), 2.28, wz(axis, a + 1.70, p), G_PIPE, P.slate, 30, 1); + segment3(f, wx(axis, a - 1.70, p), 0.05, wz(axis, a - 1.70, p), + wx(axis, a - 1.70, p), 2.28, wz(axis, a - 1.70, p), G_PIPE, P.slate, 30, 1); + segment3(f, wx(axis, a + 0.15, p - inw * 0.2), 0.45, wz(axis, a + 0.15, p - inw * 0.2), + wx(axis, a + 1.60, p - inw * 0.2), 0.45, wz(axis, a + 1.60, p - inw * 0.2), + G_UNDER, P.slate, 30, 1); + pcell(f, axis, a - 0.55, p + inw * 0.7, 0.02, G_COLON, P.azure, 24 + 30 * W_WET, 0.985); + } + + function propNewsbox(f, axis, a, wp, kp, inw, sd, dd) { + /* A news box. Small, chest-high, one ember face — the cheapest prop in the file and the one + * that makes a kerb look used. */ + panel(f, axis, a - 0.26, a + 0.26, kp, 0.42, 0.96, G_8, P.ember, 64, 26, STY_FLAT, sd); + panel(f, axis, a - 0.30, a + 0.30, kp - inw * 0.05, 0, 1.06, 0, P.shadow, 0, 0, STY_FLAT, sd); + panel(f, axis, a - 0.30, a + 0.30, kp - inw * 0.05, 1.00, 1.08, G_DASH, P.slate, 40, 0, STY_FLAT, sd); + } + + function propStair(f, axis, a, wp, kp, inw, sd, dd) { + /* A stairwell going down, with the light coming UP out of it. It is the only light in the + * whole build that arrives from below the pavement, which is why it is worth thirty cells: + * everything else down here is lit from a shopfront or a street lamp, and the eye notices the + * one thing that is not. + * Drawn as a ramp of ground cells brightening toward the wall end, so the opening reads as a + * hole with a lit throat rather than as a rug. */ + var i, j, c, aa, l, hue = hash2(9, 0, sd) < 0.7 ? P.warm : P.spring; + /* The opening reaches the kerb and stops. It ran to 2.4 m first, which is past the kerb line + * into the carriageway on any corridor narrower than six metres — a stairwell with cars + * driving over it. The pavement here is the 1.4 m strip raycast.configureFor lays out. */ + for (i = 0; i < 5; i++) { + c = wp + inw * (0.22 + i * 0.30); + l = 118 - i * 19; // brightest at the throat, against the wall + for (j = 0; j < 5; j++) { + aa = a - 0.86 + j * 0.43; + pcell(f, axis, aa, c, 0.02, i === 0 ? G_8 : G_EQ, hue, l, 0.985); + } + } + // The handrail round the opening, which is what gives the light a shape to come out of. + segment3(f, wx(axis, a - 0.95, wp + inw * 1.65), 0.98, wz(axis, a - 0.95, wp + inw * 1.65), + wx(axis, a + 0.95, wp + inw * 1.65), 0.98, wz(axis, a + 0.95, wp + inw * 1.65), + G_DASH, P.slate, 44, 1); + segment3(f, wx(axis, a + 0.95, wp + inw * 1.65), 0.05, wz(axis, a + 0.95, wp + inw * 1.65), + wx(axis, a + 0.95, wp + inw * 1.65), 1.02, wz(axis, a + 0.95, wp + inw * 1.65), + G_PIPE, P.slate, 36, 1); + } + + function propWash(f, axis, a, wp, kp, inw, sd, dd) { + /* A washing line. Four cloths on a wire, and they are the second wind gauge: the whole line + * lifts and the sheets swing on it, all off the one gust magnitude the file shares. */ + var p = wp + inw * 0.35, i, aa, s, y, amp = W_GUST * 0.34 * W_SWAY, ph = (sd & 31) * 0.2; + /* The wire runs ALONG the wall, not across the street, so it is a segment and not a cable run: + * drawCableRun sweeps `cross` at a fixed `along`, which would have strung this washing line out + * into the traffic. Over 3.8 m the sag is a couple of centimetres and worth nothing here. */ + segment3(f, wx(axis, a - 1.9, p), 4.32, wz(axis, a - 1.9, p), + wx(axis, a + 1.9, p), 4.30, wz(axis, a + 1.9, p), G_DASH, P.slate, 30, 1); + /* Nobody leaves the washing out in a downpour. The empty line stays — that is the half of the + * observation that makes the other half read — and the sheets come in above about a third of + * the reference rainfall, which is the point where the street's umbrellas go up too. */ + if (W_RAIN > 0.6) return; + for (i = 0; i < 4; i++) { + aa = a - 1.35 + i * 0.9; + s = amp * Math.sin(V.tt * 1.2 + ph + i * 0.8); + for (y = 4.18; y > 3.35; y -= 0.20) { + segment3(f, wx(axis, aa - 0.18 + s, p), y, wz(axis, aa - 0.18 + s, p), + wx(axis, aa + 0.18 + s, p), y, wz(axis, aa + 0.18 + s, p), + G_8, i & 1 ? P.white : P.slate, 40 + hash2(i, (y * 5) | 0, sd) * 22, 1); + } + } + } + + function drawProps(f) { + if (!CITY) return; + var axis, idx, n, side, r, along, dd, kind, sd, wallC, inw, wp, kp; + for (axis = 0; axis < 2; axis++) { + for (idx = idxLo(axis); idx <= idxHi(axis); idx++) { + streetSpan(axis, idx); + if (SPAN.w < 4) continue; // an alley has no pavement to stand on + for (n = alongLo(axis, 6); n <= alongHi(axis, 6); n++) { + for (side = 0; side < 2; side++) { + r = hash2(idx * 2 + side, n, BASE ^ 0x9701); + if (r > 0.50) continue; // about one prop every eleven metres per side + along = n * 6 + hash2(idx * 2 + side, n, BASE ^ 0x9702) * 4.6; + wallC = side ? SPAN.c1 : SPAN.c0; + inw = side ? -1 : 1; // from the building face toward the centre + /* -3.2 m, not the default metre: a prop is up to 4.2 m long, so its midpoint passes + * the eye plane while its far half is still across a third of the frame. The old + * midpoint test at w < 1 threw the whole prop away there, in one frame, which is the + * second half of the same pop clipNear() fixes — and unlike the panel bail it fires on + * every prop that the viewer walks past rather than only on the long ones. Everything + * that survives to be drawn is clipped exactly by clipNear(). */ + dd = spanVisible(axis, along, wallC + inw, -3.2); + /* Past forty-odd metres a prop is two fogged cells and a lie about detail; the work is + * better spent on the ones the viewer is about to walk past. */ + if (!dd || dd > 44) continue; + // Half a metre INTO the building, so the probe can never land on the street itself. + if (anchorH(axis, along, wallC - inw * 0.5) < 3) continue; + sd = BASE ^ (idx * 977 + n * 6151 + side * 37); + wp = wallC + inw * 0.45; + kp = wallC + inw * 1.55; + kind = KIND[(hash2(idx * 2 + side, n, BASE ^ 0x9703) * KIND.length) | 0]; + switch (kind) { + case K_VEND: propVend(f, axis, along, wp, kp, inw, sd, dd); break; + case K_SHUTTER: propShutter(f, axis, along, wp, kp, inw, sd, dd); break; + case K_BOLLARD: propBollard(f, axis, along, wp, kp, inw, sd, dd); break; + case K_CRATES: propCrates(f, axis, along, wp, kp, inw, sd, dd); break; + case K_AC: propAC(f, axis, along, wp, kp, inw, sd, dd); break; + case K_BANNER: propBanner(f, axis, along, wp, kp, inw, sd, dd); break; + case K_CALLBOX: propCallbox(f, axis, along, wp, kp, inw, sd, dd); break; + case K_LADDER: propLadder(f, axis, along, wp, kp, inw, sd, dd); break; + case K_PLANTER: propPlanter(f, axis, along, wp, kp, inw, sd, dd); break; + case K_HOARD: propHoard(f, axis, along, wp, kp, inw, sd, dd); break; + case K_SCAFF: propScaff(f, axis, along, wp, kp, inw, sd, dd); break; + case K_SHELTER: propShelter(f, axis, along, wp, kp, inw, sd, dd); break; + case K_NEWSBOX: propNewsbox(f, axis, along, wp, kp, inw, sd, dd); break; + case K_STAIR: propStair(f, axis, along, wp, kp, inw, sd, dd); break; + case K_WASH: propWash(f, axis, along, wp, kp, inw, sd, dd); break; + /* Unreachable while every entry in KIND has a case above, which is the point of + * writing it out: a kind added to the bag and forgotten here draws a crate rather + * than nothing, so the mistake is visible instead of silent. */ + default: propCrates(f, axis, along, wp, kp, inw, sd, dd); break; + } + } + } + } + } + } + + /* ---- registration --------------------------------------------------------------------------- + * All seven are pure functions of (world, t): no simulation state, so no update(). That also + * makes them scrub-safe — jumping to frame 900 and back gives byte-identical frames. */ + function mk(name, layer, fn) { + return { + name: name, layer: layer, + init: function (city, rng) { boot(city, rng); }, + draw: function (f, cam, t) { + view(f, cam, t === undefined ? (cam.t || 0) : t); + fn(f); + } + }; + } + + CC.ELEMENTS.push(mk('streetprops', 19, drawProps)); + CC.ELEMENTS.push(mk('skybridges', 20, drawBridges)); + CC.ELEMENTS.push(mk('rooftop-plant', 21, drawPlant)); + CC.ELEMENTS.push(mk('masts', 22, drawMasts)); + CC.ELEMENTS.push(mk('fire-escapes', 23, drawEscapes)); + CC.ELEMENTS.push(mk('cables', 24, drawCables)); + CC.ELEMENTS.push(mk('lanterns', 26, drawLanterns)); + +})(typeof CC !== 'undefined' ? CC : require('../core.js')); diff --git a/src/elements/weather.js b/src/elements/weather.js new file mode 100644 index 0000000..90c843d --- /dev/null +++ b/src/elements/weather.js @@ -0,0 +1,1337 @@ +/* CyberCity weather — the visible face of CC.Weather. + * + * Five elements, one file, because they all read the same wind vector, the same projection helper + * and the same weather block, and splitting them would mean five copies of all three. + * + * WHAT CHANGED WHEN CC.Weather LANDED. Every constant in here used to be tuned for one unchanging + * sky. They are now functions of the live weather block, and the scaling rule is the one + * weather_state.js states: an element multiplies its EXISTING tuned constant by the parameter + * divided by that parameter's value in the `rain` preset — the preset the whole build was tuned + * under — so the scale is 1.0 under `rain` and the file reproduces exactly what it printed before. + * Multiplying by the raw 0..1 parameter instead would silently re-tune the whole file to 65% of + * itself. Those reference values are the REF_* constants below; dividing by them here rather than + * calling CC.Weather.rel() is the same arithmetic without an Array#indexOf per call, and it also + * means this file still runs when weather_state.js is not loaded at all — which is exactly the + * case in tools/lightning-rate.cjs, whose whole job is to measure the envelope under the reference + * sky. + * + * PROJECTION. The raycaster's camera is planar, not cylindrical, and these elements must agree + * with it EXACTLY or a raindrop lands one column off the wall it is supposed to be in front of. + * The forward axis distance w comes from a plain dot product, the column falls out of r/w, and + * the row uses the same `horizon - (y-eyeY)*scale/w` the wall tops use. `scale` is re-derived the + * way raycast.js derives it — from fov and the cell aspect — because cam.scaleY is optional and + * the harness sets a `cam.scale` that raycast.js deliberately ignores. Nothing here hardcodes the + * horizon or the fov: the camera pitches and zooms, and a hardcoded rows*0.56 tears the rain away + * from the city the moment somebody looks up. + * + * DEPTH. Every write goes through CC.put with the point's RADIAL distance sqrt(w^2+r^2), which is + * the same quantity raycast.js stores in frame.dist (w*len). That is what makes rain fall in + * front of the near facade and vanish behind the far one instead of raining through the city. + * + * BUDGET. Weather is allowed about a point and a half of lit coverage under the `rain` preset and + * more under a downpour — a downpour that costs the same as a drizzle is not a downpour. Measured + * at 200x60 against the same frame with these five elements' draw suppressed, seeds 3, 42 and 99 + * at frame 3000, in points of lit cells and in share of cells touched: + * + * clear +0.09 / +0.25 / +0.15 0.5-1.0% of cells touched + * drizzle +0.54 / +0.52 / +0.40 0.8-1.5% + * rain +1.15 / +1.17 / +1.12 2.0-2.7% <- the reference sky + * downpour +1.79 / +2.06 / +2.14 5.3-7.3% + * mist +0.85 / -0.85 / +0.64 28-45% + * storm +1.41 / +1.18 / +1.75 4.1-5.3% + * + * Clear is steam and residual ledge drip and nothing else — the director keeps P.steam at 0.55 on + * a dry night. Mist touches half the frame and can still come out NEGATIVE on lit coverage, + * because the veil takes more of the city away than the bank puts back; that is the whole point of + * it. A lightning peak is worth about +14 on top of any of those and lasts a fifth of a second. + * The frame is 40-55% pure black and that is the look; every threshold below was pulled down until + * that held. + * + * SAFETY. The lightning envelope at the bottom of this file is the one thing in the project that + * can physically harm a viewer. It is measured, not tuned by eye, and `node tools/lightning-rate.cjs` + * is the measurement. Read the block above lgEnv before touching any constant near it. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, put = CC.put, hash1 = CC.hash1, hash2 = CC.hash2, + clamp = CC.clamp, lerp = CC.lerp, smooth = CC.smooth, vnoise = CC.vnoise; + + var G_PIPE = CC.g('|'), G_SLASH = CC.g('/'), G_BSL = CC.g('\\'), G_DOT = CC.g('.'), + G_COMMA = CC.g(','), G_COLON = CC.g(':'), G_QUOTE = CC.g("'"), G_TICK = CC.g('`'), + G_DASH = CC.g('-'), G_UNDER = CC.g('_'), G_TILDE = CC.g('~'), G_STAR = CC.g('*'), + G_SEMI = CC.g(';'), G_EQ = CC.g('='); + + /* ---- the weather block -------------------------------------------------------------------- + * Held, never copied: CC.Weather.P is a live object and a copy taken at init would freeze the + * city under the sky it was born in. The REF_* row is the `rain` preset, which is the tuning + * reference for every constant in this file. */ + var REF_RAIN = 0.65, REF_WIND = 0.55, REF_FOG = 0.30, REF_WET = 0.90, + REF_STORM = 0.12, REF_HAZE = 0.40, REF_CLOUD = 0.75, REF_STEAM = 0.85; + /* Stand-in for a harness that does not load weather_state.js. It is the reference preset itself, + * so a file rendered without the director prints the sky the build was tuned as. */ + var WFALL = { rain: REF_RAIN, wind: REF_WIND, fog: REF_FOG, wet: REF_WET, + storm: REF_STORM, haze: REF_HAZE, cloud: REF_CLOUD, steam: REF_STEAM }; + + var pRain = REF_RAIN, pWind = REF_WIND, pFog = REF_FOG, pWet = REF_WET, + pStorm = REF_STORM, pHaze = REF_HAZE, pCloud = REF_CLOUD, pSteam = REF_STEAM; + /* The same eight, divided by their reference value: 1.0 means "what this file already did". */ + var dRain = 1, dWind = 1, dFog = 1, dSteam = 1; + /* Derived weather that has no parameter of its own. See the comment on syncWeather. */ + var wChill = 0, wSleet = 0, wBreath = 0; + + /* ---- one wind for the whole system, and it gusts ------------------------------------------- + * Rain slant, splash lean, drip drift, steam drift, fog travel and cloud scud all read this. + * Independent wind per element looked like five unrelated effects sharing a screen. + * + * EXPORTED, because it is not only this file's business: banners, cables, litter, awnings and + * anything else that hangs in the street should lean the same way the rain does, and a second + * wind rolled somewhere else would be visibly out of phase with this one. The object is live and + * is never reallocated — hold it, do not copy it: + * + * CC.Weather.wind === CC.Wind === { x, z, dirX, dirZ, base, speed, gust, mult } + * + * x, z metres per second along world X and Z, gust included. This is the vector to + * use; multiply it by a time and you get a displacement. + * dirX, dirZ unit direction the wind blows TOWARD, constant for the life of a city. + * base mean speed in m/s for the current weather, gust excluded. + * speed |(x,z)|, i.e. base*mult, which is what a travel rate wants. + * gust the live wind STRENGTH on the director's own 0..1 scale: P.wind beaten by the + * gust envelope. This is the number to scale a swing, a lean or a flutter by — + * 0.55 under the reference sky, near nothing on a still night, up to about 1.6 + * on the hardest gust of a storm. structure.js's banners and lanterns read + * exactly this field and fall back to `P.wind * (0.70 + 0.66*noise)` without it, + * which is the same quantity and the same range; keep it that way. + * mult the raw gust multiplier on `base`, mean 1 by construction. Only wanted if you + * are computing a speed rather than a magnitude. + * + * It is refreshed once per t by syncWeather() below, from whichever element runs first; every + * reader in the same frame therefore sees the same vector. + * + * The init guard is keyed on the CITY OBJECT, never on a boolean. A `if (windSet) return` latch + * does the right thing for the elements of one init round and the wrong thing forever after: a + * #hashchange rebuilds the world and calls init() again with a fresh rng, and a latched wind + * meant the new city kept the previous one's weather. Comparing the city identity keeps the + * "one wind shared by every element" property — they are all handed the SAME object in one + * round, so exactly one of them draws from the rng — while still re-rolling on a real rebuild. */ + var WIND = { x: 0.0, z: 0.0, dirX: 0.0, dirZ: 1.0, base: 0.0, speed: 0.0, gust: 0.55, mult: 1.0 }; + var WBASE = 2.4, windWorld, wSeed = 0; + function initWind(rng) { + if (windWorld === WCITY) return; + windWorld = WCITY; + var a = rng() * 6.283185; + WBASE = 1.6 + rng() * 2.6; + WIND.dirX = Math.cos(a); WIND.dirZ = Math.sin(a); + wSeed = smallSeed(rng); + wxT = -1e9; // force a resync; the gust seed just moved + } + + /* ---- derived weather ---------------------------------------------------------------------- + * CHILL has no parameter in CC.Weather and deliberately so: temperature is not something the + * eight directions can carry, and adding a ninth would mean editing a file this module does not + * own. It is inferred instead, the way you would infer it standing there — a slow front that + * takes about four minutes to pass, colder when the air is full of fog and haze, warmer when it + * is raining hard, since the rain that is falling as water is by definition above freezing. + * Two things read it: sleet (which needs rain AND cold) and breath (which needs only cold). + * Under the `rain` preset a cold front reaches the sleet threshold about one pass in eight, so + * sleet stays an event rather than a look. */ + var wxT = -1e9; + function syncWeather(t) { + if (t === wxT) return; // idempotent per frame; any element may call + wxT = t; + /* Resolved every sync rather than cached at init, because load order is not guaranteed and a + * cached null would leave the city permanently under the fallback sky. */ + var W = (CC.Weather && CC.Weather.P) || WFALL; + if (CC.Weather && CC.Weather.wind !== WIND) CC.Weather.wind = WIND; + pRain = W.rain; pWind = W.wind; pFog = W.fog; pWet = W.wet; + pStorm = W.storm; pHaze = W.haze; pCloud = W.cloud; pSteam = W.steam; + dRain = pRain / REF_RAIN; dWind = pWind / REF_WIND; + dFog = pFog / REF_FOG; dSteam = pSteam / REF_STEAM; + + /* Gust. Two octaves: a slow envelope that walks the whole curtain up the street over ten + * seconds or so, and a faster ripple on top of it. Its mean is 1 by construction — (raw-0.5) + * around a unit centre — so the slant, drift and travel rates every reader derives from it + * still average what they averaged before the wind gusted at all. Amplitude scales with the + * wind parameter, which is what makes a still night still and a storm ragged. */ + var gt = CC.reducedMotion ? 0 : t; + var raw = vnoise(gt * 0.107 + 4.1, wSeed + 3) * 0.68 + vnoise(gt * 0.39, wSeed + 8) * 0.32; + var amp = clamp(dWind, 0, 1.85) * (CC.reducedMotion ? 0.12 : 1); + var g = 1 + (raw - 0.5) * 1.30 * amp; + /* Floored well above zero, and not only to keep the vector from reversing on a deep lull — + * which would be a gale blowing backwards, not a breeze. At the reference sky the swing bottoms + * out at exactly 0.35 so the floor never bites; it exists for a storm, where the amplitude is + * nearly twice that and an unfloored lull briefly stops the wind dead in the middle of a gale. */ + if (g < 0.30) g = 0.30; + WIND.mult = g; + /* Published on the director's own scale, not as the multiplier: a consumer that wants to swing + * a banner wants "how windy is it", which is P.wind beaten by the gust, and a mean-1 multiplier + * would have swung the banners just as hard on a still night as in a gale. */ + WIND.gust = clamp(pWind * g, 0, 1.6); + WIND.base = WBASE * (0.35 + 0.65 * clamp(dWind, 0, 1.85)); + WIND.speed = WIND.base * g; + WIND.x = WIND.dirX * WIND.speed; WIND.z = WIND.dirZ * WIND.speed; + + /* The cold front. Squared, so the cold end is a visit rather than half of all weather. */ + var cf = vnoise(t * 0.0037 + 11.3, wSeed + 17) * 0.66 + vnoise(t * 0.0119, wSeed + 23) * 0.34; + cf *= cf; + wChill = clamp(0.10 + cf * 1.05 - pRain * 0.25 + (pFog + pHaze) * 0.20, 0, 1); + /* Sleet needs both: cold air and something falling through it. */ + wSleet = clamp((wChill - 0.68) / 0.25, 0, 1) * clamp(pRain / 0.30, 0, 1); + wBreath = clamp((wChill - 0.50) / 0.28, 0, 1); + } + + /* ---- view binding ------------------------------------------------------------------------- + * Refreshed once per draw(); every projection in the file reads these module-level slots so + * nothing has to allocate a camera record per particle. */ + var vCols = 0, vHorizon = 0, vScale = 0, vHalf = 0, vCellA = 0.5625, + vEyeY = 1.7, vX = 0, vZ = 0, vFwx = 0, vFwz = 1, vRgx = 1, vRgz = 0, vFar = 125; + var SURF = null; + + function bindView(frame, cam) { + SURF = CC.Surf || null; + vCols = frame.cols; + var fov = cam.fov || 1.25; + vHalf = Math.tan(fov * 0.5); + vHorizon = cam.horizon !== undefined ? cam.horizon : frame.rows * 0.56; + vEyeY = cam.eyeY !== undefined ? cam.eyeY : 1.7; + vCellA = cam.cellAspect || 0.5625; + vScale = cam.scaleY !== undefined ? cam.scaleY : (frame.cols * vCellA) / (2 * vHalf); + var yaw = cam.yaw || 0; + vFwx = Math.sin(yaw); vFwz = Math.cos(yaw); + vRgx = Math.cos(yaw); vRgz = -Math.sin(yaw); + vX = cam.x; vZ = cam.z; + vFar = SURF ? SURF.FOG_END : 125; + } + + function fogLum(lum, dist) { return SURF ? SURF.fog(lum, dist) : lum; } + + /* Scratch projection result. Never returned to a caller, never retained across a call. */ + var pjW = 0, pjX = 0, pjY = 0, pjD = 0; + /* Returns 0 for a point that cannot possibly be on screen. The 1.25 slack on the horizontal + * bound keeps a near particle whose STREAK reaches back into frame from being culled. */ + function project(wx, wy, wz) { + var rx = wx - vX, rz = wz - vZ; + var w = rx * vFwx + rz * vFwz; + if (w < 0.45 || w > vFar) return 0; + var r = rx * vRgx + rz * vRgz; + var sp = r / w; + if (sp < -vHalf * 1.25 || sp > vHalf * 1.25) return 0; + pjW = w; + pjX = (sp / vHalf + 1) * 0.5 * vCols - 0.5; + pjY = vHorizon - (wy - vEyeY) * vScale / w; + pjD = Math.sqrt(w * w + r * r); + return 1; + } + + /* Wrap into [-b/2, b/2). This is what lets a fixed particle array cover an endless city: the + * drop the camera walked past reappears the same distance behind it. */ + function wrap(v, b) { return v - b * Math.floor(v / b + 0.5); } + function frac(v) { return v - Math.floor(v); } + + /* core.js's hash2 multiplies its seed by 2147483647 in floating point, so a full 32-bit seed + * pushes the product past 2^53 and the low bits — the only bits that distinguish `s` from + * `s ^ 0x66` — are rounded away. Every seed in this file is therefore drawn SMALL and its + * variants are ADDITIVE. Getting this wrong is silent and vicious: the first cut of the steam + * used `stSeed ^ 0x66` to pick steam-vs-smoke and got the identical hash it had just used to + * place the vent, so every single vent in the city came out as smoke. */ + function smallSeed(rng) { return (rng() * 30011) | 0; } + + /* A PRIVATE stream, bought with exactly one draw from the shared one. Every element in the build + * pulls from a single rng handed round in layer order, so the number of draws an init() takes is + * part of the seed of every element that inits after it. That is a live trap for anything that + * loops to a tuning constant: RN_MAX below is a capacity, nothing more, and moving it from 1800 + * to 2800 changed 31.9-41.5% of the cells of a frame across the canonical seed 3/7/42/99 sweep at + * 200x60 — including a `mist` frame where the rain element draws nothing at all, so the entire + * difference was the 29 elements downstream of it being re-seeded. Behind a fork the drop table + * costs the shared stream one number whatever RN_MAX is, and slot i's attributes depend only on + * i, which is what makes the constant safe to tune. sky.js:174 does the same thing for the same + * reason; the salt matches so the two files read as one idiom. */ + function fork(rng) { return CC.mulberry(((rng() * 4294967296) | 0) ^ 0x5C1E); } + + /* Smooth 2D value noise. core.js only exposes the 1D one, and summing two 1D fields gives + * plaid-looking banks that read as a texture rather than as weather. */ + function n2(x, z, s) { + var xi = Math.floor(x), zi = Math.floor(z); + var fx = smooth(x - xi), fz = smooth(z - zi); + return lerp(lerp(hash2(xi, zi, s), hash2(xi + 1, zi, s), fx), + lerp(hash2(xi, zi + 1, s), hash2(xi + 1, zi + 1, s), fx), fz); + } + + /* ============================================================================================ + * RAIN + * Two shells of drops, not one. A single uniform box either starves the near field (where rain + * is supposed to be a legible streak) or floods the far field (where it turns the canyon into + * static). The near shell is 13 m across and carries the streaks; the far shell is 34 m and + * contributes single dim cells that only register as texture. + * + * Everything about it now tracks the sky: the population, the fall speed, the streak length, + * the near/far balance, the slant (through the gusting wind), whether the drops are water or + * sleet, whether they splash, and whether the ledges are still dripping after it stopped. + * At P.rain 0 the whole element returns before it draws a single cell — a thin rain under a + * clear sky was the single most obviously wrong thing in the build before the director existed. + * ==========================================================================================*/ + /* The array is allocated once at the maximum and only a PREFIX of it is walked, because the + * drop count has to track the grid AND the weather: a streak is measured in cells, so a 400x100 + * grid draws each drop twice as long but has four times the cells to fill, and a world-fixed + * population that reads as rain at 200x60 disappears at 400x100. The shells are interleaved for + * exactly this reason — any prefix has to be a valid mix of near and far, and a near-then-far + * layout would have made the small-window case pure near shell. + * + * RN_MAX IS A CAPACITY AND NOTHING ELSE — see fork() above for why that sentence needs saying. + * It is sized so the cap never bites at any size the project renders at, because a cap that + * bites is a cap that flattens the difference between rain and a downpour, which is the one + * difference this file exists to draw. The largest request the presets can make is a downpour + * (P.rain 1.00, so dens 1.5385 and dens^1.55 1.9497) at the canonical verification size of + * 400x100: 640 * 1.9497 * 40000/12000 = 4159 drops. At 2800 that request was clamped by a third, + * and the cap is not a neutral one — it flattened the two heaviest skies into each other. Drawn + * drops per frame at 400x100, seeds 3/42/99: downpour 947/925/1038 against storm 931/905/997, + * a ratio of 1.03, where at 200x60 (which neither sky clamps at) the same measurement gives + * 1.36. Uncapped, 400x100 comes back at 1.32 and agrees with the smaller frame again. Every + * offline comparison of downpour with storm at the size this project verifies at was reading + * the cap. The browser never comes near it (main.js caps columns at MAXC and a 4K display gives + * ~20500 cells, where a downpour asks for 640*1.9497*1.708 = 2131), so this headroom is bought + * purely so that the size the project verifies at measures the weather and not the cap. The + * seven arrays cost 25 bytes a slot, i.e. 105 KB allocated once. */ + var RN_MAX = 4200, RN_AT_REF = 640, REF_CELLS = 200 * 60; + var rOx = null, rOz = null, rBox = null, rSpd = null, rPh = null, rHue = null, rFall = null; + var rainT = 0; + /* The city arrives at init() and is wanted in draw() — the drop needs the ground height under + * it and the vent needs to know it is standing on street. cam.city wins if a caller ever puts + * one there. + * + * ALWAYS assign. The first cut pinned the first city forever (`if (!WCITY) WCITY = city`), and + * after a #hashchange rebuilt the world the rain was still asking the PREVIOUS city for ground + * heights while the raycaster drew the new one — drops landing on buildings that were no longer + * there, vents opening inside walls — and the dead city's chunk cache could never be collected. + * A stale world reference is not a cosmetic bug; it is a leak with a picture attached. */ + var WCITY = null; + function bindWorld(city, rng) { WCITY = city || null; initWind(rng); } + + /* ---- how long the city keeps dripping ------------------------------------------------------ + * A street does not dry the moment the rain stops. P.wet already lags rain a little through the + * director's 14 s blend, but only by that blend, so this is a one-pole low-pass over it with a + * deliberately asymmetric time constant: wets in about three seconds, dries over three quarters + * of a minute. That gap IS the post-storm drip period — ledges and awnings go on releasing beads + * long after the last drop has fallen, and it is the only part of the weather that outlives the + * weather. + * + * Integrated in update() rather than derived from t, because a low-pass has no closed form over + * a schedule this file cannot see. That is safe for determinism here: main.js and + * tools/headless.cjs both replay every tick from t=0 in order, so the same seed and the same + * frame give the same value. The two guards below are what make that true in the edge cases — + * a dt spike after a tab has been in the background must not integrate a minute in one step, + * and a viewer scrubbing backwards must not have to wait for the filter to unwind. */ + var wetEma = REF_WET, wetLastT = -1e9, dripAmt = 0; + function wetIntegrate(dt, t) { + if (t < wetLastT - 0.001) wetEma = pWet; // scrubbed backwards; resync, do not unwind + wetLastT = t; + if (!(dt > 0)) return; + if (dt > 0.1) dt = 0.1; + var k = dt / (pWet > wetEma ? 3.0 : 42.0); + if (k > 1) k = 1; + wetEma += (pWet - wetEma) * k; + /* Clear sits at wet 0.12, and 0.12 has to mean a dry street, not a slow drip forever. */ + dripAmt = clamp((wetEma - 0.22) / 0.52, 0, 1); + } + + CC.ELEMENTS.push({ + name: 'rain', + layer: 12, + init: function (city, rng) { + bindWorld(city, rng); + /* The drop table is filled from a fork, not from `rng`, so that RN_MAX cannot re-seed the + * rest of the build — this element takes five numbers per slot and is the only init in the + * project whose draw count runs to five figures. */ + var r = fork(rng); + rOx = new Float32Array(RN_MAX); rOz = new Float32Array(RN_MAX); + rBox = new Float32Array(RN_MAX); rSpd = new Float32Array(RN_MAX); + rPh = new Float32Array(RN_MAX); rHue = new Uint8Array(RN_MAX); + rFall = new Float32Array(RN_MAX); + for (var i = 0; i < RN_MAX; i++) { + var near = (i & 1) === 0; + var b = near ? 13 : 34; + rBox[i] = b; + /* The wrap height is per shell and it is NOT a cloud base — it is the shortest cycle that + * still recycles a drop off the top of the frame. Measured: at forward distance w the + * visible band of world height is only ~0.77*w metres tall, so an 18 m cycle left a near + * drop on screen for a tenth of its life and the near field came out empty. These two + * numbers are the largest that still keep the reset above the top row for their shell. */ + rFall[i] = near ? 6 : 11; + rOx[i] = r() * b; rOz[i] = r() * b; + rSpd[i] = 6.5 + r() * 4.5; + rPh[i] = r(); + /* Almost all rain is achromatic — it is only visible because the city is behind it. The + * one-in-eight tinted drop is a drop passing through a sign's spill, and it is what stops + * the rain reading as grey dust. */ + var h = r(); + rHue[i] = h < 0.70 ? P.slate : (h < 0.86 ? P.ice + : (h < 0.94 ? P.amber : P.azure)); + } + syncWeather(0); + wetEma = pWet; wetLastT = -1e9; + dripAmt = clamp((wetEma - 0.22) / 0.52, 0, 1); + drSeed = smallSeed(rng); + }, + update: function (dt, t) { rainT = t; syncWeather(t); wetIntegrate(dt, t); }, + draw: function (frame, cam, t) { + if (!rOx) return; + var tt0 = t !== undefined ? t : rainT; + syncWeather(tt0); + bindView(frame, cam); + /* Frozen, not slowed: a reduced-motion viewer still gets the wet-street read from the + * static streaks, and a slow drift is more nauseating than no drift at all. */ + var tt = CC.reducedMotion ? 0 : tt0; + var city = cam.city || WCITY; + var rows = frame.rows, cols = frame.cols; + + /* Density relative to the reference sky. Below a fiftieth of it there is no rain at all, + * which is the whole point of the clear preset: not a thin rain, none. */ + var dens = clamp(dRain, 0, 1.62); + if (dens > 0.02) { + /* Screen lean per row is distance-independent — the ratio of crosswind to fall speed, + * corrected for the cell being 0.5625 as wide as it is tall. It reads the gusting wind, so + * the whole curtain leans and straightens as the gust walks through. */ + var wRight = WIND.x * vRgx + WIND.z * vRgz; + + /* The population is the density to the power of 1.55, not the density. Linear scaling made + * every sky between drizzle and downpour look like the same rain at slightly different + * brightness — the ratio between the lightest and the heaviest is only 1.54 as a raw + * parameter, and the eye does not read a 54% change in a field of streaks as weather. The + * exponent stretches that to 1.95x at a downpour and 0.30x at a drizzle while leaving 1.0 + * exactly 1.0, which is the whole trick: the reference sky is a fixed point of x^n. */ + var use = (RN_AT_REF * Math.pow(dens, 1.55) * cols * rows / REF_CELLS) | 0; + if (use > RN_MAX) use = RN_MAX; else if (use < 24) use = 24; + /* The far shell is what fills the canyon with static, and a drizzle has no business + * filling anything. Below the reference sky it thins out first and the near streaks are + * the last thing left, which is what light rain actually looks like down a long street. */ + var farUse = use * clamp(0.55 + 0.45 * dens, 0, 1); + /* The streak cap is in cells, so it has to grow with the grid too, or a 100-row frame gets + * the same four-cell stub a 60-row frame does and the near rain stops reading as fast. It + * also grows with the rain: a downpour falls faster and exposes longer. */ + var nMax = ((rows / 15) * (0.55 + 0.45 * dens)) | 0; + if (nMax < 2) nMax = 2; else if (nMax > 8) nMax = 8; + /* Sleet is a hard little particle: it falls faster, streaks shorter and is brighter than + * water because it is a scatterer rather than a lens. */ + var fallK = (0.72 + 0.28 * dens) * (1 + 0.28 * wSleet); + /* Gust sheets. A curtain of rain is not uniform — the wind walks it up the street in + * bands, and this is that band pattern sampled in WORLD space along the wind direction so + * that it travels at the wind's own speed and every drop inside a band agrees about it. + * + * THE BAND MUST BE SMALLER THAN THE SHELL IT MODULATES, and the first cut was not. At + * SH_K 0.085 one band was 11.8 m of world distance while the near shell is only 13 m + * across and both shells are wrapped around the camera, so every drop in the frame was + * standing in the SAME band and the "sheet" was a global brightness dial. Measured at + * 400x100 with a frozen camera and a frozen sky, counting this element's CC.put calls per + * frame over 60 s: downpour at seed 3 had a median of 947 drops and a minimum of 14, in + * five off-cycles of a third of a second each; seed 42 was worse, seventeen of them and a + * minimum of ZERO — a downpour with no rain in it for two and a half continuous seconds, + * and a storm at the same seed for four and a half. Seed 99 never blinked at all, which is + * what made it survive review: the wind direction and base speed are per-city, so whether + * the piece's heaviest sky switches itself off depends on the seed. At 0.24 a band is + * 4.2 m, so three sit across the near shell and eight across the far one, and a gust + * becomes a thing that walks past you rather than a light being turned off. + * + * The travel term MUST use the same constant: shPh is in the same noise-space units as the + * sample, so the pair is what makes the bands move at exactly WIND.speed. Two literal + * 0.085s meant one of them could be tuned without the other, at which point the sheets + * start sliding at the wrong speed for the wind that is drawing them. + * + * SH_MIN is the floor, and it is what stops the modulation ever being an extinction: the + * old code culled the drop outright below 0.30, which is not a gust, it is the rain being + * switched off. A gust thins a curtain. Mean is now a shade over 1 rather than exactly 1, + * which is the right side to err on — the cull it replaces took brightness away. */ + var SH_K = 0.24, SH_MIN = 0.30; + var shAmp = clamp(0.62 * dWind, 0, 1.0); + var shPh = -tt * WIND.speed * SH_K; + var splash = clamp((pRain - 0.60) / 0.40, 0, 1); + + for (var i = 0; i < use; i++) { + if ((i & 1) === 1 && i >= farUse) continue; // far shell thinned; near shell never is + var b = rBox[i]; + var wx = vX + wrap(rOx[i] - vX, b); + var wz = vZ + wrap(rOz[i] - vZ, b); + + var rx = wx - vX, rz = wz - vZ; + var w = rx * vFwx + rz * vFwz; + if (w < 0.5) continue; // behind the eye; cheapest possible cull + var rr = rx * vRgx + rz * vRgz; + if (rr > vHalf * 1.3 * w || rr < -vHalf * 1.3 * w) continue; + + /* The band this drop is standing in. Sampled at the drop's absolute world position, not + * at its wrapped offset, so a drop that has just recycled across the box joins the band + * that is passing over it rather than carrying the old one with it. */ + var sh = vnoise((wx * WIND.dirX + wz * WIND.dirZ) * SH_K + shPh, wSeed + 61); + var sm = 1 - shAmp + 2 * shAmp * sh; + /* The near shell is lifted FIRST and then floored, in that order. Written the other way + * round — which is how it shipped — the lift ran after a `continue` that had already + * thrown the drop away, and since the lift's own output floor of 0.35 sits above the old + * 0.30 cutoff it could not have rescued a single drop even if it had run. The line said + * "near streaks blink if fully modulated" and then let them blink. */ + if ((i & 1) === 0) sm = 0.35 + 0.65 * sm; // near streaks read as fast or not at all + if (sm < SH_MIN) sm = SH_MIN; // the gap between two curtains is thin, not empty + + var spd = rSpd[i] * fallK; + /* Rain lands ON things. Cycling the drop between the LOCAL surface height and the wrap + * height above it means a drop over a roof stops at the parapet instead of sinking into + * the building, where CC.put would have hidden it anyway and the near field would have + * thinned out. */ + var fall = rFall[i]; + var gh = city ? city.height(wx, wz) : 0; + var ph = frac(rPh[i] + tt * spd / fall); + var y = gh + fall * (1 - ph); + var sleet = wSleet > 0.02 && hash1(i, wSeed + 71) < wSleet; + + if (!project(wx, y, wz)) continue; + var xf = pjX, yf = pjY, d = pjD; + + /* Exposure streak: how far this drop falls in one 20 ms shutter, in rows. Near drops get + * a long streak and far drops a single cell, which is the whole "heavier near" read — + * no density gradient needed. */ + var n = (spd * 0.021 * vScale / pjW) | 0; + if (sleet) n = (n * 0.45) | 0; + if (n > nMax) n = nMax; + var lean = (wRight / spd) / vCellA; + if (sleet) lean *= 0.55; // heavier than water; the wind gets less of it + + var base = (b < 20 ? 118 : 68 * (0.70 + 0.30 * dens)) * + (1 - clamp(pjW / (b < 20 ? 15 : 30), 0, 0.68)) * sm; + var hue = sleet ? (hash1(i, wSeed + 73) < 0.45 ? P.ice : P.white) : rHue[i]; + var gl = lean > 0.55 ? G_BSL : (lean < -0.55 ? G_SLASH : G_PIPE); + if (sleet) gl = n === 0 ? G_STAR : G_SEMI; // a hailstone is a grain, not a stroke + else if (n === 0) gl = d > 14 ? G_DOT : G_QUOTE; + + for (var k = 0; k <= n; k++) { + var sy = Math.floor(yf - k); + if (sy < 0 || sy >= rows) continue; + var sx = Math.floor(xf + lean * k); + if (sx < 0 || sx >= cols) continue; + /* The tail is the older, more spread part of the streak, so it fades. */ + var lm = fogLum(base * (1 - k * 0.19), d); + if (lm < 5) continue; + put(frame, sx, sy, gl, hue, lm, d); + } + + /* Splash-back. The drop is about to reach the surface it is falling onto — ph runs to 1 + * at the moment of impact — so the crown is drawn at the drop's own landing point, which + * costs no search and puts the splash exactly where the eye just watched something land. + * Only the near shell: a splash 30 m down the street is a quarter of a cell. + * Gated hard, because at a downpour's density every near drop landing in the same sixth + * of a second would carpet the road: a quarter of them splash, and only above the + * reference rain, so `rain` keeps the road it already had and a downpour gets the band of + * ticks that says how hard it is coming down. */ + if (splash > 0 && (i & 1) === 0 && ph > 0.94 && hash1(i, wSeed + 79) < 0.30 * splash) { + var sa = (ph - 0.94) / 0.06; // 0 at contact, 1 as the crown collapses + var slum = fogLum(126 * splash * (1 - sa * 0.75), d); + if (slum > 6 && project(wx, gh + 0.05, wz)) { + var bx = Math.floor(pjX), by = Math.floor(pjY); + var shue = hash1(i, wSeed + 83) < 0.6 ? P.amber : P.ice; + put(frame, bx, by, sleet ? G_DOT : G_UNDER, shue, slum, pjD); + var lift = sa < 0.5 ? 1 : 2; // the crown climbs as it opens out + put(frame, bx - 1, by - lift, G_QUOTE, shue, slum * 0.7, pjD); + put(frame, bx + 1, by - lift, G_TICK, shue, slum * 0.7, pjD); + } + } + } + } + + /* Drips run off the same element because they are the same water, and because they must + * outlive the drops: this is the whole post-storm period. */ + if (dripAmt > 0.02 && city) drips(frame, city, tt); + } + }); + + /* ---- ledges and awnings -------------------------------------------------------------------- + * Sources are found the way the steam finds its grates — by hashing a world lattice around the + * camera each frame — but with one extra condition that makes them ledges rather than puddles: + * the point must be standing on the street with a WALL within reach of it. That is the awning + * line, the strip of pavement under the overhang, and it is where a city drips from. + * + * The fall is real: y = h - g*t^2/2, so the bead accelerates and the last few centimetres are + * two cells instead of one. A linear fall reads as a lift descending. */ + var DR_PITCH = 3.0, DR_R = 21, DR_P = 0.30, drSeed = 0; + function drips(frame, city, tt) { + var gi0 = Math.floor((vX - DR_R) / DR_PITCH), gi1 = Math.floor((vX + DR_R) / DR_PITCH); + var gj0 = Math.floor((vZ - DR_R) / DR_PITCH), gj1 = Math.floor((vZ + DR_R) / DR_PITCH); + var rows = frame.rows; + + for (var gj = gj0; gj <= gj1; gj++) { + for (var gi = gi0; gi <= gi1; gi++) { + if (hash2(gi, gj, drSeed) > DR_P) continue; + var px = gi * DR_PITCH + hash2(gi, gj, drSeed + 11) * DR_PITCH * 0.9; + var pz = gj * DR_PITCH + hash2(gi, gj, drSeed + 22) * DR_PITCH * 0.9; + + /* Frustum reject before any heightmap work: city.height() is a chunk lookup and this + * lattice is 15x15 points a frame. */ + var rx = px - vX, rz = pz - vZ; + var w0 = rx * vFwx + rz * vFwz; + if (w0 < 0.8 || w0 > 26) continue; + var r0 = rx * vRgx + rz * vRgz; + if (r0 > vHalf * 1.4 * w0 + 3 || r0 < -(vHalf * 1.4 * w0 + 3)) continue; + if (city.height(px, pz) > 0) continue; // inside a building; there is no pavement here + + /* One of the four cardinal directions, and the wall has to be in it. Testing all four + * would double the heightmap traffic to find the same ledges twice as often. */ + var q = hash2(gi, gj, drSeed + 33); + var dx = q < 0.25 ? 1 : (q < 0.5 ? -1 : 0); + var dz = q < 0.5 ? 0 : (q < 0.75 ? 1 : -1); + if (!(city.height(px + dx * 1.4, pz + dz * 1.4) > 0)) continue; + + /* Sit the drip line just under the overhang rather than out in the road. */ + var lx = px + dx * 0.55, lz = pz + dz * 0.55; + var h = 2.5 + hash2(gi, gj, drSeed + 44) * 1.2; + var tf = Math.sqrt(h / 4.9); // seconds of fall, real gravity + /* Drying slows the drip rate before it stops it, which is what a ledge does. */ + var per = (0.55 + hash2(gi, gj, drSeed + 55) * 1.30) / (0.25 + 0.75 * dripAmt); + + /* Ice is a GLINT, never a surface, and a bead of water catching a streetlight is the + * definition of one — but only a third of them are angled to catch it. The rest are the + * slate of unlit water, and the ones that land are the amber of the lamp that lit the + * pavement they landed on. */ + var hue = hash2(gi, gj, drSeed + 66) < 0.35 ? P.ice : P.slate; + var lhue = hash2(gi, gj, drSeed + 88) < 0.55 ? P.amber : P.ice; + + for (var k = 0; k < 2; k++) { + /* The lattice cell goes in as a COORDINATE, never as an addition to the seed: a walk long + * enough takes gi into the thousands, and folding that into the seed slides every drip in + * the city onto a different hash stream as the camera travels. */ + var p = frac(tt / per + k * 0.5 + hash2(gi * 2 + k, gj, drSeed + 77)); + var age = p * per; + if (age > tf + 0.14) continue; // gone; the bead has not re-formed yet + if (age > tf) { + /* Landed. A single bright tick on the wet pavement, for two frames' worth of time. */ + if (!project(lx, 0.04, lz)) continue; + var ll = fogLum(150 * dripAmt * (1 - (age - tf) / 0.14), pjD); + if (ll < 6) continue; + put(frame, Math.floor(pjX), Math.floor(pjY), G_UNDER, lhue, ll, pjD); + continue; + } + var y = h - 4.9 * age * age; + /* Drift is tiny — the drip is heavy and the fall is short — but a ledge in a gale does + * not drip straight down, and it comes free from the shared wind. */ + if (!project(lx + WIND.x * age * 0.05, y, lz + WIND.z * age * 0.05)) continue; + var lum = fogLum((66 + 90 * (age / tf)) * dripAmt, pjD); + if (lum < 6) continue; + var cy = Math.floor(pjY), cx = Math.floor(pjX); + put(frame, cx, cy, age < tf * 0.35 ? G_DOT : G_QUOTE, hue, lum, pjD); + /* Past halfway it is moving fast enough to expose as a short streak. */ + if (age > tf * 0.55 && cy - 1 >= 0 && cy - 1 < rows) + put(frame, cx, cy - 1, G_QUOTE, hue, lum * 0.55, pjD); + } + } + } + } + + /* ============================================================================================ + * STEAM — grates, street vents, and the viewer's own breath + * Sources are found by hashing a world lattice around the camera each frame rather than being + * stored, so the walk can go on forever without a spawn list that grows without bound. The + * plume itself is a pure function of t, which means no accumulated state to drift out of sync + * when the frame rate changes or the viewer scrubs. + * ==========================================================================================*/ + /* Most lattice points land inside a building and are thrown away, so the hit rate below is not + * the vent density on the street — it is about a fifth of it. At pitch 4 and p=0.28 the walk + * passes a working grate every twenty seconds or so, which is what "occasional" means here. */ + var ST_PITCH = 4, ST_R = 24, ST_NP = 5, ST_P = 0.28; + var stSeed = 0, stT = 0; + + CC.ELEMENTS.push({ + name: 'steam', + layer: 14, + init: function (city, rng) { + bindWorld(city, rng); + stSeed = smallSeed(rng); + }, + update: function (dt, t) { stT = t; syncWeather(t); }, + draw: function (frame, cam, t) { + var tt0 = t !== undefined ? t : stT; + syncWeather(tt0); + bindView(frame, cam); + var city = WCITY; + if (!city) return; + var tt = CC.reducedMotion ? 7.3 : tt0; + /* Cold air condenses more of it and warm air takes it back before it clears the grate, so + * the volume tracks P.steam and the chill together. */ + var vol = clamp(0.35 + 0.65 * dSteam, 0, 1.5) * (1 + 0.25 * wBreath); + var gate = ST_P * vol; + var gi0 = Math.floor((vX - ST_R) / ST_PITCH), gi1 = Math.floor((vX + ST_R) / ST_PITCH); + var gj0 = Math.floor((vZ - ST_R) / ST_PITCH), gj1 = Math.floor((vZ + ST_R) / ST_PITCH); + + for (var gj = gj0; gj <= gj1; gj++) { + for (var gi = gi0; gi <= gi1; gi++) { + if (hash2(gi, gj, stSeed) > gate) continue; + var sx = gi * ST_PITCH + hash2(gi, gj, stSeed + 11) * ST_PITCH * 0.9; + var sz = gj * ST_PITCH + hash2(gi, gj, stSeed + 22) * ST_PITCH * 0.9; + + /* Cheap frustum reject before touching the heightmap: city.height() is a chunk lookup + * and the lattice is 13x13 points a frame. */ + var rx = sx - vX, rz = sz - vZ; + var w0 = rx * vFwx + rz * vFwz; + if (w0 < -2 || w0 > 42) continue; + var r0 = rx * vRgx + rz * vRgz; + if (r0 > vHalf * 1.5 * w0 + 6 || r0 < -(vHalf * 1.5 * w0 + 6)) continue; + if (city.height(sx, sz) > 0) continue; // a vent inside a building is a vent nobody sees + + var sd = (hash2(gi, gj, stSeed + 33) * 30011) | 0; + /* Cold air holds the plume together for longer; wind shears it apart and flattens its + * climb, which is why the rise falls off as the wind rises rather than rising with it. */ + var life = (3.2 + hash2(gi, gj, stSeed + 44) * 2.4) * (1 + 0.45 * wBreath); + /* Both factors are 1.0 at the reference sky — 0.70+0.30 and 1-0 — which is the migration + * rule: a scale that comes out at 1.15 under `rain` has quietly re-tuned the element. */ + var rise = (0.72 + hash2(gi, gj, stSeed + 55) * 0.55) * + (0.70 + 0.30 * clamp(dSteam, 0, 1.4)) * (1 - 0.22 * clamp(dWind - 1, 0, 1)); + /* A third of the sources are a dry exhaust rather than a steam grate: same shape, much + * dimmer and colder, so the street does not read as a laundry. */ + var smoke = hash2(gi, gj, stSeed + 66) < 0.34; + var pk = (smoke ? 46 : 88) * clamp(0.55 + 0.45 * dSteam, 0, 1.35); + plume(frame, sx, sz, sd, life, rise, pk, smoke, tt); + } + } + + /* The viewer is standing in the same cold air as the grates are. */ + if (wBreath > 0.15) breath(frame, tt); + } + }); + + function plume(frame, sx, sz, sd, life, rise, peak, smoke, tt) { + var rows = frame.rows, cols = frame.cols; + for (var k = 0; k < ST_NP; k++) { + var p = frac(tt / life + k / ST_NP + hash2(k, 0, sd)); + var age = p * life; + var y = 0.12 + age * rise; + /* Drift is the puff's whole history of wind, so it integrates: the top of a plume trails + * further downwind than its root, which is what makes it read as rising and not sliding. + * It reads the gusting vector, so a gust bends the whole column over and it straightens + * again from the root up as the gust passes. */ + var wob = (vnoise(age * 0.9 + k * 3.7, sd) - 0.5) * age * 0.55; + var px = sx + WIND.x * age * 0.34 + wob; + var pz = sz + WIND.z * age * 0.34 - wob * 0.6; + if (!project(px, y, pz)) continue; + + /* Fade in fast off the grate, out slowly: a puff appears already formed and then thins. + * Multiplying the two ramps rather than squaring one keeps the middle of the puff's life at + * full brightness — squaring it left the whole plume at a third of peak and invisible. */ + var a = clamp(p / 0.12, 0, 1) * clamp((1 - p) / 0.55, 0, 1); + /* GUTTERING. A vent does not breathe evenly; it surges and lulls. The surge is sampled at + * the time this puff LEFT the grate — tt-age, not tt — so it travels up the column with the + * air that carried it. Sampling it at the current time instead brightens and dims the whole + * plume at once, which is a pulse: exactly the uniform throb this replaces. */ + var gut = vnoise((tt - age) * 0.42 + sd * 0.013, sd + 77); + /* 0.66 + 1.09*u^2 has MEAN 1 over this noise, which is the whole reason those two numbers + * are not round: E[u^2] for a smoothstep-interpolated value field is 0.312, not the 0.333 a + * uniform would give. A gutter that averages 0.65 is not a gutter, it is a 35% dimmer on the + * whole element, and it would have re-tuned the steam under the very preset it was tuned in. */ + var lum0 = peak * a * (0.66 + 1.09 * gut * gut); + if (lum0 < 5) continue; + /* Sodium light only reaches the first couple of metres above the road. Above that the plume + * is lit by nothing and goes slate — that vertical colour break is most of the depth cue, + * and the amber root is what ties the steam to the street lighting instead of leaving it a + * grey smudge floating in the canyon. */ + var hue = (!smoke && y < 2.2) ? P.amber : P.slate; + + var rad = 0.22 + age * 0.30; + var rv = rad * vScale / pjW; + var kv = rv < 0.75 ? 0 : 1; + var rh = rv / vCellA; + var kh = rh < 0.75 ? 0 : (rh < 1.9 ? 1 : 2); + var cx = Math.floor(pjX), cy = Math.floor(pjY), d = pjD; + + for (var dy = -kv; dy <= kv; dy++) { + var yy = cy + dy; if (yy < 0 || yy >= rows) continue; + for (var dx = -kh; dx <= kh; dx++) { + var xx = cx + dx; if (xx < 0 || xx >= cols) continue; + /* Keyed on the puff and the offset, never on screen position, so the holes in the puff + * travel with it instead of shimmering in place. */ + var hh = hash2(k * 17 + dx, dy * 5, sd + 401); + if (hh > 0.42) continue; + var lm = fogLum(lum0 * (0.55 + hh * 1.05), d); + if (lm < 5) continue; + /* In cold air a few cells go white — condensed water rather than warm vapour. It is a + * handful of cells and it is the difference between steam and breath. */ + var hue2 = (hue === P.slate && wBreath > 0.5 && hh < 0.10) ? P.white : hue; + put(frame, xx, yy, hh < 0.14 ? G_COLON : (hh < 0.28 ? G_DOT : G_COMMA), hue2, lm, d); + } + } + } + } + + /* ---- the viewer's breath -------------------------------------------------------------------- + * The one thing in the file that is camera-relative rather than world-fixed, and deliberately: + * it is attached to the person doing the looking. Three puffs on a 4.4 s cycle, launched a metre + * in front of the eye, drifting off with the wind and dying inside two metres. It only exists + * when the derived chill says the air is cold enough to condense it, so most nights never see it. + * It sits BELOW the eye line — breath leaves a mouth, not a forehead — which also keeps it out of + * the middle of the picture. */ + function breath(frame, tt) { + var rows = frame.rows, cols = frame.cols; + var per = 4.4; + for (var k = 0; k < 3; k++) { + var p = frac(tt / per + k * 0.16); + if (p > 0.55) continue; // most of the cycle is between breaths + var age = p * per; + var fwd = 0.85 + age * 0.55; + var px = vX + vFwx * fwd + WIND.x * age * 0.22; + var pz = vZ + vFwz * fwd + WIND.z * age * 0.22; + var y = vEyeY - 0.26 + age * 0.16; + if (!project(px, y, pz)) continue; + var a = clamp(age / 0.25, 0, 1) * clamp((2.4 - age) / 1.6, 0, 1); + var lum0 = 58 * a * wBreath; + if (lum0 < 5) continue; + var rad = 0.07 + age * 0.16; + var rv = rad * vScale / pjW; + var kv = rv < 0.8 ? 0 : 1; + var rh = rv / vCellA; + var kh = rh < 0.8 ? 0 : (rh < 2.2 ? 1 : 2); + var cx = Math.floor(pjX), cy = Math.floor(pjY), d = pjD; + for (var dy = -kv; dy <= kv; dy++) { + var yy = cy + dy; if (yy < 0 || yy >= rows) continue; + for (var dx = -kh; dx <= kh; dx++) { + var xx = cx + dx; if (xx < 0 || xx >= cols) continue; + var hh = hash2(k * 13 + dx, dy * 7, wSeed + 503); + if (hh > 0.38) continue; + /* White for the core of the puff and slate for its edge: white is structure, not light, + * and a breath that is white all through reads as a printed shape rather than as vapour. */ + put(frame, xx, yy, hh < 0.16 ? G_DOT : G_COMMA, + hh < 0.18 ? P.white : P.slate, lum0 * (0.5 + hh), d); + } + } + } + } + + /* ============================================================================================ + * FOG BANKS, and the collapse of visibility + * The bank is drawn as the top surface of a shallow layer of air, sampled per screen row by the + * same inverse projection the road uses. Because the layer sits at 0.85 m and the eye at 1.7 m, + * its depth at any row is roughly half the road's depth at that row, so it wins the depth test + * against the tarmac and loses it against anything standing on the tarmac. That is exactly the + * behaviour wanted and it falls out of the geometry rather than out of a fudge factor. + * + * Above the reference sky it stops being a bank at all and becomes the medium the city is + * standing in: the VEIL pass at the bottom re-reads what is already in the frame and takes it + * away with distance. That is the difference between `mist` and everything else — mist is not + * rain with fewer drops, it is a state where the far end of the street is simply not there. + * ==========================================================================================*/ + var fgSeed = 0, fgT = 0; + /* Fewer cells, brighter each. At a 0.40 dither the bank cost 1.2 points of coverage and was + * still invisible — a lot of lum-12 slate is just an expensive way to draw nothing. */ + var FG_TOP = 0.85, FG_TH = 0.44, FG_DITHER = 0.34; + + CC.ELEMENTS.push({ + name: 'fogbank', + layer: 8, + init: function (city, rng) { + bindWorld(city, rng); + fgSeed = smallSeed(rng); + }, + update: function (dt, t) { fgT = t; syncWeather(t); }, + draw: function (frame, cam, t) { + var tt0 = t !== undefined ? t : fgT; + syncWeather(tt0); + bindView(frame, cam); + var tt = CC.reducedMotion ? 0 : tt0; + var rows = frame.rows, cols = frame.cols; + var thick = clamp(dFog, 0, 3.4); + /* The layer deepens with the fog: a floor mist at 0.85 m, and by the `mist` preset it is up + * around the shoulders, which is what actually removes the road from the picture rather than + * decorating it. Capped below the eye — once the camera is inside the layer the top surface + * is behind the viewer and there is nothing left to draw. */ + var top = FG_TOP + 0.42 * clamp(thick - 1, 0, 2.4) - 0.30 * clamp(1 - thick, 0, 1); + /* The top surface must stay below the eye by a real margin. Let it climb to the eye line and + * the inverse projection degenerates — every row below the horizon returns almost the same + * distance — and the bank prints as one hard bar ruled across the street instead of a floor + * that recedes. Thick fog is sold by the veil below, not by pushing this to the eye. */ + if (top > vEyeY - 0.45) top = vEyeY - 0.45; + var rise = vEyeY - top; + if (rise < 0.15) return; // camera has ducked into the layer + /* Threshold down and dither up together: the bank both spreads and fills in. Every one of the + * three moves in BOTH directions around the reference — `hi` for skies thicker than `rain`, + * `lo` for thinner ones — because a coefficient that only reads clamp(thick-1,0,..) is zero + * for every sky below the reference and `clear` at P.fog 0.08 would draw the identical floor + * mist `rain` does at 0.30. The thin end is as much of this element's job as the thick end. + * + * The thick-end coefficients are deliberately modest: the first cut ran them to a 0.10 + * threshold, a 0.95 dither and a 2.3x glow, and mist cost four and a half points of lit + * coverage in the floor bank alone — a white carpet down the road, not a fog. The collapse of + * visibility is the veil's job; the bank only has to thicken enough to say the air is full. */ + var hi = clamp(thick - 1, 0, 2.4), lo = clamp(1 - thick, 0, 1); + var th = clamp(FG_TH - 0.075 * hi + 0.17 * lo, 0.10, 0.90); + var dith = clamp(FG_DITHER * (1 + 0.28 * hi - 0.60 * lo), 0, 0.95); + var glow = 1 + 0.16 * hi - 0.30 * lo; + /* Near and far limits of the bank. In thick fog it starts at your feet. */ + var nearW = lerp(4.5, 1.6, clamp(thick - 1, 0, 1)); + var farW = lerp(70, 96, clamp(thick - 1, 0, 1)); + + /* Only the low-frequency octave travels — the fine one is welded to the ground, so the bank + * evolves instead of sliding past as one rigid sheet. It moves at 0.18 of the wind, converted + * into noise-space units by the same 0.058 the sample uses: fog in the lee of a canyon barely + * moves, and at full wind speed the bank read as a scrolling texture. */ + var drx = WIND.x * tt * 0.18 * 0.058, drz = WIND.z * tt * 0.18 * 0.058; + var r0 = Math.ceil(vHorizon); + + for (var r = r0; r < rows; r++) { + var den = r + 0.5 - vHorizon; + if (den < 0.85) continue; + var w = rise * vScale / den; + if (w > farW) continue; + if (w < nearW) break; // nearer rows are inside the layer, not under it + /* Thin the bank out at both ends of its range: a hard edge at the near limit reads as a + * line ruled across the street. */ + var band = clamp((w - nearW) / 6, 0, 1) * clamp((farW - w) / 22, 0, 1); + /* The most a cell on this row can be dithered against. `amt` below is + * (bank-th)/(1-th)*band and both noises land in [0,1), so amt is strictly under `band` and + * this product is strictly above amt*dith — which makes the cheap test in the loop an + * EXACT rejection rather than an approximation of one. See the comment there. */ + var bandDith = band * dith; + + for (var x = 0; x < cols; x++) { + var sp = (2 * (x + 0.5) / cols - 1) * vHalf; + var dx = vFwx + vRgx * sp, dz = vFwz + vRgz * sp; + var px = vX + dx * w, pz = vZ + dz * w; + + /* THE DITHER IS TESTED FIRST, and that ordering is the whole cost of this element. + * The bank is dithered, never filled, so the great majority of the cells this loop walks + * were always going to be thrown away by the `hh > amt * dith` test at the bottom — and + * hh is ONE hash2 where the coarse octave below is four of them plus three lerps. + * Measured at 260x100, seed 42, one frame per sky: the loop evaluated 4680-7280 cells to + * draw 6 of them at `clear`, 45 at `rain` and 119 at `mist`. Hoisting the hash and + * testing it against the row's upper bound rejects the doomed cells for a quarter of the + * arithmetic. Nothing about the picture moves: hh > bandDith implies hh > amt*dith, so + * every cell rejected here is a cell the old order rejected too, and the canonical + * 16-frame sweep at 400x100 is byte-identical before and after. + * + * This is also why the bank has no weather gate and must not grow one. It is cheap at a + * clear sky because almost nothing survives the dither, not because it is switched off, + * and the thin floor mist a dry night gets is as much this element's job as a mist is. */ + var hh = hash2(Math.floor(px * 1.7), Math.floor(pz * 1.7), fgSeed + 7); + if (hh > bandDith) continue; + + /* The coarse octave carries 0.70 of the weight, so once it is under this the fine octave + * cannot lift the sum over the threshold however it lands — and skipping it saves four + * more hashes on the cell. The radial distance is derived BELOW this test and not above + * it for the same reason: `d` costs a sqrt and only a surviving cell has any use for it. + * Moving a test that can only reject to a later point in the same iteration cannot + * change which cells are drawn. */ + var coarse = n2(px * 0.058 + drx, pz * 0.058 + drz, fgSeed); + if (coarse * 0.70 + 0.30 <= th) continue; + var d = w * Math.sqrt(1 + sp * sp); + if (d > farW + 2) continue; + var bank = coarse * 0.70 + n2(px * 0.185, pz * 0.185, fgSeed + 5) * 0.30; + if (bank <= th) continue; + var amt = (bank - th) / (1 - th) * band; + /* Dithered, never filled. A solid low-lum fill here is the grey veil the whole project + * is built to avoid — it flattens the canyon in one pass. `hh` was already drawn at the + * top of the loop against this row's upper bound; this is the exact test it approximated. */ + if (hh > amt * dith) continue; + var lm = fogLum((14 + amt * 42) * glow, d); + if (lm < 5) continue; + put(frame, x, r, hh < 0.06 ? G_TILDE : (hh < 0.12 ? G_UNDER : G_DASH), P.slate, lm, d); + } + } + + veil(frame); + } + }); + + /* ---- the veil ------------------------------------------------------------------------------ + * Aerial perspective as a medium rather than as a curve: every cell already in the frame is + * asked how far away it is, and past a distance that shortens as the fog thickens it is either + * dimmed toward extinction or replaced outright by fog grain. That is what makes `mist` collapse + * — the far facades, the far signs and the far road do not fade to a tasteful haze, they stop + * being in the picture. + * + * IT DOES NOTHING AT OR BELOW THE REFERENCE SKY. The drive is 0.3165 under `rain` against a gate + * that opens at 0.34, so drizzle, rain and clear print exactly what they printed before this pass + * existed; mist pays for almost all of it and a downpour, whose own falling water is a medium + * whatever the fog parameter says, pays for the rest. + * + * Depth is honoured, not faked: a replaced cell is written at 0.999 of its own distance, so it + * still occludes correctly against everything drawn after it and the tone curve still treats it + * as far geometry. Writing the grain at a near distance instead would have let it swallow signs + * and rain that are physically in front of it. */ + function veil(frame) { + /* A downpour carries its own haze; it is a small term next to fog's, and it is why the far end + * of a heavy rain closes in even though the fog parameter has barely moved. */ + var drive = pFog + 0.55 * clamp(pRain - 0.62, 0, 0.38); + var v = clamp((drive - 0.34) / 0.50, 0, 1); + if (v < 0.015) return; + var cols = frame.cols, rows = frame.rows; + var ch = frame.ch, kind = frame.kind, dist = frame.dist, lum = frame.lum, col = frame.col; + /* Where the medium starts to bite and where it has finished. At full mist the street is gone + * by thirty metres, which is about four shopfronts. */ + var v0 = lerp(52, 7, v), v1 = lerp(120, 30, v); + var inv = 1 / (v1 - v0); + /* The sky slot fills in last and only in deep fog — a low cloud ceiling you cannot see past. + * It is written at 45 m rather than at the fog's near edge so that the rain, the steam and the + * signage in the first forty metres still draw over it; parking it at FOG_START would have cut + * the top off every raindrop above the rooftop line. */ + var skyV = clamp((v - 0.35) / 0.5, 0, 1); + var skyD = 45; + + for (var y = 0; y < rows; y++) { + for (var x = 0; x < cols; x++) { + var i = y * cols + x, d = dist[i]; + if (d >= vFar) { + if (skyV < 0.02) continue; + var sh = hash2(x, y, fgSeed + 61); + if (sh > skyV * 0.34) continue; + put(frame, x, y, sh < 0.05 ? G_TILDE : (sh < 0.14 ? G_DASH : G_DOT), + P.slate, (11 + 26 * skyV) * (0.6 + sh), skyD); + continue; + } + if (d <= v0 || ch[i] === 0) continue; + var a = (d - v0) * inv; + if (a > 1) a = 1; + a *= v; + /* Screen-stable grain, not a per-frame reroll: the medium is between the eye and the wall, + * so its texture belongs to the view, and a hash including t would boil. */ + var hh = hash2(x, y, fgSeed + 51); + if (hh < a * 0.34) { + /* Taken by the fog. Ambient back-scatter rises with the depth of medium in front of the + * cell and then falls away again with distance, which is what makes a fog bright near a + * streetlight and black at the end of the road. + * + * A CELL THAT WAS CARRYING A LIGHT KEEPS ITS COLOUR. Fog does not turn a sodium lamp + * grey, it turns it into a sodium-coloured smudge twice the size — so where the cell + * underneath is brighter than the ambient the grain inherits its swatch at a fraction of + * its luminance, and everywhere else it is slate. That single branch is the difference + * between a fog with a city glowing inside it and a grey sheet pulled over the frame. */ + var amb = (9 + 30 * a) * (1 - 0.55 * clamp(d / 70, 0, 1)); + var halo = lum[i] * 0.40; + var lm = halo > amb ? halo : amb; + var hue = halo > amb ? col[i] : P.slate; + if (lm < 4) lm = 4; + put(frame, x, y, hh < 0.05 * a ? G_TILDE : (hh < 0.20 * a ? G_DASH : G_DOT), + hue, lm, d * 0.999, 3); + } else { + var l0 = lum[i]; + if (l0 < 3) continue; + var nl = l0 * (1 - 0.86 * a); + if (nl >= l0 - 0.5) continue; // nothing to gain from rewriting the cell + put(frame, x, y, ch[i], col[i], nl, d * 0.999, kind[i]); + } + } + } + } + + /* ============================================================================================ + * LOW CLOUD + * The sky slot between the rooftops is the frame's biggest reservoir of black and it is not + * spent lightly — so this only exists ABOVE the reference sky. P.cloud is 0.75 under `rain` and + * the gate opens at 0.78, which means the four ordinary presets keep their stars and only a + * downpour and a storm get a ceiling scudding over the canyon. + * + * Geometry is the fog bank's, mirrored: a horizontal plane, this one 46 m up, inverse-projected + * per screen row above the horizon. Rows near the horizon are cloud a kilometre down the street, + * rows near the top of the frame are cloud directly overhead, and the perspective foreshortening + * that falls out of that is what makes it scud rather than slide. + * ==========================================================================================*/ + var clSeed = 0, clT = 0, CL_BASE = 46; + + CC.ELEMENTS.push({ + name: 'lowcloud', + layer: 7, + init: function (city, rng) { + bindWorld(city, rng); + clSeed = smallSeed(rng); + }, + update: function (dt, t) { clT = t; syncWeather(t); }, + draw: function (frame, cam, t) { + var tt0 = t !== undefined ? t : clT; + syncWeather(tt0); + var scud = clamp((pCloud - 0.78) / 0.22, 0, 1); + if (scud < 0.02) return; + bindView(frame, cam); + var tt = CC.reducedMotion ? 0 : tt0; + var cols = frame.cols, rows = frame.rows; + var dist = frame.dist; + var rise = CL_BASE - vEyeY; + /* Cloud runs ahead of the street-level wind — it is in the part of the air nothing is + * sheltering — and the 1.8 is what makes it read as weather passing over rather than as a + * texture pinned to the city. */ + var drx = WIND.x * tt * 1.8 * 0.0075, drz = WIND.z * tt * 1.8 * 0.0075; + var th = 0.52 - 0.16 * scud; + var r1 = Math.floor(vHorizon); + if (r1 > rows) r1 = rows; + + for (var r = 0; r < r1; r++) { + var den = vHorizon - (r + 0.5); + if (den < 0.9) continue; // the horizon itself is infinitely far + var w = rise * vScale / den; + if (w > 900) continue; // beyond this a row is one cloud smear + /* Fade the ceiling out as it approaches the horizon, or the last row before the rooftops + * prints as a hard bar of cloud ruled across the frame. */ + var band = clamp((900 - w) / 420, 0, 1); + if (band < 0.04) continue; + + for (var x = 0; x < cols; x++) { + var i = r * cols + x; + /* Sky and sky elements only. Anything nearer than 200 m is the city or something + * standing in it, and a cloud in front of a rooftop is not a cloud. */ + if (dist[i] < 200) continue; + var sp = (2 * (x + 0.5) / cols - 1) * vHalf; + var dx = vFwx + vRgx * sp, dz = vFwz + vRgz * sp; + var px = vX + dx * w, pz = vZ + dz * w; + /* 0.0075 is a 130 m feature; anything finer turns into noise at this distance. */ + var c = n2(px * 0.0075 + drx, pz * 0.0075 + drz, clSeed); + if (c <= th) continue; + var amt = (c - th) / (1 - th) * band * scud; + var hh = hash2(x, r, clSeed + 9); + if (hh > amt * 0.55) continue; + /* Lit from below by the city, so the underside near the rooftops carries more of it. */ + var lm = (9 + 26 * amt) * (0.65 + 0.35 * (r / (r1 + 1))); + put(frame, x, r, hh < 0.07 ? G_TILDE : (hh < 0.16 ? G_EQ : (hh < 0.34 ? G_DASH : G_UNDER)), + P.slate, lm, 60); + } + } + } + }); + + /* ============================================================================================ + * LIGHTNING + * The one element that does not add geometry: it re-reads what is already in the frame and + * re-puts it brighter, at a hair less than its own depth so CC.put accepts the overwrite. That + * keeps the flash physically honest — a wall the camera cannot see does not light up — and it + * costs no new silhouette. + * Strikes are far away, so the light arrives attenuated by the same fog curve the city uses, + * which means a flash reveals the near façades and leaves the far ones dark. That is what makes + * it read as a strike behind the skyline rather than a global brightness knob. + * ==========================================================================================*/ + var lgSeed = 0, lgI = 0, lgSide = 0, lgBear = 0, lgChan = 0; + var LG_PER = 5.5; // seconds per candidate strike window + var LG_DUR = 1.20; // seconds a stroke stays above zero + var LG_W = 6.8, LG_RISE = 0.15, LG_DECAY = 2.7, LG_FADE = 0.18; + var LG_JIT = 0.5; // earliest a stroke may start inside a window + /* A window fires at full strength when its requirement q is under P.storm*LG_K and fades out + * over the LG_BAND above it. The pair is FITTED, not chosen: the expected strength of a window + * is P.storm*LG_K + LG_BAND/2, and at the reference storm of 0.12 that has to come out at + * LG_PER/25.8 = 0.213 — one full-strength stroke every 25.8 s, which is the rate the 16 s + * window and its 0.62 chance produced before the storm had a rate at all. At P.storm 1 the same + * expression gives 0.90, a stroke every six seconds, and that is the headline. */ + var LG_K = 0.78, LG_BAND = 0.24; + /* Subtracted from every stroke, never used as a cutoff. `if (I < LG_FLOOR) return` reads like the + * same thing and is not: it makes the flash APPEAR at LG_FLOOR, a step edge whose size relative + * to the stroke grows without bound as the stroke gets weaker, and the regression test caught it + * at 44% of peak on a stroke near the gate's edge. Subtracting instead means the visible + * intensity leaves and returns to zero continuously whatever the amplitude, which is the property + * that actually matters, and it costs a full stroke 2% of itself. + * + * IT IS SUBTRACTED FROM THE ENVELOPE, NOT FROM THE SCALED INTENSITY, and that distinction is the + * whole of the fix that landed here at integration. Taken off the intensity, the floor is a + * FIXED amount off a VARIABLE peak, so on a weak sky it is a large fraction of the stroke and + * eats the first frames of the 0.15 s attack: under `drizzle` (storm 0.02) it clipped the ramp + * to 0.00 -> 6.12 -> 9.80, a 36.6%-of-peak step edge in one frame, over the 34% ceiling this + * file is written to. Nothing about that was visible before, because tools/lightning-rate.cjs + * loaded no weather director and so only ever measured the reference sky. Taken off the + * envelope — which is amplitude-invariant by construction, see lgEnv — the floor is the same + * 3.7% of peak on every stroke at every storm level, the attack keeps all of its frames, and the + * worst step stays at the envelope's own 21% whatever the sky is doing. At full amplitude, which + * is what the reference measurement samples, the two forms are the same number. */ + var LG_FLOOR = 0.02; + + /* PHOTOSENSITIVITY. THIS FUNCTION IS THE ONE PLACE IN THE PROJECT THAT CAN HURT SOMEBODY. + * It is written to a hard rule, not to taste: NO TWO BRIGHT PEAKS CLOSER THAN 0.34 s AND NO + * STEP EDGES ANYWHERE. Nothing below may be retuned by eye — retune it, then re-run + * node tools/lightning-rate.cjs + * and read the printed peak gap and single-frame step back out. + * + * The first cut multiplied the decay by a piecewise-CONSTANT table of returns, + * e * (u<0.045 ? 1 : u<0.085 ? 0.16 : u<0.15 ? 0.88 : u<0.22 ? 0.28 : 0.46) + * and it strobed. Sampled per 60 Hz frame across a stroke it ran 57.4, 52.3, 47.7, 6.6, 5.9, + * 5.4, 28.9, 26.3, 24.0, 6.6 added lum per cell — bright/dark/bright/dark with its two maxima + * 0.100 s apart, 10 Hz instantaneous against a 3 Hz ceiling, and one 16 ms frame dropping + * 47.7 -> 6.6, the entire amplitude of the flash in a single frame across the whole viewport. + * Every one of those edges came from the ternaries: a constant multiplier that changes value at + * a threshold IS a step, however smooth the exponential it multiplies. + * + * What replaced it is one continuous function with a bounded derivative everywhere. + * - cos(u*LG_W) rides on a 0.55 floor, so the trough between the returns dims rather than + * extinguishes and the eye reads a pulse instead of a blink; + * - max(0, cos) flattens the negative lobe into a plateau rather than inverting it into a + * third peak, which is what keeps the count at exactly two maxima; + * - LG_W = 6.8 puts the second return 0.924 s after the first in the raw cosine; the decay + * drags it forward and the onset ramp pushes the first back, and the MEASURED gap is + * 0.667 s = 1.50 Hz, half the ceiling, with the second return at 14% of the first; + * - the 0.15 s raised-cosine attack replaces an onset that stepped 0 -> full amplitude in one + * frame. It brings the largest single-frame change down from 100% of peak to 20.9%; + * - LG_FADE does the same job at the other end, because a hard cutoff at LG_DUR is a step + * edge too, just a dimmer one. + * + * NOTHING IN THIS FUNCTION IS ALLOWED TO DEPEND ON THE WEATHER. The storm parameter moves how + * OFTEN a stroke fires and how BRIGHT it is, never the shape or the timing of one, because the + * shape and the timing are the only things the safety measurement can check. A storm that also + * shortened LG_DUR or widened LG_W would be a different envelope on every frame and the + * regression test would be measuring a sky nobody ever sees. + * + * The strike windows are the outer guarantee, and they got TIGHTER rather than looser when the + * storm gained a rate: the window is 5.5 s and the start jitter runs from LG_JIT to LG_PER-1.2, + * so two strokes from adjacent windows can be no closer than LG_JIT + 1.2 = 1.7 s — half a + * second further apart than the 1.2 s the old 16 s window allowed. update() takes the MAXIMUM of + * the overlapping windows and never their sum, so two strokes cannot add into a brighter one, + * and the maxima of a maximum are the maxima of its arguments: overlapping strokes cannot + * manufacture a peak that neither of them has. */ + function lgEnv(u) { + if (u < 0 || u > LG_DUR) return 0; + var e = Math.exp(-u * LG_DECAY); + if (u < LG_RISE) e *= smooth(u / LG_RISE); // soft attack, never a step + /* The tail has to reach zero on its own or the cutoff at LG_DUR is itself a step edge. */ + if (u > LG_DUR - LG_FADE) e *= smooth((LG_DUR - u) / LG_FADE); + if (CC.reducedMotion) return e; // no returns at all for a viewer who asked + var c = Math.cos(u * LG_W); + return e * (0.55 + 0.45 * (c > 0 ? c : 0)); + } + + CC.ELEMENTS.push({ + name: 'lightning', + layer: 40, + init: function (city, rng) { + bindWorld(city, rng); + lgSeed = smallSeed(rng); + }, + update: function (dt, t) { + syncWeather(t); + lgI = 0; + /* A sky with no storm in it has no lightning in it. Not rare lightning: none. */ + if (pStorm < 0.004) return; + /* Amplitude relative to the reference sky, which is `rain` at storm 0.12 — a distant, + * occasional flicker. Above that the strokes get a little brighter and a lot more frequent; + * below it they fade out before the gate closes on them. */ + var ampS = 0.55 + 0.45 * clamp(pStorm / REF_STORM, 0, 1) + + 0.28 * clamp((pStorm - REF_STORM) / (1 - REF_STORM), 0, 1); + var best = 0, side = 0, bear = 0, chan = 0, bestE = 0, bestA = 0; + var n = Math.floor(t / LG_PER); + /* Look at the previous window too: a strike late in it can still be decaying now. One window + * back is enough and provably so — the latest a stroke can start is (LG_PER-1.2) into its + * window and it lasts 1.2 s, so it cannot survive past that window's end. */ + for (var j = n - 1; j <= n; j++) { + /* Each window has a fixed storm REQUIREMENT rather than a fixed chance, and the ramp over + * it is smooth. That is what lets the rate rise with the storm without any stroke ever + * switching on or off in the middle of itself: as P.storm crosses a window's requirement + * the stroke fades up from nothing over a tenth of the parameter, and P.storm itself only + * moves on the director's 14 s blend. A hard `hash > threshold(storm)` test instead would + * extinguish a stroke mid-decay the moment the threshold crossed it — a step edge across + * the whole viewport, which is the one thing this file may never print. */ + var q = hash1(j, lgSeed + 5); + var gate = (pStorm * LG_K - q) / LG_BAND + 1; + if (gate <= 0) continue; + gate = gate >= 1 ? 1 : smooth(gate); + var st = j * LG_PER + LG_JIT + hash1(j, lgSeed + 1) * (LG_PER - 1.2 - LG_JIT); + var amp = (0.42 + hash1(j, lgSeed + 2) * 0.58) * ampS * gate; + var ev = lgEnv(t - st); + var v = ev * amp; + if (v > best) { + best = v; bestE = ev; bestA = amp; + side = hash1(j, lgSeed + 3) < 0.5 ? -1 : 1; + bear = hash1(j, lgSeed + 4) * 6.283185; + chan = hash1(j, lgSeed + 6); + } + } + /* The floor comes off the envelope and the amplitude goes back on afterwards — see LG_FLOOR. + * Taking the max over the SCALED strokes and then flooring the winner's own envelope is + * exact, not an approximation: both values belong to the same stroke. */ + best = bestE > LG_FLOOR ? bestA * (bestE - LG_FLOOR) : 0; + lgI = best <= 0 ? 0 : (CC.reducedMotion ? best * 0.28 : best); + lgSide = side; lgBear = bear; lgChan = chan; + }, + draw: function (frame, cam) { + var I = lgI; + if (I <= 0) return; // the overwhelming majority of frames + bindView(frame, cam); + var cols = frame.cols, rows = frame.rows; + var ch = frame.ch, kind = frame.kind, dist = frame.dist, lum = frame.lum, col = frame.col; + var hz = vHorizon; + /* How far up the sky the cloudbase lights. A distant flicker under `rain` reaches the + * rooftop line and no further; a full storm lights the ceiling to the top of the frame. */ + var reach = 14 + 16 * clamp((pStorm - REF_STORM) / (1 - REF_STORM), 0, 1); + + for (var y = 0; y < rows; y++) { + var above = hz - y; + var sky = above > 0 && above <= reach ? I * 0.13 * (1 - above / reach) : 0; + for (var x = 0; x < cols; x++) { + var i = y * cols + x, k = kind[i], d = dist[i]; + + if (k === 0) { + /* Cloudbase, lit from behind. Only the sky near the rooftop line — a flash that lights + * the zenith turns the frame's biggest reservoir of black into grey. */ + if (sky === 0 || ch[i] !== 0) continue; + var sg = hash2(x, y, lgSeed + 193); + if (sg > sky) continue; + /* Sky is stored at Infinity and CC.put needs a strictly smaller depth, so the glow + * has to claim SOME finite distance. FOG_START is the only safe choice: anything past + * it would be crushed to black by a second, blanket fog pass, which surfaces.js + * explicitly says a caller is allowed to run. */ + put(frame, x, y, sg < 0.02 ? G_TICK : G_DOT, P.slate, + 14 + I * 40 * hash2(x, y, lgSeed + 197), SURF ? SURF.FOG_START : 12, 0); + continue; + } + if (d >= vFar) continue; + /* The flash obeys the city's own depth attenuation, so it cannot reach a wall the fog + * has already taken. */ + var att = fogLum(255, d) / 255; + if (att < 0.06) continue; + /* Light falls off across the frame away from the strike, which is what tells the viewer + * the storm has a direction. */ + var lat = 0.55 + 0.45 * (lgSide > 0 ? x / cols : 1 - x / cols); + var g = I * att * lat; + + if (ch[i] !== 0) { + var add = (k === 2 ? 46 : 78) * g; // wet tarmac takes the flash at a glancing angle + if (add < 4) continue; + put(frame, x, y, ch[i], col[i], lum[i] + add, d * 0.999, k); + } else if (k === 1) { + /* Black façade cells briefly show their structure. Dithered and dim: a full fill here + * doubles the frame's coverage for a third of a second and the flash reads as a + * white-out rather than as a building. */ + var fh = hash2(x, y, lgSeed + 211); + if (fh > g * 0.30) continue; + put(frame, x, y, fh < 0.10 ? G_PIPE : (fh < 0.20 ? G_COLON : G_QUOTE), + P.slate, 8 + g * 34, d * 0.999, k); + } + } + } + + /* The channel itself, at the top of the storm range only. It carries NO time structure of + * its own — its brightness is the same lgEnv the flash uses, so it cannot introduce a flash + * rate the measurement has not already checked — and it is one or two cells wide, so it is + * a thousandth of the viewport rather than a viewport-wide luminance step. */ + if (pStorm > 0.45 && I > 0.30 && lgChan < 0.55) bolt(frame, I, cols, rows); + } + }); + + /* The bolt is anchored to a world BEARING, not to a screen column: the storm is somewhere in + * particular, and turning your head has to be able to put it out of frame. */ + function bolt(frame, I, cols, rows) { + var yaw = Math.atan2(vFwx, vFwz); + var rel0 = lgBear - yaw; + while (rel0 > 3.14159265) rel0 -= 6.283185; + while (rel0 < -3.14159265) rel0 += 6.283185; + if (rel0 > 1.35 || rel0 < -1.35) return; // behind the viewer, or nearly + var sx0 = (Math.tan(rel0) / vHalf + 1) * 0.5 * cols; + if (sx0 < -4 || sx0 > cols + 4) return; + var strength = clamp((pStorm - 0.45) / 0.4, 0, 1) * clamp((I - 0.30) / 0.35, 0, 1); + var bottom = Math.floor(vHorizon) - 1; + if (bottom > rows - 1) bottom = rows - 1; + var x = sx0, dxs = (lgChan - 0.27) * 1.4; // the channel's overall lean + for (var y = 0; y <= bottom; y++) { + /* Keyed on the row and the stroke, so the channel is the same shape for the whole flash + * instead of re-drawing itself every frame. */ + x += dxs + (hash2(y, 0, lgSeed + 313 + ((lgChan * 811) | 0)) - 0.5) * 2.6; + var cx = Math.floor(x); + if (cx < 0 || cx >= cols) continue; + var i = y * cols + cx; + /* Stop at the skyline. 55 m is the test rather than the sky's own distance because the low + * cloud sits at 60 and a bolt that stopped at the cloud deck would be invisible in exactly + * the weather that fires it — the channel is BEHIND the cloud it is lighting up. */ + if (frame.dist[i] < 55) break; + var lm = (70 + 150 * I) * strength * (0.55 + 0.45 * (y / (bottom + 1))); + put(frame, cx, y, hash2(y, 1, lgSeed + 317) < 0.4 ? G_SLASH : G_PIPE, P.white, lm, 58); + /* A single fork, low down, on rather less than half the strokes. */ + if (lgChan < 0.22 && y > bottom * 0.55) { + var fx = (cx + (y - bottom * 0.55) * (lgChan < 0.11 ? -0.9 : 0.9)) | 0; + if (fx >= 0 && fx < cols && frame.dist[y * cols + fx] >= 55) + put(frame, fx, y, G_BSL, P.white, lm * 0.5, 58); + } + } + } + + if (CC) CC.Wind = WIND; + +})(typeof CC !== 'undefined' ? CC : require('../core.js')); diff --git a/src/main.js b/src/main.js new file mode 100644 index 0000000..4c2ceee --- /dev/null +++ b/src/main.js @@ -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')); diff --git a/src/raycast.js b/src/raycast.js new file mode 100644 index 0000000..503eb9a --- /dev/null +++ b/src/raycast.js @@ -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')); diff --git a/src/render_canvas.js b/src/render_canvas.js new file mode 100644 index 0000000..4b9a942 --- /dev/null +++ b/src/render_canvas.js @@ -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')); diff --git a/src/surfaces.js b/src/surfaces.js new file mode 100644 index 0000000..28bb45f --- /dev/null +++ b/src/surfaces.js @@ -0,0 +1,1390 @@ +/* CyberCity surfaces — pure texture lookups. No camera, no raycasting, and no per-FRAME state: + * the one piece of state in the file is two integers sky() keeps to recover the rooftop row of + * the column it is currently walking down, and it is rebuilt from scratch on every column. + * + * Every function is called once per screen cell, so nothing here allocates: each returns a + * module-level scratch object. THE CALLER MUST NOT RETAIN THE RETURNED OBJECT — copy ch/col/lum + * out before the next call to the same function. (facade/floorTex/sky each own a separate + * scratch, so holding a facade result across a floorTex call is safe; holding two facade + * results is not.) + * + * `ch === 0` means "leave this cell black" — a legal, common answer. Roughly half of every + * frame is meant to be untouched. + * + * fog() is NOT applied by facade/floorTex; they return the surface's own brightness. Whoever + * owns the world pass applies fog exactly once, or distant walls get attenuated twice and the + * street reads as a tunnel of soot. sky() is already unfogged and fog(lum, Infinity) is a + * no-op, so a blanket fog pass over the frame is safe. + * + * INTEGRATION — three things this layer cannot know, so the world pass must tell it once: + * CC.Surf.configure({ grid, streetX, streetPeriod, half, horizon }) + * grid metres per city cell; facade corner ribs land on multiples of it + * streetX world x of the canyon centreline; streetPeriod wraps the road pattern onto + * the grid so an unconfigured canyon still gets a centreline and kerbs + * half centreline-to-kerb metres + * horizon screen row of the horizon; sky() ramps its light pollution from there + * sky(sx, sy, t) takes SCREEN cells. If the camera yaws, pass a yaw-compensated column + * (x + yaw/fov*cols | 0) or the stars ride the view instead of the sky. + * ORDER MATTERS for sky() and only for sky(): call it down a column, sy DECREASING, so it can + * recover where that column's rooftop was — that is what the glow is anchored to. Everything + * else in this file may be called in any order at all. + * T_FAR should match CC.Surf.FOG_END — past it fog() returns 0 and marching is wasted work. + */ +(function (CC) { + 'use strict'; + + var P = CC.P, g = CC.g, hash2 = CC.hash2, clamp = CC.clamp, vnoise = CC.vnoise; + + /* Glyph indices resolved once — g() is a string-keyed lookup and this runs cols*rows times. */ + var G_DOT = g('.'), G_COMMA = g(','), G_COLON = g(':'), G_SEMI = g(';'), G_QUOTE = g("'"), + G_TICK = g('`'), G_DASH = g('-'), G_UNDER = g('_'), G_EQ = g('='), G_PLUS = g('+'), + G_PIPE = g('|'), G_SLASH = g('/'), G_BSLASH = g('\\'), G_HASH = g('#'), G_PCT = g('%'), + G_8 = g('8'), 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_TILDE = g('~'), G_oo = g('o'), G_DQ = g('"'), G_V = g('V'); + + /* Blocky fills only. Anything with visual "holes" (& $ ? !) reads as noise at this size. */ + var FILL = [G_8, G_0, G_O, G_HASH, G_X, G_Z, G_8, G_M, G_W, G_PCT]; + var FILL_N = FILL.length; + var DIMGL = [G_COLON, G_DOT, G_QUOTE, G_DASH, G_SEMI, G_COMMA, G_TICK, G_UNDER]; + var DIMGL_N = DIMGL.length; + + /* Facade styles. pu/pv are the bay pitch in metres — measured off real curtain wall, 2–4 m + * across and one storey (2.8–4.4 m) up. mu/sill/head are the fraction of the bay that is + * concrete rather than glass; that concrete is what makes the wall read as a slab. */ + var STYLE = [ + { pu: 2.60, pv: 3.30, mu: 0.20, sill: 0.20, head: 0.86, panes: 2, prow: 1, band: 4, gnd: 4.2 }, + { pu: 3.40, pv: 3.90, mu: 0.15, sill: 0.13, head: 0.90, panes: 3, prow: 2, band: 3, gnd: 4.8 }, + { pu: 2.10, pv: 2.90, mu: 0.26, sill: 0.26, head: 0.80, panes: 1, prow: 1, band: 5, gnd: 3.6 }, + { pu: 4.10, pv: 4.40, mu: 0.12, sill: 0.10, head: 0.93, panes: 4, prow: 2, band: 3, gnd: 5.4 }, + { pu: 3.00, pv: 3.60, mu: 0.18, sill: 0.22, head: 0.84, panes: 2, prow: 2, band: 4, gnd: 4.4 } + ]; + + /* Everything the texture layer cannot derive on its own. city.js/raycast.js should call + * CC.Surf.configure() once after the map exists; the defaults describe an 8 m grid with the + * canyon running down the middle of a cell, which is what the harness renders. */ + var CFG = { + grid: 8.0, // metres per city cell — corner ribs land on this + streetX: 4.0, // world x of the canyon centreline + streetPeriod: 8.0, // road markings repeat on the grid, so an unconfigured canyon still gets kerbs + half: 3.10, // centreline-to-kerb metres + horizon: 33.6, // screen row of the horizon; sky() needs it for the light-pollution ramp + /* The sky glow's e-fold used to be a fraction of `horizon`, and the day the camera learned to + * PITCH that stopped being a length on the picture: cam.horizon slides over 0.26..0.86 of the + * grid, so simply looking up stretched the light-pollution ramp by three and a bit and the + * roofline glow visibly grew as you tilted. `rows` is the grid, it never moves, and it is what + * the ramp is a fraction of. horizon still anchors WHERE the ramp starts. */ + rows: 60, + /* Where the cross streets cut this one, in the same axis floorTex reads as wz. This file has no + * city to ask, so the world pass loads them; with xn 0 the road simply runs on unbroken, which + * is what the bare harness wants. Fixed-length and written in place — the caster refills these + * every frame and must not be handed an allocation to do it. */ + xn: 0, + xc: new Float64Array(8), + xw: new Float64Array(8), + xz0: 0, xpitch: 26, // xc[0] and the city's block pitch, so the nearest entry can be INDEXED + // rather than searched: this runs twenty thousand times a frame + /* Whether THIS street carries tram rails. Rolled once per configure() rather than per cell: + * a rail that appears for some cells of a street and not others is not a rail. */ + rail: 0, + skySeed: 0x5EED, + /* How many of sky()'s elevation index units one screen row is worth. 1.0 means "the neutral + * camera", and the world pass overwrites it every frame from the live projection so that the + * star field magnifies under zoom instead of being re-dealt. Defaulted to 1 so an + * unconfigured harness — and the standalone parse check — still gets the shipped sky. */ + skyVScale: 1 + }; + function configure(o) { + if (!o) return CFG; + for (var k in o) if (CFG[k] !== undefined && o[k] !== undefined && k !== 'xc' && k !== 'xw') + CFG[k] = o[k]; + /* Rails belong to the street, so they are decided by the street's own centreline and width and + * nothing else — walking the same avenue twice has to give the same track. */ + CFG.rail = (CFG.half > 2.7 && hash2((CFG.streetX * 4) | 0, (CFG.half * 8) | 0, 0x5A11) < 0.34) + ? 1 : 0; + return CFG; + } + + /* ---- weather, sampled once per frame --------------------------------------------------- + * CC.Weather.rel(key) does a linear KEYS.indexOf, and this file would call it twenty thousand + * times a frame. `t` is the frame clock and changes exactly once per frame, so it is also the + * cache key — and because it is the clock and not a counter, scrubbing the harness to frame 9000 + * syncs the same weather the browser has there. + * + * MIGRATION RULE, applied throughout: every tuned constant below is scaled by rel(...), which is + * 1.0 under the 'rain' preset the whole build was tuned against. Multiplying by the raw P.wet + * would silently re-tune the street to 90% of what shipped. */ + var wT = 1 / 0, wWet = 1, wRain = 1, wWind = 1, wFogP = 0.30; + function weatherAt(t) { + if (t === wT) return; + wT = t; + var W = CC.Weather; + if (!W) return; // standalone require: hold the tuned reference look + wWet = W.rel('wet'); wRain = W.rel('rain'); wWind = W.rel('wind'); + wFogP = W.P.fog; + refog(); + } + + /* ---- cell metadata, defensively ------------------------------------------------------ + * city.js owns the cell record and may not carry every field, so read through helpers and + * fall back to a hash. A missing field must degrade, never throw or blank the wall. */ + function seedOf(cell) { + if (!cell || typeof cell !== 'object') return 0; + if (cell.seed !== undefined) return cell.seed | 0; + if (cell.id !== undefined) return cell.id | 0; + var x = cell.gx !== undefined ? cell.gx : (cell.x !== undefined ? cell.x : 0); + var z = cell.gz !== undefined ? cell.gz : (cell.z !== undefined ? cell.z : 0); + return (hash2(x, z, 7717) * 2147483647) | 0; + } + function styleOf(cell, sd) { + var s = cell && cell.style; + if (typeof s === 'number') return STYLE[((s | 0) % STYLE.length + STYLE.length) % STYLE.length]; + return STYLE[(hash2(sd, 11, 0x51) * STYLE.length) | 0]; + } + function litOf(cell) { + var r = cell && cell.litRate; + return typeof r === 'number' ? clamp(r, 0, 1) : 0.34; + } + /* One accent per building, never two — a facade that mixes ember and violet stops reading + * as one object. Violet stays rare: it is ~12% of an accent that is itself ~10% of windows. */ + function accentOf(cell, sd) { + if (cell && typeof cell.accent === 'number') return cell.accent | 0; + var r = hash2(sd, 5, 0x33A); + return r < 0.46 ? P.ember : (r < 0.86 ? P.spring : P.violet); + } + /* The building's dominant hue. city.js picks this from the DISTRICT, which is the entire + * point of having districts: it is what makes an ember pocket read as an ember pocket rather + * than as more of the same wall. Re-rolling it off the building seed — which is all this file + * used to do — flattens six districts into one and starves two of the three accents. The seed + * roll survives only as a fallback for a cell record that never carried the field. */ + function hueOf(cell, sd) { + if (cell && typeof cell.hue === 'number') return cell.hue | 0; + var dr = hash2(0, 0, sd ^ 0x2B1D); + return dr < 0.58 ? P.azure : (dr < 0.90 ? P.amber : P.warm); + } + + /* ---- facade --------------------------------------------------------------------------- + * u = metres along the wall, v = metres up from the street. + * Every hash is keyed on the bay index and the building seed, never on u/v directly and never + * on anything derived from the camera — a facade whose windows re-roll as you walk destroys + * the illusion faster than any other error in this project. */ + var FOUT = { ch: 0, col: 0, lum: 0 }; + function fset(ch, col, lum) { + FOUT.ch = ch; FOUT.col = col; + FOUT.lum = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0); + return FOUT; + } + + /* Dirt, streaking and reflection at ~8 cm — the only detail that survives when a wall is + * four metres away and one bay covers thirty columns. Keyed on quantised WORLD coordinates, + * so it is welded to the building and cannot crawl as the camera advances. */ + function grain(u, v, sd, lod) { + if (lod < 2) return 1; + var h = hash2(Math.floor(u * 11), Math.floor(v * 11), sd ^ 0x6A11); + return h < 0.12 ? 0.30 : 0.74 + h * 0.52; + } + + function facade(u, v, cell, dist, t) { + if (v < 0) v = 0; + weatherAt(t === undefined ? 0 : t); + var sd = seedOf(cell), st = styleOf(cell, sd); + + var wu = Math.floor(u / st.pu), wv = Math.floor(v / st.pv); + var fu = u / st.pu - wu, fv = v / st.pv - wv; + + /* At 40 m one character spans several metres of wall, so per-pane hashing would alias into + * static. Coarsen the lattice with distance instead: shifted bay indices are stable, so the + * pattern locks to the building rather than crawling as `dist` changes. + * The switch distance is jittered PER BAY so the boundary dissolves bay by bay instead of + * sweeping the wall as one hard line you can watch travelling towards you. */ + var lj = dist + (hash2(wu, wv, sd ^ 0x9C) - 0.5) * 7; + var lod = lj < 13 ? 2 : (lj < 34 ? 1 : 0); + /* CONTENT indices never coarsen. They used to: `bu = lod===0 ? wu>>1 : wu` fed the lit test + * and the hue picks, so crossing the 34 m LOD boundary re-rolled WHICH windows were lit and + * a whole facade visibly re-shuffled as you walked up to it — the worst possible place to + * change your mind, because the eye is already tracking that wall. Only the decorative glyph + * pick coarsens, via `glu`; swapping one blocky fill character for another at 40 m is + * invisible, while changing the lit pattern is not. */ + var bu = wu, bv = wv; + var glu = lod === 0 ? (wu >> 1) : wu; + + /* Street level is exempt from the dark-block mask below: the parade of shopfronts has its + * own rhythm, and punching four-bay holes in it breaks the band that anchors the wall to + * the ground — the one horizontal the eye uses to read the canyon's depth. */ + if (v < st.gnd) return ground(u, v, st, sd, cell, lod, t); + + /* ---- the roofline ------------------------------------------------------------------------- + * The top two metres of every wall are a PARAPET, not more windows. This is the one feature of + * a facade that cannot be derived from u and v alone — it needs the building's height, which is + * why the world pass now puts that on the cell record — and it earns the extra field because + * the rooftop line is the silhouette the entire picture is composed around. Without it a wall + * simply stops wherever its window grid ran out, and every roof in the frame is the same roof. + * + * Three courses, top down: a coping that catches the sky glow behind it, a blank upstand, and + * the shadow line where the parapet oversails the wall. Together they read as a THICKNESS at + * the top of the building, which is the whole difference between a parapet and a painted line. + * All three are cheap in coverage because they REPLACE two storeys of window lattice. */ + var bh = cell && typeof cell.h === 'number' ? cell.h : 0; + if (bh > 6 && v > bh - 2.35) { + var pu2 = Math.floor(u / 1.9); + if (v > bh - 0.42) // coping, jointed every 1.9 m like real precast + return fset((u - pu2 * 1.9) < 0.16 ? G_PIPE : G_EQ, P.slate, + 24 + hash2(pu2, 0, sd ^ 0x2A1) * 22); + if (v > bh - 1.85) { + var pg = hash2(pu2, Math.floor(v * 2.2), sd ^ 0x2A2); + return pg < 0.32 ? fset(DIMGL[(pg * DIMGL_N * 3.1) | 0], P.shadow, 14 + pg * 34) + : fset(0, P.shadow, 0); + } + return fset(G_UNDER, P.shadow, 30 + hash2(pu2, 3, sd ^ 0x2A3) * 28); + } + + /* Weather on the wall. Rain does not run evenly down a facade — it sheets off the sills and + * leaves vertical stripes of washed and unwashed concrete, and those stripes are the only + * thing on a wall that says the wall is wet. Keyed on world u ALONE, so a streak is a fixed + * feature of the building rather than something that crawls across it, and it fades in and out + * with the rain instead of switching. */ + var streak = 0; + if (lod > 0 && wRain > 0.15 && + hash2(Math.floor(u * 3.1), 0, sd ^ 0x7C1) < 0.30 * clamp(wRain, 0, 1.3)) streak = 1; + + /* Rainwater downpipe, on a third of buildings. It runs the full height inside a bay joint, so + * it lands on mullion cells rather than on glass and costs the wall almost nothing it was + * using. It is one of only two unbroken verticals a facade has — the corner rib is the other — + * and a wall with no vertical at all reads as a lattice instead of as a building. */ + if (lod > 0 && hash2(sd, 17, 0x3D1) < 0.26 && + (((bu % 3) + 3) % 3) === ((hash2(sd, 18, 0x3D1) * 3) | 0) && fu < 0.085) { + var dg = hash2(0, Math.floor(v * 1.6), sd ^ 0x3D2); + return fset(dg < 0.13 ? G_O : G_PIPE, P.slate, 13 + dg * 20); // brackets every metre or so + } + + /* Dark blocks: derelict floors, empty lets, the shadowed half of a plant room. These are + * where the 55%-black budget comes from, and being 4 bays wide they read as mass rather + * than as holes punched in a lattice. */ + /* Grain matters as much as probability here. At >>2 the mask worked in four-bay by two-storey + * blocks, which on a wall seven metres away is a twenty-by-twenty pure-black rectangle with + * hard edges — not mass, a hole cut in the building. Halving the horizontal grain and cutting + * the rate keeps the derelict floors while letting the wall stay a wall up close. */ + if (hash2(wu >> 1, wv >> 1, sd ^ 0x1F35) < 0.18) { + return fset(0, P.shadow, 0); + } + + /* Corner rib. Buildings sit on the city grid, so a wall's corners are wherever u crosses a + * grid line; the rib is brighter than the mullions so the silhouette edge stays readable. */ + if (lod > 0) { + var ge = u / CFG.grid; ge -= Math.floor(ge); + if (ge * CFG.grid < 0.20 || (1 - ge) * CFG.grid < 0.20) { + return fset(G_PIPE, P.slate, 9 + hash2(wu, wv, sd ^ 0x4C) * 13); + } + } + /* Floor band every few storeys — a belt course, the only strong horizontal on the wall. */ + if (fv < 0.11 && (wv % st.band) === 0 && hash2(wu, wv, sd ^ 0xB2) < 0.72) { + return fset(G_EQ, P.slate, 12 + hash2(wu, wv, sd ^ 0xB1) * 16); + } + + /* Lit windows must CLUSTER, not speckle. Biasing the threshold by a per-column and a + * per-storey hash (both mean 1.0, so the cell's litRate still holds on average) gives + * lit stacks and lit floors — the massed slabs the references are made of. */ + var pcol = 0.35 + 1.30 * hash2(bu, 0, sd ^ 0x71); + var prow = 0.45 + 1.10 * hash2(0, bv, sd ^ 0x37); + var lit = hash2(bu, bv, sd) < litOf(cell) * pcol * prow; + var hue = P.slate, base = 0; + + var isAcc = 0, curtain = 0, occupied = 0, ws = 0; + if (lit) { + /* Most windows take the building's DISTRICT hue; a tenant here and there breaks it. + * Colour massing per building is why the references never look like confetti. */ + if (hash2(bu, bv, sd ^ 0x4D) < 0.62) { + hue = hueOf(cell, sd); + } else { + var hr = hash2(bu >> 1, bv, sd ^ 0x2B1D); + if (hr < 0.30) hue = P.azure; // screenlight and sodium in the ratio measured off + else if (hr < 0.72) hue = P.amber; // the references: azure ~27% of lit energy, amber ~26% + else if (hr < 0.78) hue = P.warm; // someone is home — a garnish, not a third pillar + // P.ice is documented as holo/glass/rain highlight, not a facade swatch. It sat here on + // 8% of windows and, combined with the accent path, became the fourth-largest colour in + // the frame. Slate is the cold-glass read without a fourth pillar. + else if (hr < 0.86) hue = P.slate; + else { + /* An accent must be a STRIPE, never a slab. Probability alone does not bound its AREA: + * this hash is keyed on the bay column, so one unlucky roll paints every storey of a + * two-bay column, and on a wall seven metres away that is a solid 7x12-cell block of + * ember or red carrying a tenth of the frame's colour by itself. Gate it on a coarse + * lot-level slot instead — at most one bay column in five of any building may take an + * accent, and the rest fall back to a pillar. */ + var slot = (hash2(sd, 9, 0x2C7) * 5) | 0; + if ((((bu % 5) + 5) % 5) === slot) { hue = accentOf(cell, sd); isAcc = 1; } + else hue = hash2(bu, 0, sd ^ 0x2C8) < 0.5 ? P.azure : P.amber; + } + } + /* Brightness is shared along a floor, then jittered per bay — an office lit by one + * ceiling grid does not vary window to window as much as floor to floor. */ + base = 172 + hash2(0, bv, sd ^ 0x5) * 56 + hash2(bu, bv, sd ^ 0x9E) * 28; + /* Upper storeys sit further from the street's own light and read as further back; + * without this a 60 m tower is a flat wall of equal-brightness cells. */ + base *= 1 - clamp(v / 190, 0, 0.24); + /* Accents are narrow in AREA above and in ENERGY here: an ember bay at 250 out-weighs + * three azure ones and drags the whole frame's balance with it. */ + if (isAcc && base > 148) base = 148; + + /* A few tubes are failing. Every window gets its OWN phase: keying the blink on a global + * time bucket made every failing tube in the city blink in lockstep, which is not a city, + * it is a strobe. 1.9 Hz base rate, and it stops entirely under reduced motion. */ + if (lod > 0 && !CC.reducedMotion && hash2(bu, bv, sd ^ 0x5BD1) < 0.055) { + var tk = Math.floor(t * 1.9 + hash2(bu, bv, sd ^ 0x5BE2) * 40); + if (hash2(bu ^ tk, bv, sd ^ 0x77) < 0.34) base *= 0.22; + } + + /* WINDOW STATE. A lit window is not one thing, and a wall on which every lit window is the + * same lit window is the flattest surface in the frame however well its colour is massed. + * Three states beyond plain, rolled once per bay off the bay's own hash so a window keeps + * what it is as you walk past it: + * curtained a drawn blind or a net — flat, dimmer, no pane grid behind it, and warm on a + * minority because a domestic curtain is lit by a domestic lamp. Warm is a + * garnish and not a third pillar, so most curtains keep the building's own hue. + * occupied somebody standing in the glass. Drawn as an ABSENCE in the pane below, which + * is the only way a silhouette can be drawn and also the cheapest. + * dead handled in the unlit branch; a window with the glass gone. */ + ws = hash2(bu, bv, sd ^ 0x6C21); + if (ws < 0.15) { + curtain = 1; + base *= 0.64; + if (hash2(bu, bv, sd ^ 0x6C22) < 0.30) hue = P.warm; + } else if (ws < 0.22) occupied = 1; + } + + if (lod === 0) { + /* Far away the mullions are sub-cell; drawing them would just dither the slab. Unlit + * bays go black and let the raycaster's silhouette carry the building. */ + if (lit) return fset(FILL[(hash2(glu, bv, sd ^ 0x3) * FILL_N) | 0], hue, base * 0.92); + return hash2(wu, wv, sd ^ 0x5) < 0.17 + ? fset(G_COLON, P.shadow, 9 + hash2(wu, wv, sd ^ 0x6) * 6) : fset(0, P.shadow, 0); + } + + var inU = fu > st.mu && fu < 1 - st.mu; + var inV = fv > st.sill && fv < st.head; + + if (!inU || !inV) { + /* Structure — the concrete a curtain wall is hung on, and the reason a facade reads as a + * SLAB instead of as scaffolding. Two tiers, and the distinction is the whole trick: + * the mullion LINES carry an edge, and the spandrel field behind them is painted at the + * bottom of the visible range so the wall has mass without acquiring a grey veil. + * + * `lum` is not brightness. P.shadow's pigment is (40,50,66), so the swatch tops out at a + * rendered value of 60 however hard it is driven — still under P.slate at lum 60, which + * prints 65. The old code drew this tier at lum 8-27 on P.shadow, i.e. at a rendered value + * of 1-3, and then wondered where its exposure had gone: it was paying for tens of thousands + * of cells that were arithmetically indistinguishable from black. + * + * "Everything below is chosen by rendered value, not by lum" USED TO BE TRUE AND IS NOT. + * The tiers below were fitted against an EXPOSURE table that gave shadow 2.60 and slate + * 2.00; core.js's refit cut them to 0.80 and 0.60, so every literal in this function now + * prints at roughly a third of the value it was chosen for. Measured on the current table: + * shadow is invisible (v<9) below lum 12 and reaches only v 24 at lum 22; slate is invisible + * below lum 11. The spandrel salt at 8-22 therefore prints v 4-24 and the dead-glass salt at + * 6-14 prints v 2-13, which is most of the way back to the 1-3 this paragraph is about. + * + * That is NOT a licence to multiply these numbers up. The crush is now core.js's, it is + * deliberate, and it is measured there: at KNEE 0.075 "99.7% of what goes dark is slate and + * shadow", which is this file's structural dither by name. Over a 32-frame fixture (seeds + * 3001+137k, k=0..15, frames 600 and 1800 at 400x100) blank is 42.3% and black(v<9) 57.2%, + * so 14.9% of ALL cells are painted-and-invisible, nearly all of it this tier and the floor's + * — and lifting that mass back over v=9 would put the muddy band, which core.js holds at + * 27.9% against a <30 target, straight through the target. The honest description is: this + * tier is now MASS THE PRINT DELETES, and it survives as coverage rather than as texture. + * Anyone who wants it visible again has to buy it from the muddy band and say so. */ + var onU = fu < st.mu * 0.45 || fu > 1 - st.mu * 0.45; + var onV = fv < st.sill * 0.40 || fv > 1 - (1 - st.head) * 0.40; + var ml = (lod === 2 ? 62 : 48) + hash2(wu, wv + 9973, sd) * 26; + /* The mullion picks up a little of its window's colour: that spill is what turns a grid + * of bright dots into a lit slab. */ + if (lit) return fset(onV ? G_DASH : G_PIPE, hue, ml + base * 0.16); + + /* The dark tiers are P.shadow, and that is a deliberate choice against the print curve + * rather than a default. core.js prints each swatch through its own gain, and the numbers + * this argument used to quote (amber 3-148, azure never below 76, shadow 23 at lum 6) were + * taken off the pre-refit table. RE-MEASURED on the current one, near bucket, pigment + * included: amber runs 0-179, azure 0-219, shadow 0-60. The ARGUMENT still holds and it is + * now about the SLOPE rather than the floor — azure's gain is 1.00, the highest in the + * table, so it goes from invisible at lum 4 to v 77 at lum 16 and v 125 at lum 48. Its + * entire dim range is eleven units of lum wide, which is not a range anything can be dialled + * into: tinting this tier with the district hue still lights every dead wall in a screen + * district as brightly as its own windows. P.shadow spreads its whole 0-60 over the full + * 0-255 (v 24 at lum 22, v 33 at lum 50, saturating at 60), so it is still the only swatch + * that can carry MASS: present everywhere, incapable of blowing out, and it takes fog + * straight down to black. The district's colour lives in the lit tiers, where brightness is + * the point. + * + * What DID change is the floor: shadow prints nothing until lum 12 now, where the old table + * had it over v=9 from lum 3, so the "dim but present" tiers below now sit on the edge of + * the print rather than just inside it. That is the subject of the note above. */ + /* Plant: an air-conditioning box or an extract grille bolted onto the spandrel under the + * sill. One bay in seven, near only, and it is the difference between a spandrel band that + * is one continuous course of concrete for sixty metres and one that has been lived in. */ + if (lod === 2 && fv < st.sill * 0.86 && fu > 0.26 && fu < 0.74 && + hash2(bu, bv, sd ^ 0x4E1) < 0.10) { + var acg = hash2(Math.floor(u * 4.4), Math.floor(v * 4.4), sd ^ 0x4E3); + return fset(acg < 0.34 ? G_HASH : (acg < 0.72 ? G_EQ : G_PIPE), P.slate, 15 + acg * 26); + } + + if (onU || onV) { + /* Mullion on a dead bay. Broken up rather than drawn continuously — a complete tracery + * over a dead building is still a veil, just a thinner one. */ + if (hash2(wu, wv + 5, sd ^ 0xE) < 0.50) return fset(0, P.shadow, 0); + return fset(onV ? DIMGL[(hash2(wu, wv + 31, sd ^ 0xD) * DIMGL_N) | 0] : G_PIPE, + P.shadow, 30 + hash2(wu, wv + 31, sd ^ 0xD) * 50); + } + /* Spandrel field — the mass itself, at the very bottom of the visible range. Keyed on a + * sub-bay quantisation of the world position so it is a texture on the concrete and not + * one flat tone per bay. */ + /* A streak lands HERE, on the blank concrete, which is where a real one is visible. It is + * drawn as a continuous vertical rather than as more dither, because the whole point of a + * run-off mark is that it is a line the wall did not have before it rained. */ + if (streak) { + var stg = hash2(Math.floor(u * 3.1), Math.floor(v * 1.5), sd ^ 0x7C2); + if (stg < 0.50) return fset(G_PIPE, P.shadow, 24 + stg * 46); + } + if (hash2((u * 3.2) | 0, (v * 3.2) | 0, sd ^ 0xE5) < 0.82) return fset(0, P.shadow, 0); + return fset(DIMGL[(hash2((u * 3.2) | 0, (v * 3.2) | 0, sd ^ 0xD3) * DIMGL_N) | 0], + P.shadow, 8 + hash2((u * 3.2) | 0, (v * 3.2) | 0, sd ^ 0xC1) * 14); + } + + if (!lit) { + /* Dead: the glass is gone. One unlit bay in twenty, and it is the state that costs nothing — + * a broken window is mostly a hole, so this SUBTRACTS coverage rather than adding it, which + * is how a facade pays for the parapet and the pipework above. */ + if (hash2(wu, wv, sd ^ 0x1C3) < 0.07) { + var dgl = hash2(Math.floor(u * 2.6), Math.floor(v * 2.6), sd ^ 0x1C4); + return dgl < 0.24 ? fset(dgl < 0.12 ? G_SLASH : G_BSLASH, P.shadow, 30 + dgl * 60) + : fset(0, P.shadow, 0); + } + /* Unlit glass: dim but PRESENT often enough to keep the wall solid, black elsewhere. At + * 30% coverage and lum 8-15 this was neither — the dark bays came out as holes, and half + * of every facade read as scaffolding rather than as a slab of building. */ + /* 0.33, down from 0.44, and the coverage is not lost — it is MOVED. Everything this file + * added above (the parapet course, the downpipes, the plant, the awnings, the streaks) is + * structure that has a shape, and it is paid for by thinning the one tier that has none: a + * per-bay salt of colons on dead glass. That salt was fitted at a rendered value of eighteen + * and NO LONGER PRINTS THERE — with shadow's gain cut 2.60 -> 0.80 the lum 6-14 written below + * prints v 2-13, and shadow's visibility threshold on the current table is lum 12, so most of + * this tier is now below it. The tier is thinned, and the print has taken most of what was + * left; both facts are load-bearing for the coverage argument above, which is why the second + * one is stated instead of the old number being left standing. See the long note in the + * structure tier for why the answer is not to multiply the lum back up. The wall keeps its + * mass, because mass comes from the spandrel and the mullions, and the frame's black budget + * comes back out at the far end. */ + return hash2(wu, wv, sd ^ 0x1B) < 0.31 + ? fset(hash2(wu, wv, sd ^ 0x2C) < 0.5 ? G_COLON : G_QUOTE, + P.shadow, 6 + hash2(wu, wv, sd ^ 0x2C) * 8) + : fset(0, P.shadow, 0); + } + + /* A curtain hangs IN FRONT of the pane grid, so it replaces it rather than being drawn over + * it: folds instead of mullions, and a soft vertical texture at about a hand's width. This is + * why the state is worth having — a curtained bay and a plain one are different SHAPES up + * close, not just different brightnesses. */ + if (curtain && lod === 2) { + var cfd = u / 0.24; cfd -= Math.floor(cfd); + return fset(cfd < 0.42 ? G_PCT : G_HASH, hue, + base * (0.76 + 0.36 * hash2(Math.floor(u * 4.1), bv, sd ^ 0x6C23))); + } + + if (lod === 2) { + /* Close up a bay is dozens of cells tall, so subdivide into panes; otherwise a near + * window is one featureless flood of colour twenty rows high. */ + var gu = (fu - st.mu) / (1 - 2 * st.mu), gv = (fv - st.sill) / (st.head - st.sill); + var pi = (gu * st.panes) | 0, pj = (gv * st.prow) | 0; + var pfu = gu * st.panes - pi, pfv = gv * st.prow - pj; + if (pfu < 0.11 || pfv < 0.13) return fset(pfu < 0.11 ? G_PIPE : G_DASH, hue, base * 0.50); + /* Somebody at the window. A silhouette is an ABSENCE of light, so it is drawn as one — + * which also makes it the one piece of detail in this file that gives coverage back. */ + if (occupied && pfv > 0.38 && pfu > 0.28 && pfu < 0.70) return fset(0, P.shadow, 0); + var ph = hash2(bu * 7 + pi, bv * 5 + pj, sd ^ 0x77E1); + if (ph < 0.15) return fset(G_COLON, hue, base * 0.20); // blind drawn, desk light off + base *= (0.80 + ph * 0.38) * grain(u, v, sd, lod); + } + + return fset(FILL[(hash2(glu, bv, sd ^ 0x3) * FILL_N) | 0], hue, base); + } + + /* Shopfront light colour, rolled off the LOT'S OWN DISTRICT hue rather than district-blind. + * Sixteen slots read with a single index, because this is per-cell code and a chain of + * thresholds here bought nothing but branches. + * + * P.ice is deliberately absent. It used to hold 10% of this roll, and core.js documents that + * swatch as "holo, glass, rain highlight" — not a facade colour. Because this band is v < 8 m it + * fills most of the near frame, so 10% of the roll became a PILLAR: measured at seed 11 frame + * 800, ice took 48.3% of the frame's lit energy against azure's 25.6 and amber's 9.4, and 788 of + * its 1231 cells were standing inside a SODIUM block. Ice belongs on rain and glazing highlights, + * where it is a highlight. + * + * hueOf answers with the district's DOMINANT swatch, which for a concrete quarter is structure + * (slate/white) and for the two accent quarters is an accent. Shopfront glow is LIGHT, so those + * are folded onto whichever pillar they sit nearest — concrete takes either, ember leans sodium, + * spring leans screen — with the quarter's own colour surviving as a minority tenant so the + * district still reads as itself. Warm is two slots in every district: someone's counter lamp, + * a garnish, never a third pillar. */ + var SHOP = (function () { + var t = [], i; + function fill(hue, list) { t[hue] = list; } + var A = P.amber, Z = P.azure, W = P.warm; + fill(A, [A,A,A,A,A,A,A,A,A,A, Z,Z,Z,Z, W,W]); + fill(Z, [Z,Z,Z,Z,Z,Z,Z,Z,Z,Z, A,A,A,A, W,W]); + fill(P.ember, [P.ember,P.ember,P.ember,P.ember,P.ember, A,A,A,A,A,A,A, Z,Z, W,W]); + fill(P.spring, [P.spring,P.spring,P.spring,P.spring,P.spring, Z,Z,Z,Z,Z,Z,Z, A,A, W,W]); + var neutral = [A,A,A,A,A,A,A, Z,Z,Z,Z,Z,Z,Z, W,W]; + /* Sixteen rows, not twelve, so the lookup can be indexed with `& 15` and is TOTAL: a cell + * record carrying a hue this file has never heard of gets the neutral parade instead of an + * exception, which is the same contract seedOf/styleOf/litOf keep. */ + for (i = 0; i < 16; i++) if (!t[i]) t[i] = neutral; + return t; + })(); + + /* Street level: shutters, a canopy line, and the occasional open shopfront. + * This band is banded HORIZONTALLY — plinth, glazing, sign, fascia — because the camera eye + * is 1.7 m up and a near wall's ground floor can fill the whole screen edge. A single flood + * of colour there swings the frame's entire colour balance; bands keep it reading as depth. */ + function ground(u, v, st, sd, cell, lod, t) { + var su = Math.floor(u / 2.55), fs = u / 2.55 - Math.floor(u / 2.55); + var r = hash2(su, 0, sd ^ 0x7E31); + var open = r < 0.40; + /* The unit's own light colour, on its OWN hash. It cannot ride on `r`: `r` is what decides + * whether the unit is open at all, so it only ever reaches 0.40 in here and any threshold + * above that is dead code — which is exactly how "amber or warm" became "amber or warm or + * nothing else, ever". This band is the nearest and brightest thing in frame and carries + * around two-fifths of all facade energy, so whatever colour it is, the FRAME is: a parade + * of sodium shopfronts on its own turns a two-pillar city into a yellow one. */ + var cr = hash2(su, 3, sd ^ 0x1D7); + var roll = SHOP[hueOf(cell, sd) & 15]; + var lite = roll[(cr * 16) | 0]; + /* The unit's SECOND fitting, drawn from the same district roll on an unrelated hash. One unit + * of frontage is 2.55 m, and the camera passes within two metres of a wall: at that range a + * single unit is most of the screen, and a single `lite` roll was taking two thirds of the + * frame's lit energy on its own — seed 0 and seed 555 both measured one swatch over 62% at + * frame 2400. A shop is not lit by one tube. Giving the glazing a minority second colour + * bounds what any one roll can own, at the scale where the eye reads it as depth into the + * unit rather than as a change of subject. */ + var lite2 = roll[(hash2(su, 11, sd ^ 0x1D8) * 16) | 0]; + + if (v > st.gnd - 0.42) { // canopy / fascia over the whole parade + return fset(G_EQ, open ? lite : P.slate, open ? 58 : 7); + } + if (fs < 0.06 || fs > 0.94) { // pilaster between units + return fset(G_PIPE, P.slate, 7); + } + if (open) { + /* AWNING. Two units in five have one, and it is the single most useful thing that can happen + * to a ground floor: it puts a SLOPE into a band that is otherwise four stacked horizontals, + * it throws the shopfront under it into shadow, and it hangs a scalloped valance at eye + * height. Drawn as diagonals in the unit's own light colour, dimmed hard — an awning is lit + * from underneath by the shop it belongs to and it is canvas, not glass. */ + if (hash2(su, 21, sd ^ 0x8A1) < 0.40 && v > st.gnd - 2.55 && v < st.gnd - 1.62) { + var aw = (st.gnd - 1.62 - v) / 0.93; // 0 at the fascia, 1 at the front edge + if (aw > 0.86) { + /* Valance: the scalloped fringe that hangs off the leading edge. */ + var vg = u / 0.42; vg -= Math.floor(vg); + return fset(vg < 0.5 ? G_V : G_UNDER, lite, 44 + hash2(su, (u * 2.4) | 0, sd ^ 0x8A2) * 30); + } + var ag = u / 0.55; ag -= Math.floor(ag); // canvas stripes, the way awnings come + return fset(ag < 0.5 ? G_SLASH : G_EQ, ag < 0.5 ? lite : P.slate, + ag < 0.5 ? 26 + aw * 34 : 12 + aw * 14); + } + + /* Sign band under the fascia. Signage is the one place violet is allowed, and it is a + * thin strip rather than a whole surface, which is how the references use it. */ + if (v > st.gnd - 1.55) { + /* The sign takes the unit's OWN light colour: one shop is lit by one set of tubes, and a + * sign in a different hue from the window under it splits a single unit into two objects. + * It was rolled off `cr` against fixed thresholds here, which is the same district-blind + * mistake as the roll above and put azure signs on sodium blocks. */ + var sc = r < 0.09 ? accentOf(cell, sd) : lite; + var sg = hash2(su, Math.floor(u * 3.1), sd ^ 0x515); + return fset(sg < 0.22 ? 0 : FILL[(sg * FILL_N) | 0], sc, + sg < 0.22 ? 0 : 176 + sg * 79); + } + if (v < 0.62) // plinth, in its own shadow + return hash2(su, Math.floor(v * 6), sd ^ 0x3) < 0.5 ? fset(G_UNDER, P.shadow, 14) + : fset(0, P.shadow, 0); + /* Glazing: interior spill, brightest just above the deck, mullioned every 0.85 m. */ + var fm = u / 0.85; fm -= Math.floor(fm); + if (fm < 0.10) return fset(G_PIPE, P.slate, 9); + /* Keyed on world u as well as v, so the second fitting breaks the unit up in BOTH axes and + * a near shopfront cannot present one flat field of colour however much of the screen it + * covers. 1.25 m by 0.77 m patches: furniture-sized, not dither. */ + var col = hash2(Math.floor(u * 0.8), Math.floor(v * 1.3), sd ^ 0x6C1) < 0.34 ? lite2 : lite; + var fall = clamp(1 - (v - 0.62) / (st.gnd - 2.2), 0, 1); + var lum = 92 + fall * 104 + hash2(su, Math.floor(v * 2.2), sd) * 34; + if (hash2(su, Math.floor(v * 3.1), sd ^ 0x5) < 0.26) lum *= 0.40; // stock, shelving, bodies + return fset(FILL[(hash2(su, Math.floor(v * 1.7), sd ^ 0x2) * FILL_N) | 0], col, + lum * grain(u, v, sd, lod)); + } + if (r < 0.42) return fset(0, P.shadow, 0); // shuttered and truly dead + /* Roller shutter: horizontal ribbing, near black, but present. */ + var rib = Math.floor(v * 3.4); + return (rib % 3) ? fset(0, P.shadow, 0) + : fset(G_UNDER, P.shadow, 11 + hash2(su, rib, sd ^ 0xA9) * 8); + } + + /* ---- street --------------------------------------------------------------------------- + * wx/wz are world metres. The road pattern is wrapped onto the grid pitch so it still lands + * correctly if nobody calls configure() with the real canyon position. + * + * THREE THINGS COME OUT OF HERE, not one, and the second is the important one. + * ch/col/lum the tarmac itself, as before. + * mir how much of whatever is standing ABOVE this cell the surface hands back. This + * file cannot see the sign it is reflecting — it has no camera and no frame — so + * it reports the water and raycast.js's reflect pass fetches the colour once the + * column above is painted. That division is the whole reason a puddle here can + * mirror a sign rather than inventing a plausible hue for one, which is what the + * old wet-strip code did and why a wet road never quite matched the wall over it. + * wch the glyph to spend a reflection on when the cell is otherwise black. Chosen here + * because it must be keyed on WORLD position: picked screen-side it would re-roll + * every frame and the water would boil. + * + * The lower third of the frame is the largest single region in the composition, so everything + * below is chosen for what it does to that region: the long markings (kerb arris, edge line, + * rails, seams) are continuous because continuity is what carries perspective, and the field + * detail (patches, plates, puddles) is BLOCKY because a road at this resolution reads as areas + * of tone, never as speckle. + */ + var ROUT = { ch: 0, col: 0, lum: 0, mir: 0, rip: 0, wch: 0 }; + /* Set once at the top of floorTex and read back out by every rset() below, so the twenty-odd + * early returns in the cascade do not each have to carry the water with them. */ + var mirNow = 0, ripNow = 0, wchNow = 0, bounceNow = 0; + function rset(ch, col, lum) { + ROUT.ch = ch; ROUT.col = col; + ROUT.lum = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0); + ROUT.mir = mirNow > bounceNow ? mirNow : bounceNow; + ROUT.rip = ripNow; ROUT.wch = wchNow; + return ROUT; + } + + /* Smeary, low-contrast glyphs. A reflection drawn in the blocky FILL set reads as a second wall + * lying on the ground; these read as something lying ON water. */ + var WATER = [G_COLON, G_QUOTE, G_TILDE, G_SEMI, G_DQ, G_DASH, G_COMMA, G_TICK]; + var WATER_N = WATER.length; + + function floorTex(wx, wz, dist, t) { + weatherAt(t === undefined ? 0 : t); + var lane = wx - CFG.streetX; + if (CFG.streetPeriod > 0) lane -= Math.round(lane / CFG.streetPeriod) * CFG.streetPeriod; + var al = lane < 0 ? -lane : lane; + var half = CFG.half; + + /* The floor is the worst aliaser in the frame: one row near the horizon covers tens of + * metres of tarmac, so fine per-metre hashes there resolve into crawling static. Detail is + * dropped by distance band and the surviving hashes are quantised coarser. Big features + * (centreline, kerb, edge line, rails, crossings) are kept at every distance — they are what + * carries the perspective, and they are lines rather than fields so they cannot alias. */ + var fl = dist < 22 ? 2 : (dist < 50 ? 1 : 0); + + /* ---- water --------------------------------------------------------------------------- + * Two scales, doing two different jobs. + * + * The SHEET is the broad damp — metres across, slow — and it is what takes the carriageway + * from matte to specular as the weather wets it. Under 'clear' rel('wet') is 0.13 and this + * collapses to nothing; under 'downpour' it is 1.11 and the road is a mirror end to end. + * + * The PUDDLES are objects, not noise: standing water a metre or two across with an edge you + * can see, placed on a world lattice so they hold still while you walk past them. They are + * the point of the whole exercise — a puddle reflecting a sign is the defining image of the + * genre, and noise cannot make one because noise has no edge to catch the light. */ + var sheet = vnoise(wx * 0.11 + 3.1, 91) * 0.72 + vnoise(wz * 0.05, 57) * 0.62 + - 0.42 + (wWet - 1) * 0.34; + sheet = clamp(sheet, 0, 1) * clamp(wWet, 0, 1.15); + + /* 2.4 m across the road by 5.6 m along it, at most one puddle per lattice cell, and the centre + * is INSET BY THE RADIUS so a puddle can never be clipped by its own cell boundary. A clipped + * puddle shows a dead straight side and stops being water on sight; this is cheaper than + * testing the neighbouring cells and the size it costs is size a puddle does not want. */ + var pi = Math.floor(lane / 2.4), pj = Math.floor(wz / 5.6); + var pd = 0; + /* Past 50 m a puddle is smaller than a cell, so it is not computed rather than not drawn. */ + if (fl > 0 && hash2(pi, pj, 0x9D1) < 0.26 + 0.40 * clamp(wWet, 0, 1.2)) { + var pra = (0.30 + hash2(pi, pj, 0x9D4) * 0.60) * clamp(0.42 + wWet * 0.64, 0.22, 1.25); + if (pra > 1.05) pra = 1.05; + var prz = pra * (1.5 + hash2(pi, pj, 0x9D5) * 1.4); + if (prz > 2.55) prz = 2.55; + var pcx = pi * 2.4 + pra + (2.4 - 2 * pra) * hash2(pi, pj, 0x9D2); + var pcz = pj * 5.6 + prz + (5.6 - 2 * prz) * hash2(pi, pj, 0x9D3); + var dl = (lane - pcx) / pra, dpz = (wz - pcz) / prz; + var rr2 = dl * dl + dpz * dpz; + /* Squared falloff, so the middle is flat water and the last fifth of the radius is all the + * gradient there is. That narrow ring is the meniscus, and it is what gets the glint. */ + if (rr2 < 1) pd = 1 - rr2 * rr2; + } + + /* Wheel ruts. Tyres polish two strips of any carriageway and water stands in them, which is + * why a wet road photographs as two bright bands and not as one even sheet. */ + var rc = half * 0.55, rut = al - rc; if (rut < 0) rut = -rut; + rut = 1 - clamp(rut / 0.62, 0, 1); + + /* ---- the sodium pool -------------------------------------------------------------------- + * A street lamp is the first pillar of the whole palette and the road is the thing it points + * at, so the tarmac under one is the brightest amber surface in the lower third. It is also + * the only large-scale RHYTHM the carriageway has: a pool every thirteen metres, alternating + * sides the way real columns do, is a metre rule laid down the canyon, and the eye reads + * distance off it without being told to. + * + * It lives in the SURFACE rather than in an element because it is a property of the surface. + * An element would have to paint over the road it is lighting, and the kerb and the markings + * would still read as a street with no lamps on it. The lamp bodies belong to structure.js; + * this is what they land on. + * + * Squared falloff and no edge — light does not have one. */ + var lampK = 0; + if (fl > 0) { + var lj = Math.floor(wz / 13.5); + var lcl = (hash2(lj, 0, 0x1A3) < 0.5 ? 1 : -1) * (half - 0.55); + var lcz = lj * 13.5 + 3.4 + hash2(lj, 1, 0x1A3) * 6.6; + var dll = (lane - lcl) / 3.0, dlpz = (wz - lcz) / 4.1; + lampK = 1 - (dll * dll + dlpz * dlpz); + if (lampK < 0) lampK = 0; else lampK *= lampK; + } + + mirNow = clamp(pd * 0.95 + sheet * (0.40 + rut * 0.26), 0, 1); + /* The DRY BOUNCE, kept separate from the water because the two do different jobs and only one + * of them should decide whether this cell draws a water glyph. Asphalt is not a mirror, but it + * is not a hole either: a sign four metres over a dry road lays a smear of its own colour on + * it, and on a clear night that smear is the only thing putting the street's own light back + * onto the street. It goes out through ROUT.mir, and the reflect pass raises its source + * threshold when the figure is this low — see raycast.js — so only something genuinely + * emitting can spend it. That gate is the whole difference between this and the grey wash the + * old wet-strip code produced. */ + bounceNow = 0.13; + /* The mirror is broken up by ripples: a row offset the reflect pass adds before it samples. + * Keyed on WORLD position so a puddle's surface holds still as you walk past it, and given a + * travelling term only when there is rain to make one. Reduced motion freezes it outright — + * a still puddle is a mirror, which is a perfectly good thing for it to be. */ + ripNow = 0; + if (mirNow > 0.20) { // dry bounce has no surface to ripple, so it pays nothing + ripNow = (hash2(Math.floor(wx * 2.7), Math.floor(wz * 1.9), 0x2E2) - 0.5) + * (1.2 + 1.8 * clamp(wWind, 0, 1.4)); + if (!CC.reducedMotion && wRain > 0.05) + ripNow += (vnoise(wz * 0.85 + t * 1.7, 0x2E3) - 0.5) * 2.4 * clamp(wRain, 0, 1.2); + } + wchNow = WATER[(hash2(Math.floor(wx * 2.3), Math.floor(wz * 1.1), 0x2E1) * WATER_N) | 0]; + + /* ---- where the cross streets cut this one --------------------------------------------- + * A junction is the only place a street's markings STOP, and stopping them is most of what + * makes a junction read as one. Loaded by the caster; with none loaded the road runs on. */ + var xd = 1e9, xh = 0, xcv = 0, i, ad2; + if (CFG.xn > 0) { + /* The entries are evenly pitched to within city.js's own jitter, so the index of the nearest + * is arithmetic and only its two neighbours need testing. Scanning all eight cost 0.15 ms a + * frame at 400x100 for an answer that was never more than one slot away from the guess. */ + var xg = Math.round((wz - CFG.xz0) / CFG.xpitch); + var xlo = xg - 1, xhi = xg + 1; + if (xlo < 0) xlo = 0; + if (xhi > CFG.xn - 1) xhi = CFG.xn - 1; + for (i = xlo; i <= xhi; i++) { + ad2 = wz - CFG.xc[i]; if (ad2 < 0) ad2 = -ad2; + if (ad2 < xd) { xd = ad2; xh = CFG.xw[i]; xcv = CFG.xc[i]; } + } + } + var inX = xd < xh; + + /* ---- paint ----------------------------------------------------------------------------- + * Paint sits on top of the road, so it is tested first, and none of it is ever dropped for + * distance: these are the lines the perspective is read from. Wet paint is glossier than wet + * tarmac, which is why none of these branches turns the mirror off. */ + if (CFG.xn > 0) { + if (inX) { + /* Box junction. Yellow crosshatch is the one piece of road paint that is unmistakably a + * junction from any angle, and in perspective the two diagonal families converge to two + * different points, which does more for the depth of the lower third than anything else + * on the road. Rare on purpose — two in five junctions — and dim, because amber is + * already the hottest swatch in the frame and this is a large area. */ + if (al < half + xh && hash2((xcv * 2) | 0, 0, 0x2C9) < 0.40) { + var d1 = lane + wz, d2 = lane - wz; + d1 -= Math.floor(d1 / 2.6) * 2.6; d2 -= Math.floor(d2 / 2.6) * 2.6; + if (d1 < 0.14 || d2 < 0.14) { + var hb = hash2(Math.floor(wx * 1.3), Math.floor(wz * 1.3), 0x2CA); + if (hb > 0.20) // worn through in patches + return rset(d1 < 0.14 ? G_SLASH : G_BSLASH, P.amber, 30 + hb * 26); + } + } + } else if (al < half) { + var apr = xd - xh; // metres out from the junction mouth + /* Zebra. The bars run ALONG the road, which is what a crossing looks like from a footpath + * at either end of it, and at this resolution they are the single most legible object the + * carriageway can carry: half a dozen hard verticals converging together. + * + * THE WEAR THRESHOLD IS A COVERAGE CONTROL, and it was moved at integration from 0.30 to + * 0.52 after the near band was measured across the reference sweep. A crossing is close to + * the camera by construction — you cannot see one from far enough away for it to be small — + * so it lands in the biggest cells in the frame, and at 70% intact it was the largest + * single contributor of white anywhere in the picture: 736 white cells in the bottom + * twenty-two rows at seed 3, against 1220 for every other road marking put together, in a + * band where white took 27-38% of the lit energy across the sweep. White is structure, not + * light; a road at night is tarmac with paint ON it, and the frame was reading as paint + * with tarmac between. At 48% worn it is 25-32% and slate — the tarmac itself — takes the + * difference, because the worn branch below is not a discard, it is the road showing + * through. Whole-frame black did not move (39.40% before and after at seed 3 frame 600): + * this is a redistribution between swatches, not a cut in coverage, which is exactly what + * it should be. Measure the near band before touching it again. */ + if (apr > 0.40 && apr < 2.60) { + var zk = lane - Math.floor(lane / 1.30) * 1.30; + if (zk < 0.52) { + var zw = hash2(Math.floor(lane * 1.6), Math.floor(wz * 1.6), 0x2C4); + if (zw > 0.52) return rset(zw < 0.72 ? G_HASH : G_8, P.white, 24 + zw * 20); + return rset(G_DASH, P.slate, 14); // worn back to the tarmac + } + } else if (apr > 2.86 && apr < 3.04) { // stop line + /* Thin, worn and dim. A stop line is 0.2 m of paint, but it lies almost FLAT to the + * camera, so unlike a longitudinal line — which costs one column per row — it costs a + * whole row of the near frame every time it appears. Eight junctions' worth of it was + * 426 cells at seed 42 on its own, more than the centreline and both edge lines together. + * + * THE OTHER HALF OF THAT ARGUMENT IS DEAD: white was "the most expensive swatch in the + * print at a gain of 1.15", and core.js's refit made it the CHEAPEST — gain 0.30, the + * lowest entry in the table, ceiling 151, deliberately under both pillars because white + * is structure and not light. So the lums below are no longer a discount against an + * expensive swatch; they are just low. Measured: at 27-45 this line printed v 108-130 + * when it was fitted and prints v 25-63 today, and white does not clear v=9 at all until + * lum 17. The surviving reason to keep it dim is the cell count above, which is a + * coverage fact and does not care about the curve — so the code stands, but anyone + * raising it is now buying legibility with white's share of lit energy (4.3% pooled over + * the 32-frame fixture, against core.js's worst-frame ceiling of 32.4%) and not + * spending an expensive swatch. Those are different trades and only one of them is + * written down here. */ + var sw = hash2(Math.floor(lane * 1.7), 0, 0x2C5); + if (sw < 0.22) return rset(0, P.shadow, 0); + return rset(G_EQ, P.white, 27 + sw * 18); + } + } + } + + /* Painted arrows — rare, one per ~26 m of road at most. */ + if (!inX) { + var az = Math.floor(wz / 26); + if (hash2(az, 0, 0xA55) < 0.40) { + var z0 = az * 26 + hash2(az, 1, 0xA55) * 18; + var dz = wz - z0, dlz = lane - (hash2(az, 2, 0xA55) - 0.5) * 3.0; + if (dz >= 0 && dz < 3.2) { + var adl = dlz < 0 ? -dlz : dlz; + /* Thin strokes on purpose: real 0.5 m paint is several cells wide up close and turns + * into a white slab that out-shouts the neon it is meant to sit under. */ + if (dz > 1.0 && adl < 0.15) return rset(G_PIPE, P.white, 84 + sheet * 34); + var hw = dz * 0.85; + if (dz <= 1.0 && adl - hw < 0.17 && hw - adl < 0.17) + return rset(dlz < 0 ? G_SLASH : G_BSLASH, P.white, 84 + sheet * 34); + } + } + + /* Centreline: dashed, sodium-amber because that is the colour the street lamps paint it. */ + if (al < 0.13 && (wz - Math.floor(wz / 4.6) * 4.6) < 2.8) + return rset(G_PIPE, P.amber, 150 + sheet * 60); + + /* Edge line. Solid, unbroken, and the reason it is here: it is the one white line that runs + * the entire depth of the frame, so it converges to the vanishing point on its own and + * gives the near road a floor to sit on. Worn in short stretches rather than dashed. */ + var el = half - 0.46, ael = al - el; if (ael < 0) ael = -ael; + if (ael < 0.062) { + var ew = hash2(Math.floor(wz * 0.55), 0, 0x2C7); + if (ew > 0.16) return rset(G_PIPE, P.white, 26 + ew * 22 + mirNow * 22); + } + } + + /* Tram rails. Two continuous steel lines the length of the street, on the third of streets + * that have a track. The head of a rail is polished by the wheels and is the one place on a + * road that is genuinely specular, so it carries a white glint even dry — but only near, + * where a glint is a glint and not a dotted line running to the horizon. */ + if (CFG.rail && !inX) { + var rg = al - 0.62; if (rg < 0) rg = -rg; + var rg2 = al - 2.06; if (rg2 < 0) rg2 = -rg2; + if (rg < 0.055 || rg2 < 0.055) { + var rh = hash2(Math.floor(wz * 1.4), 0, 0x5A12); + if (fl === 2 && rh < 0.30) + return rset(G_EQ, P.white, 40 + rh * 62 + mirNow * 34); + return rset(G_PIPE, P.slate, 16 + rh * 22); + } + } + + /* ---- kerb and pavement ------------------------------------------------------------------ + * Neither exists inside a junction: there the cross street's carriageway runs edge to edge, + * and a kerb ruled straight through it was the clearest tell that the road was a texture + * rather than a place. */ + if (!inX && al > half && al < half + 0.34) { + /* The kerb is the one continuous line the eye can follow from the camera all the way to the + * vanishing point, so it is drawn as an EDGE and not as a texture: a lit top arris that + * catches the sodium, and a face under it that does not. */ + var kw = hash2(Math.floor(wz * 3), 0, 0x3); + if (al < half + 0.14) + /* SODIUM, not white. A kerb is structure and white is the swatch for structure, but this + * particular structure is a metre under a sodium lamp and nothing else in the frame is + * lit so unambiguously by one source. Painting it white cost the floor a third of its + * amber and handed it to a swatch that is supposed to be the quiet one; painting it amber + * puts the longest continuous line in the lower third on the first pillar, which is where + * a street lamp's light actually goes. + * + * Lum is set against the print, and THE REASON IT IS SET HIGH HAS REVERSED. The old + * argument was that amber ran at gain 0.19 against white's 1.15, so an amber cell at lum + * 200 and a white cell at lum 30 printed the same brightness — amber had to shout to be + * heard next to the paint. On core.js's current table amber is 0.50 and white is 0.30, and + * amber's pigment (max channel 232) is brighter than white's (236 — near enough equal), so + * the compensation now runs the OTHER WAY: amber at lum 124 prints v 137 while white needs + * lum 118 to reach v 113. Amber's knee is at lum 38, not 74, and it is over v=9 from lum 10 + * and over v=40 from lum 21, so "anything under about 120 reads as dark olive" is off by + * more than a factor of two — the honest figure on this table is about lum 55, which prints + * v 101. + * + * The lums below are therefore GENEROUS rather than forced, and they are kept because the + * conclusion survives its old reason: this is the longest continuous line in the lower + * third and it is the one thing in the frame lit unambiguously by a single sodium source, + * so it should sit at the top of the first pillar's range. Measured over the 32-frame + * fixture (seeds 3001+137k, k=0..15, frames 600/1800 at 400x100) the kerb's 5866 cells + * print a mean v of 143 with 3.3% of them over the v=170 hot line, against a whole-frame + * hot tail of 3.57% in core.js's 3.5-5 band — bright, in band, and not the frame's + * brightest object. If amber's gain moves again, this number is the one to re-measure. */ + return rset(G_UNDER, P.amber, 124 + kw * 34 + lampK * 74 + mirNow * 30); + return rset(G_EQ, P.slate, 10 + kw * 12); + } + + if (!inX && al > half + 0.34) { // pavement + /* Standing water does not sit on a crowned pavement the way it sits in a gutter, and a + * pavement is a metre out of the light a shopfront throws down its own frontage. */ + mirNow *= 0.35; bounceNow = 0.05; + if (fl === 0) return rset(0, P.shadow, 0); + /* Tactile paving at a crossing mouth — a hard field of dots, the one place a pavement has a + * texture of its own rather than a grid of joints. */ + if (CFG.xn > 0 && xd > xh - 0.2 && xd < xh + 2.4 && al < half + 2.2) { + var tp = hash2(Math.floor(wx * 3.4), Math.floor(wz * 3.4), 0x2D3); + if (tp < 0.38) return rset(G_oo, P.slate, 15 + tp * 34); + return rset(0, P.shadow, 0); + } + /* Cable and service ducts run parallel to the kerb under every real pavement, and their + * covers are the long straight thing that keeps the slab grid from being the only order in + * the picture. */ + if (fl === 2) { + var du = al - (half + 1.05); if (du < 0) du = -du; + if (du < 0.17) { + var dj = wz - Math.floor(wz / 1.15) * 1.15; + if (hash2(Math.floor(wz / 1.15), 0, 0x2D4) < 0.42) + return rset(dj < 0.12 ? G_PIPE : (du < 0.08 ? G_EQ : G_DASH), P.slate, + dj < 0.12 ? 10 : 20 + hash2(Math.floor(wz * 2), 0, 0x2D5) * 18); + } + } + /* Paving joints are the only perspective cue the pavement has, so they are drawn at a + * value the eye can actually resolve. The per-cell dirt speckle that used to sit under + * them is gone rather than raised: it was a fifth of every floor cell drawn at a rendered + * value of eight, which is to say the frame paid for it and got black. + * + * They used to stop dead at 22 m, which is to say they stopped exactly where perspective + * begins to do the work: everything from there to the horizon was a black band with no + * scale in it at all. The grid now runs to 50 m on a doubled pitch, because past 22 m one + * screen row covers more than a metre of slab and the 1.25 m grid aliases into a moire + * that crawls as you walk. */ + var jp = fl === 2 ? 1.25 : 2.50, jw = fl === 2 ? 0.09 : 0.17; + var jx = wx - Math.floor(wx / jp) * jp, jz = wz - Math.floor(wz / jp) * jp; + if (jx < jw || jz < jw) return rset(G_COLON, P.slate, fl === 2 ? 15 : 11); + /* The slabs BETWEEN the joints. A grid of joints on black is a wireframe, not a pavement — + * it needs a surface to be the joints in. Quantised so it is stone and not per-cell salt, + * and kept well under the joints' own value so the grid still leads. The far band gets a + * thinner version of the same thing rather than nothing at all: from 22 m to the vanishing + * point is most of the pavement's screen area and it was empty. */ + var ps = hash2(Math.floor(wx * (fl === 2 ? 1.6 : 0.8)), + Math.floor(wz * (fl === 2 ? 1.6 : 0.8)), 0x2F); + if (ps < (fl === 2 ? 0.30 : 0.15)) + return rset(ps < 0.15 ? G_DOT : G_COMMA, P.slate, (fl === 2 ? 7 : 6) + ps * 20); + return rset(0, P.shadow, 0); + } + + /* ---- the carriageway -------------------------------------------------------------------- + * Everything from here down is tarmac, and the job is coverage with STRUCTURE: a road that is + * 50% pure black in the near field is not a dark road, it is a missing one. */ + + /* Gutter. Water runs to the kerb and stands there, so the last third of a metre before the + * kerb is the wettest strip on the street whatever the weather is doing. */ + if (!inX && al > half - 0.34) { + mirNow = clamp(mirNow + 0.20 + sheet * 0.45, 0, 1); + var gt = hash2(Math.floor(wz * 2.4), 0, 0x2D8); + if (gt < 0.15 + mirNow * 0.36) + return rset(wchNow, gt < 0.09 ? P.azure : P.slate, + gt < 0.09 ? 48 + mirNow * 54 : 9 + mirNow * 30 + gt * 12); + } + + /* Ironwork. Sub-cell past ~50 m, where drawing it would just salt the road with noise. */ + if (fl > 0) { + /* Manhole covers, placed in LANE space so they can never end up under a building. */ + var mz = Math.floor(wz / 9); + var dcl = lane - (hash2(mz, 0, 0x404) - 0.5) * 4.4; + var dcz = wz - (mz * 9 + hash2(mz, 1, 0x404) * 7); + var rr = dcl * dcl + dcz * dcz; + if (hash2(mz, 2, 0x404) < 0.34 && rr < 0.42) { + if (rr > 0.30) return rset(G_O, P.slate, 16); + return rset(hash2(Math.floor(wx * 3), Math.floor(wz * 3), 0x9) < 0.5 ? G_COLON : G_DASH, + P.slate, 9 + sheet * 8); + } + /* Inspection plates: the rectangular ones, bolted down, with a raised rim. Round covers + * alone gave the road one shape repeated; a road has a whole hardware catalogue in it. */ + var iz = Math.floor(wz / 7.3); + if (hash2(iz, 3, 0x404) < 0.22) { + var ipl = lane - (hash2(iz, 4, 0x404) - 0.5) * 4.0; + var ipz = wz - (iz * 7.3 + hash2(iz, 5, 0x404) * 5.6); + var aip = ipl < 0 ? -ipl : ipl; + if (aip < 0.46 && ipz > 0 && ipz < 0.78) { + if (aip > 0.38 || ipz < 0.07 || ipz > 0.71) // rim + return rset(aip > 0.38 ? G_PIPE : G_DASH, P.slate, 26); + var bh = hash2(Math.floor(ipl * 7), Math.floor(ipz * 7), 0x405); + return rset(bh < 0.22 ? G_PLUS : G_DOT, P.slate, 11 + bh * 16); + } + } + /* Gutter grates, hard against the kerb where they belong. */ + if (!inX && al > half - 0.62 && al < half - 0.08) { + var gz = Math.floor(wz / 2.6); + if (hash2(gz, 0, 0x6A2) < 0.22 && (wz - gz * 2.6) < 1.5) + return rset(G_HASH, P.slate, 12 + sheet * 10); + } + } + + /* Tar seams. A carriageway is not poured in one piece: it is a set of strips with a filled + * joint between them, and the joint wanders. These are near-black and one cell wide, and they + * are the cheapest coverage on the road — they cost almost no light and they give the near + * tarmac a set of long lines running to the vanishing point, which is exactly the cue an + * empty lower third is missing. */ + if (fl > 0) { + var sq = Math.floor(lane / 1.35); + if (hash2(sq, 1, 0x33B) < 0.44) { + var sp = sq * 1.35 + 0.18 + hash2(sq, 0, 0x33B) * 0.98 + + (vnoise(wz * 0.21 + sq * 7.3, 0x3C) - 0.5) * 0.55; + var asp = lane - sp; if (asp < 0) asp = -asp; + if (asp < (fl === 2 ? 0.05 : 0.09)) + return rset(G_PIPE, P.slate, 8 + hash2(sq, Math.floor(wz * 0.7), 0x33C) * 12); + } + } + + /* Expansion joints across the carriageway — cheap, honest parallax as you walk, and the only + * thing on the carriageway that runs ACROSS the view, so they are the road's answer to the + * facades' belt courses. Drawn at a value that survives the crush near the camera — which is + * why the mid-LOD tier is 16 and not the 9 it used to be: the crush moved under it. With slate + * at gain 0.60 and KNEE at 0.075 a slate cell needs lum 11 to print v 9 at all, so 9 printed + * v 6 and the joints stopped existing at exactly the distance the parallax is for, while the + * tarmac they cross now prints v 14-35 (see the near-tarmac note below). At 16 both LODs print + * v 21 and the line reads at both. */ + if (fl > 0 && (wz - Math.floor(wz / 4.0) * 4.0) < 0.10) + return rset(G_DASH, P.slate, 16); + + /* The pool itself, on the tarmac. `lum` is chosen against the print curve rather than by eye, + * and the curve it is chosen against has MOVED: this used to read "amber's gain is 0.19 with + * its knee at 0.055, so an amber cell under lum 74 renders as black". core.js now runs amber + * at 0.50 with KNEE 0.075, which puts amber's knee at lum 38 and its visibility floor at lum + * 10. The black floor this branch was built to clear is therefore three times lower than the + * comment claimed, and the lums below clear it by a wide margin: 112 prints v 132 and the top + * of the range prints at amber's ceiling, v 179. + * + * FEWER CELLS, BRIGHTER survives the refit, but for the saturation half of the argument rather + * than the knee half: amber still saturates slowly (v 105 at lum 60, v 137 at 124, v 164 at + * 200), so the energy a pool carries barely changes when its dither thins while what the eye + * can SEE of it changes completely. A dense pool at lum 80 is now v 116 rather than a large + * area of nothing, so the trade is less forced than it was — it is kept because a sodium pool + * under a lamp IS the brightest thing on a wet road, not because the alternative prints black. + * Wet tarmac under a lamp is brighter again, hence the mirror term. */ + if (lampK > 0.05 && fl > 0) { + var lh = hash2(Math.floor(wx * (fl === 2 ? 2.1 : 1.0)), + Math.floor(wz * (fl === 2 ? 2.1 : 1.0)), 0x1A5); + if (lh < 0.24 + lampK * 0.40) + return rset(lh < 0.5 ? G_DOT : G_COMMA, P.amber, + 112 + lampK * 118 + lh * 26 + mirNow * 44); + } + + /* ---- water on the tarmac ---------------------------------------------------------------- + * The meniscus first. A puddle's rim is the one genuinely specular line on a street: it is a + * curved edge of water standing proud of the tarmac and it catches whatever is overhead at a + * grazing angle. Ice is a GLINT and this is what a glint is for — a ring one cell wide round + * an object a metre across, not a surface. */ + if (pd > 0.015 && pd < 0.30) { + var mh2 = hash2(Math.floor(wx * 4.1), Math.floor(wz * 4.1), 0x2E5); + if (mh2 < 0.38) + return rset(mh2 < 0.09 ? G_QUOTE : wchNow, mh2 < 0.09 ? P.ice : P.white, + 22 + pd * 90 + mh2 * 40); + } + + /* And then the water itself. Its COLOUR is not decided here — see the header: raycast.js + * fetches whatever is standing above the cell. What this branch owns is the sheen a wet road + * has where there happens to be nothing overhead worth reflecting, which is most of it: dim, + * cool, and dense enough that a wet street is never the darkest thing in the picture. */ + if (mirNow > 0.12) { + var wg = hash2(Math.floor(wx * 3.1), Math.floor(wz * 1.3), 0x717); + /* Water standing inside a sodium pool is sodium, so this branch has to come first. The + * ORDER-OF-MAGNITUDE part of that instruction was arithmetic off the old table — amber 0.19 + * against slate 2.00, meeting on the print at about ten to one in lum — and core.js's refit + * has closed that gap almost exactly: amber is 0.50 and slate 0.60, and with amber's brighter + * pigment (232 against slate's 138) the two now meet at roughly ONE to one. Amber at lum 24 + * prints v 51 where slate at lum 24 prints v 40; the ten-to-one ratio no longer exists. + * + * The branch keeps its high lums anyway, and the reason is now physical rather than + * compensatory: this is standing water inside a lamp's pool, it is the brightest thing on the + * carriageway, and it should print like it (98-220 -> v 126-170). The failure the old comment + * names — a lit puddle ending up darker than the tarmac round it — is no longer a print + * artifact waiting to happen, so if a future edit wants this dimmer, it may go dimmer than + * ten times the slate branch without inverting anything. */ + if (lampK > 0.16 && wg < 0.14 + mirNow * 0.44) + return rset(wchNow, P.amber, 98 + lampK * 76 + mirNow * 46); + if (wg < 0.13 + mirNow * 0.48) + /* A minority of the sheen is AZURE, and it is not decoration: standing water at a grazing + * angle takes its colour from the sky and from the screenlight coming off the walls, which + * is the second pillar and the coldest thing in the frame. + * + * "48 up is where azure starts existing at all" WAS TRUE AND IS NOW FALSE BY A FACTOR OF + * TEN. It was arithmetic off azure 0.34 against slate 2.00; core.js raised azure to 1.00 — + * the highest gain in the table — and cut slate to 0.60, so azure clears v=9 at lum 5 and + * v=40 at lum 11, and the 48-98 written below prints v 125-163 against the slate branch's + * v 5-63. This branch is no longer a dim cool sheen sitting alongside the tarmac; it is a + * pillar-bright one, and it is a third of a stop brighter than when it was fitted (v 84-109 + * on the old table). + * + * It is left alone on purpose and the purpose is measurable: core.js's ladder says the + * pillars own the top of the lit range, azure holds 32.5% of lit energy over the 32-frame + * fixture against amber's 46.4%, and the whole-frame hot tail is 3.57% inside its 3.5-5 + * band, so nothing here is out of calibration — the number is simply no longer a floor, + * it is a choice. Anyone who wants the old dim sheen back writes about lum 12-16, not 48, + * and should re-measure azure's share when they do. */ + return rset(wchNow, wg < 0.055 ? P.azure : P.slate, + wg < 0.055 ? 48 + mirNow * 50 : 8 + mirNow * 30 + wg * 14); + } + + /* ---- asphalt ---------------------------------------------------------------------------- + * With the road's own repair history in it. A carriageway is a patchwork of different ages of + * blacktop and the EDGES of those patches are what the eye reads; a single even tone over the + * whole lower third is the thing that made it a void. Blocky on purpose — road repairs are + * rectangles — and jittered on the lattice so the blocks are not a visible grid. */ + if (fl === 0) return rset(0, P.shadow, 0); + + var qi = Math.floor(lane / 2.6), qj = Math.floor(wz / 3.4); + var patch = hash2(qi, qj, 0x7A9) < 0.30; + if (patch && fl === 2) { + /* The seam round a patch: fresh blacktop laid into a cut, so the cut shows. */ + var el2 = lane - qi * 2.6, ez = wz - qj * 3.4; + if (el2 < 0.09 || ez < 0.09 || el2 > 2.51 || ez > 3.31) + return rset(el2 < 0.09 || el2 > 2.51 ? G_PIPE : G_DASH, P.slate, 13); + } + + /* Near tarmac. This is the single largest surface in the frame and it was printing 18% of its + * cells at lum 5-7 — through P.slate's gain THEN, 2.00, that is a rendered value of about 42, + * one notch over the threshold, on less than a fifth of the ground. The result was a piece + * about walking down a street in which the street was the darkest thing in the picture. + * + * THE LUMS BELOW ARE RAISED, AND THE REASON IS THAT THE SENTENCE ABOVE STOPPED BEING TRUE. + * core.js's refit cut slate 2.00 -> 0.60 to give the swatch its depth fade back (at 2.00 it + * sat past the SHOULDER and printed 137 near against 137 far). That is right, and it is not + * this file's to argue with — but it also means slate no longer clears v=9 until lum 11, and + * this branch was still writing the numbers that were chosen when lum 6 printed 42. Measured + * on the 32-frame fixture (seeds 3001+137k, k=0..15, frames 600 and 1800 at 400x100) BEFORE + * the change: the mid-LOD tier's whole dither, lum 6.0-10.1, printed v 3-8 — every cell of it + * under the visibility floor — and 25.5% of all painted slate floor cells printed v<9. The + * branch was paying for coverage and returning nothing, which is the exact mistake the + * spandrel tier documents and which the paragraph above says it fixed. It was a hole again. + * + * The fix is a lift, not a restoration: lum 13-22 here and 11-37 below print v 14-35 and v + * 10-56, against the v 42-90 the same dither used to reach. Restoring the old PRINTED values + * would need slate lums around 25-150, and that is not affordable — core.js holds the muddy + * v=9-119 band at 27.9% against a <30 target and 99.7% of what its KNEE crushes is slate and + * shadow, i.e. this texture, deliberately. So the road gets back over the visibility floor and + * no further. MEASURED before -> after on the 32-frame fixture, this block and the expansion + * joint above it together: painted slate floor cells printing v<9 25.5% -> 19.0% (the + * remainder is the pavement slab and joint tiers, which were left alone), slate's mean printed + * floor value 19.2 -> 21.8, muddy 27.9% -> 28.3%, hot 3.57% -> 3.57%, black(v<9) 57.2% -> + * 56.9%, blank unmoved at 42.3%, lit energy unmoved at amber 46.4 / azure 32.5. It is still + * the darkest LARGE surface, which is what it should be. + * + * NOT LIFTED, on purpose: the pavement slabs and joints next door (v 3-18) and the facades' + * spandrel salt. They are not the largest surface in the frame, the muddy budget does not + * stretch to the whole floor, and a swatch-wide correction belongs in EXPOSURE, not in forty + * literals here. If slate's gain moves again, this block is the first thing to re-measure. */ + if (fl === 1) { + var mh = hash2(Math.floor(wx * 0.9), Math.floor(wz * 0.9), 0x12); + return mh < 0.23 ? rset(mh < 0.11 ? G_DOT : G_COMMA, P.slate, 13 + mh * 40) + : rset(0, P.shadow, 0); + } + var ah = hash2(Math.floor(wx * 2.2), Math.floor(wz * 2.2), 0x12); + /* A patch is younger, blacker and smoother than the road round it, so it goes DOWN in + * coverage and up in evenness. The ruts go the other way: polished, so they hold more light. + * The patch tier keeps its lower value but not its old lum: at 7 + ah*20 with ah < 0.24 every + * patch cell in the frame printed v 4-10, so the "younger, blacker" distinction was being + * drawn entirely below the print's floor and read as a hole in the road. */ + var acov = patch ? 0.24 : 0.33 + rut * 0.12; + return ah < acov ? rset(ah < 0.15 ? G_DOT : G_COMMA, P.slate, + (patch ? 11 : 13) + ah * (patch ? 26 : 40) + rut * 6) + : rset(0, P.shadow, 0); + } + + /* ---- sky ------------------------------------------------------------------------------ + * sx/sy are screen cells. Pass a yaw-compensated column (e.g. x + yaw/fov*cols) if the camera + * turns, otherwise the stars ride the view. Nearly all of this returns blank: the slot of sky + * is the largest single reservoir of black in the frame. */ + var SOUT = { ch: 0, col: 0, lum: 0 }; + function sset(ch, col, lum) { + SOUT.ch = ch; SOUT.col = col; + SOUT.lum = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0); + return SOUT; + } + + /* THE ROOFLINE THIS COLUMN ACTUALLY HAS. + * The glow used to be measured from the horizon alone, which is why it never appeared: at + * 200x60 the open sky starts 19-21 rows above the horizon and at 400x100 it starts 31, so with + * an 11-row e-fold every visible sky cell received 0.06-0.16 of the glow — arithmetically + * present, invisible on screen. And an e-fold fixed in ROWS is not a length at all: doubling + * the grid halves the lit fraction of the same picture. + * + * The raycaster paints a column's sky top-down from the silhouette, calling sky() with sy + * strictly DECREASING and always finishing at row 0, so the first call of a new column is + * exactly the one whose sy is not lower than the previous call's. That is the row immediately + * under this column's rooftop, and it is the only extra fact the glow needs. Two integers of + * module state, no allocation, no camera term, and if a caller ever violates the sweep order + * the worst case is a glow anchored one row off. */ + var skyLastSy = 1e9, skyRoof = 0; + + function sky(sx, sy, t) { + if (sy >= skyLastSy) skyRoof = sy + 1; + skyLastSy = sy; + + /* Light pollution, not haze: the city lighting its own underside. Dithered rather than + * washed, because a solid low-lum fill would read as the grey sky the references refuse + * to have. Amber at the rooftop line, cooling to slate, gone by the top of the slot. + * + * This is what draws the ROOFLINE. A rooftop silhouette is not a thing the raycaster can + * paint — it is the boundary between a lit sky and an unlit building, so if the sky slot is + * black there is no silhouette at all, just black meeting black, and the skyline the whole + * piece is built around disappears. + * + * Two anchors, and the brighter wins. The HORIZON term is the physical one: down the canyon's + * vanishing point you are looking through the deepest column of lit air there is. The ROOFTOP + * term is the one that draws the picture: every parapet in the frame is back-lit by the city + * standing behind it, so the glow hugs whatever silhouette this column happens to have + * instead of only the ones that stop near the horizon. Where a column is fully open the two + * coincide exactly and the expression collapses to the physical one. + * + * The e-fold is a fraction of the GRID rather than a count of rows, so it is a length on the + * picture and not on the buffer: a 100-row grid gets the same sky a 60-row grid does. + * + * It used to be a fraction of CFG.horizon, which was the same number back when the horizon was + * always 0.56*rows. The camera pitches now — control.js slides cam.horizon over 0.26..0.86 of + * the grid — so that expression stretched the light-pollution ramp by a factor of three and a + * bit as you tilted, and the roofline glow visibly grew when you looked up at it. The horizon + * still says WHERE the ramp starts; the grid says how long it is. */ + var e = CFG.rows * 0.185; + if (e < 3) e = 3; + var aboveH = CFG.horizon - sy; if (aboveH < 0) aboveH = 0; + /* The star field's VERTICAL, which must be an elevation and not a screen row. + * + * The integration note at the top of this file tells the caller how to compensate for yaw and + * says nothing about pitch, because pitch did not exist when it was written — so sy went + * straight into the two hashes below and the stars ended up welded to the glass. Measured: at + * 260x100, tilting the camera by 10 rows (a third of control.js's PITCH_MAX) left 8/8, 7/7, + * 7/7 and 7/7 stars at seeds 3/7/42/99 on exactly the SAME screen cell. Look up and the city + * slides past a starfield that is painted on the inside of the visor. + * + * cam.horizon is where the pitch actually lives — the caster slides it and projects everything + * else against it — so (horizon - sy) is already invariant under pitch by construction, in the + * same way aboveH above is. skyVScale then divides out the live vertical magnification, which + * is the zoom half of the same problem. At the neutral camera it is 1.0 and this is exactly + * the old sy up to a constant offset, so the shipped sky is unchanged. + * + * Math.floor, not |0: |0 truncates toward zero and would mirror the field about the horizon + * row, printing a visibly duplicated line of stars right along the roofline. */ + var ey = Math.floor((CFG.horizon - sy) * CFG.skyVScale); + var aboveR = skyRoof - sy; if (aboveR < 0) aboveR = 0; + var glow = Math.exp(-aboveR / e) * 0.94; + var gh = Math.exp(-aboveH / e); + if (gh > glow) glow = gh; + + /* 124, not 82, and the reason WAS the print's KNEE. That instruction — "if EXPOSURE[amber] + * moves, re-measure the sky's lit fraction" — has now been honoured, because it did move, and + * the arithmetic underneath this constant no longer says what it used to. + * + * THEN: amber at gain 0.19 with KNEE 0.055 did not clear the knee until lum 74, so a glow cell + * written at 82 fell under it the moment `glow` dropped below about 0.9 and printed black + * however carefully it was dithered. NOW: amber is 0.50 and KNEE is 0.075, which puts amber's + * knee at lum 38 and its visibility floor at lum 10. At 124 the dimmest cell of the dither + * (the 0.7 tail of the jitter) stays over the knee down to glow 0.44; at 82 it would still hold + * to glow 0.66. So 82 would NOT print black now — the constant buys about a factor of 1.5 in + * how far up the slot the glow survives, not the difference between a roofline and nothing. + * + * RE-MEASURED over the 32-frame fixture (seeds 3001+137k, k=0..15, frames 600 and 1800 at + * 400x100; per column, take the six rows above the first non-sky cell from the top and count + * kind-0 cells there, blank ones included, that print v>=40): 17.9%, against the 25-35% this + * comment sets as the target. Every cell the dither actually PAINTS in that band clears v=40 + * comfortably — its lums run 60-152, i.e. v 105-147 — so the shortfall is DENSITY, not + * brightness: the gate below paints glow*0.86 of the cells and the rest stay blank sky. + * Raising 124 cannot fix that, and lowering it would not even show up in the census until it + * fell under about 42 (below which the dimmest jitter of the dimmest of those six rows stops + * clearing v=40 — amber reaches v 40 at lum 21). The number that moves this census is the + * 0.86, and moving it spends black budget, so it is left to whoever owns the sky rather than + * smuggled in under a comment repair. Either way, state the target honestly: it describes a + * density this constant does not control. */ + if (glow > 0.02 && hash2(sx, ey, CFG.skySeed) < glow * 0.86) { + var lum = 124 * glow * (0.7 + 0.6 * hash2(sx, ey, CFG.skySeed ^ 0x11)); + // The documented ramp is amber at the rooftop line cooling to slate, gone by the top of the + // slot. It used to cool straight to P.shadow (40,50,66) — near-black — so the outer two + // thirds of every sky slot printed as a dark dot on black and read as void, not as air. + if (lum >= 4) return sset(glow > 0.32 ? G_DOT : G_TICK, + glow > 0.32 ? P.amber : (glow > 0.11 ? P.slate : P.shadow), lum); + } + + /* Stars only well clear of the glow — nothing survives being seen through a city. Gated on + * the glow itself rather than on a second row count, so the two can never drift apart: + * exp(-0.64) is where the dither has thinned enough for a star to hold its own. */ + if (glow < 0.53) { + var s = hash2(sx, ey, 0x1337); + if (s < 0.0075) { + /* Twinkle is motion, and motion is opt-out. Frozen it is still a star. */ + var tw = CC.reducedMotion ? 0.86 + : 0.55 + 0.45 * hash2(sx ^ Math.floor(t * 0.8), ey, 0x99); + return sset(s < 0.0018 ? G_PLUS : G_DOT, s < 0.0035 ? P.ice : P.white, + (52 + s * 9000) * tw); + } + } + return sset(0, P.shadow, 0); + } + + /* ---- depth ---------------------------------------------------------------------------- + * Attenuation toward BLACK, never toward grey — there is no atmospheric scatter colour in + * the references, distant buildings simply stop emitting. Multiplying lum keeps the hue and + * lets brightness carry all of the depth cue. + * Apply this exactly once per cell, in the world pass. */ + var FOG_START = 12.0, FOG_END = 125.0; + /* The LIVE end of the ramp, which the weather moves. FOG_END stays the constant it always was + * because three other files use it as "further away than the world goes" — sky.js parks the moon + * past it, structure.js culls against it, core.js buckets its print curve on it — and none of + * those wants to be re-based every time it drizzles. What the weather moves is how far you can + * SEE, and that is this pair. */ + var fogEnd = FOG_END, fogSpan = FOG_END - FOG_START; + function refog() { + /* P.fog is 0.30 under the reference preset, so k is 0 for the look that shipped, +1 in a full + * mist and about -0.31 on a clear night. Deliberately a gentle swing: the house rule is that + * distance fades to BLACK, so a shorter ramp does not add haze, it removes street, and a mist + * that ate forty metres of canyon would take the frame's black budget with it. */ + var k = (wFogP - 0.30) / 0.70; + if (k > 1) k = 1; else if (k < -0.45) k = -0.45; + fogEnd = FOG_END * (1 - 0.26 * k); + fogSpan = fogEnd - FOG_START; + } + function fog(lum, dist) { + if (!(dist === dist) || dist === Infinity) return lum; // sky (Infinity) and NaN pass through + if (dist <= FOG_START) return lum; + if (dist >= fogEnd) return 0; + var k = 1 - (dist - FOG_START) / fogSpan; + k = k * Math.sqrt(k); // pow 1.5: gentle near, hard crush past ~55 m + var v = lum * k; + return v < 4 ? 0 : v | 0; // crush the tail so nothing settles into grey mush + } + + /* Called once at the top of the world pass, before any per-cell call. It syncs the weather + * cache and hands back how far marching is still worth doing — past this fog() can only return + * 0. The caster must use the RETURNED value rather than FOG_END: on a clear night the ramp runs + * ten metres further than the constant and the far end of the street would otherwise be cut off + * at exactly the distance the air stopped hiding it. */ + function beginFrame(t) { + weatherAt(t === undefined ? 0 : t); + return fogEnd; + } + + CC.Surf = { + facade: facade, floorTex: floorTex, sky: sky, fog: fog, + configure: configure, cfg: CFG, beginFrame: beginFrame, + FOG_START: FOG_START, FOG_END: FOG_END + }; +})(typeof CC !== 'undefined' ? CC : require('./core.js')); +/* Standalone `require()` of this file has no global CC, so re-resolve it rather than assuming + the concatenated-build case. require() is cached, so this is the same object either way. */ +if (typeof module !== 'undefined') + module.exports = (typeof CC !== 'undefined' ? CC : require('./core.js')).Surf; diff --git a/src/weather_state.js b/src/weather_state.js new file mode 100644 index 0000000..0503dbd --- /dev/null +++ b/src/weather_state.js @@ -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')); diff --git a/tools/domshim.cjs b/tools/domshim.cjs new file mode 100644 index 0000000..d914bca --- /dev/null +++ b/tools/domshim.cjs @@ -0,0 +1,1165 @@ +/* CyberCity DOM shim — run the SHIPPED index.html with no browser. + * + * WHY THIS FILE EXISTS. tools/headless.cjs deliberately loads only the pure modules: it never + * touches src/main.js or src/render_canvas.js, so the boot path, the glyph atlas, the bloom + * composite, the resize/layout path, fullscreen, pointer lock, every input handler in control.js + * and the pause wiring in main.js had never executed anywhere, at all, ever. Half the project was + * shipping unrun. + * + * WHAT IT TESTS. The single