Three worlds, and a day/night cycle in all of them

Worlds are now a registry rather than a pair. 1 CyberCity, 2 Frontier,
3 Moonwalk; the same seed is a place in all three, so #42 is the same
corner of the same street lattice with a different century — or a
different world — built on it.

MOONWALK. An Apollo-era lunar surface, and it is the world this
renderer was waiting for: no air means a shadow is genuinely lum 0 and
the sky is the same black at noon as at midnight, so it prints 1.3% of
its cells in the muddy band against the project's under-30% target and
the city's 64%. Crater rims are the only geometry in any world whose
height varies inside a lot. Signage is switched off by data — signP 0
in every district — rather than by code.

THE CLOCK. T steps the time of day through six stops, Shift+T back, Y
stops and restarts the automatic cycle. Seven-minute day, sun to 54
degrees with the bearing swinging east to west so the shadows swing
with it. Phase is a pure function of t plus stamped overrides, so the
offline harness still reproduces the browser.

The print was the blocker: it is fitted to a frame that is more than
half pure black, and daylight is the inverse of that picture. Answered
with a second EXPOSURE ladder blended by the clock through
Compose.post(f, cam, t), which had always been handed cam and t and
always dropped them. Surfaces blend on the sky, sources on the sun.

THE FRONTIER IS AN 1880S TOWN AGAIN. It had been running the shared
city crowd with only its silhouettes re-weighted, so 18% of it carried
a glowing phone, one in ten wore a lit visor, and a fifth was rim-lit
in screenlight blue; the city's moon was painting a cyan halo over the
sunset because it won the depth test against the frontier's own sun.
Added the desert it was missing: blowing dust, a mesa skyline, four
more plants, horses at the hitching rails, wagons, a dog.

Every world-space element now shares one camera (src/proj.js) instead
of carrying its own copy — six places for a projection that must match
raycast.js exactly to stop matching it.

domshim 288/288. All three photosensitivity gates pass, and the gate
that was frontier-only now runs every world that is not the city.
Budget 420 -> 560 KB, with the accounting in build.js.
This commit is contained in:
MiguelCarino 2026-08-18 08:01:34 -06:00
parent a901ed2892
commit a39746e97b
43 changed files with 15463 additions and 305 deletions

View file

@ -35,9 +35,14 @@ concatenates them in order and the headless harness `require`s them through a sh
| file | global | responsibility | | file | global | responsibility |
| --- | --- | --- | | --- | --- | --- |
| `src/core.js` | `CC` | Frame alloc, PALETTE, GLYPHS, rng/noise, math, `put()` | | `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/world.js` | `CC.World` | the world registry — which world is live, the id/name/alias table, and `inWorld()` |
| `src/daylight.js` | `CC.Daylight` | the clock: sun altitude and bearing, and the light directions everything reads off them |
| `src/city.js` | `CC.City` | `make(seed)` → heightmap + per-cell district/style/sign metadata, for either world |
| `src/raycast.js` | `CC.Cast` | `render(frame, cam, city)` — fills every cell: façades, floor, sky | | `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/surfaces.js` | `CC.Surf` | texture fns: `facade(u,v,cell,dist)`, `floorTex(wx,wz,dist)`, `sky(x,y,t)`; owns `configure`/`cfg`/`fog` for both worlds and delegates the three painters |
| `src/surf_west.js` | `CC.SurfWest` | the frontier's `facade` / `floorTex` / `sky`, same signatures |
| `src/surf_moon.js` | `CC.SurfMoon` | Moonwalk's, likewise. Painters self-register into `CC.SURFACES[id]`; `build.js` globs `src/surf_*.js` |
| `src/proj.js` | `CC.Proj` | the ONE copy of the element camera — `make()` hands each world-space element file its own basis and the four helpers closed over it |
| `src/elements/*.js` | pushes to `CC.ELEMENTS` | ambient systems, see below | | `src/elements/*.js` | pushes to `CC.ELEMENTS` | ambient systems, see below |
| `src/compose.js` | `CC.Compose` | fog, element pass ordering, reduced-motion damping | | `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/render_canvas.js` | `CC.Canvas` | glyph atlas, `drawImage` per cell, bloom. **Only DOM-touching module** |
@ -49,12 +54,63 @@ concatenates them in order and the headless harness `require`s them through a sh
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'rain', name: 'rain',
layer: 10, // lower draws first; elements draw after the world pass layer: 10, // lower draws first; elements draw after the world pass
world: 'cyber', // OPTIONAL: an id, or an ARRAY of ids. Absent means EVERY world —
// which is a materially different promise now there are three, and is
// why the atmospheric elements had to be given ['cyber','west'].
init(city, rng) {}, // allocate persistent state init(city, rng) {}, // allocate persistent state
update(dt, t, cam) {}, // advance simulation; no drawing 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 draw(frame, cam, t) {}, // use CC.put(frame, x, y, glyph, colour, lum, dist) — it depth-tests for you
}); });
``` ```
## Worlds
`CC.World` names the live world and calls back when it changes; `main.js` responds by tearing the
map down and building a new one on the **same seed**. Everything downstream keeps its own data for
both worlds next to the numbers it already has — `city.js` holds two district tables, `weather_state.js`
two preset tables, `surfaces.js` delegates its three painters — rather than reading from one central
theme object. The URL fragment is `#<seed>` for the default world and `#<world>/<seed>` otherwise.
Rules for worlds:
- An element that belongs to one world says so with `world:` on itself, as an id or an array of
them. The test is `CC.inWorld(el, id)` and there is exactly ONE definition of it, in `world.js`,
shared by `main.js`, `tools/headless.cjs` and the photosensitivity gates — because those three had
three copies and an offline reference frame rendered from a different element set than the
browser's is not a reference frame. `main.js` filters **before** the layer sort, because every
element draws from one shared rng in layer order and which elements are present decides every
later element's noise stream.
- A world is added by appending a row to `world.js`'s `LIST` (never prepending — `LIST[0]` is the
URL default and every `#42` link ever shared addresses it), a theme block and district table in
`city.js`'s `THEMES`, a painter file that self-registers, a weather table in `weather_state.js`,
and element files tagged with its id. Nothing in the tree switches on a world id with a ternary
any more; every one of those is a registry lookup with a documented fallback.
- Nothing decides geometry by reading `CC.World` at draw time. The map resolved the world once,
inside `make()`, and carries the answer on itself as `city.world`; between a keypress and the
rebuild those two differ by a frame.
- `CC.Weather.rel()` denotes the same physical quantity in every world. Its reference row is the
city's `rain` preset, permanently, because it is the contract every element was tuned against.
## The clock
`CC.Daylight` is a director of exactly `CC.Weather`'s shape: one live parameter block, recomputed
each tick, read by everything. Its phase is a pure function of `t` plus a seeded offset — never an
accumulator — and its two viewer controls are STAMPS (`T` moves an offset, `Y` records the instant
the clock stopped), so a frame stays a pure function of `(seed, t)` and the offline harness keeps
reproducing the browser.
Rules for the clock:
- **Every daylight scale must be the identity at night.** The shipped night look is the tuned
baseline that a 128-frame census was fitted against, so a factor of `0.22 + 0.93 * lamp` — which
is 1.15 at night — silently re-tunes the picture the feature was supposed to leave alone. It did,
once, and moved 1083 cells of a 12000-cell reference frame before the byte comparison caught it.
- Read the RIGHT direction. `sky` is what lifts structure (in daylight a wall is lit by the whole
hemisphere, not by the sun); `lamp` is what takes artificial light away and has hysteresis;
`sun` is only for things that need a shadow; `star` keys on the twilight curve and not on the
sun, because the whole of civil twilight has no sun in it and no stars either.
- The print has TWO exposure ladders (`EXPOSURE` and `EXPOSURE_DAY` in `core.js`) blended by the
clock through `CC.Compose.post(f, cam, t)` — which has always been called with `cam` and `t` and
always ignored them. The LUT is rebuilt only when the blend crosses one of 32 quantised steps.
Rules for elements: Rules for elements:
- **Never** write to the typed arrays directly; always go through `CC.put`, which honours `frame.dist`. - **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 be allocation-free in `update`/`draw` (pre-allocate in `init`) — this runs 60×/sec.
@ -63,6 +119,6 @@ Rules for elements:
## Verification (this is not optional) ## Verification (this is not optional)
`node tools/headless.mjs <seed> <frame> <cols> <rows> > f.txt` renders one frame with **no browser** `node tools/headless.cjs <seed> <frame> <cols> <rows> [--west|--moon] [--time=noon] > 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 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. image with the same bloom the canvas does. Every change gets looked at this way before it ships.

190
README.md
View file

@ -1,14 +1,71 @@
# CyberCity # CyberCity
A walkable cyberpunk city drawn entirely in text characters, in one self-contained HTML file. Three walkable worlds drawn entirely in text characters, in one self-contained HTML file, with the
sun going round.
No build step to run it, no dependencies, no network requests. Open `index.html` and you are No build step to run it, no dependencies, no network requests. Open `index.html` and you are
standing on a street at night in the rain. standing on a street in the rain. Press **2** and you are on a dirt road on the frontier; press
**3** and you are on the Moon.
**[cybercity.carino.systems](https://cybercity.carino.systems)** **[cybercity.carino.systems](https://cybercity.carino.systems)**
![A street canyon at night, lit tower faces either side](docs/street.png) ![A street canyon at night, lit tower faces either side](docs/street.png)
## Three worlds
| key | world | |
|---|---|---|
| `1` | **CyberCity** | a rain-lit city — neon, aerial traffic, police, market stalls |
| `2` | **Frontier** | an 1880s timber town — veranda posts, painted boards, telegraph, horses, open desert |
| `3` | **Moonwalk** | an Apollo-era lunar surface — regolith, craters, a black sky with Earth in it |
They are the same engine and the same seed. `#42` is a place in all three, so pressing 1, 2 and 3
in turn shows you the same corner of the same street lattice with a different century — or a
different world — built on it. That is the point of having three.
![A frontier main street at dusk, veranda posts and a sunset band](docs/frontier.png)
![A lunar plain at local noon, Earth hanging in a black sky](docs/moonwalk.png)
## The day
Every world runs a day/night cycle. Seven minutes is a full day; the sun climbs to 54 degrees and
its bearing swings from east to west, so the shadows swing across the street with it and which side
of the road is lit changes as the morning turns into the afternoon. Lamps come on at dusk and are
still burning after dawn. `T` steps the clock through its six stops — night, dawn, morning, noon,
afternoon, dusk — and `Y` stops and restarts the automatic cycle.
That was not a free feature, and the reason is worth stating: the whole print pipeline is fitted to
a frame that is more than half pure black with a thin scatter of bright glyphs, and daylight is the
inverse of that picture. It is answered with a **second exposure ladder**. By day the two night
pillars go out — a sodium lamp at noon is a grey tube and a screen is a dark rectangle — and white
and slate take the top of the table, because in daylight the bright things are surfaces rather than
sources. The two ladders are blended by the clock and the lookup table is rebuilt when the blend
crosses one of 32 steps, about once every thirteen seconds.
So a city at noon is a grey concrete canyon with dark glass in it under a bright sky, which is what
a city at noon is; and the frontier at noon is a pale road under a deep blue dome. Neither is the
night frame with the brightness turned up.
![The same city at noon: concrete, dark glass, and the neon barely reading](docs/city-noon.png)
An honest note on the numbers: `tools/metrics.py` prints a "muddy" census — the share of the frame
in the middle of the print's range — with a target under 30%, and a daylight frame does not meet
it. It cannot: that target describes a night picture, where the middle of the range is haze to be
crushed, and in daylight the middle of the range is where a lit wall, a road and a blue sky all
live. Measured at 200x60, seed 42: the city runs 32% at night, 56% at dusk and 64% at noon; the frontier
36% / 34% / 26%; and Moonwalk **2.8% / 1.8% / 1.3%**. The Moon can hold the night target at every
hour of its day because it has no air, which is the whole argument for it being the third world.
The other number in that census is the hot tail — the share above the print's highlight line, with
a 3.5-5% target — and it moves the other way: the city is 8.0% at night and 3.2% at noon, the
frontier 0.6% at dusk and 5.6% at noon, Moonwalk 3.5% at night and 6.6% at noon. Twilight in the
two atmospheric worlds is the flattest hour of the three, and that is not a bug to be tuned out:
it is the hour when the neon and the sky are the same brightness, which is exactly what makes it
look like twilight.
![A dust storm coming up the road](docs/dust.png)
Every cell you see is a character. There is no bitmap anywhere in the renderer — the towers, the Every cell you see is a character. There is no bitmap anywhere in the renderer — the towers, the
rain, the wet road, the people on the pavement and the traffic lights are all `8`, `%`, `M`, `|` rain, the wet road, the people on the pavement and the traffic lights are all `8`, `%`, `M`, `|`
and `.` in twelve colours. and `.` in twelve colours.
@ -39,6 +96,71 @@ like and it hands them over; stop steering and it picks the walk back up from wh
![Storey-scale advertising above a wet street](docs/signage.png) ![Storey-scale advertising above a wet street](docs/signage.png)
## What is in Moonwalk
The Moon is the world this renderer was waiting for, and that is not a flourish — it is why the
third world is the Moon and not, say, a jungle. The art direction is a frame that is more than half
pure black with a thin scatter of very bright glyphs, and every other world has to be composed to
deliver that. The Moon delivers it by having no air: a shadow with nothing to fill it is genuinely
lum 0, a sunlit surface under an unfiltered sun is genuinely the brightest thing there is, and the
sky is the same absolute black at noon as at midnight. Measured, a lunar frame prints **2.5% of its
cells in the muddy band** against the project's under-30% target and the city's 32%.
- **The ground** is an open regolith plain: the street lattice is still there and is made invisible
— the pitch nearly doubles, the corridors double again and the blocks go 90% vacant — so the walk
still has somewhere to walk and you cannot see why.
- **Craters.** The one piece of geometry in any world whose height is a function of position
*inside* a lot: a flat walkable floor with a raised rim round it on a sine profile, so the route
can cross a crater rather than being fenced out of one.
- **Terrain types instead of colour masses** — mare, ejecta, rim, highland, landing site, plain —
with boulder and crater rates rather than window-lighting rates. There are no signs anywhere,
and that is switched off by *data*: every district has `signP: 0`, so the signage path is never
entered and no neon blade sign can appear on a crater rim.
- **A hard terminator.** No penumbra and no fill, so the sun response is a step where the other
worlds use a ramp, and an unlit face past 25 m is a true blank that reads only by its razor edge
against the lit one beside it.
- **Earth**, hanging in the black and never moving, because the Moon is tidally locked.
## What is in the frontier
The same machinery, told to be somewhere else. The street lattice, the walk, the weather director,
the crowd, the cat and every optic are shared; the map generator, the texture layer, the weather
table and about a third of the elements are the frontier's own.
- **The town** is timber. False fronts — a flat board wall carried a metre and a half above the
building's own roofline so it looks bigger from the street — clapboard, board-and-batten, adobe
and fieldstone, in six quarters from the main street to the mission.
- **Open range.** A quarter of the ground is a district that is mostly not a district: empty lots,
sagebrush, saguaro, and one lot in fourteen carrying a flat-topped sandstone butte.
- **The light.** One low sun in a fixed direction, and every wall in the world is either rimmed in
amber or a silhouette. Which side of the street is lit changes when the walk turns a corner.
- **The sky.** It is a third of the frame out here, so it is the subject: a banded dusk gradient,
the sun with its halo, altocumulus bars lit orange along their undersides, the earth-shadow band
rising in the east, and three vultures on a thermal.
- **The street.** Boardwalks with a step down to the dirt, veranda posts every two and a half
metres, awnings, porch lanterns, hitching rails, water troughs, barrels, wagon ruts that hold the
water after a squall.
- **The telegraph**, on one side of the road, with the wire sagging between the poles.
- **Chimneys with smoke, water tanks on legs, bell towers and windmills** on the rooflines.
- **One tumbleweed**, rolling and bouncing, coming off the wind.
- **Weather** out here is a drought broken by a storm: blazing, breeze, dust, squall, overcast,
thunder.
- **Desert.** Blowing dust that thickens into a sheet under the dust presets, a far skyline of
mesas and buttes drawn past the fog distance as a pure function of bearing, yucca, mesquite and
ocotillo alongside the sage and saguaro, and dry washes on the flat.
- **Horses at the hitching rails** — placed on the same lattice the rails are, so they line up —
wagons crossing the junctions, and a dog.
The frontier also had a de-cyberpunking pass, because it needed one. The crowd is shared with the
city and only its silhouettes had been re-weighted, so 18% of an 1880s town was carrying a glowing
phone, one in ten wore a lit HUD visor, some had electroluminescent piping down the coat, and a
fifth of everybody was rim-lit in screenlight blue. The city's moon element was drawing itself and
a cyan halo straight over the sunset because it won the depth test against the frontier's own sun,
and four hundred stars — the brightest of them in the neon-cyan swatch — were being painted over a
sky with the sun still visibly above the horizon. All of that is gone: the sci-fi costume fields
are gated, the night sky is driven by the clock so it fades out properly at dawn, and no surface in
that world takes azure, violet or ice any more.
## Controls ## Controls
It plays itself, so all of this is optional. It plays itself, so all of this is optional.
@ -53,17 +175,34 @@ It plays itself, so all of this is optional.
| scroll wheel | zoom | | scroll wheel | zoom |
| `Tab` | take the controls / give them back | | `Tab` | take the controls / give them back |
| `Esc` | give them back | | `Esc` | give them back |
| `P` | photo mode — freezes the city, you can still look and move | | `P` | photo mode — freezes the world, you can still look and move |
| `1`–`6` | weather: clear, drizzle, rain, downpour, mist, storm | | `1` `2` `3` | world: CyberCity, Frontier, Moonwalk (gamepad: `Y` / triangle cycles) |
| `T` | step the time of day (`Shift`+`T` steps back) |
| `Y` | stop / restart the automatic day cycle |
| `Shift`+`1`–`6` | weather |
| `[` `]` | cycle weather | | `[` `]` | cycle weather |
| `N` | new city | | `N` | new seed |
| `F` | fullscreen | | `F` | fullscreen |
| `H` | show the controls | | `H` | show the controls |
On a phone or tablet the left half of the screen walks, the right half looks, and a tap goes The weather presets are `clear, drizzle, rain, downpour, mist, storm` in the city,
fullscreen. Gamepads work too. `blazing, breeze, dust, squall, overcast, thunder` on the frontier, and on the Moon exactly one,
`vacuum`, with every parameter at zero — which is not a placeholder but the honest answer, and it
is what makes the whole weather machinery collapse to nothing there without a single special case. They moved onto `Shift` when
the worlds took the digit row: which world you are standing in is the larger fact, and it is the
one a viewer told "press 1 or 2" reaches for.
The URL carries the seed — `#seed=42` — so a city you liked is a link you can send. On a phone or tablet the left half of the screen walks, the right half looks, and a tap goes
fullscreen. There is no world gesture: every gesture on a touchscreen is already spoken for by
those two halves, and a hidden two-finger something that rebuilds the world is a trap rather than
a control — so on a phone the second world is reached by its URL, `#west/42`.
Gamepads work too, and a pad is the one input device other than a keyboard that can reach the
second world: **Y** (triangle) cycles it.
The URL carries the world and the seed — `#42` for a city, `#west/42` or `#moon/42` for the same
seed elsewhere — so a place you liked is a link you can send. The bare `#seed=42` form still works,
and so do the words people actually type: `#western/42`, `#lunar/42`, `#apollo/42`.
![A downpour, ember quarter](docs/downpour.png) ![A downpour, ember quarter](docs/downpour.png)
@ -72,11 +211,29 @@ The URL carries the seed — `#seed=42` — so a city you liked is a link you ca
Nothing in this flashes above 3 Hz. That is a hard rule and it is verified rather than asserted: Nothing in this flashes above 3 Hz. That is a hard rule and it is verified rather than asserted:
`tools/flicker-rate.cjs` walks every element that modulates over time, under all six weather `tools/flicker-rate.cjs` walks every element that modulates over time, under all six weather
states, and measures the per-cell luminance step and its rate. `tools/lightning-rate.cjs` does the states, and measures the per-cell luminance step and its rate. `tools/lightning-rate.cjs` does the
same for storm lightning specifically. Both have to pass before anything ships. same for storm lightning specifically. `tools/west-flicker.cjs` does it for every world that is not the
city, with the camera pinned so nothing in the frame can change except time, in every one of that
world's weather states. All three have to pass before anything ships.
A word on how to run it: under two seconds of measured window the 3-20 Hz figure is noise, and the
tool now says so. The same tree measured 10.6% in-band at one second and 2.65% at three; only the
second number means anything, and believing the first cost twenty minutes.
The frontier's gate found two real hazards and both were redesigned rather than tuned down. The
windmill was eight dark spokes chopping a bright sky at 4.7 big steps a second against a limit of
1 — it is now a static rim with one bright vane travelling round it, because no rotation rate low
enough to be safe still reads as a turning wheel. The chimney smoke was five discrete dark puffs
crossing the sunset; it is now a continuous plume, drawn far paler, so the cells it occupies stay
occupied and only the sway moves them. After both, the frontier's own elements step at 1.7 times a
second against the city's own 7.7, and carry 2.6% of full scale in the 3-20 Hz band against the
city's 6.5%. The tumbleweed's roll rate and the cloud bars' drift were sized against the same rule
in advance, with the arithmetic written down next to the constant.
`prefers-reduced-motion` is honoured throughout. With it on, the walk slows, the rain calms, the `prefers-reduced-motion` is honoured throughout. With it on, the walk slows, the rain calms, the
police lightbar holds steady instead of alternating, and the aerial traffic parks — but the city police lightbar holds steady instead of alternating, the aerial traffic parks, the windmill's vane
stays populated. The point is stillness, not deletion. stops and the tumbleweed slows to a third — but both worlds stay populated. The point is stillness,
not deletion. Measured: with the flag on, the frontier's own elements produce **no** step over a
third of full scale anywhere and an empty 3-20 Hz band, in every weather state.
## Running it ## Running it
@ -102,7 +259,9 @@ buildings, all for free and all at character resolution.
Everything after that — rain, people, signage, cars, optics — is an *element*: a small module with Everything after that — rain, people, signage, cars, optics — is an *element*: a small module with
`init`, `update` and `draw`, drawn in layer order onto the same character buffer, depth-tested `init`, `update` and `draw`, drawn in layer order onto the same character buffer, depth-tested
against the world so a walker goes behind a lamp post. There are 42 of them. against the world so a walker goes behind a lamp post. There are 51 of them. Each one belongs to
one world or to both — an element carries `world: 'cyber'` or `world: 'west'` on itself and
`main.js` filters the list on a rebuild, so the city gets 42 and the frontier gets 26.
The last stage is a print. Each of the twelve colours has its own exposure weight, then a gamma The last stage is a print. Each of the twelve colours has its own exposure weight, then a gamma
lift, a knee and a shoulder rolloff, bucketed by distance. It is the difference between a frame lift, a knee and a shoulder rolloff, bucketed by distance. It is the difference between a frame
@ -115,13 +274,14 @@ Everything here runs without a browser, which is how the thing gets verified at
| | | | | |
|---|---| |---|---|
| `tools/headless.cjs` | render any frame of any seed offline, as a text dump | | `tools/headless.cjs` | render any frame of any seed offline, as a text dump — `--west` / `--moon`, `--time=`, `--weather=`, `--yaw=` |
| `tools/topng.py` | turn that dump into a PNG, with the bloom the canvas applies | | `tools/topng.py` | turn that dump into a PNG, with the bloom the canvas applies |
| `tools/metrics.py` | the print census — exposure bands, colour split, what each layer costs | | `tools/metrics.py` | the print census — exposure bands, colour split, what each layer costs |
| `tools/peds.cjs` | the crowd alone, against an empty frame, at a size you can actually see | | `tools/peds.cjs` | the crowd alone, against an empty frame, at a size you can actually see |
| `tools/flicker-rate.cjs` | the photosensitivity gate | | `tools/flicker-rate.cjs` | the photosensitivity gate, for the city's signage |
| `tools/lightning-rate.cjs` | the same, for storms | | `tools/lightning-rate.cjs` | the same, for storms |
| `tools/domshim.cjs` | runs the built page against a fake DOM — boot, resize, input, tab loss | | `tools/west-flicker.cjs` | the same, for every world that is not the city — pinned camera, per cell, against the city as its baseline |
| `tools/domshim.cjs` | runs the built page against a fake DOM — boot, resize, input, worlds, tab loss |
The renderer is deterministic: the same seed and frame give a byte-identical picture in a browser The renderer is deterministic: the same seed and frame give a byte-identical picture in a browser
and in `headless.cjs`, which is what makes any of the above worth running. and in `headless.cjs`, which is what makes any of the above worth running.

View file

@ -21,9 +21,18 @@ const OUT = path.join(ROOT, 'index.html');
* to not exist yet — so it is filtered out rather than assumed. */ * to not exist yet — so it is filtered out rather than assumed. */
const ORDER = [ const ORDER = [
'core.js', 'core.js',
'world.js', // first after core: city.js resolves CC.World inside make(), weather_state
// inside init(), surfaces inside beginFrame — all of them AFTER load, so
// only the registry's existence matters here, not its value
'proj.js', // the shared element camera; every world-space element file holds one
'daylight.js', // before weather_state.js and before the elements: both read the hour
'weather_state.js', // before the elements: they read CC.Weather from init() onwards 'weather_state.js', // before the elements: they read CC.Weather from init() onwards
'city.js', 'city.js',
'surfaces.js', 'surfaces.js',
'@painters', // expands to src/surf_*.js, sorted. Globbed rather than named one by one
// for the same reason @elements is: a painter dropped into src/ and not
// added to this list is silently absent from the bundle, and the symptom
// is not an error — it is a world that renders as the city
'raycast.js', 'raycast.js',
'control.js', // after city.js, whose route it re-anchors to; before main.js, which drives it 'control.js', // after city.js, whose route it re-anchors to; before main.js, which drives it
'compose.js', 'compose.js',
@ -35,6 +44,11 @@ const ORDER = [
function expand(list) { function expand(list) {
const out = []; const out = [];
for (const name of list) { for (const name of list) {
if (name === '@painters') {
for (const pf of fs.readdirSync(SRC).sort())
if (/^surf_.*\.js$/.test(pf)) out.push(path.join(SRC, pf));
continue;
}
if (name === '@elements') { if (name === '@elements') {
const dir = path.join(SRC, 'elements'); const dir = path.join(SRC, 'elements');
if (!fs.existsSync(dir)) continue; if (!fs.existsSync(dir)) continue;
@ -163,7 +177,7 @@ if (/<\/script/i.test(bundle)) throw new Error('build: source contains a closing
/* Every module named its global; if one is missing it was dropped, mis-ordered, or the comment /* 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. */ * 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', for (const need of ['var CC', 'CC.City', 'CC.Surf', 'CC.Cast', 'CC.Canvas', 'CC.Main',
'CC.ELEMENTS.push']) 'CC.World', 'CC.SurfWest', 'CC.Daylight', 'CC.ELEMENTS.push'])
if (!bundle.includes(need)) throw new Error('build: bundle is missing ' + need); 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: /* Compiles the bundle without running it. This is what makes the comment scanner safe to trust:
@ -258,8 +272,78 @@ console.log('index.html ' + bytes + ' bytes (' + (bytes / 1024).toFixed(1) + '
* So the honest budget is: this is a single self-contained file that must stay downloadable in * So the honest budget is: this is a single self-contained file that must stay downloadable in
* one response and readable by a human, and 420 KB raw / ~115 KB gzipped is comfortably inside * one response and readable by a human, and 420 KB raw / ~115 KB gzipped is comfortably inside
* both. What is NOT licensed by this raise is another one. Three raises in a row is not a budget, * both. What is NOT licensed by this raise is another one. Three raises in a row is not a budget,
* it is a formality, and the next pass that lands here should cut before it edits this line. */ * it is a formality, and the next pass that lands here should cut before it edits this line.
if (bytes > 420 * 1024) { *
console.error('build: index.html is over the 420 KB budget'); * ---- AND THE PASS AFTER THAT COULD NOT HOLD IT. 420 KB -> 560 KB. ----
* Third raise, and this note is written before the number is changed rather than after, because
* the paragraph below says the next pass must CUT and that instruction is owed an answer rather
* than an edit.
*
* WHAT LANDED: a third world (Moonwalk — a painter, a district table, a theme block and two
* element files), a day/night cycle across all three (a director, a second EXPOSURE ladder and a
* day branch in both existing texture layers), and the frontier's missing content (desert and
* livestock). The stripped bundle went 416 -> 482 KB before the Moon's elements were in.
*
* WHAT WAS ACTUALLY CUT, and the honest number is smaller than the estimate that justified it. The
* world-space element files each carried their own byte-identical copy of the same projection
* scaffolding — the V basis, view(), project(), emit(), column() and litFace() — because
* west_town.js was written first and every file since was written by copying it. That is real
* duplicated CODE rather than duplicated prose, so the comment stripper does not touch it.
*
* Estimated at 8-11 KB from the comment-stripped source; MEASURED at 7.3 KB gross across the four
* frontier files and 4.6 KB net once src/proj.js's own 2.7 KB is paid for. About one per cent of
* the bundle. The estimate was high because it counted per-file weather and day caches that had to
* stay behind in each file's own view().
*
* The bytes were the cheap reason. The real one is that six copies of a projection which MUST match
* src/raycast.js exactly is six places for it to stop matching, and the way that fails is never a
* crash — it is one file quietly keeping an old term and its objects sinking into the ground while
* nothing reports it. That is now impossible.
*
* AND IT COST SOMETHING TO TAKE, which is worth recording. Three of the four files kept a
* per-frame cache (W_WIND, D_SUN, SUN/LAMP/WARM) that was assigned inside the view() body being
* moved; two of those were missed on the first pass and sat at their declared defaults, so the
* desert and the livestock stopped following the clock while the street behind them still did.
* Caught by byte-comparing three frontier fixtures before and after — which is the only reason it
* was caught at all, and is why that comparison is the standing procedure here. The residual after
* the repair is 49-362 cells of 12000 per fixture, and the cause is an ordering effect the shared
* version genuinely fixes: the old litFace() read a module handle that view() assigned, so on the
* first frame of a replay it returned a neutral 0.5 and the new one returns the real value.
*
* WHAT WAS NOT CUT, and why not: stripping indentation is worth about 25 KB and the decomment note
* above refuses it on the grounds that it turns a viewable page source into a wall, which is still
* true. Deleting content to make a number is what the paragraph below forbids and it is still the
* wrong way round. Splitting the worlds into separate payloads — named below as the escape hatch —
* costs the "one self-contained file" property, which is the whole deliverable, and is not spent
* for a number that is still comfortably inside every constraint the budget was protecting.
*
* SO WHAT DOES 560 KB STILL MEAN? Exactly what 420 meant and 300 meant before it: one HTTP
* response, ~145 KB gzipped, parsing in well under a frame, and a page source a person can open
* and read. Three worlds and a day cycle in 560 KB is still smaller than one photograph.
*
* AND THE NUMBER WAS SET TWICE IN ONE PASS, which is worth admitting rather than tidying away. It
* was first raised to 520 while the tree was incomplete — the Moon's painter was in and its two
* element files were not — and 520 was chosen against a 484 KB measurement that had 55 KB of world
* still to arrive. When it did, the build failed at 523 and the line had to move again. The lesson
* is not about the number: it is that a budget set against a half-finished tree is a guess with a
* decimal point on it, and the right moment to set one is after the last file lands.
*
* THE MOON COST 55 KB stripped — 11.5 for the painter, 43.4 for eleven elements — against the
* frontier's 65. Neither is bloated; a world in this engine is simply about that big.
*
* ---- AND THE PASS BEFORE THIS ONE DID NOT EDIT IT. 420 KB HELD, AT 416.0. ----
* The second world landed — src/world.js, src/surf_west.js and three src/elements/west_*.js, plus
* a second district table and a second weather table inside existing files — and it came to 53 KB
* stripped against 57 KB of headroom. Nothing was cut and nothing needed to be. 24 modules, 416.0
* KB, four under the line.
*
* WHICH MEANS THE NEXT PASS IS THE ONE THAT HAS TO CUT, and it should read the paragraph above as
* addressed to it rather than to this one. Four kilobytes is not headroom; it is one element file.
* There is now an obvious place to find room that did not exist before — the frontier and the city
* do not need to be in the same response, and splitting them is a real answer that costs the
* "one self-contained file" property. Spend that only when it is the last option, and write down
* that you did. */
if (bytes > 560 * 1024) {
console.error('build: index.html is over the 560 KB budget');
process.exit(1); process.exit(1);
} }

BIN
docs/city-noon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 949 KiB

BIN
docs/dust.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 726 KiB

BIN
docs/frontier.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 KiB

BIN
docs/moonwalk.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 747 KiB

5095
index.html

File diff suppressed because it is too large Load diff

View file

@ -9,7 +9,7 @@
: (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null; : (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null;
var hash2, clamp, vnoise, P; // bound on first make(), never at load time var hash2, clamp, vnoise, P; // bound on first make(), never at load time
var STYLE = null, SIGN_G = null; var STYLE = null, SIGN_G = null, STYLE_W = null, SIGN_G_W = null;
/* ---- salt spreading ------------------------------------------------- /* ---- salt spreading -------------------------------------------------
* Every draw below is hash2(coord, coord, S + k) for a small literal k, and hash2 mixes its * Every draw below is hash2(coord, coord, S + k) for a small literal k, and hash2 mixes its
@ -52,11 +52,48 @@
]; ];
var SIGN_CH = ['#', '8', '0', 'X', 'O', '=', 'Z']; var SIGN_CH = ['#', '8', '0', 'X', 'O', '=', 'Z'];
/* ---- the frontier's timber -------------------------------------------------------------------
* Same triple, read the same way by surfaces: [lit opening, dim fill, small-window alt]. What
* changes is that out here the DIM glyph is the wall rather than the mullion — a clapboard front
* is a solid mass of horizontal boards with two or three openings punched in it, so the fill has
* to carry the whole facade and the lit glyph is a rarity. The city's fills are lattices (':',
* '=', '|') because a curtain wall IS a lattice; these are strokes, because a board is a stroke.
*
* '~' and '_' were both tried as the plank fill and both are too thin at 9 px to mass — a wall
* of them prints as scan-lines and the building dissolves. '-' and '=' hold. */
var STYLE_CH_WEST = [
['8', '-', 'o'], // 0 clapboard — horizontal boards, the main-street standard
['0', '|', 'o'], // 1 batten — vertical board-and-batten, barns and warehouses
['O', '=', ':'], // 2 falsefront — planed and painted, the storefronts with money
['#', "'", 'o'], // 3 adobe — rendered mud brick, almost no openings
['X', '.', ':'], // 4 fieldstone — rubble wall, a bank or a jail
['8', '=', 'o'], // 5 log — squared timber, the oldest buildings in town
/* 6 is NOT a building. A `range` lot that drew a butte is marked with this style and nothing
* else — surf_west.js switches to rock on it, and it is carried as a style index rather than
* as a new record field because the style is the one piece of the record raycast.js already
* copies into the scratch it hands the texture layer. One integer, no new plumbing. */
['%', '&', ':'] // 6 rock — sandstone butte, bedded and weathered
];
/* A painted board, not a neon tube: the glyphs that read as LETTERING at two cells tall. 'M',
* 'W' and 'N' are in here because a shop board seen down the street is legible as the SHAPE of
* writing long before it is legible as writing, and those three carry that shape. */
var SIGN_CH_WEST = ['M', 'W', 'N', 'H', 'X', 'A', 'K'];
/* ---- the Moon's two surfaces, and there are only two ------------------------------------------
* A world with no buildings needs no styles: index 7 is regolith and index 8 is rock, and the
* triple is read by surf_moon.js as [sunlit, shadowed, grain]. The indices continue the west
* table's numbering rather than restarting, because city.js's `style` is one integer shared by
* every world and a reader who sees 8 should be able to find it in one table. */
var STYLE_CH_MOON = [
['%', '.', ':'], // 7 regolith — powder, and mostly not painted at all
['8', ':', '%'] // 8 rock — breccia and basalt, blocky and hard-edged
];
// Districts are the colour masses. Weights keep the two pillars dominant and violet rare, // 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). // which is the reference ratio (amber ~26% of lit pixels, azure ~27%, violet a garnish).
var DIST = null; var DIST = null, DIST_CYBER = null, DIST_WEST = null, DIST_MOON = null;
function buildDistricts() { function buildDistricts() {
DIST = [ DIST_CYBER = [
// hMin is the floor of the canyon wall, not the average: with the squared height curve most // 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. // 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 // The lit/weight pairs were tuned against a 1.44 M-cell census until facade-area x litRate
@ -112,27 +149,250 @@
{ name: 'arcade', hue: P.azure, mix: P.amber, mixP: 0.55, accent: P.warm, styles: [1, 3], { name: 'arcade', hue: P.azure, mix: P.amber, mixP: 0.55, accent: P.warm, styles: [1, 3],
hMin: 13, hMax: 27, lit: 0.30, signP: 0.60, landmark: 0.004, w: 0.06 } hMin: 13, hMax: 27, lit: 0.30, signP: 0.60, landmark: 0.004, w: 0.06 }
]; ];
/* ---- the frontier's five and a half ----------------------------------------------------------
* Same job: districts are the colour masses, and they are what stops a town of timber boxes
* printing as one timber box. Read against the city table above, three things are different and
* all three are the setting rather than a taste:
*
* hMin/hMax are 4-11 against the city's 8-56. A frontier main street is TWO STOREYS, and the
* whole reason to build this world is what that does to the frame — the city gives you a slot
* of sky between rooflines, this gives you a horizon, and the horizon is the picture. It is
* also why `landmark` is so much likelier here (a steeple or a water tank at 14-24 m is the
* only vertical for a mile) and why the landmark heights below are a fifth of the city's.
*
* lit is a THIRD of the city's, because there is no grid out here. A window is lit when
* somebody is in the room with a lamp, so the litRate numbers are what a kerosene town can
* actually afford, and the mass of every facade is unlit board carried by the dim glyph.
*
* `range` is the district that is mostly NOT a district: 62% of its lots are empty ground and
* one in fourteen is a butte instead of a building. It is 26% of the ground by weight, which
* is what opens the town out into country every few blocks instead of tiling frontage to the
* horizon. Its `hue` still matters — a butte is lit by the same low sun as everything else.
*/
DIST_WEST = [
{ name: 'main', hue: P.warm, mix: P.amber, mixP: 0.72, accent: P.amber, styles: [0, 2, 0, 2],
hMin: 6.2, hMax: 10, lit: 0.20, signP: 0.66, landmark: 0.022, w: 0.21,
vacant: 0.07, butte: 0 },
{ name: 'dust', hue: P.slate, mix: P.white, mixP: 0.74, accent: P.white, styles: [0, 1, 5],
hMin: 5.0, hMax: 8.5, lit: 0.11, signP: 0.18, landmark: 0.004, w: 0.19,
vacant: 0.20, butte: 0 },
{ name: 'adobe', hue: P.ember, hue2: P.warm, mix: P.warm, mixP: 0.66, accent: P.warm, styles: [3, 3, 4],
hMin: 4.4, hMax: 7.5, lit: 0.13, signP: 0.12, landmark: 0.010, w: 0.14,
vacant: 0.16, butte: 0 },
{ name: 'ranch', hue: P.ember, mix: P.slate, mixP: 0.58, accent: P.red, styles: [1, 1, 5],
hMin: 5.4, hMax: 9.5, lit: 0.09, signP: 0.09, landmark: 0.006, w: 0.13,
vacant: 0.30, butte: 0.004 },
/* The mission quarter: lime-washed plaster and the one place with trees in it. white leads,
* spring is the cottonwood, and it carries the church — landmark 0.05 is by far the highest
* in either world, because a mission IS its bell tower. */
{ name: 'mission', hue: P.white, mix: P.amber, mixP: 0.60, accent: P.spring, styles: [3, 4, 2],
hMin: 5.4, hMax: 9.5, lit: 0.14, signP: 0.07, landmark: 0.050, w: 0.07,
vacant: 0.22, butte: 0 },
{ name: 'range', hue: P.slate, mix: P.ember, mixP: 0.62, accent: P.ember, styles: [4, 1, 4],
hMin: 4.4, hMax: 7.5, lit: 0.06, signP: 0.02, landmark: 0.000, w: 0.26,
vacant: 0.62, butte: 0.072 }
];
/* ---- MOONWALK: districts as TERRAIN TYPES rather than colour masses ---------------------
* Every field means what it means everywhere else; what changes is that the thing being
* described is ground rather than architecture. `lit: 0` and `signP: 0` on every row are
* doing real work: signP 0 leaves rec.sign null, so raycast.js's signPixel is never entered
* and the entire signage path — the brightest thing the caster can draw — is switched off by
* DATA, with no code change and no way for a neon blade sign to appear on a crater rim.
*
* `hue` is white or slate and never anything warm, and that is the lighting doctrine in the
* table: there is no atmosphere to redden anything, and core.js prints slate at a ceiling of
* 114 — under the muddy band's own ceiling — so slate can never be the LIT face of anything.
* It is the shadow swatch here and nothing else. */
DIST_MOON = [
/* The floor of a mare, and the district that IS the plain: 94% of its lots are open ground,
* which is why it is the heaviest row in the table. */
{ name: 'mare', hue: P.slate, mix: P.white, mixP: 0.70, accent: P.white, styles: [7],
hMin: 0.5, hMax: 1.8, lit: 0, signP: 0, landmark: 0.000, w: 0.30,
vacant: 0.94, boulder: 0.10, crater: 0.06 },
/* Ejecta — the blanket thrown out of a crater, and the one place the ground has real relief
* in it. Its lots are rock piles a metre to five metres high. */
{ name: 'ejecta', hue: P.white, mix: P.slate, mixP: 0.62, accent: P.pure, styles: [7, 8],
hMin: 1.2, hMax: 5.0, lit: 0, signP: 0, landmark: 0.000, w: 0.20,
vacant: 0.70, boulder: 0.55, crater: 0.10 },
/* Rim. The crater branch in computeCell fires here: a raised ring round a flat walkable
* floor, and the only district in any world that draws a SHAPE rather than a height. */
{ name: 'rim', hue: P.white, mix: P.slate, mixP: 0.66, accent: P.pure, styles: [8],
hMin: 2.0, hMax: 7.0, lit: 0, signP: 0, landmark: 0.004, w: 0.16,
vacant: 0.52, boulder: 0.18, crater: 0.46 },
/* Highland — older, rougher, higher, and the only district that draws a massif. That is
* what puts something on the horizon which is terrain rather than backdrop. */
{ name: 'highland', hue: P.white, mix: P.slate, mixP: 0.74, accent: P.pure, styles: [8, 7],
hMin: 3.5, hMax: 15.0, lit: 0, signP: 0, landmark: 0.030, w: 0.14,
vacant: 0.58, boulder: 0.24, crater: 0.08 },
/* The landing site: flat, scoured, and the district the hardware elements probe for. Its
* ground is 96% empty because the descent engine cleared it. */
{ name: 'site', hue: P.slate, mix: P.white, mixP: 0.60, accent: P.amber, styles: [7],
hMin: 0.3, hMax: 1.2, lit: 0, signP: 0, landmark: 0.000, w: 0.08,
vacant: 0.96, boulder: 0.04, crater: 0.02, hardware: 1 },
/* Regolith plain — the transitional ground, and deliberately the dullest row in the table.
* It exists so that two interesting districts are rarely adjacent. */
{ name: 'plain', hue: P.slate, mix: P.white, mixP: 0.80, accent: P.white, styles: [7],
hMin: 0.4, hMax: 1.4, lit: 0, signP: 0, landmark: 0.000, w: 0.12,
vacant: 0.92, boulder: 0.14, crater: 0.04 }
];
norm(DIST_CYBER); norm(DIST_WEST); norm(DIST_MOON);
/* Hung on the themes, so make() reads TH.dist and nothing selects a table by comparing a
* string. The three-line `west ? A : B` chain this replaced is the exact shape that made a
* third world silently inherit the city's districts. */
TH_CYBER.dist = DIST_CYBER; TH_WEST.dist = DIST_WEST; TH_MOON.dist = DIST_MOON;
DIST = DIST_CYBER;
}
function norm(T) {
var acc = 0; var acc = 0;
for (var i = 0; i < DIST.length; i++) { acc += DIST[i].w; DIST[i].acc = acc; } for (var i = 0; i < T.length; i++) { acc += T[i].w; T[i].acc = acc; }
DIST.total = acc; T.total = acc;
}
/* ---- what a world changes about the ground plan ----------------------------------------------
* Only the numbers that ARE the setting, and each one is here because leaving it at the city's
* value produced something that read wrong rather than because a table wanted filling.
*
* AVE/CROSS block pitch. The frontier's is 70% longer in both axes: a town is a handful of
* buildings on a long road, and at the city's 30 m pitch you get a crossroads
* every ten seconds of walking, which reads as a city with short buildings.
* half street half-width, and this is the single biggest change in the file. A city
* street is a canyon 7-13 m across; a frontier main street is 17-21 m of dirt,
* wide enough to turn a wagon team in, and that width is most of what makes the
* frame read as open country rather than as a demolished city.
* lot* footprints. Smaller and shallower — a shopfront is 5-9 m of frontage.
* alley/plaza the city's block-breakers. Alleys stay (a gap between two buildings is a
* frontier staple); plazas become the corral/square and get bigger and commoner.
* setback INVERTED, and see computeCell: the city drops a lot's outer ring to a podium,
* the frontier raises the outer ring into a false front and drops the interior.
* butte* the height band a `range` lot's rock rises to, when it draws one.
*/
var TH_CYBER = {
id: 'cyber', AVE: 30, CROSS: 26,
aveJit: 15, aveOff: -7, crossJit: 13, crossOff: -6,
aveWide: 6, aveMid: 4, aveNarrow: 3, aveMidP: 0.35, aveEvery: 4,
crossWide: 3, crossMid: 2, crossNarrow: 1, crossMidP: 0.28, crossEvery: 5,
lotW: 6, lotWVar: 7, lotD: 6, lotDVar: 8,
alleyMin: 10, alleyP: 0.45, alleyDeepMin: 11, alleyDeepP: 0.35,
plazaP: 0.13, plazaBigP: 0.26, plazaR: 5, plazaRVar: 7,
vacant: 0.06, setbackP: 0.42, podMin: 7, podVar: 10, falseFront: 0,
lmMin: 58, lmVar: 46, crownTall: 55, DG: 26, sky: 0,
styleCh: STYLE_CH, signCh: SIGN_CH, styleBase: 0,
setbackMode: 'podium', signShape: 'blade', signPalette: 'neon'
};
var TH_WEST = {
id: 'west', AVE: 52, CROSS: 44,
aveJit: 19, aveOff: -9, crossJit: 15, crossOff: -7,
aveWide: 9, aveMid: 7, aveNarrow: 6, aveMidP: 0.42, aveEvery: 3,
crossWide: 6, crossMid: 4, crossNarrow: 3, crossMidP: 0.34, crossEvery: 4,
lotW: 5, lotWVar: 5, lotD: 6, lotDVar: 6,
alleyMin: 9, alleyP: 0.52, alleyDeepMin: 10, alleyDeepP: 0.40,
plazaP: 0.20, plazaBigP: 0.34, plazaR: 6, plazaRVar: 9,
vacant: 0.14, setbackP: 0.68, podMin: 0, podVar: 0, falseFront: 1,
lmMin: 14, lmVar: 10, crownTall: 13, DG: 34, sky: 1,
butteMin: 9, butteVar: 23, rockStyle: 6,
styleCh: STYLE_CH_WEST, signCh: SIGN_CH_WEST, styleBase: 0,
setbackMode: 'falsefront', signShape: 'board', signPalette: 'painted'
};
/* ---- MOONWALK ---------------------------------------------------------------------------
* The lattice is kept and made INVISIBLE, which is the only way an engine whose route walker
* follows street centrelines can render an open plain. Three moves at once: the pitch roughly
* doubles against the frontier, the corridors roughly double again, and the blocks go almost
* entirely vacant. What is left is a plain with faint 25-40 m seams through it that nothing
* marks — and a walk that still has somewhere to walk, because a corridor is still a corridor
* even when there is nothing built along it.
*
* AVE 96 / CROSS 84 — at SPEED 1.6 that is a crossing every 52-60 s against the frontier's
* 30. A crossroads you meet twice a minute reads as a grid; one you meet once a minute
* reads as a coincidence.
* aveJit 38 / aveOff -18 — the jitter has to stay bounded well under AVE/2 or colX's block
* arithmetic breaks; 20 against 48 is safe, and it is large enough that no two consecutive
* corridors are the same distance apart, which is what kills the ruled-grid read.
* setbackP 0 — the setback/false-front branch is a BUILDING idea. A rock has no podium and no
* capping board, so the branch is skipped outright rather than asked to pick a half.
* lmMin/lmVar 26-60 m — a "landmark" here is a massif. raycast.js's HMAX is 108 and must never
* under-estimate the tallest thing emitted; 60 is comfortably under, so HMAX is untouched.
* startT 0.10 — see chooseStart. The city's threshold asks for a wall at 57 degrees on both
* sides, which nothing on the Moon clears, so every seed would scan all 64 candidates and
* then fall back to the argmax anyway.
*/
var TH_MOON = {
id: 'moon', AVE: 96, CROSS: 84,
aveJit: 38, aveOff: -18, crossJit: 34, crossOff: -16,
aveWide: 20, aveMid: 15, aveNarrow: 11, aveMidP: 0.55, aveEvery: 2,
crossWide: 17, crossMid: 13, crossNarrow: 10, crossMidP: 0.50, crossEvery: 2,
lotW: 7, lotWVar: 9, lotD: 7, lotDVar: 9,
alleyMin: 12, alleyP: 0.70, alleyDeepMin: 12, alleyDeepP: 0.70,
plazaP: 0.55, plazaBigP: 0.70, plazaR: 14, plazaRVar: 16,
vacant: 0.62, setbackP: 0.00, podMin: 0, podVar: 0, falseFront: 0,
lmMin: 26, lmVar: 34, crownTall: 999, DG: 58, sky: 1,
rimMin: 1.4, rimVar: 4.2, startT: 0.10,
styleCh: STYLE_CH_MOON, signCh: SIGN_CH_WEST, styleBase: 7,
setbackMode: 'none', signShape: 'none', signPalette: 'none'
};
/* ---- the theme registry ---------------------------------------------------------------------
* A MAP, not a ternary. The line this replaced was `id === 'west' ? TH_WEST : TH_CYBER`, and its
* failure mode with a third world was not an error: an unknown id fell through to the city and
* built a cyberpunk heightmap under somebody else's name. A missing key still falls back — a
* world with no theme has to build SOMETHING — but adding a world is now one row. */
var THEMES = { cyber: TH_CYBER, west: TH_WEST, moon: TH_MOON };
function themeOf(id) { return THEMES[id] || TH_CYBER; }
function worldId() {
return (C && C.World && C.World.id) ? C.World.id : 'cyber';
} }
function bind() { function bind() {
if (!C) C = (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null; if (!C) C = (typeof globalThis !== 'undefined' && globalThis.CC) ? globalThis.CC : null;
if (!C) throw new Error('CC.City needs core.js loaded first'); if (!C) throw new Error('CC.City needs core.js loaded first');
hash2 = C.hash2; clamp = C.clamp; vnoise = C.vnoise; P = C.P; hash2 = C.hash2; clamp = C.clamp; vnoise = C.vnoise; P = C.P;
STYLE = []; /* One pass over the registry rather than four named slots. `styleBase` is the index the
for (var i = 0; i < STYLE_CH.length; i++) * theme's first style row occupies in the world-wide numbering, so a record's `style` stays a
STYLE.push([C.g(STYLE_CH[i][0]), C.g(STYLE_CH[i][1]), C.g(STYLE_CH[i][2])]); * single integer that means the same thing wherever it is read. */
SIGN_G = []; for (var k in THEMES) {
for (var j = 0; j < SIGN_CH.length; j++) SIGN_G.push(C.g(SIGN_CH[j])); var T = THEMES[k];
T.styles = glyphTable(T.styleCh);
T.signs = signTable(T.signCh);
}
STYLE = THEMES.cyber.styles; STYLE_W = THEMES.west.styles;
SIGN_G = THEMES.cyber.signs; SIGN_G_W = THEMES.west.signs;
buildDistricts(); buildDistricts();
} }
function glyphTable(src) {
var out = [];
for (var i = 0; i < src.length; i++)
out.push([C.g(src[i][0]), C.g(src[i][1]), C.g(src[i][2])]);
return out;
}
function signTable(src) {
var out = [];
for (var j = 0; j < src.length; j++) out.push(C.g(src[j]));
return out;
}
function make(seed) { function make(seed) {
if (!STYLE) bind(); if (!STYLE) bind();
var S = seed | 0; var S = seed | 0;
/* THE WORLD IS RESOLVED ONCE, HERE, and then shadowed into locals for the whole of make().
* Every function below closes over these names, so a city built as the frontier stays the
* frontier no matter what the viewer presses afterwards — main.js rebuilds on a world change
* rather than mutating a live map, and this is what makes that safe. It is also why nothing
* downstream ever reads CC.World to decide geometry: the map already decided. */
/* THE BOOLEAN IS GONE. This used to read `west = TH.falseFront === 1`, and the whole of the
* per-world behaviour of make() hung off it — the district table, the glyph tables, the sign
* palette and the sign geometry — inferred from an unrelated geometry field. Every `if (west)`
* below really meant "if not the city", so a third world would have inherited the city's
* districts, its glyphs, its violet-bearing sign palette and its blade signs, silently. Each
* of those is now a field the theme states about itself. */
var TH = themeOf(worldId());
var AVE = TH.AVE, CROSS = TH.CROSS;
var DIST = TH.dist;
var STY = TH.styles;
var SIGNS = TH.signs;
/* ---- street lattice ------------------------------------------------ /* ---- street lattice ------------------------------------------------
Avenues run along +z, cross streets along +x. Position jitter is a function of the 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 street's index alone, so a street stays perfectly straight while spacing stays irregular
@ -140,10 +400,16 @@
// Half-widths, in metres. These set how much of the frame the walls can eat: at 9 m the near // 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 // 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. // 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 ax(k) { return k * AVE + ((hash(k, 0, S + 101) * TH.aveJit) | 0) + TH.aveOff; }
function aw(k) { return (k % 4 === 0) ? 6 : (hash(k, 0, S + 102) < 0.35 ? 4 : 3); } function aw(k) {
function cz(m) { return m * CROSS + ((hash(0, m, S + 201) * 13) | 0) - 6; } return (k % TH.aveEvery === 0) ? TH.aveWide
function cw(m) { return (m % 5 === 0) ? 3 : (hash(0, m, S + 202) < 0.28 ? 2 : 1); } : (hash(k, 0, S + 102) < TH.aveMidP ? TH.aveMid : TH.aveNarrow);
}
function cz(m) { return m * CROSS + ((hash(0, m, S + 201) * TH.crossJit) | 0) + TH.crossOff; }
function cw(m) {
return (m % TH.crossEvery === 0) ? TH.crossWide
: (hash(0, m, S + 202) < TH.crossMidP ? TH.crossMid : TH.crossNarrow);
}
// Scratch records: computeCell is only ever called from buildChunk, never re-entrantly. // 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 SX = { street: 0, k: 0, b: 0, x0: 0, x1: 0 };
@ -175,7 +441,7 @@
A plain modulo grid would tile the city into visible squares; nearest-site over a jittered 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 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. */ study landed on. Neighbouring cells that draw the same type simply merge into a bigger mass. */
var DG = 26; var DG = TH.DG;
function districtType(p, q) { function districtType(p, q) {
var r = hash(p, q, S + 7) * DIST.total, i; 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; for (i = 0; i < DIST.length - 1; i++) if (r < DIST[i].acc) return i;
@ -209,12 +475,12 @@
var t, wid, pos; var t, wid, pos;
// Alleys split the block wall so the canyon breaks and you glimpse depth down a slot. // 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) { if (bw >= TH.alleyMin && hash(bK, bM, S + 301) < TH.alleyP) {
wid = hash(bK, bM, S + 302) < 0.25 ? 2 : 1; wid = hash(bK, bM, S + 302) < 0.25 ? 2 : 1;
pos = x0 + 3 + ((hash(bK, bM, S + 303) * (bw - 6 - wid)) | 0); 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 (gx >= pos && gx < pos + wid) { cH = 0; cD = districtAt(gx, gz); return; }
} }
if (bd >= 11 && hash(bK, bM, S + 304) < 0.35) { if (bd >= TH.alleyDeepMin && hash(bK, bM, S + 304) < TH.alleyDeepP) {
wid = hash(bK, bM, S + 305) < 0.25 ? 2 : 1; wid = hash(bK, bM, S + 305) < 0.25 ? 2 : 1;
pos = z0 + 3 + ((hash(bK, bM, S + 306) * (bd - 6 - wid)) | 0); 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; } if (gz >= pos && gz < pos + wid) { cH = 0; cD = districtAt(gx, gz); return; }
@ -224,8 +490,8 @@
// twice as likely on a boulevard because that is where the camera spends most of its walk. // twice as likely on a boulevard because that is where the camera spends most of its walk.
var kk, mm, r, dxp, dzp; var kk, mm, r, dxp, dzp;
for (kk = bK; kk <= bK + 1; kk++) for (mm = bM; mm <= bM + 1; mm++) { 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)) { if (hash(kk, mm, S + 401) < (kk % 4 === 0 ? TH.plazaBigP : TH.plazaP)) {
r = 5 + ((hash(kk, mm, S + 402) * 7) | 0); r = TH.plazaR + ((hash(kk, mm, S + 402) * TH.plazaRVar) | 0);
dxp = gx - ax(kk); if (dxp < 0) dxp = -dxp; dxp = gx - ax(kk); if (dxp < 0) dxp = -dxp;
dzp = gz - cz(mm); if (dzp < 0) dzp = -dzp; 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; } if (dxp < r && dzp < r && dxp + dzp < r * 1.4) { cH = 0; cD = districtAt(gx, gz); return; }
@ -235,8 +501,8 @@
// Lots: a whole footprint shares one height and one look, so buildings read as slabs. // 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 // 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. // references are all wide masses.
var lw = 6 + ((hash(bK, bM, S + 307) * 7) | 0); var lw = TH.lotW + ((hash(bK, bM, S + 307) * TH.lotWVar) | 0);
var ld = 6 + ((hash(bK, bM, S + 308) * 8) | 0); var ld = TH.lotD + ((hash(bK, bM, S + 308) * TH.lotDVar) | 0);
var lx = x0 + (((gx - x0) / lw) | 0) * lw; var lx = x0 + (((gx - x0) / lw) | 0) * lw;
var lz = z0 + (((gz - z0) / ld) | 0) * ld; var lz = z0 + (((gz - z0) / ld) | 0) * ld;
@ -247,18 +513,62 @@
var D = DIST[did]; var D = DIST[did];
var h; var h;
if (hash(lx, lz, S + 504) < 0.06) { /* Vacancy is the district's own now rather than one number for the whole map, because on the
h = 0; // vacant lot / interior courtyard * frontier it is not an exception — `range` is 62% empty ground and that emptiness is the
* entire reason the world has a horizon in it. The city's six districts all carry 0.06,
* which is exactly the literal that used to be here. */
var vac = D.vacant !== undefined ? D.vacant : TH.vacant;
if (hash(lx, lz, S + 504) < vac) {
h = 0; // vacant lot / interior courtyard / open range
} else if (D.butte && TH.butteMin !== undefined && hash(lx, lz, S + 507) < D.butte) {
/* A BUTTE, and the only piece of geology in either world. It takes the whole lot at one
* height with no setback and no record fields that mean anything to a facade — surf_west
* reads `h` against the district and paints rock rather than boards. Flat-topped on
* purpose: the silhouette is what does the work at 90 m, and a rounded top reads as a
* spoil heap. */
h = TH.butteMin + hash(lx, lz, S + 508) * TH.butteVar;
} else if (D.crater && TH.rimMin !== undefined && hash(lx, lz, S + 509) < D.crater) {
/* A CRATER RIM, and the only place in any world where a lot's height is a function of
* position INSIDE the lot. Everything else in this file gives a lot one height, because a
* building is a slab; a crater is a SHAPE, and it has to be, because the thing that reads
* at character resolution is the RING — a flat floor with a raised lip round it, seen
* edge-on from a metre seven off the ground.
*
* The floor is height 0, which is deliberate twice over: it is walkable, so the route can
* cross a crater instead of being fenced out of one, and it costs the ray marcher nothing
* until the ray actually reaches the rim.
*
* A sine profile rather than a step, for the same reason the frontier's rock strata are
* not ruled lines: a step reads as masonry. */
var ccx = lx + lw * 0.5, ccz = lz + ld * 0.5;
var crr = (lw < ld ? lw : ld) * 0.5;
var cdx = gx + 0.5 - ccx, cdz = gz + 0.5 - ccz;
var cq = Math.sqrt(cdx * cdx + cdz * cdz) / crr; // 0 at the centre, 1 at the rim
if (cq > 1 || cq < 0.68) h = 0;
else h = (TH.rimMin + hash(lx, lz, S + 510) * TH.rimVar) *
Math.sin(((cq - 0.68) / 0.32) * Math.PI);
} else { } else {
t = hash(lx, lz, S + 501); t = hash(lx, lz, S + 501);
h = D.hMin + t * t * (D.hMax - D.hMin); // squared: most blocks modest, a few tall 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; if (hash(lx, lz, S + 502) < D.landmark) h = TH.lmMin + hash(lx, lz, S + 503) * TH.lmVar;
// Setback: the lot's outer ring drops to a podium, which is what gives the rooftop if (lw >= 4 && ld >= 4 && hash(lx, lz, S + 505) < TH.setbackP) {
// 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; var ix = gx - lx, iz = gz - lz;
if (ix === 0 || iz === 0 || ix === lw - 1 || iz === ld - 1) { var edge = (ix === 0 || iz === 0 || ix === lw - 1 || iz === ld - 1);
var pod = 7 + hash(lx, lz, S + 506) * 10; if (TH.setbackMode === 'falsefront') {
/* THE FALSE FRONT, and it is the city's setback turned inside out. A frontier
* storefront is a shed with a flat board wall carried a metre and a half above its own
* roofline so the building looks bigger from the street than it is — the defining
* silhouette of the whole setting, and it is one comparison away from the podium rule
* the city already had. The OUTER ring keeps the lot's height and the interior drops,
* so every roofline in town steps DOWN away from the street instead of up. */
if (!edge) {
var drop = 1.1 + hash(lx, lz, S + 506) * 1.7;
h -= drop; if (h < 2.4) h = 2.4;
}
} else if (TH.setbackMode === 'podium' && edge) {
// 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.
var pod = TH.podMin + hash(lx, lz, S + 506) * TH.podVar;
if (pod < h) h = pod; if (pod < h) h = pod;
} }
} }
@ -269,6 +579,20 @@
/* ---- per-cell record ------------------------------------------------ */ /* ---- per-cell record ------------------------------------------------ */
function signHue(lx, lz, D) { function signHue(lx, lz, D) {
var r = hash(lx, lz, S + 701); var r = hash(lx, lz, S + 701);
/* NO AZURE AND NO VIOLET OUT HERE, and that is the whole discipline of the frontier palette
* in one function. Both of those swatches read as EMITTED light — they are the screen and
* the tube, and the city earns them because it is lit by screens and tubes. A painted board
* is lit by the sun or by a lamp behind it, so the frontier's signs live in the warm half of
* the palette and the only cool thing in the frame is shadow. Put one azure sign on a
* timber front and the whole world stops being a place and starts being a filter. */
if (TH.signPalette === 'none') return P.white; // no signs are rolled at all; see DIST_MOON
if (TH.signPalette === 'painted') {
if (r < 0.30) return P.warm;
if (r < 0.58) return P.amber;
if (r < 0.76) return P.white;
if (r < 0.90) return P.ember;
return P.red;
}
// Signage obeys the same two-pillar discipline as everything else; violet stays a garnish, // 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. // 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 (D.accent === P.violet) return r < 0.42 ? P.violet : (r < 0.74 ? P.azure : P.amber);
@ -282,35 +606,77 @@
function makeRec(gx, gz, h, did, lx, lz) { function makeRec(gx, gz, h, did, lx, lz) {
var D = DIST[did]; var D = DIST[did];
var style = D.styles[(hash(lx, lz, S + 601) * D.styles.length) | 0]; var rock = !!(D.butte && TH.rockStyle !== undefined && hash(lx, lz, S + 507) < D.butte);
var g = STYLE[style]; var style = rock ? TH.rockStyle : D.styles[(hash(lx, lz, S + 601) * D.styles.length) | 0];
var lit = clamp(D.lit * (0.5 + hash(lx, lz, S + 602) * 1.3), 0.02, 0.5); /* THE STYLE INDEX IS WORLD-WIDE AND THE GLYPH TABLE IS PER-THEME, which is why this
* subtraction exists. `style` travels on the record and out to the painters, and a reader who
* sees 8 should be able to find row 8 in one table rather than having to know which world's
* table it belongs to — the frontier's rock is 6, the Moon's regolith is 7 and its rock is 8,
* and none of those numbers repeats. The theme's own glyph table is short and starts at
* `styleBase`, so the lookup takes the offset off again. Without it the Moon indexed row 7 of
* a two-row table and every cell record came back with an undefined glyph. */
var g = STY[style - (TH.styleBase | 0)] || STY[0];
var lit = rock ? 0 : clamp(D.lit * (0.5 + hash(lx, lz, S + 602) * 1.3), 0.02, 0.5);
var sign = null; var sign = null;
if (hash(lx, lz, S + 603) < D.signP) { if (!rock && D.signP > 0 && TH.signShape !== 'none' && hash(lx, lz, S + 603) < D.signP) {
var vert = hash(lx, lz, S + 604) < 0.45 && h > 16; if (TH.signShape === 'board') {
var sh = vert ? 5 + hash(lx, lz, S + 605) * 7 : 2 + hash(lx, lz, S + 606) * 2.5; /* A PAINTED BOARD, not a blade sign, and the two differ in every dimension. The city's
var room = h - sh - 4; if (room < 1) room = 1; * sign is TALL and NARROW and hung out over the street so it is legible down the canyon;
sign = { * a frontier sign is WIDE and SHORT and nailed flat across the false front, because the
y: 3 + hash(lx, lz, S + 607) * room, // metres up the facade to the sign's foot * front is a flat board wall that exists to be written on and there is no canyon to be
h: sh, * legible down. The one vertical form out here is the hanging shingle over a doorway,
w: vert ? 1 : 2 + ((hash(lx, lz, S + 608) * 3) | 0), * which is small and rare.
hue: signHue(lx, lz, D), *
glyph: SIGN_G[(hash(lx, lz, S + 609) * SIGN_G.length) | 0], * It sits high: `y` is measured up from the false front's foot, so the board lands in the
vertical: vert, * top third of the building where the storey below can still be a lit window. */
seed: hash(lx, lz, S + 610) var vertW = hash(lx, lz, S + 604) < 0.14;
}; /* 1.15-1.95 m tall, and the number is set by signPixel's reveal rather than by what a
* shop board measures. That function keeps a fixed 22 cm dark margin all the way round —
* right for a city blade sign five metres tall — so a 70 cm board, which is what a real
* one is, came out with a 26 cm strip of lit paint down the middle and printed as a
* dashed line. The box is drawn oversize so the LIT part of it is board-sized. */
var shW = vertW ? 1.4 + hash(lx, lz, S + 605) * 1.0 : 1.00 + hash(lx, lz, S + 606) * 0.7;
var roomW = h - shW - 2.6; if (roomW < 0.4) roomW = 0.4;
sign = {
y: vertW ? 2.3 + hash(lx, lz, S + 607) * 0.5 : 2.6 + hash(lx, lz, S + 607) * roomW,
h: shW,
w: vertW ? 0.9 : 2.4 + hash(lx, lz, S + 608) * 2.2,
hue: signHue(lx, lz, D),
glyph: SIGNS[(hash(lx, lz, S + 609) * SIGNS.length) | 0],
vertical: vertW,
board: 1,
seed: hash(lx, lz, S + 610)
};
} else {
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: SIGNS[(hash(lx, lz, S + 609) * SIGNS.length) | 0],
vertical: vert,
seed: hash(lx, lz, S + 610)
};
}
} }
var cr = hash(lx, lz, S + 611); var cr = hash(lx, lz, S + 611);
var tall = h > TH.crownTall;
return { return {
district: D.name, did: did, style: style, district: D.name, did: did, style: style, rock: rock,
hue: hash(lx, lz, S + 615) < D.mixP ? D.hue : D.mix, accent: D.accent, hue: rock ? D.hue : (hash(lx, lz, S + 615) < D.mixP ? D.hue : D.mix), accent: D.accent,
glyph: g[0], dim: g[1], alt: g[2], glyph: g[0], dim: g[1], alt: g[2],
dimLum: 22 + ((hash(lx, lz, S + 612) * 20) | 0), // suggested brightness for the fill glyph dimLum: 22 + ((hash(lx, lz, S + 612) * 20) | 0), // suggested brightness for the fill glyph
litRate: lit, sign: sign, litRate: lit, sign: sign,
h: h, landmark: h > 55, h: h, landmark: tall,
crown: h > 55 ? 3 : (cr < 0.14 ? 1 : (cr < 0.24 ? 2 : 0)), // 0 none 1 mast 2 tank 3 beacon /* 0 none 1 mast 2 tank 3 beacon in the city; 0 none 1 chimney 2 water tank 3 steeple on the
* frontier. Same field, same three shapes at the same three rates — what differs is which
* element reads it (structure.js against west_roof.js), and a rock never wears one. */
crown: rock ? 0 : (tall ? 3 : (cr < 0.14 ? 1 : (cr < 0.24 ? 2 : 0))),
lotX: lx, lotZ: lz, lotX: lx, lotZ: lz,
seed: hash(lx, lz, S + 613), // stable per building — hash this for per-facade variety 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 face: hash(gx, gz, S + 614) // stable per cell — hash this for per-column variety
@ -608,7 +974,13 @@
* opening frame, over the 32-seed sweep at frame 600: 1.00 gives facade min 48.0 with 5 of 32 * 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 * 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. */ * thirty-two is not worth trading a third of the city's boulevards for. */
var START_T = 1.00; /* THEMED, because 1.00 rad asks for a parapet at 57 degrees on BOTH sides within 14 m and
* nothing on the Moon clears that. Left at the city's value, every lunar seed would scan all
* 64 candidates — some 59,000 height() calls and a few hundred chunk builds on page load — and
* then fall back to the argmax anyway, which is exactly the outcome this search exists to
* avoid. The Moon asks for 0.10 rad instead: a 1.4 m boulder at 14 m, or a crater rim at 20,
* which is enough that the opening frame has something in the near field. */
var START_T = TH.startT !== undefined ? TH.startT : 1.00;
var _start = { k: 0, m: 0, back: 18 }; var _start = { k: 0, m: 0, back: 18 };
function chooseStart(o) { function chooseStart(o) {
var N = 8 * 8 * START_BACKS.length, j, k, m, b, sc; var N = 8 * 8 * START_BACKS.length, j, k, m, b, sc;
@ -648,7 +1020,12 @@
isStreet: function (gx, gz) { return height(gx, gz) <= 0; }, isStreet: function (gx, gz) { return height(gx, gz) <= 0; },
// Exposed for surfaces/elements that want to reason about the corridor itself. // Exposed for surfaces/elements that want to reason about the corridor itself.
aveX: ax, aveW: aw, crossZ: cz, crossW: cw, aveX: ax, aveW: aw, crossZ: cz, crossW: cw,
AVE: AVE, CROSS: CROSS, SPEED: SPEED AVE: AVE, CROSS: CROSS, SPEED: SPEED,
/* WHICH WORLD THIS MAP IS, carried on the map rather than read off CC.World. An element that
* asks the registry is asking what the viewer last pressed; an element that asks the city is
* asking what it is actually standing in, and between the keypress and the rebuild those are
* two different answers. */
world: TH.id
}; };
} }

View file

@ -220,6 +220,8 @@
* event; the once-a-second probe underneath it is the fallback for a browser that fires the * 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. */ * event before we attach, or not at all. */
var padSeen = 0, padProbe = 0; var padSeen = 0, padProbe = 0;
/* Edge state for the world button; see pollPad. */
var padWorld = 0;
function pollPad(dt) { function pollPad(dt) {
K.gx = 0; K.gz = 0; K.grun = 0; K.glx = 0; K.gly = 0; K.gx = 0; K.gz = 0; K.grun = 0; K.glx = 0; K.gly = 0;
if (typeof navigator === 'undefined' || !navigator.getGamepads) return; if (typeof navigator === 'undefined' || !navigator.getGamepads) return;
@ -253,6 +255,26 @@
var v = typeof bb === 'number' ? bb : (bb.value !== undefined ? bb.value : (bb.pressed ? 1 : 0)); var v = typeof bb === 'number' ? bb : (bb.value !== undefined ? bb.value : (bb.pressed ? 1 : 0));
if (v > 0.35) K.grun = 1; if (v > 0.35) K.grun = 1;
} }
/* BUTTON 3 CYCLES THE WORLD — Y on an Xbox pad, triangle on a PlayStation one, and the
* standard mapping puts it there on both. It is the only thing on a pad that is not a
* movement, and it is here because a pad is the one input device that CAN reach the second
* world without a keyboard. (A phone cannot, and is not given a gesture for it: every
* gesture on a touchscreen is already spoken for by the screen-split walk and look, and a
* hidden two-finger something that rebuilds the world is a trap rather than a control. The
* URL is the answer there — cybercity.carino.systems/#west/42 — and the README says so.)
*
* EDGE-TRIGGERED, held in `padWorld`. A button read level-triggered at 60 Hz would rebuild
* the world sixty times a second for as long as a thumb rested on it. */
var y = b[3];
var down = y ? (typeof y === 'number' ? y > 0.5 : !!y.pressed) : false;
if (down && !padWorld && CC.World && hooksRef && hooksRef.world) {
/* One cycling rule rather than this open-coded forward-only copy of it, which was
* correct for exactly two worlds and would have needed two presses to come home from
* the third. */
hooksRef.world(CC.World.LIST[(CC.World.index + 1) % CC.World.count].id);
K.act = 1;
}
padWorld = down;
} }
} }
/* Only a deflected stick counts as somebody driving. A pad sitting on a sofa with a sticky /* Only a deflected stick counts as somebody driving. A pad sitting on a sofa with a sticky
@ -458,9 +480,14 @@
* Everything below this line is skipped entirely when there is no window, which is what keeps * Everything below this line is skipped entirely when there is no window, which is what keeps
* the offline reference frame honest. */ * the offline reference frame honest. */
var el = null; var el = null;
/* The hooks main.js hands over, held at module scope because pollPad() needs one of them and
* runs from update() rather than from an event handler. Null until attach(), which is exactly
* the offline case: the harness never attaches, so nothing here can fire in a reference frame. */
var hooksRef = null;
function attach(win, doc, canvas, hooks) { function attach(win, doc, canvas, hooks) {
if (!win || !doc) return; if (!win || !doc) return;
hooksRef = hooks || null;
el = canvas || doc.documentElement; el = canvas || doc.documentElement;
function set(e, down) { function set(e, down) {
@ -501,17 +528,64 @@
case 'KeyP': paused = paused ? 0 : 1; Control.paused = paused; break; case 'KeyP': paused = paused ? 0 : 1; Control.paused = paused; break;
case 'KeyF': if (hooks && hooks.fullscreen) hooks.fullscreen(); break; case 'KeyF': if (hooks && hooks.fullscreen) hooks.fullscreen(); break;
case 'KeyN': if (hooks && hooks.reseed) hooks.reseed(); break; case 'KeyN': if (hooks && hooks.reseed) hooks.reseed(); break;
/* ---- the clock ------------------------------------------------------------------------
* T steps the time of day round its six named stops — night, dawn, morning, noon,
* afternoon, dusk — and Shift+T steps it back. It is a "toggle" in the sense the request
* asked for and rather more: two presses from noon gets you to dusk, four gets you back.
*
* Y stops and restarts the automatic cycle. Neither seizes the camera (hit stays 2):
* changing the hour is not a reason for the walk to stop, which is the same rule the
* weather presets have obeyed since they existed. */
case 'KeyT':
if (CC.Daylight) CC.Daylight.step(hooks && hooks.now ? hooks.now() : 0,
e.shiftKey ? -1 : 1);
break;
case 'KeyY':
if (CC.Daylight) CC.Daylight.freeze(hooks && hooks.now ? hooks.now() : 0);
break;
case 'BracketLeft': if (CC.Weather) CC.Weather.cycle(hooks && hooks.now ? hooks.now() : 0, -1); 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; case 'BracketRight': if (CC.Weather) CC.Weather.cycle(hooks && hooks.now ? hooks.now() : 0, 1); break;
default: hit = 0; default: hit = 0;
} }
if (!hit && /^Digit[1-6]$/.test(c) && CC.Weather) { /* THE DIGITS ARE THE WORLDS NOW, and the weather has moved onto the same digits held with
CC.Weather.set(parseInt(c.slice(5), 10) - 1, hooks && hooks.now ? hooks.now() : 0); * Shift. That is a demotion of the weather keys and it is the right way round: which world
hit = 2; * you are standing in is the larger fact — it rebuilds the map, the sky and half the
} * element list — and it is the one a viewer who has just been told "press 1 or 2" will
if (!hit && h && h.length === 1 && h >= '1' && h <= '6' && CC.Weather) { * reach for. The weather keeps [ and ], which is the control that was already there and
CC.Weather.set(h.charCodeAt(0) - 49, hooks && hooks.now ? hooks.now() : 0); * the one that survives on a keyboard with no digit row worth speaking of.
hit = 2; *
* Shift is also the RUN key, so shift-2 walks faster for as long as it is held. That is
* accepted rather than worked around: the alternative was a modifier this file has to
* swallow, and a viewer who runs half a step while changing the weather has lost nothing.
*
* Both spellings, as before: `code` for a physical digit row, `key` for the layouts where
* the top row is not digits at all. With Shift down, `key` is the SHIFTED character ('!'
* for Digit1 on a US layout, '"' on a UK one, and so on), so the key path cannot read the
* digit and only the code path handles the weather — which is why the shifted branch is
* code-only and the unshifted one keeps both. */
var dg = /^Digit[1-9]$/.test(c) ? parseInt(c.slice(5), 10)
: (h && h.length === 1 && h >= '1' && h <= '9' ? h.charCodeAt(0) - 48 : 0);
if (!hit && dg) {
if (e.shiftKey) {
/* Gated on the LIVE preset table rather than on the literal 6, which was correct only
* because both worlds happened to ship exactly six presets. PRESETS is a getter on the
* weather director precisely so it tracks the world. */
if (CC.Weather && /^Digit[1-9]$/.test(c) && dg <= CC.Weather.PRESETS.length) {
CC.Weather.set(dg - 1, hooks && hooks.now ? hooks.now() : 0);
hit = 2;
}
} else if (hooks && hooks.world && CC.World && dg <= CC.World.count) {
/* The rebuild happens inside the hook — main.js owns the city — and it takes long
* enough (a fresh heightmap, 40-odd element inits) that the frame it lands on is a
* cold one. giveBack() is NOT called: a viewer who has taken the controls and then
* asks for the other world wants to be standing in it, not watching the autopilot. */
/* No hint stamp here: the hook rebuilds, the rebuild calls Control.reset(), and
* reset() re-arms the overlay from t=0 — which the new world also restarts. The
* controls therefore reintroduce themselves on arrival, which is what a viewer who
* has just been moved somewhere else actually wants. */
hooks.world(dg);
hit = 2;
}
} }
} }
/* THE RELEASE KEYS MUST NOT RE-ARM THE TAKE-OVER, and for a long time they did: Escape and /* THE RELEASE KEYS MUST NOT RE-ARM THE TAKE-OVER, and for a long time they did: Escape and
@ -680,7 +754,7 @@
K.fwd = K.back = K.left = K.right = K.run = K.crouch = 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.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; K.tx = K.tz = K.trun = 0; K.gx = K.gz = K.grun = 0; K.glx = K.gly = 0;
seedWanted = 0; seedWanted = 0; padWorld = 0;
/* N rebuilds the city and calls through here, and a new city that arrives paused is a viewer /* 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. */ * staring at a still they did not ask for. */
paused = 0; Control.paused = 0; paused = 0; Control.paused = 0;

View file

@ -418,15 +418,122 @@ var CC = (function () {
* given a distance beyond it so that it self-occludes against the world pass. */ * given a distance beyond it so that it self-occludes against the world pass. */
var SKY_D = FOG_END; var SKY_D = FOG_END;
// LUT[(bucket*12 + colour)*256 + lum] -> printed lum. 24 KB, built once, never allocated again. /* ---- THE DAY LADDER ---------------------------------------------------------------------------
var LUT = (function () { * The table above is fitted to a NIGHT frame and says so at length: LIGHT OUTRANKS STRUCTURE, the
var np = PALETTE.length, t = new Uint8Array(DBUCKETS * np * 256); * two pillars own the top of the lit range, white is 0.30 because "white is the thing the light
* lands on" and slate is 0.60 because it is unlit concrete. Every one of those sentences is
* false at noon, and the inversion is total rather than a scale:
*
* THE PILLARS GO OFF. Sodium and screenlight are what a city has INSTEAD of daylight. At noon
* a sodium lamp is a grey tube and a screen is a dark rectangle, so amber
* and azure drop to the bottom of the ladder — azure hardest, from 1.00
* to 0.30, because it is the highest gain in the night table and a lit
* window painted at that gain under a bright sky is the one cell that
* gives away that nothing has really changed.
* STRUCTURE OUTRANKS LIGHT. White is render, board, bone and dust with the sun on it, and slate
* is concrete and shadowed rock; between them they are most of a daylight
* frame's area, so they take the top of the ladder — white 0.30 -> 0.92,
* slate 0.60 -> 0.78.
* SHADOW STOPS BEING A HOLE. At night `shadow` is a swatch the print deletes on purpose. By day
* a shadow is filled by the whole bright sky above it, so it lifts from
* 0.30 to 0.46 — which is what stops a daylight frame reading as a lit
* object cut out of black paper.
* ICE AND PURE ARE THE SKY AND THE SPECULAR. Ice carries a daylight sky, which is the largest
* bright surface in either atmospheric world, so it goes 0.36 -> 0.66.
*
* GAMMA AND KNEE MOVE WITH IT. The night curve exists to lift a frame that is 55% black and crush
* its dither back down; a daylight frame has no dither to crush and no hole to lift, so the day
* values are a much weaker lift (0.33 -> 0.62) and a much smaller crush (0.075 -> 0.030). The
* muddy band that the night targets fight to keep under 30% is where a daylight picture LIVES —
* a lit wall, dust, a blue sky are all mid-tones — so by day the census that matters is the hot
* tail, not the muddy one, and tools/metrics.py's targets describe night and only night. */
var EXPOSURE_DAY = [
/* 0.42 and 0.52, not 0.30 and 0.30, and the correction was forced by a measurement rather than
* by taste. At 0.30 the pillars' PRINTED CEILINGS fall to about 150 and 165 — both under the
* 170 the census counts as a highlight — so from the moment the blend started, no amber or
* azure cell in the frame could be hot however brightly it was written. At the dusk stop the
* city had 3061 pillar cells in the frame, exactly none of them hot, against 1477 of 3403 at
* night, and the max printed value was 165. A dusk with the neon lit and nothing in the frame
* allowed to be bright is not a picture.
*
* The physical reading is also better at these values. A sodium lamp at noon is a grey tube,
* which is what 0.42 says relative to white's 0.92; a large LED sign at noon is perfectly
* visible and merely not dazzling, which is what 0.52 says. The swatch that carries a DAYLIGHT
* sky is ice, not azure, so raising azure here costs the sky nothing. */
0.42, // 0 amber — a sodium lamp in daylight: still there, no longer the brightest thing
0.52, // 1 azure — a big screen in daylight: readable, and not a highlight
0.46, // 2 ember — rust, brick, red rock: a real daylight surface, and it keeps its place
0.70, // 3 spring — foliage, and by day there is enough of it to matter
0.26, // 4 violet — still the rarest thing in the table, and daylight has no use for it
0.92, // 5 white — THE daylight swatch: render, planed board, bone, dust, cloud
0.50, // 6 red — paint and hazard, unchanged in kind
0.78, // 7 slate — concrete and shadowed rock, and the second largest area by day
0.62, // 8 warm — sunlit timber and skin; it stops being "interior spill" at noon
0.66, // 9 ice — the daylight sky, which is the largest bright surface either world has
0.85, // 10 pure — specular, and specular is what a sun makes
0.46 // 11 shadow — filled by the sky rather than empty; see the note above
];
var GAMMA_DAY = 0.62, KNEE_DAY = 0.030;
/* ---- how much of the day table is mixed in ------------------------------------------------------
* Quantised, and that is the whole implementation trick. The LUT is 24 KB of pow() and exp() and
* the file has always said it is "built once at load, never allocated again"; rebuilding it every
* frame would put 24576 transcendental calls on the frame budget. Rebuilding it when a QUANTISED
* mix changes puts them on one frame in every four hundred — the clock runs a 420 s cycle and
* there are 32 steps across it, so the rebuild happens about once every thirteen seconds, costs
* about a millisecond, and lands inside a 16 ms budget with room to spare.
*
* 32 steps and not 8: the mix moves fastest through dawn and dusk, which is exactly where the eye
* is watching the light change, and at 8 steps the ladder visibly clunks between two frames. */
var DAY_STEPS = 32;
var dayMix = 0, daySun = 0, dayStep = -1;
/* ---- THE BLEND IS NOT THE SAME SHAPE FOR EVERY SWATCH -------------------------------------
* Surfaces gain their daylight EARLY and sources lose theirs LATE, and blending both linearly
* against the same number is what made the transitional hours the flattest pictures in the build.
*
* The physics is ordinary: a wall starts being lit by the sky as soon as there is any sky, so
* white and slate should climb from the first light of dawn. A neon sign, a sodium lamp or a lit
* window, on the other hand, is still the brightest thing in the frame right through the golden
* hour and only stops competing once the sun is properly up — anyone who has seen a lit shopfront
* at sunset knows it reads. Under a linear blend the two pillars had already given up half their
* gain at the dusk stop, and the city printed 0.68% of its cells hot there against 8.02% at
* night and 3.20% at noon: the one hour with both neon AND a bright sky in it was the dimmest
* frame of the three.
*
* Squaring the mix for the four SOURCE swatches holds them near their night gains until the mix
* passes about 0.6 and then drops them quickly, which is the shape the eye expects and the shape
* that keeps a lit sign lit through dusk. */
function ladder(c, mix, sunMix) {
/* SOURCES BLEND ON THE SUN, SURFACES ON THE SKY, and they are two different numbers because
* they answer two different questions. "Is this wall lit?" is answered by the sky, which is
* bright through the whole of twilight. "Has this lamp stopped being the brightest thing in
* the frame?" is answered by the SUN, which is down for all of it — and a sodium lamp at dusk
* has emphatically not stopped, which is the entire look of the hour.
*
* Blending both on the sky cost the city its dusk in a way no amount of tuning elsewhere could
* reach: amber's gain had already fallen from 0.50 to 0.41 by the golden hour, which puts its
* printed ceiling UNDER the 170 the census counts as a highlight, so no amber cell in the frame
* could be hot however bright it was written. The measurement said 0.38% of cells hot at dusk
* against 8.02% at night. Squared on top, because even direct sun takes a while to beat a neon
* sign at close range. */
var src = (c === 0 || c === 1 || c === 8 || c === 9); // amber azure warm ice
var m = src ? sunMix * sunMix : mix;
return EXPOSURE[c] + (EXPOSURE_DAY[c] - EXPOSURE[c]) * m;
}
// LUT[(bucket*12 + colour)*256 + lum] -> printed lum. 24 KB, rebuilt only when the day step moves.
var LUT = new Uint8Array(DBUCKETS * PALETTE.length * 256);
function buildLUT(mix, sunMix) {
var np = PALETTE.length, t = LUT;
var GM = GAMMA + (GAMMA_DAY - GAMMA) * mix;
var KN = KNEE + (KNEE_DAY - KNEE) * mix;
for (var b = 0; b < DBUCKETS; b++) { for (var b = 0; b < DBUCKETS; b++) {
// bucket centre as a 0..1 depth fraction; the lift is retired linearly across it // bucket centre as a 0..1 depth fraction; the lift is retired linearly across it
var df = (b + 0.5) / DBUCKETS; var df = (b + 0.5) / DBUCKETS;
var gm = GAMMA + (1 - GAMMA) * df; var gm = GM + (1 - GM) * df;
for (var c = 0; c < np; c++) { for (var c = 0; c < np; c++) {
var gain = EXPOSURE[c]; var gain = ladder(c, mix, sunMix);
for (var l = 0; l < 256; l++) { for (var l = 0; l < 256; l++) {
var x = l * gain / 255; var x = l * gain / 255;
/* A hard clamp here was quietly cancelling the whole point of EXPOSURE: a swatch /* A hard clamp here was quietly cancelling the whole point of EXPOSURE: a swatch
@ -435,15 +542,31 @@ var CC = (function () {
* The shoulder is an exponential rolloff that never reaches 1, so a swatch can be * 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. */ * 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))); if (x > SHOULDER) x = SHOULDER + (1 - SHOULDER) * (1 - Math.exp(-(x - SHOULDER) / (1 - SHOULDER)));
var k = x / KNEE; if (k > 1) k = 1; var k = x / KN; if (k > 1) k = 1;
var y = Math.pow(x, gm) * (k * k * (3 - 2 * k)); var y = Math.pow(x, gm) * (k * k * (3 - 2 * k));
var v = (y * 255 + 0.5) | 0; var v = (y * 255 + 0.5) | 0;
t[(b * np + c) * 256 + l] = v > 255 ? 255 : v; t[(b * np + c) * 256 + l] = v > 255 ? 255 : v;
} }
} }
} }
return t; }
})(); buildLUT(0, 0);
dayStep = 0;
/* Called once per frame from Compose.post, before tone(). `mix` is the day/night blend the
* daylight director publishes; everything else here is the quantiser. */
function setDayMix(mix, sunMix) {
if (!(mix >= 0)) mix = 0; else if (mix > 1) mix = 1;
if (!(sunMix >= 0)) sunMix = 0; else if (sunMix > 1) sunMix = 1;
/* Quantised on the PAIR, packed into one integer, so the table is still rebuilt only when the
* light has actually moved a step rather than once per frame. */
var step = Math.round(mix * DAY_STEPS) * (DAY_STEPS + 1) + Math.round(sunMix * DAY_STEPS);
if (step === dayStep) return;
dayStep = step;
dayMix = Math.round(mix * DAY_STEPS) / DAY_STEPS;
daySun = Math.round(sunMix * DAY_STEPS) / DAY_STEPS;
buildLUT(dayMix, daySun);
}
var DSCALE = DBUCKETS / (FOG_END - FOG_START); var DSCALE = DBUCKETS / (FOG_END - FOG_START);
@ -475,7 +598,29 @@ var CC = (function () {
* CC.Compose.post, which is precisely why the print lives behind that name — the offline * 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. * 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. */ * A later src/compose.js taking this slot over MUST call CC.tone itself. */
var Compose = { post: function (f) { tone(f); } }; /* ---- the per-frame print hook ------------------------------------------------------------------
* main.js and tools/headless.cjs have both always called this as `post(frame, cam, t)` while the
* function took only `f` — the two extra arguments have been arriving and being dropped since the
* day it was written. They are what the daylight cycle needs: the print ladder has to know what
* time it is, and this is the one place in the pipeline that runs once per frame with the whole
* frame in hand and nothing else to do.
*
* The DIRECTION it reads is `sky` rather than `sun`, and the difference matters at both ends of
* the day. `sun` is direct light, which is zero for the whole of twilight — and twilight is not a
* night frame: the sky is still the brightest thing in the world and the print has to be part way
* up the day ladder to render it. `sky` is exactly that quantity.
*
* BOTH are passed, because they answer different questions and ladder() sorts them: a SURFACE
* gains its daylight from the sky and a SOURCE loses its advantage only to the sun. See the note
* on `sky` in daylight.js for why that parameter carries a misleading name on an airless world
* and why it is still the right input here. */
var Compose = {
post: function (f, cam, t) {
var D = CC && CC.Daylight;
setDayMix(D ? D.P.sky : 0, D ? D.P.sun : 0);
tone(f);
}
};
/* HOW WIDE THE PAVEMENT IS, in metres from the building face to the kerb face, and it lives here /* HOW WIDE THE PAVEMENT IS, in metres from the building face to the kerb face, and it lives here
* rather than in raycast.js because three files have to agree on it or the street comes apart: * rather than in raycast.js because three files have to agree on it or the street comes apart:
@ -492,7 +637,8 @@ var CC = (function () {
return { return {
PALETTE: PALETTE, P: P, GLYPHS: GLYPHS, g: g, GI: GI, PAVE: PAVE, PALETTE: PALETTE, P: P, GLYPHS: GLYPHS, g: g, GI: GI, PAVE: PAVE,
tone: tone, Compose: Compose, EXPOSURE: EXPOSURE, tone: tone, Compose: Compose, EXPOSURE: EXPOSURE, EXPOSURE_DAY: EXPOSURE_DAY,
setDayMix: setDayMix, get dayMix() { return dayMix; }, get daySun() { return daySun; },
makeFrame: makeFrame, clearFrame: clearFrame, put: put, poke: poke, makeFrame: makeFrame, clearFrame: clearFrame, put: put, poke: poke,
hash1: hash1, hash2: hash2, mulberry: mulberry, hash1: hash1, hash2: hash2, mulberry: mulberry,
lerp: lerp, clamp: clamp, smooth: smooth, vnoise: vnoise, lerp: lerp, clamp: clamp, smooth: smooth, vnoise: vnoise,

336
src/daylight.js Normal file
View file

@ -0,0 +1,336 @@
/* CyberCity daylight — the one place that decides what time of day it is.
*
* It is weather_state.js's sibling and it is deliberately built to the same pattern, because the
* pattern is the thing that made the weather work: ONE fact, computed once per tick, read by
* everybody. Rain, fog, the wetness of the road and whether a pedestrian has an umbrella were all
* the same fact seen from eight files, and before the director existed each of those files picked
* its own constant and the city ended up with heavy rain falling through a clear starfield. The
* time of day is exactly the same shape of problem, one size larger: the sun's altitude decides
* the sky, which wall is lit, whether a window has a lamp in it, whether there are stars, whether
* the neon reads, how bright the road is and how many people are on it. Left to themselves, nine
* files would disagree about what hour it is.
*
* ---- WHY THIS IS HARD HERE, AND WHAT THE ANSWER IS ---------------------------------------------
* core.js prints through a fixed LUT built at load from the EXPOSURE table, and the whole art
* direction is a frame that is more than half pure black with a thin scatter of very bright glyphs.
* Daylight is the inverse of that picture, and the obvious implementation — rebuild the print curve
* for the day — is not available: the LUT is 24 KB of Uint8Array built once and the curve is what
* every other tuned constant in the project was fitted against.
*
* So DAYLIGHT IS NOT A CHANGE TO THE PRINT. It is a set of directions that surfaces and elements
* multiply into the constants they already have, exactly as they already do with CC.Weather.rel().
* What makes a daylight frame work inside a night-tuned print is not more light everywhere, it is
* a REDISTRIBUTION: the sky becomes the bright mass and the lit windows go out. A city at noon is a
* grey concrete canyon under a bright sky with dark glass in it — which is both what a city at noon
* looks like and a picture this renderer can actually make.
*
* ---- WHAT IT EXPORTS ---------------------------------------------------------------------------
* Every field of P is a DIRECTION, 0..1 unless stated, and none of them is a multiplier for any
* particular element's constants:
*
* phase 0..1 round the clock. 0.00 midnight, 0.25 sunrise, 0.50 noon, 0.75 sunset.
* alt the sun's altitude in RADIANS. Negative at night. Peaks at ALT_MAX, deliberately not
* at the zenith — see ALT_MAX.
* az the sun's azimuth as a world bearing, in the project's convention (yaw 0 faces +z).
* It SWINGS: sunrise in the east, sunset in the west, and the shadow direction turning
* through the day is most of what makes a cycle read as a cycle rather than as a dimmer.
* sun direct sunlight, 0 below the horizon rising to 1 with altitude. The number a surface
* multiplies its lit-side brightness by.
* sky how much light the SKY itself is emitting. Non-zero through twilight, when the sun is
* down and the sky is still the brightest thing in the frame — which is the state the
* frontier was originally built at and the best-looking hour in either world.
*
* THE NAME IS WRONG ON A WORLD WITH NO SKY, and the author of src/surf_moon.js was right
* to raise it. This module reports `sky` = 1.0 at Moonwalk's local noon, on a body that
* has no atmosphere and therefore no sky luminance at all, and core.js's print hook uses
* exactly that number to decide how far up the daylight exposure ladder to blend.
*
* The VALUE is nevertheless right and the output is good, which is why this is a note
* rather than a change. What the print hook actually needs to know is "how much of this
* frame is lit by daylight rather than by lamps", and on an airless world at noon the
* honest answer is "all of it" — the surfaces are in full unfiltered sun. `sky` tracks
* that closely enough on all three worlds to be the right input under the wrong name.
* What it is NOT right for is anything that models the medium: the aerial-perspective
* floor in surfaces.js's refog() read it too, and that one was genuinely wrong, so a
* painter now declares `airless` and refog() skips it.
*
* If a fourth world ever separates the two — a lit surface under a black sky, or a bright
* sky over unlit ground — this parameter has to split into `skyLuminance` and
* `dayBlend`, and the two readers have to be sorted between them. Until then, splitting
* it would mean re-tuning surf_moon.js, which currently compensates for the blend with a
* documented CC.dayMix term and produces the best census in the project.
* warm 1 when the light is low and orange, 0 at noon and 0 in the dead of night. What a
* surface uses to choose between amber and white.
* lamp artificial light: 1 at night, 0 in the day, WITH HYSTERESIS (see below).
* star stars and moon, 0 by day.
* night 1 while the sun is down, as a hard flag for things that simply do not happen by day.
* name 'night' | 'dawn' | 'morning' | 'noon' | 'afternoon' | 'dusk', for the readout.
*
* ---- DETERMINISM -------------------------------------------------------------------------------
* A frame must be a pure function of (seed, t) or tools/headless.cjs stops reproducing the browser,
* which is what makes every offline measurement in this project worth anything. So the phase is
* computed from t and a seeded offset, never accumulated; the two viewer controls are STAMPED
* exactly the way weather_state.js stamps its override — T records an offset, Y records the instant
* the clock stopped — and both are still pure functions of t afterwards. Nothing here integrates.
*/
(function (CC) {
'use strict';
var clamp = CC.clamp, smooth = CC.smooth;
/* ---- the length of a day ----------------------------------------------------------------------
* Seven minutes. The constraint from below is that a viewer who watches for two minutes must see
* the light MOVE; the constraint from above is that this is an ambient piece and the sun crossing
* the sky in ninety seconds is a time-lapse, which is a different thing to look at and a worse
* one. Seven minutes puts about a hundred seconds in each of dawn, day, dusk and night, which is
* the same order as weather_state.js's 78-170 s segments — the two clocks are comparable rather
* than one visibly outrunning the other. */
var PERIOD = 420;
/* ---- how high the sun gets ---------------------------------------------------------------------
* 0.95 rad, i.e. 54 degrees, and NOT the zenith. This is the single most load-bearing constant in
* the file and it is a composition decision rather than an astronomical one.
*
* A sun overhead lights every vertical face equally, and both worlds get their entire sense of
* form from the fact that one side of the street is lit and the other is not — surf_west.js's
* whole lighting model is one dot product, and surfaces.js's facades are read against the sky
* behind them. At the zenith all of that flattens into one tone and the frame reads as a
* technical drawing. At 54 degrees there is always a lit face and a shadowed face, shadows are
* always shorter than the thing casting them at noon and longer than it near the ends of the day,
* and the picture keeps its modelling at every hour. It is also a perfectly ordinary sun altitude
* for most of the inhabited world outside high summer. */
var ALT_MAX = 0.95;
/* How far below the horizon the sun goes. It only has to be far enough that `sun` and `sky` are
* both properly zero in the middle of the night; the depth of the anti-solar point is not a thing
* the frame can see. */
var ALT_MIN = -0.42;
/* The sun's bearing at local noon, and how far either side of it the day swings. The project's
* convention is that yaw 0 faces +z, so this is "south" for a northern-hemisphere sun. SWING is
* 1.35 rad (77 degrees), which puts sunrise at bearing -1.85 and sunset at +0.85 — both of them
* comfortably off the avenue axis, so the low sun is in frame at the ends of the day without
* being straight down the street. */
var AZ_NOON = -0.5, AZ_SWING = 1.35;
var S = 0; // seed
/* The seeded starting hour currently folded into `off`, kept so a rebuild can swap one city's
* base for another's without disturbing the viewer's own offset on top of it. */
var base = 0;
/* The two stamped impurities, and the ONLY ones. `off` is added to t before the phase is taken,
* so T moves the clock without ever making the phase depend on anything but t. `holdAt` is the
* instant Y stopped it: while frozen the phase is evaluated at holdAt instead of at t, which is
* still a pure function — just of a constant. */
var off = 0, holdAt = -1, frozen = 0;
var KEYS = ['alt', 'az', 'sun', 'sky', 'warm', 'lamp', 'star', 'night'];
/* The live 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 sky. */
var P = { phase: 0.78, name: 'dusk', alt: 0, az: AZ_NOON, sun: 0, sky: 0, warm: 0,
lamp: 1, star: 1, night: 1, frozen: false, period: PERIOD };
/* ---- the six names, and where they sit on the clock ---------------------------------------------
* These are what T steps between and what the HUD prints. They are phases rather than hours
* because the interesting moments of a day are not evenly spaced: dawn and dusk are minutes long
* and are where the whole picture lives, and 'morning' and 'afternoon' exist so that stepping
* from dawn does not jump straight over the best-lit hour of the day. */
/* THE STOPS ARE NOT AT THE OBVIOUS PHASES, and the two that matter are dawn and dusk. Sunrise is
* phase 0.25 by construction — the sun exactly on the horizon, where `sun` is 0.10. That is the
* blue hour, not the golden one, and the look both worlds are built around is a LOW sun rather
* than a set one: the frontier's entire lighting model is a dot product that needs the sun ABOVE
* the horizon for one side of the street to be lit at all. So the dawn and dusk stops sit two
* hundredths of a cycle inside the day, where `sun` reaches 0.65 and the light is grazing —
* which is the hour a viewer pressing T for "dusk" is actually asking for. */
var STOPS = [
{ name: 'night', phase: 0.00 },
{ name: 'dawn', phase: 0.27 },
{ name: 'morning', phase: 0.36 },
{ name: 'noon', phase: 0.50 },
{ name: 'afternoon', phase: 0.64 },
{ name: 'dusk', phase: 0.73 }
];
function nameOf(ph) {
if (ph < 0.225 || ph >= 0.795) return 'night';
if (ph < 0.315) return 'dawn';
if (ph < 0.435) return 'morning';
if (ph < 0.575) return 'noon';
if (ph < 0.695) return 'afternoon';
return 'dusk';
}
function frac(x) { return x - Math.floor(x); }
/* ---- the sky model ------------------------------------------------------------------------------
* Three curves and no more, because everything downstream is a multiplier on a constant somebody
* has already tuned and a fourth curve would only give nine files a fourth thing to disagree about.
*
* alt a sine on the phase. Not a physical solar declination model: the frame cannot tell the
* difference and a sine is what makes dawn and dusk symmetrical, which they are not in
* life but are in every viewer's expectation.
* sun smoothstep of the altitude above the horizon, so direct light arrives and leaves over a
* few degrees rather than switching. The 0.06 rad shoulder below zero is refraction and
* is why the sun's disc is still visible after it has technically set.
* sky the one that is NOT a function of `sun`, and the reason this file has three curves
* rather than two. Civil twilight is the sun 0 to -6 degrees, where there is no direct
* light at all and the sky is still the brightest object in the world. That state is the
* frontier's original look and the best hour either world has, so it gets its own curve:
* it peaks a little BELOW sunrise and decays over about 12 degrees of depression.
*/
function stateAt(tt) {
var ph = frac(tt / PERIOD);
var a = Math.sin((ph - 0.25) * 6.283185307); // -1 at midnight, +1 at noon
/* The two halves take DIFFERENT scales, and writing it as one expression is how this got wrong
* twice: the sun climbs to ALT_MAX by day and only sinks to ALT_MIN by night, because how far
* below the horizon it goes is invisible past the point where the twilight has gone but how
* high it gets decides the shadows all day. */
var alt = a >= 0 ? a * ALT_MAX : a * (-ALT_MIN);
var sun = clamp((alt + 0.06) / 0.30, 0, 1);
sun = sun * sun * (3 - 2 * sun);
/* Twilight, in radians of depression below the horizon. */
var depr = -alt;
var sky;
if (alt >= 0) sky = clamp(0.55 + 0.45 * (alt / ALT_MAX), 0, 1);
else sky = clamp(1 - depr / 0.21, 0, 1) * 0.55;
sky = sky * sky * (3 - 2 * sky);
/* Warmth peaks where the light is grazing — a low sun, up or down — and is zero at noon and
* zero once the sky has gone. The band is 0.35 rad wide either side of the horizon. */
var warm = clamp(1 - Math.abs(alt) / 0.36, 0, 1);
warm = warm * warm * (3 - 2 * warm) * clamp((alt + 0.30) / 0.24, 0, 1);
/* ---- LAMPS COME ON LATE AND GO OFF LATER, which is the point of giving them their own curve
* instead of using 1-sun. The evening and the morning are not mirror images: a lamp goes on
* when somebody can no longer see, and goes off when somebody eventually notices it is still
* burning, which is a good deal further into the morning. Two offsets, and the morning's being
* the LOWER of the two is the whole asymmetry — it holds the lamps on to a higher sun on the
* way up than the way down.
*
* BOTH ARE GENEROUS ENOUGH THAT THE GOLDEN HOURS ARE LIT, and that is a composition decision
* on top of the behavioural one. A lamp in a window is the brightest cell either world has at
* street level; the dawn and dusk stops are where the light is best; and a version of this
* curve that switched the lamps off at a sun 7 degrees up took the porch lanterns out of the
* exact frame they were designed for. Lamps are lit whenever the sun is low. */
var evening = ph > 0.5;
var lampAlt = alt + (evening ? -0.16 : -0.24);
var lamp = clamp(1 - (lampAlt + 0.02) / 0.26, 0, 1);
lamp = lamp * lamp * (3 - 2 * lamp);
/* Stars need a genuinely dark sky, so they key on the twilight curve rather than on the sun. */
var star = clamp(1 - sky / 0.34, 0, 1);
star = star * star * (3 - 2 * star);
/* Sunrise in the east, sunset in the west, with a cosine between so the bearing moves fastest
* at noon — backwards from a real sun, and the right way round for this frame, because the
* shadow direction at the ends of the day is what the eye reads and it wants to hold still
* there long enough to be seen.
*
* The phase is measured from SUNRISE, not from midnight. Taken from midnight the sun came up
* due south and was pointing east in the middle of the night, which is a sun going round the
* wrong way at half the speed. */
var az = AZ_NOON + AZ_SWING * -Math.cos((ph - 0.25) * 6.283185307);
return { ph: ph, alt: alt, az: az, sun: sun, sky: sky, warm: warm, lamp: lamp, star: star };
}
function apply(s) {
P.phase = s.ph; P.alt = s.alt; P.az = s.az;
P.sun = s.sun; P.sky = s.sky; P.warm = s.warm;
P.lamp = s.lamp; P.star = s.star;
P.night = s.alt < 0 ? 1 : 0;
P.name = nameOf(s.ph);
P.frozen = !!frozen;
return P;
}
function update(dt, t) {
if (!(t >= 0)) t = 0;
return apply(stateAt((frozen ? holdAt : t) + off));
}
var Daylight = {
P: P, KEYS: KEYS, STOPS: STOPS, PERIOD: PERIOD,
ALT_MAX: ALT_MAX, AZ_NOON: AZ_NOON, AZ_SWING: AZ_SWING,
/* Takes the city, like CC.Weather.init, and for the same reason: the starting hour is a pure
* function of the seed, so #42 opens at the same time of day every time anyone loads it.
*
* IT DOES NOT CLEAR THE VIEWER'S OVERRIDE, and that is the one place this file deliberately
* differs from the weather director. The weather belongs to the city, so a new city gets new
* weather; the time of day belongs to the VIEWER, and somebody who has pressed T to stand in
* the noon light and then presses 2 to see the frontier means to see the frontier at noon. The
* offset and the freeze therefore survive a rebuild, and only the seeded base moves. */
init: function (city) {
S = city && city.seed !== undefined ? (city.seed | 0) : 0;
/* Spread over the clock by the seed, but never opening in the dead of night: the first thing
* anyone sees should be a picture, and a black frame reads as a page that has not loaded.
* 0.62-0.97 of the cycle is afternoon through dusk into early night, which is the band both
* worlds look best in. */
var h = CC.hash1 ? CC.hash1(0, (S + 4177) | 0) : 0.5;
/* Folded straight into `off`, minus whatever base a previous city put there, so the viewer's
* own T and Y stamps ride on top of it undisturbed across a rebuild. */
off += (0.62 + h * 0.35) * PERIOD - base;
base = (0.62 + h * 0.35) * PERIOD;
return update(0, 0);
},
update: update,
/* T. Steps to the next named stop, which is a toggle a viewer can hold down a rhythm on: four
* presses from dusk gets you back to dusk through night, dawn and noon. Stamped as an OFFSET,
* so the clock keeps running from wherever it was put unless Y has stopped it. */
step: function (t, dir) {
if (!(t >= 0)) t = 0;
var cur = frac(((frozen ? holdAt : t) + off) / PERIOD);
var d = dir < 0 ? -1 : 1, i, want = -1, bestGap = 2;
/* THE NEAREST STOP AHEAD, not the first one in the array with a gap — which is what this did
* first, and it made T alternate between night and dawn forever instead of walking the clock
* round. The 0.02 margin stops a second press a frame or two later from landing on the stop
* it is already standing on. */
for (i = 0; i < STOPS.length; i++) {
var gap = d > 0 ? frac(STOPS[i].phase - cur) : frac(cur - STOPS[i].phase);
if (gap > 0.02 && gap < bestGap) { bestGap = gap; want = STOPS[i].phase; }
}
if (want < 0) want = STOPS[0].phase;
off += (want - cur) * PERIOD;
/* Frozen, the stop has to be written into holdAt as well or the clock would jump back the
* moment it was released. Not needed — off carries it — but keeping holdAt in step with the
* displayed phase is what makes `resume` behave. */
return P.name;
},
/* Y. Stops and restarts the automatic cycle. Stopping stamps the instant; starting again moves
* `off` so the clock picks up from the hour it was stopped at rather than snapping to wherever
* the world clock has got to in the meantime — which is the difference between a pause and a
* skip. */
freeze: function (t) {
if (!(t >= 0)) t = 0;
if (frozen) { off -= (t - holdAt); frozen = 0; holdAt = -1; }
else { holdAt = t; frozen = 1; }
P.frozen = !!frozen;
return !!frozen;
},
get frozen() { return !!frozen; },
get current() { return P.name; },
/* For the offline harness and for tests: put the clock at a named stop, or at a phase, with no
* reference to a viewer. Returns false for a name it does not know. */
set: function (nameOrPhase, t) {
if (!(t >= 0)) t = 0;
var want = -1;
if (typeof nameOrPhase === 'number') want = frac(nameOrPhase);
else for (var i = 0; i < STOPS.length; i++)
if (STOPS[i].name === nameOrPhase) { want = STOPS[i].phase; break; }
if (want < 0) return false;
var cur = frac(((frozen ? holdAt : t) + off) / PERIOD);
off += (want - cur) * PERIOD;
update(0, t);
return true;
}
};
Object.defineProperty(Daylight, 'offset', { get: function () { return off; } });
CC.Daylight = Daylight;
if (typeof module !== 'undefined') module.exports = Daylight;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -929,6 +929,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'ads', name: 'ads',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 34, layer: 34,
/* EXACTLY ONE rng() call, always. The stream is shared across every element and drawing a /* EXACTLY ONE rng() call, always. The stream is shared across every element and drawing a

View file

@ -167,8 +167,8 @@
* is edited. */ * is edited. */
var TIERS = [ var TIERS = [
['WASD MOVE', 'DRAG LOOK'], ['WASD MOVE', 'DRAG LOOK'],
['WASD MOVE SHIFT RUN', 'DRAG LOOK H KEYS'], ['WASD MOVE SHIFT RUN', 'DRAG LOOK 1-3 WORLD T TIME'],
['WASD MOVE SHIFT RUN C CROUCH', 'DRAG LOOK 1-6 SKY N CITY P PHOTO'] ['WASD MOVE SHIFT RUN C CROUCH', 'DRAG LOOK 1-3 WORLD T TIME Y HOLD N SEED']
]; ];
/* THE SAME LIST FOR A DEVICE WITH NO KEYS ON IT. Every string above names a key — WASD, SHIFT, /* THE SAME LIST FOR A DEVICE WITH NO KEYS ON IT. Every string above names a key — WASD, SHIFT,
@ -229,6 +229,8 @@
/* Uppercased once. CC.Weather.P.name is lower case and toUpperCase() in draw() would /* Uppercased once. CC.Weather.P.name is lower case and toUpperCase() in draw() would
* allocate a string sixty times a second. */ * allocate a string sixty times a second. */
this.wnames = []; this.wnames = [];
/* Read through the getter, so a world whose table is one row long (the Moon's `vacuum`) caches
* one name rather than the previous world's six. */
var pr = CC.Weather ? CC.Weather.PRESETS : null; 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()); 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. // Pre-split so the speed readout is a table lookup rather than a concatenation.
@ -295,6 +297,46 @@
x = text(f, 'M/S', x, y, SLATE, kl, a) + CW; x = text(f, 'M/S', x, y, SLATE, kl, a) + CW;
} }
} }
/* WHICH WORLD, ahead of what the sky is doing, and only when the frame is wide enough to
* carry both.
*
* WHAT IT COSTS THE CITY'S REFERENCE FRAMES, written down rather than discovered later, and
* re-measured now that a third world and a clock have been added to the same line.
*
* THIS FILE IS THE ONLY THING IN EITHER PASS THAT MOVES A NIGHT FRAME THE CITY ALREADY HAD.
* The mechanism is indirect and worth stating because it is not obvious: the overlay is drawn
* for the eight seconds it is up, optics.js's exposure pass integrates the whole frame's
* luminance over those frames, and a different number of lit cells in the corner lands the
* adaptation gain a fraction of a percent elsewhere — which then multiplies every cell in the
* frame, forever after.
*
* Measured at seed 42, 200x60, frame 600: with the two-world hint strings, 15 cells of 12000
* differed by 1 lum. With the three-world strings plus the clock readout, 331 cells differ,
* the largest by 8 lum. Reverting ONLY the hint strings takes it back to byte-identical, so
* the whole of it is the help text being correct rather than any change to what the city
* draws — every other file in both passes was checked against the same fixture and came back
* byte-identical. It is the price of the overlay saying true things, and it is worth paying. It is first because it is the larger fact and because it is the one a viewer
* who has just pressed a digit is looking for confirmation of; it is conditional because on
* a 48-column grid the status line has room for one word and that word is the weather, which
* changes on its own and therefore has something to say every time you look at it.
*
* Read off CC.World rather than off the city, unlike everything else in the build: this is a
* readout of what the VIEWER chose, and between the keypress and the rebuild those differ by
* one frame. Naming the old world in that frame is the one wrong answer available here. */
if (tier > 0 && CC.World && CC.World.name) {
var wn = CC.World.name;
if (x + textW(wn) + CW + 44 <= cols - MARGIN_X) x = text(f, wn, x, y, SLATE, kl, a) + CW;
}
/* THE HOUR, between the world and the weather, and only on the widest tier. The status line
* is read left to right as "where, when, what" — CYBERCITY NOON RAIN — which is the order a
* viewer who has just pressed a key wants the confirmation in. A frozen clock is marked with
* a leading dash rather than a word: Y is a hold, and a hold is best shown as the readout
* having stopped rather than as a second thing to read. */
if (tier > 1 && CC.Daylight) {
var dn = CC.Daylight.P.name.toUpperCase();
if (CC.Daylight.P.frozen) dn = '-' + dn;
if (x + textW(dn) + CW + 24 <= cols - MARGIN_X) x = text(f, dn, x, y, SLATE, kl, a) + CW;
}
var w = CC.Weather ? CC.Weather.P.name : ''; var w = CC.Weather ? CC.Weather.P.name : '';
for (var wi = 0; wi < this.wnames.length; wi++) { for (var wi = 0; wi < this.wnames.length; wi++) {
if (CC.Weather.PRESETS[wi].name === w) { if (CC.Weather.PRESETS[wi].name === w) {

View file

@ -842,6 +842,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'market', name: 'market',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
/* 17: free, and below streetprops (19) and the pedestrians (20) on purpose. Both of those draw /* 17: free, and below streetprops (19) and the pedestrians (20) on purpose. Both of those draw
* after this file and both are depth-tested, so a walker in front of a stall correctly cuts a * after this file and both are depth-tested, so a walker in front of a stall correctly cuts a
* hole in the counter light rather than being painted over by it. */ * hole in the counter light rather than being painted over by it. */

1402
src/elements/moon_craft.js Normal file

File diff suppressed because it is too large Load diff

1230
src/elements/moon_ground.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -133,6 +133,9 @@
var shaft = { var shaft = {
name: 'lightshafts', name: 'lightshafts',
layer: 78, // before every modulation pass: the shafts are in the world, not on the lens layer: 78, // before every modulation pass: the shafts are in the world, not on the lens
/* THE TWO WORLDS WITH AIR IN THEM. A shaft is light scattering off something in the air.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
this.seed = ((rng() * 4294967296) | 0) ^ 0x5A17; this.seed = ((rng() * 4294967296) | 0) ^ 0x5A17;
@ -398,6 +401,9 @@
var wash = { var wash = {
name: 'lightwash', name: 'lightwash',
layer: 79, // still in the world: this is light on surfaces, not dirt on glass layer: 79, // still in the world: this is light on surfaces, not dirt on glass
/* THE TWO WORLDS WITH AIR IN THEM. Likewise: this is airglow round a bright source.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
// Small seed, varied additively — see the note in weather.js about hash2 and large seeds. // Small seed, varied additively — see the note in weather.js about hash2 and large seeds.
@ -620,6 +626,9 @@
var mistfar = { var mistfar = {
name: 'mistfar', name: 'mistfar',
layer: 80, layer: 80,
/* THE TWO WORLDS WITH AIR IN THEM. Mist.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { this.seed = (rng() * 30011) | 0; }, init: function (city, rng) { this.seed = (rng() * 30011) | 0; },
@ -796,6 +805,9 @@
var beads = { var beads = {
name: 'lensrain', name: 'lensrain',
layer: 94, layer: 94,
/* THE TWO WORLDS WITH AIR IN THEM. Beads of rain on the lens.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
var s = ((rng() * 4294967296) | 0) ^ 0x0F71C5; var s = ((rng() * 4294967296) | 0) ^ 0x0F71C5;

View file

@ -1031,6 +1031,9 @@
* ============================================================================================ */ * ============================================================================================ */
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'police', name: 'police',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 25, layer: 25,
init: function (city, rng, dims) { init: function (city, rng, dims) {
this.city = city; this.city = city;

View file

@ -853,6 +853,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'shopSpill', name: 'shopSpill',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 28, layer: 28,
/* The interface hands `city` to init but not to draw, so park it on the element rather than /* The interface hands `city` to init but not to draw, so park it on the element rather than
@ -1325,6 +1328,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'neon', name: 'neon',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 30, layer: 30,
init: function (city, rng) { init: function (city, rng) {
@ -1389,6 +1395,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'signals', name: 'signals',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 31, layer: 31,
init: function (city, rng) { init: function (city, rng) {
@ -1494,6 +1503,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'holo', name: 'holo',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 33, layer: 33,
init: function (city, rng) { init: function (city, rng) {

View file

@ -70,6 +70,22 @@
* Where an EXISTING tuned constant is scaled — the searchlight's mote brightness — rel() is used * Where an EXISTING tuned constant is scaled — the searchlight's mote brightness — rel() is used
* and is named as such at the site. */ * 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; var W_CLOUD = 0.75, W_FOG = 0.30, W_HAZE = 0.40, W_RAIN = 0.65, W_WIND = 0.55, W_FOGREL = 1;
/* ---- the hour ---------------------------------------------------------------------------------
* Every object in this file is a NIGHT object — a star, a moon, a beacon, a searchlight, an
* airliner's strobe — and until the clock existed, "night" was an assumption baked into the fact
* that the file ran at all. It is now a number, and the four things that read it read it here.
*
* D_STAR is the one that matters most and it is not `1 - sun`: a star needs a genuinely DARK
* sky, not merely an absent sun, and the whole of civil twilight has no sun in it and no stars
* either. CC.Daylight.P.star is exactly that quantity — it keys on the twilight curve rather
* than on the solar altitude — which is why this file reads `star` and not `night`. */
var D_STAR_V = 1, D_LAMP = 1, D_SKY = 0;
function bindDay() {
var D = CC.Daylight;
D_STAR_V = D ? D.P.star : 1;
D_LAMP = D ? D.P.lamp : 1;
D_SKY = D ? D.P.sky : 0;
}
function bindWeather() { function bindWeather() {
var Wm = CC.Weather, p = Wm ? Wm.P : null; var Wm = CC.Weather, p = Wm ? Wm.P : null;
W_CLOUD = p ? p.cloud : 0.75; W_CLOUD = p ? p.cloud : 0.75;
@ -123,6 +139,7 @@
function setup(frame, cam) { function setup(frame, cam) {
bindWeather(); bindWeather();
bindDay();
var yaw = cam.yaw || 0, fov = cam.fov || 1.25; var yaw = cam.yaw || 0, fov = cam.fov || 1.25;
CB.fwx = Math.sin(yaw); CB.fwz = Math.cos(yaw); CB.fwx = Math.sin(yaw); CB.fwz = Math.cos(yaw);
CB.rgx = Math.cos(yaw); CB.rgz = -Math.sin(yaw); CB.rgx = Math.cos(yaw); CB.rgz = -Math.sin(yaw);
@ -202,6 +219,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'cloudbase', name: 'cloudbase',
layer: 3, layer: 3,
/* THE TWO WORLDS WITH AIR IN THEM. There is no deck for the town to light the underside of.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
draw: function (frame, cam, t) { draw: function (frame, cam, t) {
setup(frame, cam); setup(frame, cam);
/* Under about 0.4 the deck is a few wisps nobody would notice and 20 000 noise evaluations /* Under about 0.4 the deck is a few wisps nobody would notice and 20 000 noise evaluations
@ -259,8 +279,13 @@
* continuous amber strip along the rooftops is a sunset, and this is one in the morning * 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 * 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. */ * 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) { /* THE UNDERGLOW IS TEN THOUSAND STREETLIGHTS, so it belongs to a world that has them and
hue = P.amber; lum = 44 + 30 * v; * to an hour at which they are lit. In the frontier — a kerosene town of two hundred
* people — it was painting a sodium wash on the underside of the cloud deck, and by day
* in either world there is nothing under the cloud bright enough to light it at all. */
if (row > lowRow && v > 0.55 && D_LAMP > 0.15 && CC.World && CC.World.is('cyber') &&
hash2((nx * 190) | 0, (ny * 260) | 0, 0x71C4) < 0.30) {
hue = P.amber; lum = (44 + 30 * v) * D_LAMP;
} }
plot(frame, col, row, gl, hue, lum, D_CLOUD); plot(frame, col, row, gl, hue, lum, D_CLOUD);
} }
@ -281,6 +306,10 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'stars', name: 'stars',
layer: 4, layer: 4,
/* Both atmospheric worlds, and NOT the Moon: a lunar sky has stars at noon and they are hard,
* colourless and welded to a black dome, which is a different object drawn a different way —
* see elements/moon_ground.js. This one is a star seen through air. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng), i; var r = fork(rng), i;
stX = new Float32Array(NSTAR); stY = new Float32Array(NSTAR); stZ = new Float32Array(NSTAR); stX = new Float32Array(NSTAR); stY = new Float32Array(NSTAR); stZ = new Float32Array(NSTAR);
@ -333,6 +362,16 @@
* half of fading — a star going behind a cloud edge, which is what it is. */ * half of fading — a star going behind a cloud edge, which is what it is. */
var thr = cloudThr() - 0.05, FEATHER = 0.05; var thr = cloudThr() - 0.05, FEATHER = 0.05;
var vis = 1 - W_FOG * 1.25; if (vis <= 0) return; if (vis > 1) vis = 1; var vis = 1 - W_FOG * 1.25; if (vis <= 0) return; if (vis > 1) vis = 1;
/* THE THIRD THING THAT TAKES THE STARS AWAY, and the one that was missing: daylight. Before
* the clock existed this element ran unconditionally, which was harmless in a city that was
* always at night and actively wrong in the frontier, where four hundred stars — the
* brightest of them in ICE, the neon-cyan swatch — were painted over a sunset with the sun
* still visibly above the horizon.
*
* A DIMMER rather than a mask, unlike the cloud above it, because that is what dawn actually
* does: the faint ones go first and the two or three brightest hold on into the blue. The
* magnitude curve at init does the rest for free. */
vis *= D_STAR_V; if (vis <= 0.01) return;
for (var i = 0; i < NSTAR; i++) { for (var i = 0; i < NSTAR; i++) {
var p = proj(stX[i], stY[i], stZ[i]); var p = proj(stX[i], stY[i], stZ[i]);
if (!p.ok) continue; if (!p.ok) continue;
@ -356,6 +395,12 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'moon', name: 'moon',
layer: 5, layer: 5,
/* Both atmospheric worlds — and it used to run in the LUNAR one too, which would have been
* absurd, and in the frontier, where it was worse than absurd: sky.js parks the moon at
* D_MOON 9.0e4 and west_sky.js parks the sun at 1.02e5, so the moon won the depth test and
* painted itself and a cyan halo straight over the sunset. It is now gated to the two worlds
* that have a sky to hang it in, and faded out by daylight below. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng); var r = fork(rng);
moAz0 = (r() - 0.5) * 0.26; // the avenue runs +z, which is yaw 0 moAz0 = (r() - 0.5) * 0.26; // the avenue runs +z, which is yaw 0
@ -390,6 +435,11 @@
* enough to swallow the moon whole. That rise-and-fall is why it is a product of the haze * 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. */ * 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; var disc = 1.18 - 1.28 * W_CLOUD; if (disc <= 0.02) return; if (disc > 1) disc = 1;
/* Daylight takes the moon before cloud does. A daytime moon is a real and lovely thing, but
* it is a pale grey wafer at a tenth of this luminance, and drawing a night moon into a lit
* sky is the single most obvious way to announce that nothing about the light has actually
* changed. It keeps a tenth of itself through twilight and goes entirely by mid-morning. */
disc *= 0.10 + 0.90 * D_STAR_V; if (disc <= 0.02) return;
/* sqrt, not the disc itself. Multiplying by disc linearly made the halo strongest exactly /* 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 — * 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 * the square root keeps a scattering term that is still worth something when the disc behind
@ -443,6 +493,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'aircraft', name: 'aircraft',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 6, layer: 6,
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng), i; var r = fork(rng), i;
@ -513,6 +566,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'searchlights', name: 'searchlights',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 8, layer: 8,
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng), i; var r = fork(rng), i;
@ -624,6 +680,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'beacons', name: 'beacons',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 7, layer: 7,
init: function (city) { init: function (city) {
var r = forkCity(city, 0x2B9A31), i; var r = forkCity(city, 0x2B9A31), i;
@ -691,6 +750,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'skyrare', name: 'skyrare',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 9, layer: 9,
init: function (city) { init: function (city) {
var r = forkCity(city, 0x77E115); var r = forkCity(city, 0x77E115);
@ -787,6 +849,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'blimps', name: 'blimps',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 12, layer: 12,
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng), i, j; var r = fork(rng), i, j;
@ -896,6 +961,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'drones', name: 'drones',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 13, layer: 13,
init: function (city, rng) { init: function (city, rng) {
var r = fork(rng), i; var r = fork(rng), i;

View file

@ -782,6 +782,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'skylanes', name: 'skylanes',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 16, layer: 16,
/* ZERO draws from the shared rng, on purpose. CC.ELEMENTS is init'd in layer order off one /* ZERO draws from the shared rng, on purpose. CC.ELEMENTS is init'd in layer order off one

View file

@ -272,6 +272,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'foodstalls', name: 'foodstalls',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 18, layer: 18,
init: function (city, rng) { init: function (city, rng) {
this.city = city; this.city = city;
@ -566,36 +569,36 @@
* other of the two things a head can do at this size * other of the two things a head can do at this size
*/ */
var ARCH = [ var ARCH = [
{ name: 'plain', w: 0.13, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, { name: 'plain', w: 0.13, ww: 0.140, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.00, stride: 1.00, bob: 0.035, spd: 1.00, accP: 0.06, acc: 3, tallB: 0.00, stride: 1.00, bob: 0.035, spd: 1.00, accP: 0.06, acc: 3,
visP: 0.10, scarf: 0, hair: 0.00 }, visP: 0.10, scarf: 0, hair: 0.00 },
{ name: 'coat', w: 0.14, hem: 0.70, hemTop: 0.46, hemBot: 0.97, legTop: 1.00, legW: 0.30, { name: 'coat', w: 0.14, ww: 0.200, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.00, stride: 0.86, bob: 0.028, spd: 0.96, accP: 0.10, acc: 3, tallB: 0.00, stride: 0.86, bob: 0.028, spd: 0.96, accP: 0.10, acc: 3,
visP: 0.08, scarf: 1, hair: 0.00 }, visP: 0.08, scarf: 1, hair: 0.00 },
{ name: 'hood', w: 0.12, hem: 0.26, hemTop: 0.58, hemBot: 0.92, legTop: 1.00, legW: 0.30, { name: 'hood', w: 0.12, ww: 0.030, 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, wide: 1.02, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 1, umb: 0, wide: 1.02, crest: 0.00, cane: 0,
tallB: 0.00, stride: 0.96, bob: 0.024, spd: 1.08, accP: 0.14, acc: 1, tallB: 0.00, stride: 0.96, bob: 0.024, spd: 1.08, accP: 0.14, acc: 1,
visP: 0.22, scarf: 0, hair: 0.00 }, visP: 0.22, scarf: 0, hair: 0.00 },
{ name: 'skirt', w: 0.10, hem: 0.34, hemTop: 0.50, hemBot: 0.76, legTop: 0.76, legW: 0.19, { name: 'skirt', w: 0.10, ww: 0.120, 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, wide: 0.92, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 0.92, crest: 0.00, cane: 0,
tallB: 0.00, stride: 1.24, bob: 0.052, spd: 1.02, accP: 0.10, acc: 4, tallB: 0.00, stride: 1.24, bob: 0.052, spd: 1.02, accP: 0.10, acc: 4,
visP: 0.08, scarf: 1, hair: 0.00 }, visP: 0.08, scarf: 1, hair: 0.00 },
{ name: 'courier', w: 0.09, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, { name: 'courier', w: 0.09, ww: 0.000, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.00, pack: 0.55, bag: 0.00, hood: 0, umb: 0, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.00, stride: 1.14, bob: 0.030, spd: 1.30, accP: 0.34, acc: 2, tallB: 0.00, stride: 1.14, bob: 0.030, spd: 1.30, accP: 0.34, acc: 2,
visP: 0.34, scarf: 0, hair: 0.00 }, visP: 0.34, scarf: 0, hair: 0.00 },
/* The one figure allowed a narrow accent down its own seam, and it is 5% of the crowd. */ /* The one figure allowed a narrow accent down its own seam, and it is 5% of the crowd. */
{ name: 'shell', w: 0.06, hem: 0.16, hemTop: 0.55, hemBot: 0.95, legTop: 1.00, legW: 0.30, { name: 'shell', w: 0.06, ww: 0.000, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.14, stride: 0.98, bob: 0.032, spd: 1.04, accP: 0.78, acc: 1, tallB: 0.14, stride: 0.98, bob: 0.032, spd: 1.04, accP: 0.78, acc: 1,
visP: 0.40, scarf: 0, hair: 0.00 }, visP: 0.40, scarf: 0, hair: 0.00 },
{ name: 'hat', w: 0.07, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, { name: 'hat', w: 0.07, ww: 0.230, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.55, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.00, stride: 0.92, bob: 0.026, spd: 0.94, accP: 0.06, acc: 3, tallB: 0.00, stride: 0.92, bob: 0.026, spd: 0.94, accP: 0.06, acc: 3,
visP: 0.04, scarf: 0, hair: 0.00 }, visP: 0.04, scarf: 0, hair: 0.00 },
{ name: 'bagger', w: 0.11, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.30, { name: 'bagger', w: 0.11, ww: 0.080, 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, wide: 1.00, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.60, hood: 0, umb: 1, wide: 1.00, crest: 0.00, cane: 0,
tallB: 0.00, stride: 1.00, bob: 0.034, spd: 0.97, accP: 0.18, acc: 4, tallB: 0.00, stride: 1.00, bob: 0.034, spd: 0.97, accP: 0.18, acc: 4,
visP: 0.08, scarf: 0, hair: 0.00 }, visP: 0.08, scarf: 0, hair: 0.00 },
@ -609,7 +612,7 @@
* The narrow office figure. Reads by being the only thing on the street with a straight edge * The narrow office figure. Reads by being the only thing on the street with a straight edge
* all the way down: no hem, no hood, narrow shoulders, a hard case at the hip, and the * all the way down: no hem, no hood, narrow shoulders, a hard case at the hip, and the
* briskest walk in the table that is not a courier's. */ * briskest walk in the table that is not a courier's. */
{ name: 'suit', w: 0.08, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.26, { name: 'suit', w: 0.08, ww: 0.030, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.26,
brim: 0.00, pack: 0.00, bag: 0.34, hood: 0, umb: 1, wide: 0.90, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.34, hood: 0, umb: 1, wide: 0.90, crest: 0.00, cane: 0,
tallB: 0.04, stride: 1.06, bob: 0.022, spd: 1.12, accP: 0.05, acc: 4, tallB: 0.04, stride: 1.06, bob: 0.022, spd: 1.12, accP: 0.05, acc: 4,
visP: 0.06, scarf: 1, hair: 0.00 }, visP: 0.06, scarf: 1, hair: 0.00 },
@ -618,7 +621,7 @@
* docker, somebody in three coats, somebody with a load. `wide` feeds the screen-area budget, * docker, somebody in three coats, somebody with a load. `wide` feeds the screen-area budget,
* so this one is retired further out than the rest; that is correct rather than a side effect, * so this one is retired further out than the rest; that is correct rather than a side effect,
* because it blacks out half as much frame again at the same distance. */ * because it blacks out half as much frame again at the same distance. */
{ name: 'heavy', w: 0.06, hem: 0.10, hemTop: 0.62, hemBot: 0.94, legTop: 1.00, legW: 0.34, { name: 'heavy', w: 0.06, ww: 0.050, hem: 0.10, hemTop: 0.62, hemBot: 0.94, legTop: 1.00, legW: 0.34,
brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, wide: 1.46, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, wide: 1.46, crest: 0.00, cane: 0,
tallB: -0.06, stride: 0.78, bob: 0.030, spd: 0.82, accP: 0.12, acc: 3, tallB: -0.06, stride: 0.78, bob: 0.030, spd: 0.82, accP: 0.12, acc: 3,
visP: 0.10, scarf: 0, hair: 0.00 }, visP: 0.10, scarf: 0, hair: 0.00 },
@ -626,14 +629,14 @@
* costume feature that survives all the way down to six rows, because it changes the OUTLINE * costume feature that survives all the way down to six rows, because it changes the OUTLINE
* of the head rather than adding anything beside it, and the head is the last thing a figure * of the head rather than adding anything beside it, and the head is the last thing a figure
* has left. Piping, because this is the same person the technical shell exists for. */ * has left. Piping, because this is the same person the technical shell exists for. */
{ name: 'crest', w: 0.05, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.28, { name: 'crest', w: 0.05, ww: 0.000, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.28,
brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, wide: 0.94, crest: 0.16, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 0, wide: 0.94, crest: 0.16, cane: 0,
tallB: 0.02, stride: 1.10, bob: 0.040, spd: 1.14, accP: 0.46, acc: 1, tallB: 0.02, stride: 1.10, bob: 0.040, spd: 1.14, accP: 0.46, acc: 1,
visP: 0.44, scarf: 0, hair: 0.00 }, visP: 0.44, scarf: 0, hair: 0.00 },
/* Slow, stooped, and the only figure whose gait has a third beat in it: the stick lands /* Slow, stooped, and the only figure whose gait has a third beat in it: the stick lands
* between the feet. Its pace is the point — a crowd in which everybody moves at within 30% of * between the feet. Its pace is the point — a crowd in which everybody moves at within 30% of
* everybody else is a crowd on a conveyor, and this is the low end. */ * everybody else is a crowd on a conveyor, and this is the low end. */
{ name: 'elder', w: 0.05, hem: 0.30, hemTop: 0.48, hemBot: 0.90, legTop: 1.00, legW: 0.28, { name: 'elder', w: 0.05, ww: 0.080, hem: 0.30, hemTop: 0.48, hemBot: 0.90, legTop: 1.00, legW: 0.28,
brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 0.96, crest: 0.00, cane: 1, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 0.96, crest: 0.00, cane: 1,
tallB: -0.11, stride: 0.70, bob: 0.016, spd: 0.66, accP: 0.08, acc: 4, tallB: -0.11, stride: 0.70, bob: 0.016, spd: 0.66, accP: 0.08, acc: 4,
visP: 0.02, scarf: 1, hair: 0.00 }, visP: 0.02, scarf: 1, hair: 0.00 },
@ -660,7 +663,7 @@
* out. That is not a side effect to be worked around — a cloak blacks out more picture than * out. That is not a side effect to be worked around — a cloak blacks out more picture than
* anything else on the pavement, and the whole point of retiring on AREA is that the costume * anything else on the pavement, and the whole point of retiring on AREA is that the costume
* that occludes most goes first. */ * that occludes most goes first. */
{ name: 'cloak', w: 0.055, hem: 0.95, hemTop: 0.42, hemBot: 0.74, legTop: 1.00, legW: 0.30, { name: 'cloak', w: 0.055, ww: 0.075, hem: 0.95, hemTop: 0.42, hemBot: 0.74, legTop: 1.00, legW: 0.30,
brim: 0.00, pack: 0.00, bag: 0.00, hood: 1, umb: 0, wide: 0.94, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 1, umb: 0, wide: 0.94, crest: 0.00, cane: 0,
tallB: 0.00, stride: 0.82, bob: 0.022, spd: 0.90, accP: 0.16, acc: 1, tallB: 0.00, stride: 0.82, bob: 0.022, spd: 0.90, accP: 0.16, acc: 1,
visP: 0.16, scarf: 0, hair: 0.00 }, visP: 0.16, scarf: 0, hair: 0.00 },
@ -680,7 +683,7 @@
* silhouette argument — * silhouette argument —
* mass around the head and shoulders — and because a figure whose outline is soft at the top * mass around the head and shoulders — and because a figure whose outline is soft at the top
* wants something that moves. */ * wants something that moves. */
{ name: 'mane', w: 0.05, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.26, { name: 'mane', w: 0.05, ww: 0.020, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 1.00, legW: 0.26,
brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 0.96, crest: 0.00, cane: 0, brim: 0.00, pack: 0.00, bag: 0.00, hood: 0, umb: 1, wide: 0.96, crest: 0.00, cane: 0,
tallB: 0.00, stride: 1.08, bob: 0.046, spd: 1.06, accP: 0.20, acc: 4, tallB: 0.00, stride: 1.08, bob: 0.046, spd: 1.06, accP: 0.20, acc: 4,
visP: 0.12, scarf: 1, hair: 0.30 }, visP: 0.12, scarf: 1, hair: 0.30 },
@ -700,7 +703,7 @@
* about one figure in twenty-four — the rate the lamp was asked for. It reads as a property of * about one figure in twenty-four — the rate the lamp was asked for. It reads as a property of
* THIS costume rather than as a lottery every walker enters, which is the same argument the * THIS costume rather than as a lottery every walker enters, which is the same argument the
* technical shell makes for its piping. */ * technical shell makes for its piping. */
{ name: 'rigger', w: 0.070, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 0.66, legW: 0.50, { name: 'rigger', w: 0.070, ww: 0.050, hem: 0.00, hemTop: 0.00, hemBot: 1.00, legTop: 0.66, legW: 0.50,
brim: 0.00, pack: 0.30, bag: 0.00, hood: 0, umb: 0, wide: 1.12, crest: 0.00, cane: 0, brim: 0.00, pack: 0.30, bag: 0.00, hood: 0, umb: 0, wide: 1.12, crest: 0.00, cane: 0,
tallB: -0.02, stride: 0.84, bob: 0.026, spd: 0.88, accP: 0.75, acc: 5, tallB: -0.02, stride: 0.84, bob: 0.026, spd: 0.88, accP: 0.75, acc: 5,
visP: 0.30, scarf: 0, hair: 0.00 } visP: 0.30, scarf: 0, hair: 0.00 }
@ -708,7 +711,7 @@
/* How far a swinging arm reaches past the shoulder line, in shoulder half-widths. See the arm /* How far a swinging arm reaches past the shoulder line, in shoulder half-widths. See the arm
* block in the column loop for why the arms are part of the cut-out rather than a lit mark. */ * block in the column loop for why the arms are part of the cut-out rather than a lit mark. */
var ARM_EXT = 0.20; var ARM_EXT = 0.20;
var ARCH_TOT = 0; var ARCH_TOT = 0, ARCH_TOT_W = 0;
(function () { (function () {
/* `ext` is how far past the shoulder line this costume can possibly reach, so the column loop /* `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. */ * knows where to stop without testing every accessory on every column of every figure. */
@ -725,10 +728,32 @@
if (ARM_EXT > e) e = ARM_EXT; if (ARM_EXT > e) e = ARM_EXT;
A.ext = e; A.ext = e;
ARCH_TOT += A.w; A.acc0 = ARCH_TOT; ARCH_TOT += A.w; A.acc0 = ARCH_TOT;
/* THE SECOND COLUMN IS THE FRONTIER'S, and it is a re-weighting rather than a second table:
* the fifteen silhouettes are the same fifteen, because a body is a body and every one of
* these was drawn as a shape rather than as a costume. What changes is how often each comes
* up. A courier's satchel and a visored head are the two that are unmistakably of the city,
* so they fall to near nothing; the brimmed hat goes from 7% of the crowd to 20% and the
* long coat from 14% to 18%, which between them are the frontier's silhouette; and `cloak`,
* which the city uses for a long cape, is the serape and triples.
*
* An archetype may go to ZERO — `shell` does — and the pick below handles that correctly
* because it tests the RUNNING TOTAL: a zero-weight entry has the same accumulator as its
* predecessor and can never win the comparison. */
ARCH_TOT_W += (A.ww === undefined ? A.w : A.ww); A.acc1 = ARCH_TOT_W;
} }
})(); })();
/* Which crowd this is. Read off the CITY rather than off CC.World, for the reason world.js
* gives: between a keypress and the rebuild those are two different answers, and this one has to
* match the map the walkers are standing on. */
var PED_WEST = 0;
function archPick(h) { function archPick(h) {
var r = h * ARCH_TOT, i; var i;
if (PED_WEST) {
var rw = h * ARCH_TOT_W;
for (i = 0; i < ARCH.length - 1; i++) if (rw < ARCH[i].acc1) return ARCH[i];
return ARCH[ARCH.length - 1];
}
var r = h * ARCH_TOT;
for (i = 0; i < ARCH.length - 1; i++) if (r < ARCH[i].acc0) return ARCH[i]; for (i = 0; i < ARCH.length - 1; i++) if (r < ARCH[i].acc0) return ARCH[i];
return ARCH[ARCH.length - 1]; return ARCH[ARCH.length - 1];
} }
@ -1003,26 +1028,52 @@
* which is the same two-pillar rule the facades themselves obey. One in five breaks it, * 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. */ * because a street has more light in it than the wall behind you. */
var scr = bestH === P.azure; var scr = bestH === P.azure;
p.rim = (h10 < 0.80 ? scr : !scr) ? P.azure : P.amber; /* AZURE IS SCREENLIGHT AND THERE ARE NO SCREENS ON THE FRONTIER. The rim is the colour of
* whatever is lighting this figure, and out there that is a kerosene lamp behind a window or
* the last of the sun — both warm. One in five still breaks the rule, as in the city, because
* a street has more light in it than the wall behind you; it just breaks it towards warm
* rather than towards a shopfront monitor. */
p.rim = PED_WEST ? ((h10 < 0.80) ? P.amber : P.warm)
: ((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(). */ /* 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.umbOwn = A.umb && h9 < 0.62 ? 1 : 0;
p.uRate = 0.20 + h1 * 0.26; // seconds-scale, and different for every figure 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, /* 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 * 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. */ * draw — the same trick pays for the accent below. */
if (h12 < 0.18) { /* NOBODY ON THE FRONTIER IS LOOKING AT A SCREEN. This was the single most visible piece of the
* wrong century left in that world: one figure in five carrying a small azure or violet glow
* at chest height, which is a phone, which is a hundred and thirty years early. The draw is
* still TAKEN so the hash stream downstream of it is unchanged between worlds — only the
* result is thrown away. */
if (h12 < 0.18 && !PED_WEST) {
var q = h12 / 0.18; var q = h12 / 0.18;
p.phone = q < 0.70 ? P.azure : (q < 0.88 ? P.ice : P.violet); p.phone = q < 0.70 ? P.azure : (q < 0.88 ? P.ice : P.violet);
} else p.phone = -1; } else p.phone = -1;
/* THE ONE BODY ACCENT, and only about one figure in five has one. */ /* THE ONE BODY ACCENT, and only about one figure in five has one. */
if (h8 < A.accP) { if (h8 < A.accP) {
var qa = h8 / A.accP; var qa = h8 / A.accP;
p.acc = A.acc; /* WHICH KIND OF ACCENT, and on the frontier three of the six kinds do not exist. The colour
* was already re-mapped below, but `p.acc` decides the SHAPE and the shape is drawn from a
* hardcoded swatch further down:
* acc 1 a seam of piping down the body — electroluminescent, no 1880s referent
* acc 2 a courier's reflective strip — drawn in P.ice regardless of accHue, and
* retroreflective tape is a 1930s material
* acc 5 a shoulder lamp with a light cone — an electric torch on a strap
* All three fall back to acc 3, which is a cigarette: an ember dot at the face, which is
* period-correct, is the same one-cell cost, and is a better read on a frontier figure than
* any of them. acc 4 (something carried and lit — a lantern) is kept as it is. */
p.acc = PED_WEST ? ((A.acc === 1 || A.acc === 2 || A.acc === 5) ? 3 : A.acc) : A.acc;
/* Piping leans violet rather than spring, and that is a PRINT decision, not a taste one: /* 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 * 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 * prints spring more than twice as hot and a green seam was reading as the brightest thing
* on the pavement. */ * on the pavement. */
p.accHue = A.acc === 1 ? (qa < 0.34 ? P.spring : P.violet) /* The frontier's accents are DYED CLOTH, not piping and not a glowing seam: a red
* neckerchief, an ember bandana, a white collar. Spring, violet and ice all come off the
* ladder there — the first two are the city's signage garnish and the third is a glint on
* something manufactured. */
p.accHue = PED_WEST ? (qa < 0.42 ? P.red : (qa < 0.76 ? P.ember : P.white))
: A.acc === 1 ? (qa < 0.34 ? P.spring : P.violet)
: A.acc === 2 ? P.ice : A.acc === 2 ? P.ice
: A.acc === 3 ? P.ember : A.acc === 3 ? P.ember
: A.acc === 5 ? P.amber : A.acc === 5 ? P.amber
@ -1042,7 +1093,7 @@
* licence covers, and red is hazard, which is what a targeting overlay is. At 15.9% of the * licence covers, and red is hazard, which is what a targeting overlay is. At 15.9% of the
* crowd wearing one, red at 0.07 of those is under 1 figure in 90 and does not move red's * crowd wearing one, red at 0.07 of those is under 1 figure in 90 and does not move red's
* 0.3% share of lit energy measurably. */ * 0.3% share of lit energy measurably. */
if (h17 < A.visP) { if (h17 < A.visP && !PED_WEST) {
var qv = h17 / A.visP; var qv = h17 / A.visP;
p.vis = 1; p.vis = 1;
p.visHue = qv < 0.46 ? P.azure : (qv < 0.74 ? P.ember : (qv < 0.87 ? P.ice p.visHue = qv < 0.46 ? P.azure : (qv < 0.74 ? P.ember : (qv < 0.87 ? P.ice
@ -1054,8 +1105,15 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'pedestrians', name: 'pedestrians',
layer: 20, layer: 20,
/* THE TWO WORLDS WITH AIR IN THEM. Nobody walks a lunar plain in shirtsleeves; the crowd is an atmospheric-world
* object and a suited figure is a different silhouette that this element cannot draw.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng, dims) { init: function (city, rng, dims) {
this.city = city; this.city = city;
/* Which world's costume weights the crowd draws from — see archPick. Set here, at the one
* moment the map is handed over, rather than read per walker. */
PED_WEST = (city && city.world === 'west') ? 1 : 0;
/* Small seed and additive offsets, per the house rule for hash2 — and the draw is still one /* 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. */ * rng() call, so no downstream element's stream moves. */
this.seed = (rng() * 30011) | 0; this.seed = (rng() * 30011) | 0;
@ -1668,6 +1726,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'cat', name: 'cat',
layer: 21, layer: 21,
/* THE TWO WORLDS WITH AIR IN THEM. For the same reason as the crowd, and more so.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
this.city = city; this.city = city;
this.seed = (rng() * 2147483647) | 0; this.seed = (rng() * 2147483647) | 0;
@ -1782,6 +1843,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'traffic', name: 'traffic',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 22, layer: 22,
init: function (city, rng) { init: function (city, rng) {
this.city = city; this.city = city;
@ -1997,6 +2061,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'litter', name: 'litter',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 24, layer: 24,
init: function (city, rng) { init: function (city, rng) {
this.city = city; this.city = city;

View file

@ -1288,6 +1288,12 @@
function mk(name, layer, fn) { function mk(name, layer, fn) {
return { return {
name: name, layer: layer, name: name, layer: layer,
/* CITY ONLY, all seven of them. Every one is a cyberpunk noun — a skybridge, a comms mast, a
* fire escape, a bundle of overhead cable — and the frontier's answer to the same job (a
* hitching rail, a water tank, a telegraph line) is a different shape drawn against a
* different street, so it lives in src/elements/west_*.js rather than behind a flag in here.
* See src/world.js for why the gate is a field on the element and not a branch in the draw. */
world: 'cyber',
init: function (city, rng) { boot(city, rng); }, init: function (city, rng) { boot(city, rng); },
draw: function (f, cam, t) { draw: function (f, cam, t) {
view(f, cam, t === undefined ? (cam.t || 0) : t); view(f, cam, t === undefined ? (cam.t || 0) : t);

View file

@ -337,6 +337,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'rain', name: 'rain',
layer: 12, layer: 12,
/* THE TWO WORLDS WITH AIR IN THEM. Vacuum has no weather; rain on the Moon was diagonal streaks across a black sky.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
bindWorld(city, rng); bindWorld(city, rng);
/* The drop table is filled from a fork, not from `rng`, so that RN_MAX cannot re-seed the /* The drop table is filled from a fork, not from `rng`, so that RN_MAX cannot re-seed the
@ -364,8 +367,17 @@
* one-in-eight tinted drop is a drop passing through a sign's spill, and it is what stops * 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. */ * the rain reading as grey dust. */
var h = r(); var h = r();
rHue[i] = h < 0.70 ? P.slate : (h < 0.86 ? P.ice /* THE TINTED FIFTH IS A DROP PASSING THROUGH A SIGN'S SPILL, so it takes the colour of the
: (h < 0.94 ? P.amber : P.azure)); * light there is. In the city that is neon — ice and azure. On the frontier it is a lantern
* or a lit window, and both of those are warm; a cyan raindrop over a timber town is the
* city's palette leaking into a world that has no source for it.
*
* `world` is read once at init, from the city, rather than per drop: the pool is built once
* and a rebuild is what a world change is. */
var wWest = !!(city && city.world === 'west');
rHue[i] = h < 0.70 ? P.slate
: wWest ? (h < 0.86 ? P.white : (h < 0.94 ? P.amber : P.warm))
: (h < 0.86 ? P.ice : (h < 0.94 ? P.amber : P.azure));
} }
syncWeather(0); syncWeather(0);
wetEma = pWet; wetLastT = -1e9; wetEma = pWet; wetLastT = -1e9;
@ -636,6 +648,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'steam', name: 'steam',
/* CITY ONLY. See src/world.js: an element with no `world` belongs to both, and main.js
* filters CC.ELEMENTS on this before the layer sort. */
world: 'cyber',
layer: 14, layer: 14,
init: function (city, rng) { init: function (city, rng) {
bindWorld(city, rng); bindWorld(city, rng);
@ -818,6 +833,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'fogbank', name: 'fogbank',
layer: 8, layer: 8,
/* THE TWO WORLDS WITH AIR IN THEM. Fog is suspended water. There is none.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
bindWorld(city, rng); bindWorld(city, rng);
fgSeed = smallSeed(rng); fgSeed = smallSeed(rng);
@ -1029,6 +1047,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'lowcloud', name: 'lowcloud',
layer: 7, layer: 7,
/* THE TWO WORLDS WITH AIR IN THEM. A cloud deck needs an atmosphere to hold it up.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
bindWorld(city, rng); bindWorld(city, rng);
clSeed = smallSeed(rng); clSeed = smallSeed(rng);
@ -1182,6 +1203,9 @@
CC.ELEMENTS.push({ CC.ELEMENTS.push({
name: 'lightning', name: 'lightning',
layer: 40, layer: 40,
/* THE TWO WORLDS WITH AIR IN THEM. A stroke needs a charged medium to travel through.
* See src/world.js: `world` may be a string or a set, and absent means every world. */
world: ['cyber', 'west'],
init: function (city, rng) { init: function (city, rng) {
bindWorld(city, rng); bindWorld(city, rng);
lgSeed = smallSeed(rng); lgSeed = smallSeed(rng);

814
src/elements/west_desert.js Normal file
View file

@ -0,0 +1,814 @@
/* CyberCity frontier desert — the country the frontier was missing. Layers 10, 16 and 22.
*
* THREE HOLES, FOUND BY READING WHAT THE FRONTIER ALREADY HAD, and this file is the answer to all
* three because they are one subject: what the west looks like when you are not in the town.
*
* 1. NO DUST IN THE AIR. west_range.js computes `W_DUST = CC.Weather.P.haze` in its view() and
* then never reads it again. Three of the frontier's six presets are ABOUT dust — the whole
* difference between blazing, breeze and dust is haze 0.30 / 0.52 / 0.88 against wind 0.18 /
* 0.52 / 0.82 — and none of it reached the frame except as a slightly lifted sky floor.
* 2. NO SKYLINE. The only geology in the world is city.js's butte, which is ONE LOT: 9-32 m tall
* in a 5-10 m footprint, so it is a spire. Frontier country is composed against a BAND of
* flat-topped mesas, and that band is what says the ground goes on past the last building.
* 3. TWO PLANTS. drawBrush has sage (knee-high) and saguaro (five metres) and nothing at all in
* the human-scale middle — the stuff you would actually walk past.
*
* The view/project/emit/column helpers are west_range.js's, COPIED rather than shared: they must
* agree with raycast.js exactly, and the project keeps that true by making a caster change one that
* is repeated in every element file — loud, rather than silent in one shared helper. All three
* elements are PURE FUNCTIONS OF (world, t) with no update(), the dust included: a grain's position
* is its wrapped origin plus the wind vector times t. west_range's tumbleweed is the frontier's one
* stateful element and one is the budget.
*/
(function (CC) {
'use strict';
/* One projector per element — see src/proj.js. V and PJ are this element's own
* basis and scratch; the four functions are closed over them. */
var PR = CC.Proj.make(), V = PR.V, PJ = PR.PJ;
var project = PR.project, emit = PR.emit, column = PR.column, litFace = PR.litFace;
var P = CC.P, hash2 = CC.hash2, put = CC.put, vnoise = CC.vnoise, clamp = CC.clamp;
var G_DOT = CC.g('.'), G_COMMA = CC.g(','), G_TICK = CC.g('`'), G_QUOTE = CC.g("'"),
G_DASH = CC.g('-'), G_UNDER = CC.g('_'), G_TILDE = CC.g('~'),
G_PIPE = CC.g('|'), G_SLASH = CC.g('/'), G_BSL = CC.g('\\'), G_STAR = CC.g('*'),
G_PCT = CC.g('%'), G_AMP = CC.g('&'), G_o = CC.g('o'), G_8 = CC.g('8');
var TAU = 6.283185307;
var CITY = null, BASE = 0, Surf = null, WEST = null;
function boot(city) {
CITY = (city && city.aveX && city.world === 'west') ? city : null;
/* A private lattice offset off the city's own seed, as west_town.js and market.js do it: an
* element that draws placement noise from the shared rng reshuffles every element below it,
* and this file registers three. 52711 is a multiplier no other file uses. */
BASE = CITY ? ((Math.imul(CITY.seed | 0, 52711) >>> 6) & 0x3fffff) : 0;
}
/* haze goes through rel() where surf_west.js reads P.haze raw, and the difference is what the
* number is FOR: surf_west uses it as a physical fact about the air, this file as a dial on a
* population it chose, which is the case rel() exists for. 1.0 is the city's 0.40; the frontier
* runs 0.75 (blazing) to 2.20 (dust) of it. */
var W_WIND = 1, W_HAZE = 1, W_RAIN = 0;
/* Defaults are the tuned dusk this world was built at, so a harness without daylight.js still
* renders the picture the frontier shipped as. */
var D_SKY = 0.66, D_SUN = 0.64, D_WARM = 0.74;
/* The camera basis and its four helpers live in src/proj.js — see that file for
* why there is only one copy of them. What stays here is whatever THIS element
* caches per frame on top of it. */
function view(f, cam, t) {
PR.view(f, cam, t);
/* The two module handles the old in-file view() used to set. They were assigned
* inside the body that moved to src/proj.js, and leaving them null took the
* fallback branch at every site that reads WEST — which is how a refactor that was
* supposed to be byte-identical moved 1105 cells of a frontier frame. Resolved off
* the painter registry rather than by CC.SurfWest's name, so an element copied into
* another world picks up that world's painter. */
if (!Surf) Surf = CC.Surf;
if (!WEST) WEST = (CC.SURFACES && CC.World) ? CC.SURFACES[CC.World.id] : null;
var Wm = CC.Weather;
W_WIND = Wm && Wm.rel ? Wm.rel('wind') : 1;
W_HAZE = Wm && Wm.rel ? Wm.rel('haze') : 1;
W_RAIN = Wm && Wm.P ? Wm.P.rain : 0;
/* THE THREE DAY CACHES, and losing them is what the factoring cost before it was caught. They
* are read fourteen times in this file and were assigned in the view() body that moved to
* src/proj.js; left unassigned they sat at their declared defaults — the dusk values — and the
* desert quietly stopped responding to the clock while every other file in the world did. */
var Dm = CC.Daylight;
D_SKY = Dm ? Dm.P.sky : 0.66;
D_SUN = Dm ? Dm.P.sun : 0.64;
D_WARM = Dm ? Dm.P.warm : 0.74;
}
/* The backdrop's writer, and it is a second function rather than a flag because Surf.fog()
* returns 0 for anything past FOG_END and the mesas are parked at 8.6e4. Through emit() every
* cell of a mesa comes back black — a fine silhouette at midnight and an invisible mountain at
* noon. Distance up here is a DEPTH KEY, not a length; the aerial perspective a real range has
* is applied by hand below, where it can be a function of the haze instead of the caster's ramp. */
function far(f, x, y, ch, col, lum, d) {
if (x < 0 || y < 0 || x >= V.cols || y >= V.rows) return;
put(f, x, y, ch, col, lum, d, 3);
}
/* A LEANING stem — the only shape in either frontier file that column() cannot draw. A vertical
* drawn at an offset is not the same thing: the whip has to start at the plant's own base or an
* ocotillo reads as five separate sticks standing near each other. The fill and its two guards
* are drawTelegraph's wire loop, for its reasons (a failed sample BREAKS the run; a segment whose
* depth doubles is crossing the eye plane). k = u*u so the whip leaves the ground vertically and
* leans at the top; linear gives a straight diagonal, which is a guy wire and not a plant. */
function strand(f, x0, z0, y0, x1, z1, y1, ch, col, lum) {
var n = 9, lx = -1, ly = 0, ld = 0, i;
for (i = 0; i <= n; i++) {
var u = i / n, k = u * u;
if (!project(x0 + (x1 - x0) * k, y0 + (y1 - y0) * u, z0 + (z1 - z0) * k)) { lx = -1; continue; }
var px = Math.floor(PJ.x), py = Math.floor(PJ.y), pd = PJ.d;
if (lx >= 0 && (pd > ld * 2 || ld > pd * 2)) lx = -1;
if (lx >= 0) {
var dx = px - lx, dy = py - ly;
var st = Math.abs(dx) > Math.abs(dy) ? Math.abs(dx) : Math.abs(dy);
if (st > V.rows * 3) st = 0;
for (var q = 1; q < st; q++) {
var tq = q / st;
emit(f, lx + Math.round(dx * tq), ly + Math.round(dy * tq), ch, col, lum,
ld + (pd - ld) * tq);
}
}
emit(f, px, py, ch, col, lum, pd);
lx = px; ly = py; ld = pd;
}
}
/* ---- where a plant may stand -----------------------------------------------------------------
* The height probe is drawBrush's and is kept: a plant is anywhere the town is not.
*
* THE ROAD TEST IS NOT drawBrush's, AND THIS IS THE ONE PLACE THIS FILE KNOWINGLY DIFFERS FROM
* ITS SIBLING — written down rather than quietly fixed there. west_range.js keeps brush off the
* carriageway by asking whether the four cells at +-2.4 m are ALSO clear and thinning by a coin
* flip if they are, reasoning that the road is the wide-open part of the map. In the range
* district it is not: 62% of those lots are empty, so open country passes that test exactly as
* the road does, and what the probe really does is thin the brush by half everywhere except
* within 2.4 m of a building. Good look, wrong reason — and copying it here would have put
* yuccas up the middle of Main Street.
*
* The street lattice is on the city record, so this asks it directly, and checks ONE NEIGHBOUR
* EITHER SIDE because the arithmetic guess can be a slot out on a jittered lattice — seed 42's
* avenues sit at x = -110, -60, 7, 46, 111, 160 against a nominal pitch of 52. That is
* surf_west.js's inCross test, for its reason. `pad` also clears the boardwalk. */
function onRoad(px, pz, pad) {
var i = Math.round(px / CITY.AVE), j = Math.round(pz / CITY.CROSS), k;
for (k = -1; k <= 1; k++) {
var c = CITY.aveX(i + k) + 0.5, hw = CITY.aveW(i + k) + pad;
if (px > c - hw && px < c + hw) return 1;
var c2 = CITY.crossZ(j + k) + 0.5, hw2 = CITY.crossW(j + k) + pad;
if (pz > c2 - hw2 && pz < c2 + hw2) return 1;
}
return 0;
}
/* Room for a plant of this radius, and near enough to be worth drawing? Returns the forward
* distance so the caller can size its detail off it, or 0 for "do not draw". The horizontal bound
* is generous because a plant whose centre is off screen can still have a whip in frame; emit()'s
* per-cell check is the real gate. */
function standing(px, pz, clear, near, far2) {
if (CITY.height(px, pz) > 0.1) return 0;
if (clear > 0 && (CITY.height(px + clear, pz) > 0.1 || CITY.height(px - clear, pz) > 0.1 ||
CITY.height(px, pz + clear) > 0.1 || CITY.height(px, pz - clear) > 0.1)) return 0;
var rx = px - V.ox, rz = pz - V.oz;
var w = rx * V.fwx + rz * V.fwz;
if (w < near || w > far2) return 0;
var s = rx * V.rgx + rz * V.rgz, lim = w * V.hp + 8;
if (s < -lim || s > lim) return 0;
return w;
}
/* ================================================================================================
* 1. THE BACKDROP — a band of mesas and buttes on the horizon.
*
* A DIRECTION, NOT A PLACE. These are kilometres away, where a 1.6 m/s walk moves the parallax by
* a two-hundredth of a cell per minute — so a world-space mesa and a bearing-space one are the
* same picture, and the bearing-space one cannot drift and cannot be walked past. Up here nothing
* should move, and the cheapest guarantee is to make position impossible to express.
*
* THE LATTICE WRAPS: the slot index is taken modulo a fixed count round the compass rather than
* off floor(bearing/pitch), because cam.yaw accumulates — turn through a full circle and an
* unwrapped lattice hands you a different mountain range in the same place. The pitch is DERIVED
* from the count so slot 0 and slot N are the same landform to the last bit.
*
* DEPTH, past Surf.FOG_END so the world pass always wins — sky.js's D_STAR/D_CLOUD/D_MOON
* mechanism — and the ordering against the frontier's own sky is deliberate:
* west-birds 8.0e4 in front: a vulture over a distant range
* mesas near 8.6e4
* mesas far 8.8e4 the nearer band occludes the farther
* cloud bars 9.6e4 behind: bars stack up FROM the ridge line, which is what they do
* stars 1.0e5 behind, so a mesa is a hole in the star field
* the sun 1.02e5 behind: the sun sets INTO the mesas
* None of it depends on layer order; put() is a depth test.
* ============================================================================================= */
/* 45 and 29 slots — coprime, so the two bands never line up into one ridge, and 45 gives a mean
* form 8 degrees wide, a real mesa's angular size at this range. The first cut ran 90 and the
* horizon came out a picket fence of spires.
*
* THE HEIGHTS ARE ANGLES AND THEY ARE NOT THE ANGLES A THIRTY-MILE MESA SUBTENDS. Same trade
* west_sky.js makes for the sun, and the first cut got it wrong by believing the arithmetic: a
* 600 m mesa at 30 km subtends 0.02 rad, a row and a half at 77 rows per radian, and a band built
* to that scale put 103 cells in the frame at seed 42 frame 600. A two-storey false front thirty
* metres away covers everything under about 0.18 rad and the only sky a street contains is above
* it — the honest mesa was behind the town in every frame the walk takes.
*
* SO THE TWO BANDS ARE TWO DIFFERENT PICTURES. Band 0 is low (0.03-0.145 rad, 2-11 rows) and
* common: the open range district's far rim. Band 1 answers the street — 0.105-0.255 rad, tall
* enough to clear a roofline, and deliberately RARE at 30% of 29 slots, about nine landmarks
* round the whole compass. With the walk at the emptiest 60 m square seed 42 has (13.6% built),
* band 0 alone put ZERO cells in the frame at four of five test bearings. */
var MB_N = [45, 29];
var MB_H0 = [0.030, 0.105]; // lowest cap, radians above the horizon
var MB_HS = [0.115, 0.150]; // and the span above it
var MB_P = [0.62, 0.30]; // share of slots carrying a landform at all
var MB_TONE = [1.00, 0.72]; // aerial perspective: the far band is PALER, not dimmer
var MB_D = [8.8e4, 8.6e4];
var MB_PITCH = [TAU / MB_N[0], TAU / MB_N[1]];
/* One landform's profile at a bearing offset: a flat cap, a bench where the caprock has fallen
* away, and a talus fan down to the flat. Three steps, and three is the least that reads as
* stratified rock rather than as a box. */
function step(dd) {
if (dd < 0.55) return 1.0;
if (dd < 0.78) return 0.66;
if (dd < 1.00) return 0.34;
return 0;
}
/* The winning landform's flank sign, set by ridge() and read by the draw: +1 means this column is
* on the form's right-hand side as the camera sees it, so its rock faces screen-right. */
var MF_SIDE = 0;
function ridge(bear, b) {
var pitch = MB_PITCH[b], n = MB_N[b];
var k0 = Math.floor(bear / pitch), best = 0, bestSide = 0, kk;
for (kk = k0 - 1; kk <= k0 + 1; kk++) {
/* The hash reads the WRAPPED slot so the range is periodic; the centre is built from the
* UNWRAPPED index so it lands beside the bearing being asked about. */
var slot = ((kk % n) + n) % n;
if (hash2(slot, b, BASE + 0x71) > MB_P[b]) continue;
var c = (kk + 0.5 + (hash2(slot, b, BASE + 0x72) - 0.5) * 0.60) * pitch;
var w = pitch * (0.26 + 0.36 * hash2(slot, b, BASE + 0x73));
/* Cubed: most of the band is low and a genuinely tall mesa is an event. A uniform roll gives
* a horizon of equal-height blocks, which is a city skyline. */
var hh = hash2(slot, b, BASE + 0x74);
var top = MB_H0[b] + hh * hh * hh * MB_HS[b];
var off = bear - c;
var s = step((off < 0 ? -off : off) / w);
if (s <= 0) continue;
var e = top * s;
if (e > best) { best = e; bestSide = off < 0 ? -1 : 1; }
}
MF_SIDE = bestSide;
/* The far band also carries a continuous low ridge under its buttes; the near band does not.
* Without it the horizon between two mesas is a naked line where the sky meets the dirt, which
* is what an ocean has. Half a row to a row and a half, so it is a texture, not an object. */
if (b === 0) {
var base = 0.0055 + 0.0115 * vnoise(bear * 2.6 + 31.7, BASE + 0x75);
if (base > best) { best = base; MF_SIDE = 0; }
}
return best;
}
function drawMesas(f) {
var sunX = WEST ? WEST.SUN_X : -0.479, sunZ = WEST ? WEST.SUN_Z : 0.878;
var cols = V.cols, hp = V.hp, scale = V.scale;
var horiz = V.horizon, hrow = Math.floor(horiz);
if (hrow < 0) return;
if (hrow > V.rows - 1) hrow = V.rows - 1;
/* AIRLIGHT — the brightness of the air BETWEEN here and the mesa, which is what decides how a
* distant range looks at every hour. It is not the light on the rock: kilometres of atmosphere
* scatter more toward the eye than the rock reflects, which is why a far mountain is paler than
* a near one. So the sky drives it, the haze multiplies it, and the rock is a FRACTION of it.
* At night sky is 0, this collapses to 4, and the range is the black cut-out it should be.
*
* 190 AND NOT 112, which is a fact about core.js's print and not about the air: a noon mesa has
* to read PALER than the sky behind it or it is a stain. The frontier's noon sky prints its
* dither around v=55; white tops out at a printed 151 and slate at 114. At the first cut's 112
* the body landed at lum 57-100, printing 45-80 on slate — the sky's own tone, and the range
* vanished into it. */
var airlight = (4 + 190 * D_SKY) * clamp(0.42 + 0.46 * W_HAZE, 0.34, 1.30);
var x, r;
for (x = 0; x < cols; x++) {
var sp = ((x + 0.5) * 2 / cols - 1) * hp;
/* This column's unit direction, straight off the camera basis and with no trig — it is the
* vector raycast.js marches. The bearing is wanted only for the lattice; that is the one atan. */
var dirx = V.fwx + V.rgx * sp, dirz = V.fwz + V.rgz * sp;
var il = 1 / Math.sqrt(dirx * dirx + dirz * dirz);
var nx = dirx * il, nz = dirz * il;
var bear = V.yaw + Math.atan(sp);
/* Toward the sun, and to the right of this column. The right vector of a direction (nx, nz)
* in the project's convention (yaw 0 faces +z) is (nz, -nx). */
var toSun = nx * sunX + nz * sunZ;
var rgtSun = nz * sunX - nx * sunZ;
var b;
for (b = 0; b < 2; b++) {
var elev = ridge(bear, b);
if (elev <= 0) continue;
/* Math.tan and not the small-angle elevation: it is what west_sky.js's proj() does and the
* two must agree, and by 0.12 rad the difference is already half a row. */
var yTop = horiz - Math.tan(elev) * scale;
var r0 = Math.floor(yTop);
if (r0 > hrow) continue;
if (r0 < 0) r0 = 0;
/* Which way this flank faces the sun, on west_range.js's litFace curve so a mesa and a
* telegraph pole cannot disagree about where the light is. The normal is expressed in
* SCREEN terms — a right-hand flank is lit when the sun is to the right of the column —
* because a bearing-space object has no world normal to hand. */
var d = MF_SIDE * rgtSun;
var kk = clamp(0.5 + 0.62 * d, 0, 1);
var lit = 0.10 + 0.90 * kk * kk * (3 - 2 * kk);
lit = 0.35 + 0.65 * lit * D_SUN; // at night nothing is lit and it all flattens
/* CONTRE-JOUR. A range with the sun behind it is a silhouette with a burning rim; one with
* the sun behind the viewer is a lit wall. Same rock, and the difference is most of what a
* desert photograph is about. It rides D_WARM, so it is strongest at the two golden hours
* and gone at noon when the sun is overhead and neither applies. */
var backlit = clamp(toSun, 0, 1) * D_WARM;
var tone = MB_TONE[b];
/* 0.34-0.92 of the airlight: never brighter than the air in front of it (that is snow) and
* never black by day (that is a hole). */
var body = airlight * tone * (0.34 + 0.58 * lit) * (1 - 0.42 * backlit);
var dist = MB_D[b];
for (r = r0; r <= hrow; r++) {
if (r === r0) {
/* THE CAP LINE, and it is the whole element: a mesa is recognised by a dead-level top
* with a sharp edge, and that edge is one row of cells. Drawn at every hour and in
* every weather even when the body is invisible, because a black silhouette with a lit
* rim IS the picture at dawn and dusk. The rim term fires only where the sun is behind
* the ridge and the light is warm; amber tops out at a printed 180 and this is the one
* thing up here allowed near it. */
var cl = body * 1.5 + airlight * tone * 0.30 +
190 * backlit * clamp(toSun - 0.30, 0, 0.7) * 1.4;
var ccol = (D_WARM > 0.35 && (backlit > 0.18 || lit > 0.72)) ? P.amber
: (D_SKY > 0.42 ? P.white : P.slate);
far(f, x, r, elev > 0.030 ? G_UNDER : G_DASH, ccol, cl, dist - 1);
continue;
}
/* THE FACE. Every cell of the body is painted whatever the hour, at lum 0 in the dark,
* so the range is a HOLE in the star field and in surf_west's sky dither rather than a
* stain over it — which is what "a black cut-out against stars" has to mean in a renderer
* whose sky is drawn before its elements are. What is painted into it is bedding, the
* same read surf_west.js's rockFace gets its buttes from. The dither is keyed on the
* BEARING and on height above the horizon, never on the screen column: hash2(x, r) welds
* the texture to the glass and the range crawls through a fixed stipple as the camera
* turns, which is the bug west_sky.js's cloud bars were rewritten to avoid. */
var dens = 0.16 + 0.40 * D_SKY;
var h = hash2(Math.floor(bear * 240), (hrow - r) * 3 + b, BASE + 0x76);
if (h > dens || body < 4) { far(f, x, r, 0, P.shadow, 0, dist); continue; }
/* White by day, ember while the light is warm, slate for the blue hour between. White is
* the only swatch that can out-brighten the noon sky and ember the only one that can be a
* warm dark against a sunset; slate is neither, which is right for the twenty minutes
* when the picture is neither. */
far(f, x, r, h < dens * 0.42 ? G_DASH : (h < dens * 0.78 ? G_UNDER : G_TICK),
D_SKY > 0.55 ? P.white : (D_WARM > 0.40 ? P.ember : P.slate),
body * (0.62 + 0.70 * (h / dens)), dist);
}
}
}
}
/* ================================================================================================
* 2. THE PLANTS — four more, on four lattices, and none of them green.
*
* SPRING IS SPENT AND THIS FILE GETS NONE. west_range.js's note is right: sage is the one living
* colour out here and is deliberately a couple of cells per clump. So a yucca is slate with a
* white head, a mesquite slate, an ocotillo slate with an ember tip, dead grass amber — which is
* also what they look like. Mesquite reads grey-brown at any distance and an ocotillo out of leaf
* (most of the year) is a bundle of grey sticks.
*
* FOUR LATTICES WITH NO COMMON FACTOR — 6.7, 11.3, 13.9, 9.7 m — so no two plants can grow out of
* each other, which is the thing that most reliably announces a procedural field.
* ============================================================================================= */
var YUC_LAT = 6.7, MES_LAT = 11.3, OCO_LAT = 13.9, WASH_LAT = 9.7;
function drawPlants(f) {
var i, j, w, x, y, dd;
var sunX = (WEST && WEST.SUN_X < 0) ? -1 : 1;
/* One lit/dark decision for the whole field: a two-metre bush forty metres away subtends three
* degrees, so its own bearing cannot change the answer. drawTelegraph takes it once per line
* for the same reason. */
var sunA = litFace(1, 0), sunB = litFace(0, 1);
var sun = sunA > sunB ? sunA : sunB;
/* D_SUN and not the litFace value alone, or the plants stay rimmed in amber all night — which
* is what the frontier's furniture did before the clock existed. */
var day = clamp(0.14 + 0.86 * D_SUN, 0, 1);
var hot = sun > 0.6 && D_SUN > 0.35;
/* ---- the yucca ------------------------------------------------------------------------------
* A stiff rosette with a flower stalk out of the middle, and the STALK is the whole silhouette:
* a yucca in bloom is a pale spike standing a metre clear of everything round it, which at this
* cell size is two cells of white on a dark tuft. It is the only plant in the world that points. */
var lo = Math.floor((V.ox - 46) / YUC_LAT), hi = Math.floor((V.ox + 46) / YUC_LAT);
var lo2 = Math.floor((V.oz - 46) / YUC_LAT), hi2 = Math.floor((V.oz + 46) / YUC_LAT);
for (j = lo2; j <= hi2; j++) {
for (i = lo; i <= hi; i++) {
var yh = hash2(i, j, BASE + 0x21);
if (yh > 0.28) continue;
var yx = i * YUC_LAT + hash2(i, j, BASE + 0x22) * YUC_LAT;
var yz = j * YUC_LAT + hash2(i, j, BASE + 0x23) * YUC_LAT;
if (onRoad(yx, yz, 2.4)) continue;
w = standing(yx, yz, 1.3, 1.0, 52);
if (!w) continue;
var stalk = 1.5 + (yh / 0.28) * 1.0; // 1.5-2.5 m
column(f, yx, yz, 0, 0.55, G_STAR, P.slate, 24 + 30 * day, 0);
/* Two blades either side of the base — a rosette seen from any angle without an angle. */
if (w < 22) {
if (project(yx - 0.34, 0.42, yz)) emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_SLASH, P.slate, 20 + 26 * day, PJ.d);
if (project(yx + 0.34, 0.42, yz)) emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_BSL, P.slate, 20 + 26 * day, PJ.d);
}
column(f, yx, yz, 0.5, stalk, G_PIPE, P.slate, 18 + 34 * day, 0);
if (project(yx, stalk + 0.12, yz)) {
x = Math.floor(PJ.x); y = Math.floor(PJ.y); dd = PJ.d;
emit(f, x, y, G_8, hot ? P.white : P.slate, (hot ? 128 : 40) * (0.6 + 0.5 * day), dd);
if (w < 26) emit(f, x, y + 1, G_o, hot ? P.white : P.slate, (hot ? 92 : 30) * (0.6 + 0.5 * day), dd);
}
}
}
/* ---- the mesquite ---------------------------------------------------------------------------
* A WIDE LOW MASS and nothing else. It earns a lattice because it is the only thing in the
* frontier with horizontal bulk: every other object this world contains is a vertical (post,
* pole, cactus, stalk) or a flat plane.
*
* DRAWN AS A SPAN, NOT AS FIVE POSTS, and the first cut was the five posts. A bush three metres
* across at ten metres is twenty screen columns wide, so five world-space columns landed four
* columns apart and the plant rendered as a row of separate bars — looked at, and it read as a
* fence. Every column of the span is drawn instead, on a round profile with a per-column roll.
*
* THE TOP EDGE IS PAINTED AND THE BODY IS NOT, surf_west.js's board rule applied to a plant:
* that span filled solid is 700 cells for one bush, every one in the print's muddy band. The
* crown line is what the eye reads a bush by; an interior at a quarter density reads as foliage
* with light through it, which is what mesquite is. */
lo = Math.floor((V.ox - 62) / MES_LAT); hi = Math.floor((V.ox + 62) / MES_LAT);
lo2 = Math.floor((V.oz - 62) / MES_LAT); hi2 = Math.floor((V.oz + 62) / MES_LAT);
for (j = lo2; j <= hi2; j++) {
for (i = lo; i <= hi; i++) {
var mh = hash2(i, j, BASE + 0x31);
if (mh > 0.46) continue;
var mx = i * MES_LAT + hash2(i, j, BASE + 0x32) * MES_LAT;
var mz = j * MES_LAT + hash2(i, j, BASE + 0x33) * MES_LAT;
if (onRoad(mx, mz, 2.8)) continue;
w = standing(mx, mz, 2.0, 1.4, 62);
if (!w) continue;
var top = 2.0 + (mh / 0.46) * 1.0; // 2-3 m
var half = 0.9 + mh * 1.8; // 0.9-1.7 m: wider than it is tall
if (!project(mx, 0.10, mz)) continue;
var bcx = PJ.x, bry = PJ.y, bd = PJ.d;
if (!project(mx, top, mz)) continue;
var trY = PJ.y;
var rw = half * V.colK / w;
var iw = Math.ceil(rw); if (iw > 30) iw = 30;
var q, r2;
for (q = -iw; q <= iw; q++) {
var u = rw > 0.5 ? q / rw : 0;
if (u < -1 || u > 1) continue;
var qh = hash2(i * 31 + q, j, BASE + 0x34);
/* sqrt is the circle; the roll is what stops the crown being a drawn arc. */
var prof = Math.sqrt(1 - u * u) * (0.72 + 0.34 * qh);
var rTop = Math.floor(bry + (trY - bry) * (0.34 + 0.66 * prof));
var rBot = Math.floor(bry);
var cx2 = Math.floor(bcx + q);
var side = (q * sunX > 0) ? 1 : 0;
var mcol = hot && side ? P.amber : P.slate;
var mlum = (hot && side ? 68 : 24) * (0.55 + 0.60 * day);
for (r2 = rTop; r2 <= rBot; r2++) {
var deep = r2 - rTop;
if (deep > 1 && hash2(cx2 * 3 + deep, i * 5 + j, BASE + 0x35) > 0.26) continue;
emit(f, cx2, r2, deep === 0 ? G_AMP : (qh < 0.6 ? G_PCT : G_STAR),
mcol, mlum * (deep === 0 ? 1.25 : 0.8) * (0.7 + 0.5 * qh), bd);
}
}
/* Its own shade, which is the blackest thing on the flat at midday and what stops the plant
* floating above the ground. */
if (w < 24 && project(mx, 0.05, mz))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_UNDER, P.slate, 12, PJ.d);
}
}
/* ---- the ocotillo ---------------------------------------------------------------------------
* Half a dozen bare whips out of one point in the ground, spreading as they rise. It is in this
* file because it is the only plant shape the frontier can draw that is neither a blob nor a
* stick: a splay. Four to six strands at two to four metres, about thirty cells. The tip
* flowers fire on one plant in five and are the only red in the country. */
lo = Math.floor((V.ox - 58) / OCO_LAT); hi = Math.floor((V.ox + 58) / OCO_LAT);
lo2 = Math.floor((V.oz - 58) / OCO_LAT); hi2 = Math.floor((V.oz + 58) / OCO_LAT);
for (j = lo2; j <= hi2; j++) {
for (i = lo; i <= hi; i++) {
var oh = hash2(i, j, BASE + 0x41);
if (oh > 0.32) continue;
var ox = i * OCO_LAT + hash2(i, j, BASE + 0x42) * OCO_LAT;
var oz = j * OCO_LAT + hash2(i, j, BASE + 0x43) * OCO_LAT;
if (onRoad(ox, oz, 2.6)) continue;
w = standing(ox, oz, 1.8, 1.6, 58);
if (!w) continue;
var nw = 4 + Math.floor(hash2(i, j, BASE + 0x44) * 3); // 4-6 whips
var bloom = hash2(i, j, BASE + 0x45) < 0.22;
var q2;
for (q2 = 0; q2 < nw; q2++) {
var a = (q2 / nw) * TAU + hash2(i * 17 + q2, j, BASE + 0x46) * 0.9;
var wh2 = hash2(i, j * 13 + q2, BASE + 0x47);
var len = 2.0 + wh2 * 2.0; // 2-4 m
var spread = 0.55 + wh2 * 0.85;
strand(f, ox, oz, 0.05,
ox + Math.cos(a) * spread, oz + Math.sin(a) * spread, len,
Math.abs(Math.cos(a)) > 0.72 ? (Math.cos(a) > 0 ? G_SLASH : G_BSL) : G_PIPE,
P.slate, (16 + 40 * day) * (0.7 + 0.5 * wh2));
if (bloom && project(ox + Math.cos(a) * spread, len + 0.1, oz + Math.sin(a) * spread))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_STAR, P.ember, 58 + 90 * day, PJ.d);
}
}
}
/* ---- the dry wash and the dead grass ---------------------------------------------------------
* The one thing here not standing up, and it earns its place for a reason none of the others
* do: it is a LINE ON THE FLAT. Open country has exactly one of those (the telegraph) and needs
* more — a wash runs ACROSS the view and gives the ground a direction the way the road's ruts
* do in town. The bearing is hashed per patch and the samples run along it, so a wash is a
* streak of grit seven metres long, which is the difference between a creek and a bald spot. */
lo = Math.floor((V.ox - 40) / WASH_LAT); hi = Math.floor((V.ox + 40) / WASH_LAT);
lo2 = Math.floor((V.oz - 40) / WASH_LAT); hi2 = Math.floor((V.oz + 40) / WASH_LAT);
for (j = lo2; j <= hi2; j++) {
for (i = lo; i <= hi; i++) {
var gh = hash2(i, j, BASE + 0x51);
if (gh > 0.34) continue;
var gx = i * WASH_LAT + hash2(i, j, BASE + 0x52) * WASH_LAT;
var gz = j * WASH_LAT + hash2(i, j, BASE + 0x53) * WASH_LAT;
if (onRoad(gx, gz, 3.0)) continue;
w = standing(gx, gz, 1.6, 1.2, 40);
if (!w) continue;
var ba = hash2(i, j, BASE + 0x54) * TAU;
var bx = Math.cos(ba), bz = Math.sin(ba);
var q3, N = w < 16 ? 15 : 9;
for (q3 = 0; q3 < N; q3++) {
var u2 = (q3 / (N - 1)) * 2 - 1;
var jit = hash2(i * 7 + q3, j * 3, BASE + 0x55) - 0.5;
var wxp = gx + bx * u2 * 3.6 - bz * jit * 1.1;
var wzp = gz + bz * u2 * 3.6 + bx * jit * 1.1;
if (CITY.height(wxp, wzp) > 0.1) continue;
var g2 = hash2(i * 11 + q3, j * 5, BASE + 0x56);
/* The bed: scoured sand, an underscore because the point of it is that it lies BELOW the
* flat around it. A dry wash at noon is the brightest thing on the ground out here, which
* is why you can see one from a mile away. */
if (project(wxp, 0.02, wzp))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), g2 < 0.5 ? G_UNDER : G_TILDE,
hot ? P.white : P.slate, (18 + 66 * day) * (0.6 + 0.6 * g2), PJ.d);
/* Dead grass on the bank — amber, which is what season-old bunchgrass is — and only on
* the outer third of the run, so it LINES the wash instead of filling it. */
if (g2 > 0.62 && (u2 < -0.35 || u2 > 0.35) && project(wxp, 0.10 + g2 * 0.34, wzp))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), g2 > 0.86 ? G_QUOTE : G_TICK,
P.amber, (26 + 76 * day) * (0.6 + 0.5 * g2), PJ.d);
}
}
}
}
/* ================================================================================================
* 3. THE DUST — what the wind is actually carrying.
*
* THE POOL IS weather.js's `rain` STRUCTURE, nearly line for line: one array at a capacity, a
* PREFIX of it walked whose length tracks the grid and the weather, two interleaved shells so any
* prefix is a valid mix of near and far, and every grain wrapped into a box round the camera so a
* finite pool covers an endless desert. That file's comments explain each and they all transfer.
* What does not is the fall: dust TRAVELS, so the phase term is the wind vector times t along the
* ground and the streak lies across the frame — which is also why it needs no update().
*
* ---- PHOTOSENSITIVITY, the design constraint rather than a check at the end -------------------
* A field of streaks crossing a sunset is the hazard the windmill and the chimney smoke were
* redesigned for. AMPLITUDE: the brightest a dust cell is ever written is 74 of 255, 29% of full
* scale, under the gate's big-step line of a third. DENSITY: under the preset this exists for,
* several hundred grains cover the lower third of the frame at three to five cells each, so a
* cell is under SOME streak most of the time and what changes is which — a sparse field of short
* bright streaks was the first cut. REDUCED MOTION FREEZES IT outright, t replaced by a constant.
* Measured with tools/west-flicker.cjs at 100x34, the frontier's own worst step, big-step rate and
* 3-20 Hz band are IDENTICAL with these three elements drawn and suppressed (72.5%, 2.00/s,
* 2.65%): they add nothing to any of the three.
* ============================================================================================= */
/* A CAPACITY, not a tuning constant — RN_MAX's sentence in weather.js, true here for its reason:
* the pool is filled from a fork of the shared rng so its size cannot re-seed anything below it.
* Sized so the cap never bites at any grid this project renders (the largest request is `dust` at
* the 400x100 verification size, 420 * 2.2 * 3.33 = 3077). A cap that bites flattens the
* difference between a breeze and a dust storm, which is the difference this element draws. */
var DU_MAX = 3600, DU_AT_REF = 420, DU_REF_CELLS = 200 * 60;
var DU_BOX_N = 24, DU_BOX_F = 68;
var duOx = null, duOz = null, duY = null, duSpd = null, duHue = null;
function initDust(rng) {
/* One draw from the shared stream buys a private one; the salt is sky.js's and weather.js's, so
* the three read as one idiom. */
var r = CC.mulberry(((rng() * 4294967296) | 0) ^ 0x5C1E), i;
duOx = new Float32Array(DU_MAX); duOz = new Float32Array(DU_MAX);
duY = new Float32Array(DU_MAX); duSpd = new Float32Array(DU_MAX);
duHue = new Uint8Array(DU_MAX);
for (i = 0; i < DU_MAX; i++) {
var near = (i & 1) === 0;
var b = near ? DU_BOX_N : DU_BOX_F;
duOx[i] = r() * b; duOz[i] = r() * b;
/* THE HEIGHT DISTRIBUTION IS THE WHOLE "LOW" IN "low, near-horizontal streaks", and it is a
* fourth power rather than a threshold: blown dust has no top, it is a concentration that
* falls off with height. Squaring twice puts three quarters of the near shell under 35 cm —
* ankle deep, where dust on a road is — and leaves the odd grain at chest height for a fringe.
*
* The ceilings are set by the frame, not the metre: the eye is at 1.7 m, so a grain at 1.4 m
* two metres off projects just BELOW the horizon — the lower third, where this belongs — and
* one at 4 m projects twenty rows above it, which is a cloud in the sky. The near shell is
* capped under the eye line; the far one is never closer than 20 m and gets the extra metres
* it needs to fill the band along the horizon. */
var u = r(); u = u * u; u = u * u;
duY[i] = near ? u * 1.45 : u * 3.40;
duSpd[i] = 0.62 + r() * 0.76;
/* WHITE, AMBER, SLATE — never cool, and that is a statement about what dust IS. Suspended
* mineral dust forward-scatters the sun and is the reason a desert horizon goes orange hours
* before sunset; there is no mechanism that makes it blue, and ice or azure here would read
* as spray. Weighted to slate because most of the field is in shadow at any hour. */
var h = r();
duHue[i] = h < 0.52 ? P.slate : (h < 0.82 ? P.white : P.amber);
}
}
function wrap(v, b) { return v - b * Math.floor(v / b + 0.5); }
function drawDust(f) {
if (!duOx || !CITY) return;
/* Rain settles dust, in the literal sense of what dust does when it gets wet, so the two
* frontier presets that carry rain have none in the air. A hard cut is fine because the
* parameter it keys on already fades: `squall` reaches rain 0.72 over the director's 14 s blend
* and this reaches zero somewhere in the middle of it. */
var settle = 1 - clamp(W_RAIN * 1.5, 0, 1);
if (settle <= 0.02) return;
/* HOW MUCH DUST, and both terms are needed: haze alone puts a full sheet in the air on a
* dead-still `overcast` (haze 0.54, wind 0.34), which is a valley full of smoke and not a dust
* storm, and wind alone blows a clean sky around under `thunder`. The product is what makes
* `dust` (haze 0.88, wind 0.82) the one preset that blows. The exponent is weather.js's trick
* for its reason — the raw parameter spans only 0.75 to 2.20 of the reference and the eye does
* not read a 3x change in a field of streaks as weather — stretched to 0.66-3.15 with 1.0 still
* a fixed point.
*
* MEASURED at 260x60, camera pinned, in cells written: blazing 25, breeze 168, dust 2221 (14%
* of the frame — weather.js's downpour touches 5-7%, and a dust storm is allowed to be the
* heaviest sky the frontier has), overcast 96, thunder 13, squall 0. `blazing` is nearly nothing
* on purpose; it is the still, clear, hot preset. The field SATURATES before the clamp — 2.6x
* the population moved the cell count 6%, because the streaks have started landing on each
* other, which is what a sheet is. */
var amt = Math.pow(clamp(W_HAZE, 0.15, 2.6), 1.45) *
(0.30 + 0.70 * clamp(W_WIND, 0, 2.0)) * settle;
var use = (DU_AT_REF * clamp(amt, 0, 2.2) * V.cols * V.rows / DU_REF_CELLS) | 0;
if (use > DU_MAX) use = DU_MAX; else if (use < 6) return;
/* THE WIND VECTOR IS THE SHARED ONE. weather.js publishes CC.Weather.wind and asks every
* hanging, leaning, drifting thing in the build to read it rather than roll a second — "a
* second wind rolled somewhere else would be visibly out of phase with this one" — and dust
* crossing a street at right angles to the rain in it is the loudest possible example. */
var Wd = CC.Weather ? CC.Weather.wind : null;
var wdx, wdz, wspd;
if (Wd) { wdx = Wd.dirX; wdz = Wd.dirZ; wspd = Wd.speed; }
else { wdx = 0.92; wdz = 0.39; wspd = 2.4 * (0.35 + 0.65 * clamp(W_WIND, 0, 1.85)); }
/* Frozen, not slowed. 7.0 is an arbitrary instant far enough into the drift that the field is
* not sitting on its own initial lattice. */
var tt = CC.reducedMotion ? 7.0 : V.t;
var travX = wdx * wspd * tt, travZ = wdz * wspd * tt;
/* How fast the field crosses the SCREEN, taken once per frame rather than per particle — which
* is the whole reason the streak is affordable. */
var crossV = (wdx * V.rgx + wdz * V.rgz) * wspd;
var dirSign = crossV < 0 ? -1 : 1;
/* Dust is a scatterer and nothing else: no colour of its own, invisible in the dark. So this is
* the sky's luminance with a lift for the low sun, which is what makes a plume glow at the ends
* of the day. */
var lift = (0.06 + 0.94 * D_SKY) * (1 + 0.55 * D_WARM * D_SUN);
/* Under a light haze the far shell goes first and what is left is a little dust round your
* boots; under a storm the whole valley fills in. The rain's farUse, same shape. */
var farUse = use * clamp(0.34 + 0.46 * amt, 0.22, 1);
var rows = V.rows, cols = V.cols, i;
for (i = 0; i < use; i++) {
var near = (i & 1) === 0;
if (!near && i >= farUse) continue;
var b = near ? DU_BOX_N : DU_BOX_F;
var wx = V.ox + wrap(duOx[i] + travX * duSpd[i] - V.ox, b);
var wz = V.oz + wrap(duOz[i] + travZ * duSpd[i] - V.oz, b);
var rx = wx - V.ox, rz = wz - V.oz;
var w = rx * V.fwx + rz * V.fwz;
if (w < 0.8) continue;
var rr = rx * V.rgx + rz * V.rgz;
if (rr > V.hp * 1.3 * w || rr < -V.hp * 1.3 * w) continue;
/* A grain standing inside a building. put()'s depth test would hide most of these anyway, but
* only after projecting them, and the height probe is cheaper — and it also catches the case
* the depth test cannot, a grain drawn at the near face of a wall it is physically inside. */
var gh = CITY.height(wx, wz);
if (gh > 0.4) continue;
if (!project(wx, gh + duY[i], wz)) continue;
var px = PJ.x, py = Math.floor(PJ.y), d = PJ.d;
/* The exposure streak, in columns: how far the grain slides across the frame in one 28 ms
* shutter. Longer than the rain's because the motion is nearly horizontal and a cell is
* 0.5625 as wide as it is tall, so the same world speed buys nearly twice the cells across as
* down. Capped at five, past which it stops reading as a particle and starts reading as a
* rule drawn on the picture. */
var n = (Math.abs(crossV) * duSpd[i] * 0.028 * V.colK / w) | 0;
if (n > 5) n = 5;
/* NOT SCALED BY `amt`, which was the first cut's mistake: tying a grain's brightness to the
* same number that decides how many grains there are squares the weather. Measured at 260x60,
* `blazing` came out at nine cells against `dust`'s 2111 — a ratio of 235 for a population
* ratio of 16 — because the few grains a still day has were also written too dim to survive
* the lum floor. surf_west.js's road learned the identical lesson. 74 is the photosensitivity
* ceiling above; both shells fall off through their own box so a grain does not pop at the
* wrap. */
var base = (near ? 74 : 46) * lift *
(1 - clamp(w / (near ? DU_BOX_N * 0.82 : DU_BOX_F * 0.85), 0, 0.72));
if (base < 5) continue;
/* THE PER-GRAIN LEVEL IS PART OF THE ANSWER TO THE FLICKER, not decoration. A field where
* every particle is the same brightness turns on and off as a unit as the wind walks it;
* spreading the population over the whole range makes the sum over any one cell change
* smoothly as grains cross it. */
var g = hash2(i, 0, BASE + 0x61);
base *= 0.55 + 0.72 * g;
var hue = duHue[i];
/* Amber only survives where there is warm light to make it. An amber field under a white noon
* sun is the most obvious way to make a picture look like it has a filter on it. */
if (hue === P.amber && D_WARM < 0.30) hue = P.white;
var gl = n >= 3 ? G_DASH : (n >= 1 ? G_TILDE : (d > 18 ? G_DOT : G_COMMA));
var k;
for (k = 0; k <= n; k++) {
var sx = Math.floor(px - dirSign * k);
if (sx < 0 || sx >= cols) continue;
if (py < 0 || py >= rows) continue;
/* The tail is the older part of the streak and fades — which is also what keeps the run
* under the step budget where two streaks land on the same cell. */
var lm = base * (1 - k * 0.17);
if (lm < 4) continue;
emit(f, sx, py, k === 0 ? gl : (n >= 3 ? G_DASH : G_TICK), hue, lm, d);
}
}
/* ---- the sheet ------------------------------------------------------------------------------
* Above about twice the reference haze the grains stop being the picture and the AIR becomes it:
* in a dust storm you do not watch grains go past, you see that the far end of the street has
* gone. surf_west.js's sky already lifts its floor with haze and the fog ramp already shortens;
* what is missing is the BOTTOM of the frame, where the ground stays sharp because that ramp is
* radial and the road at your feet is two metres away. So a thin veil goes over the lower band,
* at 44 m — behind the near street furniture, in front of the far end of the road.
*
* The dither is ONE drifting noise field, never a per-cell reroll — a reroll steps every cell
* by the veil's full amplitude every frame, the exact failure west_sky.js's cloud bars were
* rewritten to avoid. It drifts at a fifth of the wind: a sheet travels, its grains faster. */
if (W_HAZE < 1.55 || CC.reducedMotion) return;
var veil = clamp((W_HAZE - 1.55) / 0.75, 0, 1) * settle;
var vl = (10 + 40 * lift) * veil;
if (vl < 5) return;
var top = Math.floor(V.horizon - V.rows * 0.10);
if (top < 0) top = 0;
var drift = tt * wspd * 0.055, vy, vx2;
for (vy = top; vy < rows; vy++) {
var band = (vy - top) / (rows - top);
var dv = 0.10 + 0.34 * band * veil;
for (vx2 = 0; vx2 < cols; vx2++) {
var sp2 = ((vx2 + 0.5) * 2 / cols - 1) * V.hp;
var hv = vnoise((V.yaw + sp2) * 9.0 + (vy - top) * 0.37 + drift, BASE + 0x62);
if (hv > dv) continue;
emit(f, vx2, vy, band > 0.55 ? G_DOT : G_TICK, P.white, vl * (0.6 + 0.7 * band), 44);
}
}
}
/* ---- registration ---------------------------------------------------------------------------
* The layers are bookkeeping only — the depth constants decide what occludes what. 10 runs the
* backdrop after west_sky's sun and cloud bars; 16 sits the plants immediately after west-brush
* at 15 so the two floras draw as one pass; 22 puts the dust over every solid object in the world
* and under the tumbleweed at 23, which is right — the weed is a solid thing rolling THROUGH the
* dust, not behind it. */
function mk(name, layer, fn) {
return {
name: name, layer: layer, world: 'west',
init: function (city) { boot(city); },
draw: function (f, cam, t) {
if (!CITY) return;
view(f, cam, t === undefined ? (cam.t || 0) : t);
fn(f);
}
};
}
CC.ELEMENTS.push(mk('west-mesas', 10, drawMesas));
CC.ELEMENTS.push(mk('west-desert-plants', 16, drawPlants));
CC.ELEMENTS.push({
name: 'west-dust',
layer: 22,
world: 'west',
init: function (city, rng) { boot(city); initDust(rng); },
draw: function (f, cam, t) {
if (!CITY) return;
view(f, cam, t === undefined ? (cam.t || 0) : t);
drawDust(f);
}
});
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

360
src/elements/west_range.js Normal file
View file

@ -0,0 +1,360 @@
/* CyberCity frontier country — what is outside the town, and the one thing that moves in it.
* Layers 15-23.
*
* city.js's `range` district is 26% of the frontier's ground by weight and 62% of its lots are
* empty, which means the walk regularly comes out of a street of shopfronts into open country.
* Empty ground rendered honestly is empty: surf_west.js paints dirt and that is all there is. So
* everything in this file exists to give the country three things the town gets for free —
*
* A LINE THAT CONVERGES. The telegraph runs beside the road whether or not there is a town
* round it, and a row of poles with a wire slung between them is the only perspective cue
* available on open ground. It is also, historically, the correct one: the line went in with
* the road and it is the first thing built anywhere out here.
* SOMETHING WITH A SIZE. Brush and cactus. A saguaro is human-scale and a sage clump is
* knee-high, and having both means the eye can read distance off them.
* SOMETHING THAT MOVES. One tumbleweed. It is the single most recognisable motion in the
* setting and it costs about forty cells.
*
* The poles and the brush are pure functions of (world, t). The tumbleweed is the only element in
* either world that carries simulation state, and it is written so that state is recoverable from
* t alone — see the note on it.
*/
(function (CC) {
'use strict';
/* One projector per element — see src/proj.js. V and PJ are this element's own
* basis and scratch; the four functions are closed over them. */
var PR = CC.Proj.make(), V = PR.V, PJ = PR.PJ;
var project = PR.project, emit = PR.emit, column = PR.column, litFace = PR.litFace;
var P = CC.P, hash2 = CC.hash2, put = CC.put, vnoise = CC.vnoise, clamp = CC.clamp;
var G_PIPE = CC.g('|'), G_DASH = CC.g('-'), G_UNDER = CC.g('_'), G_DOT = CC.g('.'),
G_COMMA = CC.g(','), G_TICK = CC.g('`'), G_QUOTE = CC.g("'"), G_STAR = CC.g('*');
var CITY = null, BASE = 0, Surf = null, WEST = null;
function boot(city) {
CITY = (city && city.aveX && city.world === 'west') ? city : null;
BASE = CITY ? ((Math.imul(CITY.seed | 0, 26417) >>> 7) & 0x3fffff) : 0;
}
var W_WIND = 1, W_RAIN = 0, W_DUST = 0.3;
/* The camera basis and its four helpers live in src/proj.js — see that file for
* why there is only one copy of them. What stays here is whatever THIS element
* caches per frame on top of it. */
function view(f, cam, t) {
PR.view(f, cam, t);
/* The two module handles the old in-file view() used to set. They were assigned
* inside the body that moved to src/proj.js, and leaving them null took the
* fallback branch at every site that reads WEST — which is how a refactor that was
* supposed to be byte-identical moved 1105 cells of a frontier frame. Resolved off
* the painter registry rather than by CC.SurfWest's name, so an element copied into
* another world picks up that world's painter. */
if (!Surf) Surf = CC.Surf;
if (!WEST) WEST = (CC.SURFACES && CC.World) ? CC.SURFACES[CC.World.id] : null;
W_WIND = CC.Weather ? CC.Weather.rel('wind') : 1;
W_RAIN = CC.Weather ? CC.Weather.P.rain : 0;
W_DUST = CC.Weather ? CC.Weather.P.haze : 0.3;
}
function wx(axis, along, cross) { return axis ? along : cross; }
function wz(axis, along, cross) { return axis ? cross : along; }
function nearIdx(axis) {
return Math.round((axis ? V.oz : V.ox) / (axis ? CITY.CROSS : CITY.AVE));
}
/* ================================================================================ telegraph ===
* ONE SIDE OF THE ROAD ONLY, and always the same side of the same street, because a telegraph
* line down both sides is a thing that has never existed and reads immediately as wrong. Which
* side is a function of the street index, so walking the same avenue twice gives the same line.
*
* The WIRE is the reason this element is worth its cost. A row of poles is a row of sticks; a
* row of poles with a catenary between them is a line running to the horizon, and a catenary is
* three multiplications. It is drawn in world space and sampled, so it takes the perspective for
* free and sags correctly in the near span where the sag is actually visible.
*/
var POLE_PITCH = 27.0, POLE_H = 7.4;
function drawTelegraph(f, axis, idx) {
var c, hw;
if (axis) { c = CITY.crossZ(idx); hw = CITY.crossW(idx); }
else { c = CITY.aveX(idx); hw = CITY.aveW(idx); }
/* Just outside the boardwalk on its chosen side — a pole stands off the road, not in it. */
var side = hash2(idx, axis, BASE + 0x11) < 0.5 ? -1 : 1;
var cross = c + 0.5 + side * (hw + 0.75);
var here = axis ? V.ox : V.oz;
var lo = Math.floor((here - 90) / POLE_PITCH), hi = Math.floor((here + 90) / POLE_PITCH);
if (hi - lo > 12) hi = lo + 12;
var sunA = litFace(axis ? 1 : 0, axis ? 0 : 1);
var sunB = litFace(axis ? -1 : 0, axis ? 0 : -1);
var sun = sunA > sunB ? sunA : sunB;
var pcol = sun > 0.6 ? P.amber : P.slate, plum = sun > 0.6 ? 96 : 26;
for (var k = lo; k <= hi; k++) {
var a0 = k * POLE_PITCH + hash2(k, idx, BASE + 0x12) * 3.0;
var a1 = (k + 1) * POLE_PITCH + hash2(k + 1, idx, BASE + 0x12) * 3.0;
var hgt = POLE_H + hash2(k, idx, BASE + 0x13) * 1.2;
/* A pole standing inside a building is a pole nobody put there. */
if (CITY.height(wx(axis, a0, cross), wz(axis, a0, cross)) > 0.5) continue;
column(f, wx(axis, a0, cross), wz(axis, a0, cross), 0, hgt, G_PIPE, pcol, plum, 0);
/* The crossarm, two cells either side of the head — the shape that says telegraph and not
* fencepost, and the only place the insulators can go. */
var ay = hgt - 0.55;
var i;
for (i = -1; i <= 1; i++) {
if (!i) continue;
var ax2 = wx(axis, a0, cross + i * 0.9), az2 = wz(axis, a0, cross + i * 0.9);
if (project(ax2, ay, az2))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_DASH, pcol, plum, PJ.d);
}
/* The wire. Sag is a fraction of the span and it is only ever visible on the near one or
* two, which is why it is worth having at all. */
var span = a1 - a0, sag = 0.9;
var lx = -1, ly = 0, ld = 0;
for (i = 0; i <= 16; i++) {
var u = i / 16, a = a0 + span * u;
var yy = hgt - 0.2 - sag * 4 * u * (1 - u);
if (!project(wx(axis, a, cross), yy, wz(axis, a, cross))) { lx = -1; continue; }
var px = Math.floor(PJ.x), py = Math.floor(PJ.y), pd = PJ.d;
if (lx >= 0 && (pd > ld * 2 || ld > pd * 2)) lx = -1;
if (lx >= 0) {
var dx = px - lx, dy = py - ly;
var st = Math.abs(dx) > Math.abs(dy) ? Math.abs(dx) : Math.abs(dy);
if (st > V.cols * 2) st = 0;
for (var q = 1; q < st; q++) {
var tq = q / st;
emit(f, lx + Math.round(dx * tq), ly + Math.round(dy * tq), G_DOT, P.slate,
sun > 0.6 ? 40 : 18, ld + (pd - ld) * tq);
}
}
emit(f, px, py, G_DOT, P.slate, sun > 0.6 ? 40 : 18, pd);
lx = px; ly = py; ld = pd;
}
}
}
/* ==================================================================================== brush ===
* Sage on a 3 m lattice and saguaro on a 17 m one, both restricted to cells that are genuinely
* open ground. The height probe is the whole placement rule: a plant is anywhere the town is not.
*
* SAGE IS THE ONLY THING IN EITHER WORLD PAINTED IN SPRING. core.js keeps that swatch for
* "foliage" and the city spends it on rooftop planting; out here it is the one living colour in
* the frame and it is deliberately kept to a couple of cells per clump — a desert is not green,
* it has green things in it. */
var SAGE_LAT = 3.1, CACTUS_LAT = 17.0, BRUSH_R = 52;
function drawBrush(f) {
var lo0 = Math.floor((V.ox - BRUSH_R) / SAGE_LAT), hi0 = Math.floor((V.ox + BRUSH_R) / SAGE_LAT);
var lo1 = Math.floor((V.oz - BRUSH_R) / SAGE_LAT), hi1 = Math.floor((V.oz + BRUSH_R) / SAGE_LAT);
var i, j;
for (j = lo1; j <= hi1; j++) {
for (i = lo0; i <= hi0; i++) {
var h = hash2(i, j, BASE + 0x21);
if (h > 0.16) continue;
var px = i * SAGE_LAT + hash2(i, j, BASE + 0x22) * SAGE_LAT;
var pz = j * SAGE_LAT + hash2(i, j, BASE + 0x23) * SAGE_LAT;
/* Open ground only, and not in the middle of the carriageway — a wheel rut is not where a
* bush grows. The road test is cheap: the road is where the walk is, and the walk is where
* the height is 0 for a long way in both directions, so instead the probe asks whether the
* NEIGHBOURING cells are also clear. Two probes, not eight: this runs a thousand times. */
if (CITY.height(px, pz) > 0.1) continue;
if (CITY.height(px + 2.4, pz) <= 0.1 && CITY.height(px - 2.4, pz) <= 0.1 &&
CITY.height(px, pz + 2.4) <= 0.1 && CITY.height(px, pz - 2.4) <= 0.1 &&
hash2(i, j, BASE + 0x24) > 0.45) continue; // wide open: that is the road, thin it
var rx = px - V.ox, rz = pz - V.oz;
var w = rx * V.fwx + rz * V.fwz;
if (w < 0.9 || w > 60) continue;
var hh = 0.30 + h * 2.6; // 0.3-0.75 m
if (!project(px, hh, pz)) continue;
var x = Math.floor(PJ.x), y = Math.floor(PJ.y), d = PJ.d;
if (x < -1 || x >= V.cols + 1) continue;
var lum = 30 + h * 260;
emit(f, x, y, h < 0.06 ? G_STAR : G_TICK, P.spring, lum, d);
if (d < 16) {
emit(f, x - 1, y, G_QUOTE, P.spring, lum * 0.6, d);
emit(f, x + 1, y, G_TICK, P.spring, lum * 0.6, d);
if (project(px, hh * 0.4, pz))
emit(f, x, Math.floor(PJ.y), G_COMMA, P.slate, 22, PJ.d);
}
}
}
/* The saguaro. Two arms and a trunk, three to five metres, and it is the one plant out here
* that is taller than a person — which is why it gets a lit side and a dark side like a
* building rather than a single colour like the sage. */
var c0 = Math.floor((V.ox - 70) / CACTUS_LAT), c1 = Math.floor((V.ox + 70) / CACTUS_LAT);
var c2 = Math.floor((V.oz - 70) / CACTUS_LAT), c3 = Math.floor((V.oz + 70) / CACTUS_LAT);
for (j = c2; j <= c3; j++) {
for (i = c0; i <= c1; i++) {
var ch2 = hash2(i, j, BASE + 0x31);
if (ch2 > 0.34) continue;
var qx = i * CACTUS_LAT + hash2(i, j, BASE + 0x32) * CACTUS_LAT;
var qz = j * CACTUS_LAT + hash2(i, j, BASE + 0x33) * CACTUS_LAT;
if (CITY.height(qx, qz) > 0.1) continue;
if (CITY.height(qx + 3, qz) > 0.1 || CITY.height(qx - 3, qz) > 0.1) continue;
var rx2 = qx - V.ox, rz2 = qz - V.oz;
var w2 = rx2 * V.fwx + rz2 * V.fwz;
if (w2 < 1.2 || w2 > 78) continue;
var th = 2.6 + ch2 * 7.0;
/* A CYLINDER, NOT A WALL, which is why it does not go through litFace. Every other object
* in this world is a flat face with one normal and is either lit or not; a saguaro trunk
* presents every normal at once, so the honest thing is the lit half and the dark half
* side by side. Close up that is two columns — the sunward one in spring, the other in
* slate — and far away it collapses to the lit one, which is correct: at forty metres the
* dark half is under a cell wide. */
var sunX = (WEST && WEST.SUN_X < 0) ? -1 : 1;
column(f, qx, qz, 0, th, G_PIPE, P.spring, 98, 0);
if (w2 < 18) column(f, qx - sunX * 0.30, qz, 0, th * 0.96, G_PIPE, P.slate, 26, 0);
var col = P.spring, lum = 98;
/* The arms: up, out, up. Drawn as three short columns rather than as a curve, because at
* this cell size a curve is three cells anyway and a curve costs an atan. */
var ah = th * (0.42 + ch2 * 0.4);
column(f, qx - 0.55, qz, ah, ah + th * 0.34, G_PIPE, col, lum, 0);
if (project(qx - 0.28, ah, qz)) emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_UNDER, col, lum, PJ.d);
if (ch2 < 0.20) {
column(f, qx + 0.55, qz, ah * 0.8, ah * 0.8 + th * 0.28, G_PIPE, col, lum, 0);
if (project(qx + 0.28, ah * 0.8, qz)) emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_UNDER, col, lum, PJ.d);
}
}
}
}
/* =============================================================================== tumbleweed ===
* THE ONE STATEFUL ELEMENT IN THE BUILD, and it is worth the exception. Everything else here is
* a pure function of (world, t) so the offline harness reproduces the browser exactly; a
* tumbleweed cannot be, because where it is depends on where it has BEEN — it rolls until it
* hits something and then it goes round it.
*
* The exception is contained the same way the weather director contains its override: the state
* is reset from t in init(), it advances only in update(), and it is a single position and phase
* per weed. The harness replays every tick, so it gets the same answer the browser does at the
* same frame — see the replay note in tools/headless.cjs, which exists for exactly this shape of
* element. What it is NOT is scrub-safe: jumping to frame 9000 without replaying gives a weed
* somewhere else. Nothing measures a weed.
*/
var NWEED = 3;
var wdX, wdZ, wdVX, wdVZ, wdPh, wdR, wdLife;
function respawn(i, rnd) {
/* Upwind of the camera, out at the fog line, on a bearing that will bring it across the view.
* The wind is +x-ish with the sun's own bearing rotated a quarter turn, which is not physics —
* it is that a weed crossing the frame reads and a weed coming straight at the camera does
* not. */
var a = rnd * 6.2831853;
wdX[i] = V.ox + Math.cos(a) * 46;
wdZ[i] = V.oz + Math.sin(a) * 46;
var b = a + 3.14159 + (rnd - 0.5) * 1.5;
var sp = 2.4 + rnd * 3.0;
wdVX[i] = Math.cos(b) * sp; wdVZ[i] = Math.sin(b) * sp;
wdPh[i] = rnd * 6.28;
wdR[i] = 0.30 + rnd * 0.34;
wdLife[i] = 26 + rnd * 30;
}
CC.ELEMENTS.push({
name: 'west-tumbleweed',
layer: 23,
world: 'west',
init: function (city, rng) {
boot(city);
wdX = new Float64Array(NWEED); wdZ = new Float64Array(NWEED);
wdVX = new Float64Array(NWEED); wdVZ = new Float64Array(NWEED);
wdPh = new Float64Array(NWEED); wdR = new Float64Array(NWEED);
wdLife = new Float64Array(NWEED);
/* Placed relative to the origin rather than to the camera, because init() runs before the
* first camera update and V is still zeroed. They walk into range within a few seconds. */
V.ox = city && city.startX !== undefined ? city.startX : 0;
V.oz = city && city.startZ !== undefined ? city.startZ : 0;
for (var i = 0; i < NWEED; i++) respawn(i, rng());
},
update: function (dt, t, cam) {
if (!CITY) return;
V.ox = cam.x; V.oz = cam.z;
var gust = 0.55 + 0.9 * W_WIND;
var damp = CC.reducedMotion ? 0.3 : 1;
for (var i = 0; i < NWEED; i++) {
wdLife[i] -= dt;
var nx = wdX[i] + wdVX[i] * dt * gust * damp;
var nz = wdZ[i] + wdVZ[i] * dt * gust * damp;
/* It bounces off buildings rather than stopping at them: a weed that parks against a wall
* is a weed the eye finds and then watches not move. */
if (CITY.height(nx, wdZ[i]) > 0.1) { wdVX[i] = -wdVX[i] * 0.7; nx = wdX[i]; }
if (CITY.height(wdX[i], nz) > 0.1) { wdVZ[i] = -wdVZ[i] * 0.7; nz = wdZ[i]; }
wdX[i] = nx; wdZ[i] = nz;
/* THE ROLL RATE IS CAPPED BY THE FLICKER RULE, not by how fast a tumbleweed rolls. The
* draw modulates the weed's luminance on |sin(ph)|, which beats at twice the phase rate,
* and the project's hard limit is nothing above 2% of full scale between 3 and 20 Hz. At
* the first cut's 2.6 + 3.4*rel(wind) the phase reached 8.6 rad/s under `thunder`, which
* is 2.7 Hz of a 16% modulation — inside the danger band with room to spare on amplitude.
* 2.0 + 1.6*rel(wind) tops out at 4.9 rad/s, i.e. 1.5 Hz, and the amplitude came down with
* it. A weed that rolls a little slower than life is not a thing anyone can notice. */
wdPh[i] += dt * (2.0 + 1.6 * W_WIND) * damp;
var dx = nx - cam.x, dz = nz - cam.z;
if (wdLife[i] < 0 || dx * dx + dz * dz > 4900)
respawn(i, hash2(i, (t * 3) | 0, BASE + 0x41));
}
},
draw: function (f, cam, t) {
if (!CITY) return;
view(f, cam, t === undefined ? (cam.t || 0) : t);
if (W_RAIN > 0.5) return; // it soaks and stops
for (var i = 0; i < NWEED; i++) {
var r = wdR[i];
/* It BOUNCES: the height is a rectified sine, which is what a rolling ball of sticks does
* on rough ground, and it is the whole read at this size. */
var bounce = Math.abs(Math.sin(wdPh[i] * 0.5)) * r * 1.5;
if (!project(wdX[i], r + bounce, wdZ[i])) continue;
var x = Math.floor(PJ.x), y = Math.floor(PJ.y), d = PJ.d;
var rw = r * V.colK / (d * 0.85), rh = r * V.scale / (d * 0.85);
var lum = 74 + 24 * Math.abs(Math.sin(wdPh[i]));
if (rw < 1.1) { emit(f, x, y, G_STAR, P.slate, lum, d); continue; }
var iw = Math.ceil(rw), ih = Math.ceil(rh), dx, dy;
if (iw > 9) iw = 9; if (ih > 9) ih = 9;
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.05) continue;
/* Open, tangled, and turning: the hash is keyed on the ROTATED offset, so the tangle
* spins with the weed instead of shimmering inside a moving circle. */
var ca = Math.cos(wdPh[i]), sa = Math.sin(wdPh[i]);
var ru = u * ca - v * sa, rv = u * sa + v * ca;
if (hash2(Math.round(ru * 5), Math.round(rv * 5), BASE + 0x42) > 0.42) continue;
emit(f, x + dx, y + dy, r2 > 0.6 ? G_TICK : G_STAR, P.slate, lum * (1 - 0.3 * r2), d);
}
}
}
}
});
function mk(name, layer, fn) {
return {
name: name, layer: layer, world: 'west',
init: function (city) { boot(city); },
draw: function (f, cam, t) {
if (!CITY) return;
view(f, cam, t === undefined ? (cam.t || 0) : t);
fn(f);
}
};
}
CC.ELEMENTS.push(mk('west-brush', 15, drawBrush));
CC.ELEMENTS.push(mk('west-telegraph', 19, function (f) {
var i;
for (i = -1; i <= 1; i++) drawTelegraph(f, 0, nearIdx(0) + i);
for (i = -1; i <= 1; i++) drawTelegraph(f, 1, nearIdx(1) + i);
}));
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

265
src/elements/west_sky.js Normal file
View file

@ -0,0 +1,265 @@
/* CyberCity frontier sky — the sun, the cloud bars it lights from underneath, and the birds.
* Layers 4-9, i.e. under everything on the ground and over the sky pass that surf_west.js paints.
*
* WHY THE SKY NEEDS ITS OWN ELEMENTS OUT HERE AND DOES NOT IN THE CITY. The city's sky is a slot
* between rooftops — two per cent of the frame — so sky.js can put a moon and a scatter of stars
* in it and that is a complete answer. The frontier's sky is a THIRD of the frame and it is what
* the whole world is composed against: a town of two-storey boxes has no verticals to look at, so
* the eye goes up, and what it finds there has to be worth the trip. surf_west.js's gradient is
* the ground of that picture; this file is the subject.
*
* THREE THINGS, in the order they matter:
* the SUN one object, low, and the only thing in either world bright enough to be
* looked at directly. It is also the source every other file's lighting model
* already assumes — surf_west.js decides which wall is lit from SUN_AZ, and
* before this element the viewer could see the effect and never the cause.
* the CLOUD BARS horizontal, lit from beneath, and the single most characteristic thing about
* a desert sunset. They are also what stops the sky being a gradient: a smooth
* ramp has no scale in it and reads as a wash however carefully it is dithered.
* the BIRDS three of them, turning. Sixty cells in the whole frame and they are what
* makes the sky a place with air in it rather than a backdrop.
*/
(function (CC) {
'use strict';
var P = CC.P, g = CC.g, put = CC.put, hash2 = CC.hash2, vnoise = CC.vnoise, clamp = CC.clamp;
var G_DOT = g('.'), G_TICK = g('`'), G_QUOTE = g("'"), G_DASH = g('-'), G_EQ = g('='),
G_o = g('o'), G_8 = g('8');
/* Past Surf.FOG_END so any facade wins the depth test, and ordered among themselves: the sun is
* behind the cloud, the cloud is behind the birds. Same mechanism sky.js uses. */
var D_SUN = 1.02e5, D_CLOUD = 9.6e4, D_BIRD = 8.0e4;
var W_CLOUD = 0.1, W_HAZE = 0.3, W_WIND = 0.2, W_RAIN = 0;
function bindWeather() {
var p = CC.Weather ? CC.Weather.P : null;
W_CLOUD = p ? p.cloud : 0.1;
W_HAZE = p ? p.haze : 0.3;
W_WIND = p ? p.wind : 0.2;
W_RAIN = p ? p.rain : 0;
}
/* ---- camera basis, copied from sky.js so the two can never disagree ------------------------- */
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 of a DIRECTION (not a point): w is the forward component, and a direction
* with w <= 0 is behind the eye plane. */
var VP = { ok: 0, x: 0, y: 0, w: 0 };
function proj(dx, dy, dz) {
var w = dx * CB.fwx + dz * CB.fwz;
if (w <= 0.02) { VP.ok = 0; return VP; }
var s = dx * CB.rgx + dz * CB.rgz;
VP.ok = 1; VP.w = w;
VP.x = (s / w) * CB.colsPerTan + CB.cols * 0.5;
VP.y = CB.horizon - (dy / w) * CB.scale;
return VP;
}
function plot(frame, x, y, ch, col, lum, d) {
x = Math.round(x); y = Math.round(y);
if (x < 0 || y < 0 || x >= CB.cols || y >= CB.rows) return;
if (lum < 3) return;
put(frame, x, y, ch, col, lum > 255 ? 255 : lum | 0, d, 3);
}
function sunAz() { return CC.SurfWest ? CC.SurfWest.SUN_AZ : -0.5; }
/* ================================================================================= the sun ===
* ALTITUDE 0.16 RAD, and that is nine degrees rather than the half a degree a sun "on the
* horizon" actually sits at. The reason is occlusion: a two-storey false front sixty metres down
* the street subtends about six degrees, so a sun placed where it physically belongs is behind
* the town in every frame the walk ever takes and the one object the whole lighting model refers
* to is never seen. Nine degrees clears a seven-metre roofline at forty-four metres, which is
* where the street usually opens out, and it still reads as low — the give-away for a low sun is
* not its height, it is that everything vertical is rimmed down one side, and surf_west.js has
* already done that.
*
* IT IS NOT AN EMITTER, IT IS A DISC WITH A HALO. A filled bright circle at this size prints as
* a hole punched in the sky; what makes a sun read is the graded surround, so most of the cells
* here are the halo and the disc itself is small. */
var SUN_ALT = 0.16, SUN_R = 0.030;
CC.ELEMENTS.push({
name: 'west-sun',
layer: 5,
world: 'west',
draw: function (frame, cam) {
setup(frame, cam);
var az = sunAz(), ca = Math.cos(SUN_ALT);
var p = proj(Math.sin(az) * ca, Math.sin(SUN_ALT), Math.cos(az) * ca);
if (!p.ok) return;
var cx = p.x, cy = p.y;
var rw = SUN_R * CB.colsPerTan / p.w, rh = SUN_R * CB.scale / p.w;
if (rw < 0.6) return;
/* Cloud takes the sun out, haze does not — it spreads it. Under a full overcast there is no
* disc at all and the halo is the whole of it, which is exactly what a sun behind a deck
* looks like and is the only way this sky changes rather than being recoloured. */
var disc = 1.20 - 1.25 * W_CLOUD; if (disc > 1) disc = 1; if (disc < 0) disc = 0;
var halo = clamp(0.35 + 0.85 * W_HAZE + 0.5 * W_CLOUD, 0, 1.35) * (0.35 + 0.65 * disc);
/* The halo, dithered, out to four radii and falling off as the square. It is drawn first so
* the disc always wins the cells they share. */
var hr = 4.4, hiw = Math.ceil(rw * hr), hih = Math.ceil(rh * hr), hx, hy, hu, hv, h2;
if (hiw > CB.cols) hiw = CB.cols;
if (hih > CB.rows) hih = CB.rows;
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 < 0.98 || h2 > hr * hr) continue;
var fall = 1 - (Math.sqrt(h2) - 1) / (hr - 1);
fall = fall * fall;
if (hash2(hx, hy, 0x5A17) > 0.30 + 0.62 * fall) continue;
plot(frame, cx + hx, cy + hy,
fall > 0.6 ? G_EQ : (fall > 0.3 ? G_DASH : G_TICK),
fall > 0.55 ? P.amber : P.ember,
(166 * fall + 20) * halo, D_SUN);
}
}
if (disc <= 0.03) return;
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;
/* Flattened at the base by refraction — the classic squashed setting sun — and banded
* across by whatever is on the horizon. Both are cheap and both are the difference
* between a sun and a circle. */
var bandK = hash2(0, Math.floor(dy * 1.3), 0x77) < 0.22 ? 0.42 : 1;
plot(frame, cx + dx, cy + dy, r2 > 0.78 ? G_o : G_8,
r2 > 0.86 ? P.amber : P.pure, (236 - 40 * r2) * disc * bandK, D_SUN);
}
}
}
});
/* ============================================================================== cloud bars ===
* HORIZONTAL, and that is the whole design. Cumulus over a city is a lumpy field; what a desert
* sunset has is altocumulus in long parallel bars, lit orange along the bottom edge and dark
* slate on top, stacked up from the horizon. That underlit edge is the single most recognisable
* thing in the sky at this hour and it is one row of cells per bar.
*
* The field is sampled in ELEVATION and BEARING rather than in a direction vector, because bars
* are a function of height above the horizon and nothing else — a noise in three dimensions
* would give clouds that are not bars. */
var NBAR = 7;
CC.ELEMENTS.push({
name: 'west-cloudbars',
layer: 6,
world: 'west',
draw: function (frame, cam, t) {
setup(frame, cam);
if (W_CLOUD < 0.03) return;
var tt = CC.reducedMotion ? 0 : t * (0.004 + 0.016 * W_WIND);
var az0 = sunAz();
/* One pass over the sky rows of the frame. Cheaper than walking a sphere and exact: every
* cell that could carry a bar is a cell of this frame. */
var x, y, y0 = 0, y1 = Math.floor(CB.horizon);
if (y1 > CB.rows) y1 = CB.rows;
for (x = 0; x < CB.cols; x++) {
var sp = (2 * (x + 0.5) / CB.cols - 1) * CB.half;
var bear = (cam.yaw || 0) + Math.atan(sp);
var da = bear - az0;
da = Math.atan2(Math.sin(da), Math.cos(da));
var west = 1 - Math.abs(da) / Math.PI;
for (y = y0; y < y1; y++) {
/* Elevation of this row, in radians, from the same projection the caster uses. */
var el = (CB.horizon - y - 0.5) / CB.scale;
if (el < 0.02 || el > 0.62) continue;
/* Bars: a sine ladder in elevation, jittered by a slow noise so they are not ruled. The
* ladder's pitch grows with elevation because perspective foreshortens a flat deck —
* bars near the horizon are far away and crowd together. */
var lad = Math.log(el * 14 + 1) * NBAR + vnoise(bear * 1.7 + tt * 3, 0x81) * 1.4;
var fb = lad - Math.floor(lad);
/* CONTINUOUS, NOT HASHED, and this is the photosensitivity rule rather than a taste.
* A hash keyed on a quantised time re-rolls whether a rung is cloud, so a cell steps from
* lum 150 to 0 between two frames — 59% of full scale in one frame, against a limit of a
* third. A value noise drifting through the same range moves the EDGE of a bar instead:
* any given cell changes state at most a couple of times as the edge sweeps over it, at
* the drift rate, which is 0.004-0.02 of a cycle a second. */
var body = vnoise(Math.floor(lad) * 3.1 + bear * 2.0 + tt * 3, 0x9C1);
/* Not every rung of the ladder is cloud; cover is the weather. */
if (body > 0.22 + 0.68 * W_CLOUD) continue;
/* Keyed on the SKY, not on the glass. hash2(x, y) welds the dither to the screen, so
* turning the camera slides the cloud through a fixed stipple — the same bug the star
* field had before surfaces.js started hashing on bearing and elevation. */
var d = hash2(Math.floor(bear * 220), Math.floor(el * 900), 0x33B);
if (fb > 0.66) continue; // the gap between two bars
if (fb > 0.50) {
/* THE LIT UNDERSIDE. One or two rows, ember going to amber where the sun is, and the
* brightest thing in the sky after the disc itself. */
if (d > 0.72) continue;
plot(frame, x, y, G_DASH, west > 0.68 ? P.amber : P.ember,
(86 + 132 * west) * (0.7 + 0.5 * d), D_CLOUD);
} else {
/* The body: dark, and mostly not painted at all. A cloud at dusk is a silhouette. */
if (d > 0.34 - 0.18 * fb) continue;
plot(frame, x, y, fb > 0.28 ? G_TICK : G_DOT, P.slate,
(26 + 30 * (1 - fb)) * (0.6 + 0.6 * d), D_CLOUD);
}
}
}
}
});
/* =================================================================================== birds ===
* Three turkey vultures on one thermal, which is a real thing and also the cheapest way to put a
* living creature in the sky: a vulture on a thermal does not flap, so the whole animation is a
* circle and a shape that changes with the angle you see it from. Two cells each, most of the
* time. */
var NBIRD = 3;
var bSeed = 0;
CC.ELEMENTS.push({
name: 'west-birds',
layer: 9,
world: 'west',
init: function (city, rng) {
/* One draw from the shared stream, and it is declared: this element needs a thermal centre
* that is not the same in every town, and the city seed alone would put the birds over the
* same corner of every map. One draw shifts the streams below layer 9, which is optics only
* in this world. */
bSeed = (rng() * 4294967296) | 0;
},
draw: function (frame, cam, t) {
setup(frame, cam);
if (W_RAIN > 0.35) return; // nothing is up there in the wet
var tt = CC.reducedMotion ? 12.0 : t;
for (var i = 0; i < NBIRD; i++) {
var ph = tt * (0.055 + 0.014 * i) + i * 2.3 + (bSeed & 255) * 0.01;
/* The thermal: a circle in azimuth about a fixed bearing, slowly rising and falling. */
var az = -1.1 + (bSeed >> 8 & 255) * 0.012 + Math.sin(ph) * 0.30;
var alt = 0.30 + 0.09 * i + Math.cos(ph * 0.7) * 0.05;
var ca = Math.cos(alt);
var p = proj(Math.sin(az) * ca, Math.sin(alt), Math.cos(az) * ca);
if (!p.ok) continue;
/* The silhouette turns with the bird: broadside it is a shallow V three cells wide,
* end-on it is a single dot. cos of the phase IS the aspect. */
var asp = Math.abs(Math.cos(ph));
var x = p.x, y = p.y;
plot(frame, x, y, G_DOT, P.slate, 62, D_BIRD);
if (asp > 0.45) {
plot(frame, x - 1, y - (asp > 0.8 ? 1 : 0), G_TICK, P.slate, 54, D_BIRD);
plot(frame, x + 1, y - (asp > 0.8 ? 1 : 0), G_QUOTE, P.slate, 54, D_BIRD);
}
}
}
});
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

1074
src/elements/west_stock.js Normal file

File diff suppressed because it is too large Load diff

449
src/elements/west_town.js Normal file
View file

@ -0,0 +1,449 @@
/* CyberCity frontier town — the street furniture of the west. Layers 17-21.
*
* WHAT THIS FILE IS FOR. surf_west.js paints the walls and the ground, and a town made only of
* those two things is a corridor: two flat fronts and a strip of dust, with nothing standing
* between the viewer and the buildings and therefore no depth in the near field at all. Everything
* here is an OBJECT in the street — a post, a rail, a trough, a lantern, a water tank on a roof —
* and between them they do three jobs the surfaces cannot:
*
* 1. THE POSTS ARE THE RHYTHM. A veranda post every two and a half metres down both sides of the
* road is a colonnade, and a colonnade in perspective is the strongest depth cue available in
* a still frame. It is also the single most recognisable silhouette of the setting.
* 2. THE LANTERNS ARE THE LIGHT. core.js's EXPOSURE ladder puts every SURFACE swatch in this
* world under 0.42 gain, so nothing surf_west.js paints can reach the v>=170 band the print
* wants 3.5-5% of the frame in. A flame can: amber at lum 200+, a handful of cells per porch.
* Measured before this file existed, the frontier printed 0.18% hot.
* 3. THE ROOFLINE GETS SOMETHING ON IT. A town of two-storey boxes has a flat skyline, and a
* flat skyline against the biggest sky in the project is a ruler laid across the frame. The
* crowns — chimney, water tank, steeple — are what break it.
*
* Everything is a pure function of (world, t). No update(), no simulation state, no draw from the
* shared rng: the lattice offset comes from the city's own seed, exactly as market.js does it and
* for the same reason — an element that draws from the shared stream reshuffles the noise of every
* element initialised after it.
*/
(function (CC) {
'use strict';
/* One projector per element — see src/proj.js. V and PJ are this element's own
* basis and scratch; the four functions are closed over them. */
var PR = CC.Proj.make(), V = PR.V, PJ = PR.PJ;
var project = PR.project, emit = PR.emit, column = PR.column, litFace = PR.litFace;
var P = CC.P, hash2 = CC.hash2, put = CC.put, vnoise = CC.vnoise, clamp = CC.clamp;
var G_PIPE = CC.g('|'), G_DASH = CC.g('-'), G_EQ = CC.g('='), G_DOT = CC.g('.'),
G_COLON = CC.g(':'), G_TICK = CC.g('`'), G_CARET = CC.g('^'), G_STAR = CC.g('*'),
G_0 = CC.g('0'), G_O = CC.g('O'), G_o = CC.g('o'), G_HASH = CC.g('#'), G_PLUS = CC.g('+'),
G_TILDE = CC.g('~');
var CITY = null, BASE = 0, Surf = null, WEST = null;
function boot(city) {
CITY = (city && city.aveX && city.world === 'west') ? city : null;
BASE = CITY ? ((Math.imul(CITY.seed | 0, 40503) >>> 8) & 0x3fffff) : 0;
}
/* ---- the view — mirrors raycast.js exactly ------------------------------------------------- */
var W_WIND = 1, W_WET = 1;
/* The camera basis and its four helpers live in src/proj.js — see that file for
* why there is only one copy of them. What stays here is whatever THIS element
* caches per frame on top of it. */
function view(f, cam, t) {
PR.view(f, cam, t);
/* The two module handles the old in-file view() used to set. They were assigned
* inside the body that moved to src/proj.js, and leaving them null took the
* fallback branch at every site that reads WEST — which is how a refactor that was
* supposed to be byte-identical moved 1105 cells of a frontier frame. Resolved off
* the painter registry rather than by CC.SurfWest's name, so an element copied into
* another world picks up that world's painter. */
if (!Surf) Surf = CC.Surf;
if (!WEST) WEST = (CC.SURFACES && CC.World) ? CC.SURFACES[CC.World.id] : null;
W_WIND = CC.Weather ? CC.Weather.rel('wind') : 1;
W_WET = CC.Weather ? CC.Weather.rel('wet') : 1;
}
/* ---- street geometry ------------------------------------------------------------------------
* axis 0 = avenue (runs along +z, span crosses in x); axis 1 = cross street (spans z). Same
* derivation as market.js and structure.js: city.js puts street cells at |g - centre| <= half, so
* the wall faces sit at centre-half and centre+half+1. */
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; }
/* The outward normal of the frontage on side s, in world axes: side 0 is the low face (its
* buildings are at smaller cross, so it looks toward +cross) and side 1 is the high face. */
function nX(axis, s) { return axis ? 0 : (s ? -1 : 1); }
function nZ(axis, s) { return axis ? (s ? -1 : 1) : 0; }
/* The pavement actually available. CC.PAVE is the building-face-to-kerb width and it is read,
* never rewritten; raycast floors the carriageway at 1.7 m, so on a narrow street the walk is
* whatever is left. Same arithmetic as market.js's paveOf. */
function paveOf(spanW) {
var p = CC.PAVE, avail = spanW * 0.5 - 1.7;
return avail < p ? avail : p;
}
/* Is there continuous frontage behind this stretch? Four probes, all must hit — a veranda that
* bridges an alley mouth is a veranda standing across a side street. */
function frontage(axis, a0, len, cross, dirIn) {
var i, a, c = cross - dirIn * 0.7;
for (i = 0; i <= 3; i++) {
a = a0 + len * (i / 3);
if (CITY.height(wx(axis, a, c), wz(axis, a, c)) < 2.5) return 0;
}
return 1;
}
function objVisible(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 || 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;
}
/* ---- a horizontal run along the street ------------------------------------------------------
* Sampled rather than projected end-to-end, because a rail seen nearly end-on covers hundreds of
* columns and a two-point fill would step. The step is chosen off the projected length so a rail
* two metres away costs the same per column as one forty metres away. */
function beam(f, axis, a0, a1, cross, y, ch, col, lum) {
/* Screen-space interpolation between world samples, and BOTH coordinates of it. The first cut
* of this filled only in x, at the row of the newer sample, and it drew a horizontal line clean
* across the frame every time a sample dropped out behind the eye plane — the run would resume
* forty metres later and the fill would join the two, which is a rail across the sky.
*
* So: a sample that fails to project BREAKS the run (lx = -1), the fill walks x and y together,
* and a segment whose depth jumps by more than double is dropped rather than joined — that jump
* only happens where the span passes the eye plane, and joining across it connects two points
* that are behind each other. */
var n = 22, i, a, lx = -1, ly = 0, ld = 0;
for (i = 0; i <= n; i++) {
a = a0 + (a1 - a0) * (i / n);
if (!project(wx(axis, a, cross), y, wz(axis, a, cross))) { lx = -1; continue; }
var x = Math.floor(PJ.x), r = Math.floor(PJ.y), d = PJ.d;
if (lx >= 0 && (d > ld * 2 || ld > d * 2)) lx = -1;
if (lx >= 0) {
var dx = x - lx, dy = r - ly;
var steps = Math.abs(dx) > Math.abs(dy) ? Math.abs(dx) : Math.abs(dy);
if (steps > 4 * V.cols) steps = 0; // degenerate; draw the endpoint only
for (var q = 1; q < steps; q++) {
var t2 = q / steps;
emit(f, lx + Math.round(dx * t2), ly + Math.round(dy * t2), ch, col, lum,
ld + (d - ld) * t2);
}
}
emit(f, x, r, ch, col, lum, d);
lx = x; ly = r; ld = d;
}
}
/* ================================================================================================
* THE VERANDA — posts, awning fascia, and the lanterns hung off them.
* ============================================================================================= */
var POST = 2.6; // post spacing in metres. A frontier veranda bay is 8-9 feet.
var AWN_Y = 2.94; // underside of the awning at the post; it slopes up to the wall
function drawVeranda(f, axis, idx) {
streetSpan(axis, idx);
var pave = paveOf(SPAN.w);
if (pave < 1.1) return; // no room for a walk, so no veranda
var pitch = axis ? CITY.AVE : CITY.CROSS; // the OTHER family's pitch: along this street
var lo = Math.floor(((axis ? V.ox : V.oz) - 60) / POST);
var hi = Math.floor(((axis ? V.ox : V.oz) + 60) / POST);
if (hi - lo > 60) hi = lo + 60;
for (var s = 0; s < 2; s++) {
var face = s ? SPAN.c1 : SPAN.c0, dirIn = s ? -1 : 1;
var postC = face + dirIn * (pave - 0.34);
var nx = nX(axis, s), nz = nZ(axis, s);
var sun = litFace(nx, nz);
/* A post is a black cut-out with one lit edge — the house idiom for a near object. The lit
* edge is on the sun side and it is what makes a colonnade read as round timber rather than
* as a row of slots. */
var pcol = sun > 0.6 ? P.amber : P.slate;
var plum = sun > 0.6 ? 74 : 20;
for (var k = lo; k <= hi; k++) {
var along = k * POST + 0.5;
var w = objVisible(axis, along, postC, 0.7);
if (!w) continue;
if (!frontage(axis, along - POST * 0.5, POST, face, dirIn)) continue;
var hh = hash2(k, idx * 2 + s, BASE + (axis ? 0x51 : 0x52));
/* The post. Two cells wide inside 12 m so it has some mass when you walk past it. */
column(f, wx(axis, along, postC), wz(axis, along, postC), 0.0, AWN_Y,
G_PIPE, pcol, plum, w < 12 ? 1 : 0);
/* THE AWNING, one bay at a time. It used to be a single run down the whole street and that
* is wrong twice over: it bridged every alley mouth and vacant lot in the block, and a
* fifty-metre span sampled at a fixed rate is coarse near the camera and wasteful far from
* it. Drawn per bay it inherits the frontage test above for free. */
beam(f, axis, along - POST, along, postC, AWN_Y + 0.06, G_EQ,
sun > 0.6 ? P.amber : P.slate, sun > 0.6 ? 96 : 26);
beam(f, axis, along - POST, along, postC, AWN_Y - 0.12, G_DASH, P.shadow, 0);
/* A lantern on one post in three, and never two in a row — a porch light is a thing a
* shopkeeper hangs, not a street lighting scheme. It is the brightest object in the world
* and it is four cells; see the header. */
if (hh < 0.30 && hash2(k + 1, idx * 2 + s, BASE + 0x53) > 0.30) {
var ly = AWN_Y - 0.42;
if (project(wx(axis, along, postC), ly, wz(axis, along, postC))) {
var lx = Math.floor(PJ.x), lr = Math.floor(PJ.y), ld = PJ.d;
/* The flame, then the glass around it. Fog is applied by emit, so a lantern at the far
* end of the street dims with everything else instead of hanging in the dark. */
emit(f, lx, lr, G_o, P.amber, 236, ld);
emit(f, lx, lr - 1, G_DOT, P.warm, 150, ld);
if (ld < 22) {
emit(f, lx + 1, lr, G_TICK, P.warm, 108, ld);
emit(f, lx - 1, lr, G_TICK, P.warm, 108, ld);
}
}
}
}
}
}
/* ================================================================================================
* HITCHING RAILS, TROUGHS, BARRELS — what stands between the veranda and the road.
* ============================================================================================= */
var RAIL_PITCH = 15.0;
function drawStreetProps(f, axis, idx) {
streetSpan(axis, idx);
var pave = paveOf(SPAN.w);
var lo = Math.floor(((axis ? V.ox : V.oz) - 48) / RAIL_PITCH);
var hi = Math.floor(((axis ? V.ox : V.oz) + 48) / RAIL_PITCH);
for (var s = 0; s < 2; s++) {
var face = s ? SPAN.c1 : SPAN.c0, dirIn = s ? -1 : 1;
var sun = litFace(nX(axis, s), nZ(axis, s));
var edge = face + dirIn * (pave + 0.15); // just off the boardwalk, in the road
for (var k = lo; k <= hi; k++) {
var h0 = hash2(k, idx * 2 + s, BASE + 0x61);
if (h0 > 0.62) continue;
var along = k * RAIL_PITCH + h0 * 9;
var w = objVisible(axis, along, edge, 0.8);
if (!w) continue;
if (!frontage(axis, along, 5.2, face, dirIn)) continue;
var kind = hash2(k, idx * 2 + s, BASE + 0x62);
if (kind < 0.52) {
/* A HITCHING RAIL. Two short posts and a bar at 1.05 m — waist height on the figures
* street.js draws, which is what makes it read as furniture rather than as fence. */
var L = 3.6 + kind * 3.2;
column(f, wx(axis, along, edge), wz(axis, along, edge), 0, 1.28, G_PIPE,
sun > 0.6 ? P.amber : P.slate, sun > 0.6 ? 62 : 18, 0);
column(f, wx(axis, along + L, edge), wz(axis, along + L, edge), 0, 1.28, G_PIPE,
sun > 0.6 ? P.amber : P.slate, sun > 0.6 ? 62 : 18, 0);
beam(f, axis, along, along + L, edge, 1.06, G_DASH,
sun > 0.6 ? P.amber : P.slate, sun > 0.6 ? 72 : 20);
} else if (kind < 0.74) {
/* A WATER TROUGH. A dark box with a lit rim, and — the only reason it is worth drawing —
* a surface in it, which is the one horizontal reflector at ground level in a world with
* no wet road. It picks up the sky, so it is ember at dusk and it is the brightest thing
* on the ground. */
var TL = 2.5;
beam(f, axis, along, along + TL, edge, 0.62, G_EQ, sun > 0.6 ? P.white : P.slate,
sun > 0.6 ? 76 : 24);
beam(f, axis, along, along + TL, edge, 0.30, G_HASH, P.shadow, 0);
beam(f, axis, along + 0.15, along + TL - 0.15, edge - dirIn * 0.02, 0.55,
G_TILDE, P.ember, 128);
} else {
/* BARRELS AND CRATES, up on the boardwalk against the wall where a shopkeeper would put
* them. Round ones and square ones, and the difference is one glyph. */
var bc = face + dirIn * 0.55;
for (var b = 0; b < 3; b++) {
var bh = hash2(k * 7 + b, idx * 2 + s, BASE + 0x63);
if (bh > 0.66) continue;
var ba = along + b * 0.95;
if (!objVisible(axis, ba, bc, 0.8)) continue;
var tall = 0.42 + bh * 0.62;
column(f, wx(axis, ba, bc), wz(axis, ba, bc), 0.18, 0.18 + tall,
bh < 0.33 ? G_O : G_HASH, sun > 0.6 ? P.amber : P.slate,
sun > 0.6 ? 56 : 16, 1);
}
}
}
}
}
/* ================================================================================================
* ROOFTOP CROWNS — what breaks the skyline. Reads city.js's `crown`, which the frontier means as
* 0 nothing, 1 chimney, 2 water tank, 3 steeple.
* ============================================================================================= */
function drawCrowns(f) {
var R = 74; // a crown past this is under a cell tall
var gx0 = Math.floor(V.ox - R), gx1 = Math.floor(V.ox + R);
var gz0 = Math.floor(V.oz - R), gz1 = Math.floor(V.oz + R);
/* Walked on a 4 m lattice rather than per cell: a crown belongs to a LOT, and stepping every
* metre over a 148 m square is 22000 height lookups a frame for at most a dozen objects. */
for (var gz = gz0; gz <= gz1; gz += 4) {
for (var gx = gx0; gx <= gx1; gx += 4) {
var h = CITY.height(gx, gz);
if (h < 3) continue;
var rec = CITY.cell(gx, gz);
if (!rec || !rec.crown || rec.rock) continue;
/* One crown per lot, placed at a fixed offset inside it so walking past does not make it
* jump from one cell of the roof to another. */
var cx = rec.lotX + 1.6 + rec.seed * 2.2, cz = rec.lotZ + 1.4 + rec.face * 2.4;
if (Math.abs(cx - gx) > 4 || Math.abs(cz - gz) > 4) continue;
var w = objVisible(0, cz, cx, 2.0);
if (!w) continue;
var sun = litFace(WEST ? WEST.SUN_X : -1, WEST ? WEST.SUN_Z : 0);
var lum = 66, col = P.amber;
if (rec.crown === 1) {
/* A stone chimney and its smoke. The smoke is the only thing in this file that moves,
* and it is the reason a chimney is worth more than the eight cells it costs: a slow
* vertical drift is what tells you the town is inhabited. */
var ch2 = 1.1 + rec.seed * 0.9;
column(f, cx, cz, h, h + ch2, G_HASH, P.slate, 30, 1);
emit2smoke(f, cx, cz, h + ch2, rec);
} else if (rec.crown === 2) {
/* A WATER TANK on legs — four verticals and a drum, and the most recognisable roofline
* object of the period after the false front itself. */
var ty = h + 1.5, td = 1.5 + rec.seed * 0.8;
column(f, cx - 0.7, cz - 0.7, h, ty, G_PIPE, P.slate, 24, 0);
column(f, cx + 0.7, cz - 0.7, h, ty, G_PIPE, P.slate, 24, 0);
column(f, cx - 0.7, cz + 0.7, h, ty, G_PIPE, P.slate, 24, 0);
column(f, cx + 0.7, cz + 0.7, h, ty, G_PIPE, P.slate, 24, 0);
for (var q = 0; q < 5; q++) {
var qx = cx - 0.9 + q * 0.45;
column(f, qx, cz, ty, ty + td, G_0, sun > 0.6 ? P.amber : P.slate,
sun > 0.6 ? 86 : 26, 0);
}
beam(f, 0, cz - 1.0, cz + 1.0, cx, ty + td, G_EQ, P.amber, 96);
} else {
/* A STEEPLE, or a windmill — the two things out here that are taller than anything else
* and the only reason the eye ever goes above the second storey. Both are a thin shaft
* with something on top; the roll decides which. */
var mill = rec.seed > 0.55;
var sy = h + 2.2 + rec.face * 3.4;
column(f, cx, cz, h, sy, G_PIPE, sun > 0.6 ? P.amber : P.slate, sun > 0.6 ? 72 : 22, 0);
if (mill) {
/* ---- THE WHEEL, AND WHY IT DOES NOT TURN THE WAY IT FIRST DID ---------------------
* A rotating windmill is the single most dangerous object either world has ever
* contained, and it failed tools/west-flicker.cjs on the first run: eight spokes drawn
* at lum 5 sweeping across sky cells at lum 189 chopped those cells at 4.7 big steps a
* second, against a limit of 1.0 — a dark blade crossing a bright background at a few
* hertz is the textbook photosensitive trigger, and it is exactly what a real farm
* windmill does.
*
* The fix is not to slow it down. A blade-crossing rate low enough to be safe is far
* below what reads as a turning wheel, so the wheel would have to look wrong to be
* safe. What is drawn instead is a STATIC RIM — twelve cells that are always painted,
* so no cell of it ever alternates with the sky behind it — and one bright vane
* travelling round that rim. The motion is carried entirely by the glint, whose step is
* held under the third-of-full-scale line (54 to 128, i.e. 29%) and which visits any
* one rim cell about once every ten seconds.
*
* At the distance a windmill is ever seen here the wheel is five cells across, so a
* disc with a moving highlight and a spoked wheel are the same picture anyway. */
if (project(cx, sy, cz)) {
var mx = Math.floor(PJ.x), my = Math.floor(PJ.y), md = PJ.d;
for (var b2 = 0; b2 < 12; b2++) {
var an = b2 * Math.PI / 6;
emit(f, mx + Math.round(Math.cos(an) * 2.2), my + Math.round(Math.sin(an) * 1.2),
G_PLUS, P.slate, 54, md);
}
emit(f, mx, my, G_O, P.amber, 120, md);
var sp = CC.reducedMotion ? 0.9 : V.t * 0.5 * (0.3 + 0.5 * W_WIND);
emit(f, mx + Math.round(Math.cos(sp) * 2.2), my + Math.round(Math.sin(sp) * 1.2),
G_STAR, P.amber, 128, md);
}
} else {
/* A bell tower: a taper and a cross. */
column(f, cx, cz, sy, sy + 1.2, G_CARET, P.white, 84, 0);
if (project(cx, sy + 1.5, cz))
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), G_PLUS, P.amber, 148, PJ.d);
}
}
}
}
}
/* Chimney smoke — a CONTINUOUS plume, not a string of puffs, and the difference is a
* photosensitivity fix as much as a look.
*
* Five discrete puffs on a phase cycle put five dark cells travelling up through the brightest
* part of the sky, and a dark object crossing a bright cell is a step: measured at lum 5 against
* a lum 189 sunset, which is 72% of full scale, several times a second on any cell under the
* plume. Sampling the same path densely instead means the cells the plume occupies are occupied
* CONTINUOUSLY — the plume is a shape that leans, not a sequence of things that arrive — and a
* given cell changes only when the lean carries the edge across it, which happens at the sway's
* own rate of about a third of a hertz.
*
* It is also drawn far brighter than the first cut. Wood smoke at this hour is lit from the side
* by the same sun everything else is; it is a pale grey-orange column, not a black one, and
* painting it dark was both wrong and the whole reason the step was large.
*
* Pure in t, so it scrubs. */
function emit2smoke(f, cx, cz, y0, rec) {
var lean = 1.5 * W_WIND;
var tt = CC.reducedMotion ? 4.0 : V.t;
var sway = vnoise(tt * 0.33 + rec.seed * 7, 0x2A) - 0.5;
var N = 16;
for (var i = 0; i < N; i++) {
var u = i / (N - 1);
var yy = y0 + 0.15 + u * 3.8;
/* Leans downwind as it rises, and the lean itself drifts. u*u so the base is vertical and
* the top is where the wind has had time to work on it. */
var dx = (lean * u * u + sway * 0.9 * u) * 1.6;
if (!project(cx + dx, yy, cz + dx * 0.35)) continue;
/* Thins with height, and the fade is smooth so the top of the plume dissolves rather than
* ending. slate at 46-104 against a sky that runs 120-200: a soft column, and a step of
* under a third of full scale wherever the edge does move. */
var lum = 104 * (1 - u) * (1 - u * 0.5);
if (lum < 6) continue;
emit(f, Math.floor(PJ.x), Math.floor(PJ.y), u < 0.35 ? G_HASH : (u < 0.7 ? G_COLON : G_DOT),
P.slate, lum, PJ.d);
}
}
/* ---- which streets to draw ------------------------------------------------------------------ */
function nearIdx(axis) {
return Math.round((axis ? V.oz : V.ox) / (axis ? CITY.CROSS : CITY.AVE));
}
function eachStreet(f, fn) {
var i;
for (i = -1; i <= 1; i++) fn(f, 0, nearIdx(0) + i);
for (i = -1; i <= 1; i++) fn(f, 1, nearIdx(1) + i);
}
function mk(name, layer, fn) {
return {
name: name, layer: layer, world: 'west',
init: function (city) { boot(city); },
draw: function (f, cam, t) {
if (!CITY) return;
view(f, cam, t === undefined ? (cam.t || 0) : t);
fn(f);
}
};
}
/* 17 street props, 18 verandas, 21 crowns — under the pedestrians at 20 for the props that share
* the pavement with them, and the crowns are up on the roofs where nothing else goes. */
CC.ELEMENTS.push(mk('west-props', 17, function (f) { eachStreet(f, drawStreetProps); }));
CC.ELEMENTS.push(mk('west-veranda', 18, function (f) { eachStreet(f, drawVeranda); }));
CC.ELEMENTS.push(mk('west-crowns', 21, drawCrowns));
})(typeof CC !== 'undefined' ? CC : require('../core.js'));

View file

@ -25,8 +25,34 @@
* A city is a pure function of its seed, so the fragment IS the artwork's address. Anything that * 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 * is not an integer is folded with FNV-1a, which means #shinjuku is a perfectly good city and
* people can name their own. */ * people can name their own. */
/* ---- world in the fragment -------------------------------------------------------------------
* The address of a place is now WHICH WORLD and WHICH SEED, and the old form has to keep working
* because it is the form that has been sent to people: `#42` is city 42 and always will be. A
* world other than the default prefixes itself — `#west/42` — which is a URL somebody can also
* type from memory, and which reads as a path rather than as a query because that is what it is.
*
* Returns the world id, or null for "the fragment did not say", which the boot path distinguishes
* from "the fragment said cyber": neither changes anything today, but a third world added later
* must not silently inherit whatever was live. */
function worldFromHash() {
var h = (window.location.hash || '').replace(/^#/, '').trim();
var i = h.indexOf('/');
/* NO PREFIX MEANS THE DEFAULT WORLD, not "the fragment did not say", and the difference is a
* real bug that only shows on a navigation. `#42` addresses the city — that is the whole point
* of fragment() omitting the prefix for LIST[0] — so returning null here made the hashchange
* handler read "no opinion" and leave a viewer standing on the frontier while the URL in front
* of them said otherwise. Going from #west/42 to #42 by editing the address bar, or by a back
* button, did nothing at all. */
if (i < 0) return CC.World ? CC.World.DEFAULT : 'cyber';
var w = CC.World && CC.World.at(h.slice(0, i));
return w ? w.id : null;
}
function seedFromHash() { function seedFromHash() {
var h = (window.location.hash || '').replace(/^#/, '').replace(/^seed=/, '').trim(); var h = (window.location.hash || '').replace(/^#/, '').trim();
var sl = h.indexOf('/');
if (sl >= 0) h = h.slice(sl + 1);
h = h.replace(/^seed=/, '').trim();
if (!h) return null; // null, not 0 — #0 is a legitimate city 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 /* 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 * #-1 keeps working, unsigned at the top because that is the form replaceState writes and a
@ -42,6 +68,17 @@
return s >>> 0; return s >>> 0;
} }
/* The fragment, written from the two facts that make it. One function, because there were three
* call sites writing '#' + seed by hand and a world that only two of them knew about is a link
* that takes the reader somewhere else. */
function fragment(w, sd) {
return '#' + (w && w !== CC.World.DEFAULT ? w + '/' : '') + (sd >>> 0);
}
function writeFragment() {
if (window.history && history.replaceState)
history.replaceState(null, '', fragment(CC.World ? CC.World.id : 'cyber', seed));
}
/* ---- viewport ------------------------------------------------------------------------------ /* ---- viewport ------------------------------------------------------------------------------
* Showing LESS city on a small screen is the correct answer; shrinking the cell until the glyphs * 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 * turn to grey mush is not, because the glyph shapes ARE the texture. So the cell width is
@ -100,6 +137,11 @@
cam.z = city && city.startZ !== undefined ? city.startZ : 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 /* 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. */ * the element stream below, so adding it did not reshuffle every element's noise. */
/* THE CLOCK IS INITIALISED BEFORE THE WEATHER AND BEFORE EVERY ELEMENT, because both of those
* read it: an element's init() may size itself to the hour, and the weather director's first
* update happens under whatever sky the clock says. Unlike the weather it is NOT reset by a
* rebuild — see daylight.js's init — so pressing 2 at noon puts you on the frontier at noon. */
if (CC.Daylight) CC.Daylight.init(city);
if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635)); if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635));
if (CC.Control) CC.Control.reset(); if (CC.Control) CC.Control.reset();
var rng = CC.mulberry(seed ^ 0x9e3779b9); var rng = CC.mulberry(seed ^ 0x9e3779b9);
@ -120,7 +162,16 @@
* tools/headless.cjs in the same edit: the harness sorts CC.ELEMENTS itself, and a harness * 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 * ordering elements differently from the browser is an offline reference frame that is not
* the frame the browser draws. */ * the frame the browser draws. */
var seq = CC.ELEMENTS, rank = [], q; /* THE WORLD GATE, and it happens BEFORE the sort for the reason the tie-break note below
* spells out: every element pulls from one shared rng in layer order, so which elements are
* present decides what every later element's noise stream is. Filtering after the sort would
* give the same answer here and a different one the day someone reorders the filter. An
* element with no `world` belongs to both — see src/world.js. */
var live = CC.World ? CC.World.id : 'cyber';
var seq = [], q;
for (q = 0; q < CC.ELEMENTS.length; q++)
if (CC.inWorld(CC.ELEMENTS[q], live)) seq.push(CC.ELEMENTS[q]);
var rank = [];
for (q = 0; q < seq.length; q++) rank.push(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); }); rank.sort(function (a, b) { return ((seq[a].layer | 0) - (seq[b].layer | 0)) || (a - b); });
els = []; els = [];
@ -142,7 +193,9 @@
* INSTANCE that make() returns. Guarding on the module put the whole piece in a chair: 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 * camera was placed once in build() and never moved again, so a browser showed one still
* frame with rain falling on it. */ * frame with rain falling on it. */
/* Weather first — an element updating this tick must see this tick's sky, not last tick's. */ /* Clock first, then weather: an element updating this tick must see this tick's sky, not last
* tick's, and the weather is read against the hour rather than the other way round. */
if (CC.Daylight) CC.Daylight.update(dt, t);
if (CC.Weather) CC.Weather.update(dt, t); if (CC.Weather) CC.Weather.update(dt, t);
/* Through CC.Control, which arbitrates between the autopilot and whoever is holding the keys. /* 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 * With nothing attached and nothing pressed it delegates straight to city.camera, so the walk
@ -276,6 +329,10 @@
CC.Canvas.init(canvas); CC.Canvas.init(canvas);
layout(); layout();
/* World first, seed second, and in that order because city.js resolves CC.World inside make():
* building the city and then setting the world gives a frontier flag over a city map. */
var w0 = worldFromHash();
if (w0 && CC.World) CC.World.force(w0);
var s = seedFromHash(); var s = seedFromHash();
/* === null, not !s. seedFromHash already distinguishes "no fragment" (null) from "#0", and /* === 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 * testing falsiness threw that distinction away: #0 built a RANDOM city and then replaceState
@ -284,7 +341,8 @@
s = (Math.random() * 4294967296) >>> 0; s = (Math.random() * 4294967296) >>> 0;
/* replaceState, not location.hash: writing the hash directly would push a history entry and /* replaceState, not location.hash: writing the hash directly would push a history entry and
* fire hashchange, rebuilding the city we are about to build. */ * fire hashchange, rebuilding the city we are about to build. */
if (window.history && history.replaceState) history.replaceState(null, '', '#' + s); seed = s;
writeFragment();
} }
build(s); build(s);
@ -295,8 +353,15 @@
// that DID go fullscreen would keep drawing at the old grid until something else resized it. // that DID go fullscreen would keep drawing at the old grid until something else resized it.
document.addEventListener('webkitfullscreenchange', onResize); document.addEventListener('webkitfullscreenchange', onResize);
window.addEventListener('hashchange', function () { window.addEventListener('hashchange', function () {
var ns = seedFromHash(); /* Two facts can have moved, and a world change with the SAME seed is still a move — which is
if (ns !== null && ns !== seed) build(ns); // same reason: navigating to #0 is a real move * why the seed test alone is no longer enough to decide whether to rebuild. force(), not
* set(): set() would fire the change callback and rebuild, and then this would rebuild
* again on the next line. */
var nw = worldFromHash(), ns = seedFromHash();
var moved = 0;
if (nw && CC.World && nw !== CC.World.id) { CC.World.force(nw); moved = 1; }
if (ns !== null && ns !== seed) moved = 1; // same reason: navigating to #0 is a real move
if (moved) build(ns === null ? seed : ns);
}); });
window.addEventListener('pointerdown', goFullscreen, { passive: true }); window.addEventListener('pointerdown', goFullscreen, { passive: true });
window.addEventListener('keydown', function (e) { window.addEventListener('keydown', function (e) {
@ -312,9 +377,22 @@
fullscreen: goFullscreen, fullscreen: goFullscreen,
reseed: function () { reseed: function () {
var ns = (Math.random() * 4294967296) >>> 0; var ns = (Math.random() * 4294967296) >>> 0;
if (window.history && history.replaceState) history.replaceState(null, '', '#' + ns); seed = ns;
writeFragment();
build(ns); build(ns);
} },
/* WORLD SWITCH. The seed is kept: #42 is a place in every world, and pressing 2 is
* therefore "show me this seed as the frontier" rather than "take me somewhere random".
* That is the whole reason the switch is worth having on a key — the two worlds share
* their street lattice indices, so the same number puts you on the same corner of the
* same map with a different town built on it. */
world: function (v) {
if (!CC.World || !CC.World.set(v)) return 0;
writeFragment();
build(seed);
return 1;
},
worldName: function () { return CC.World ? CC.World.name : ''; }
}); });
/* Pointer lock is a mouse-look, and a mouse-look nobody asked for is a trap: it is only /* 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. */ * requested on a real click, which is also the gesture that goes fullscreen. */

124
src/proj.js Normal file
View file

@ -0,0 +1,124 @@
/* CyberCity element projection — the one copy of the camera the world-space elements share.
*
* WHY THIS FILE EXISTS AT ALL, and it is two reasons, one of which is the important one.
*
* THE CHEAP REASON is bytes. Six element files draw objects in world space — the frontier's
* veranda, props, brush, telegraph, desert and livestock, and Moonwalk's ground and hardware — and
* every one of them was written by copying the previous one, so every one carried its own byte-
* identical copy of the same view/project/emit/column pair. Measured across the four frontier files
* alone that is about 14 KB of the shipped bundle, against a budget build.js has now had to raise
* three times. This is the cut that note asks the next pass to take before it edits the line again.
*
* THE IMPORTANT REASON is that six copies of a projection which MUST match src/raycast.js exactly
* is six places for it to stop matching. The comment those copies all carry says so out loud —
* "elements are handed `cam` and nothing else, and a projection that disagrees with the caster by
* one term puts a stall through the wall it is standing against" — and the way that goes wrong is
* never a crash. It is one file quietly keeping an old term after the caster changes: objects in
* one element sink half a metre into the ground and nothing anywhere reports it. One copy can be
* wrong; it cannot be inconsistent.
*
* WHAT IT IS NOT. It is not a scene graph and it does not own anything. `make()` hands back a small
* record with a per-element basis in it and four functions closed over that basis, because two
* elements drawing in the same frame need two bases — the pedestrians retire on screen area and
* the brush does not, and both have to be able to hold their own `far`. Nothing here allocates
* after init: the basis and the projection scratch are each made once per element, for the life of
* the page.
*/
(function (CC) {
'use strict';
var put = CC.put, clamp = CC.clamp;
CC.Proj = {
/* One per element. The returned object is held for the life of the page; view() refills it in
* place at the top of every draw. */
make: function () {
/* Mirrors raycast.js, exactly. Planar camera: w is the perpendicular distance and the
* projection divisor, and the radial distance the depth test wants is w*sqrt(1+sp^2). */
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
};
var PJ = { x: 0, y: 0, d: 0 };
var Surf = null;
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;
return V;
}
/* Continuous cell coordinates: column i covers [i, i+1). The caller floors; this returns the
* real number so a caller that wants a sub-cell position can have one. */
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 the world pass has already fogged its own
* cells; an unfogged object at 40 m would read nearer than the wall behind it. A cell fogged
* to nothing is still written: it is unlit mass in front of something, and that occlusion is
* most of what these files contribute. */
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);
}
/* A vertical. Every post, leg, pole and trunk goes through here: it projects the two ENDS and
* fills between them, which is the only way to get a vertical that stays one cell wide and
* does not shear as the camera pans — sampling world points up the post and projecting each
* one separately puts them in different columns whenever the post is off-axis. */
function column(f, px, pz, y0, y1, ch, col, lum, wide) {
if (!project(px, y0, pz)) return;
var x = Math.floor(PJ.x), yb = PJ.y, d = PJ.d;
if (x < -2 || x >= V.cols + 2) return;
if (!project(px, y1, pz)) return;
var yt = PJ.y;
if (yt > yb) { var s = yt; yt = yb; yb = s; }
var r0 = Math.floor(yt), r1 = Math.floor(yb);
if (r1 - r0 > V.rows) r1 = r0 + V.rows;
for (var r = r0; r <= r1; r++) {
emit(f, x, r, ch, col, lum, d);
if (wide) emit(f, x + 1, r, ch, col, lum, d);
}
}
/* How lit a face pointing (nx, nz) is, against whichever painter owns the live world. It
* lives here rather than in each element because a post and the wall behind it disagreeing
* about where the light is coming from is the most visible possible error, and it happened
* once already when the sun stopped being a constant. */
function litFace(nx, nz) {
var W = CC.SURFACES && CC.World ? CC.SURFACES[CC.World.id] : null;
if (!W || W.SUN_X === undefined) return 0.5;
var d = nx * W.SUN_X + nz * W.SUN_Z;
var k = clamp(0.5 + 0.62 * d, 0, 1);
return 0.10 + 0.90 * k * k * (3 - 2 * k);
}
return { V: V, PJ: PJ, view: view, project: project, emit: emit,
column: column, litFace: litFace };
}
};
if (typeof module !== 'undefined') module.exports = CC.Proj;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -14,7 +14,7 @@
'use strict'; 'use strict';
var P = CC.P, poke = CC.poke, hash2 = CC.hash2, vnoise = CC.vnoise; var P = CC.P, poke = CC.poke, hash2 = CC.hash2, vnoise = CC.vnoise;
var G_COLON = CC.g(':'); var G_COLON = CC.g(':'), G_DASH = CC.g('-');
/* city.js can emit 58+46 for a landmark. The far-cutoff below must never UNDER-estimate this or /* 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. */ * a tower is dropped from the skyline the instant a nearer roof lifts the silhouette. */
@ -41,7 +41,13 @@
* different heights and the memo would hand the podium the tower's parapet. surfaces.js needs it * 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 * 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. */ * 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 }; /* `faceX` and `side` are set after bindCell alongside `h`, and for the same reason: they are
* properties of the HIT, not of the building, so the memo must not cache them. They say which of
* the cell's four walls the ray crossed, which is dead weight in the city — its light comes from
* the street and every face is lit the same — and is the entire lighting model of the frontier,
* where a single low sun means one side of the road is amber and the other is a silhouette.
* Two stores per wall hit, on a path that already does one. */
var SC = { seed: 0, style: 0, litRate: 0.3, accent: 0, hue: undefined, h: 0, faceX: 1, side: 1 };
var scRec = null; var scRec = null;
function bindCell(rec) { function bindCell(rec) {
if (rec !== scRec) { if (rec !== scRec) {
@ -77,10 +83,32 @@
if (seg > 0.72) return sgset(0, P.shadow, 0); if (seg > 0.72) return sgset(0, P.shadow, 0);
} }
var sd = (s.seed * 4294967296) | 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. /* 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. */ * Any camera term in here and the signage boils as you walk. On a painted board the same term
* is the lamp under it guttering, which is the same 14% and reads correctly as either. */
var pulse = CC.reducedMotion ? 0.93 : 0.86 + 0.14 * vnoise(t * 0.7 + s.seed * 40, 0x51); var pulse = CC.reducedMotion ? 0.93 : 0.86 + 0.14 * vnoise(t * 0.7 + s.seed * 40, 0x51);
/* ---- a PAINTED BOARD, not a lit panel ---------------------------------------------------
* city.js's frontier signs carry `board`, and they are the opposite object to a neon sign in
* the one way that matters here: a neon sign IS the light, so filling its whole box with a lit
* glyph is correct, and a board is a dark plank with a few letters painted on it. Filling a
* 5x2 m board the neon way put a solid white rectangle the size of a shopfront in the middle
* of the frame — measured at seed 42 it was the largest single object in the picture.
*
* So the box is mostly plank: a sparse slate grain at lum 16, which reads as timber and still
* occludes the wall behind it. The LETTERING is a coarse lattice inside the middle band, about
* 40% covered, and it is the only bright thing here. Two hashes on the same lattice, because
* the letters and the grain must not be able to occupy the same cell. */
if (s.board) {
var lu = Math.floor(du * 2.9), lv = Math.floor(dv * 3.4);
var ink = hash2(lu, lv, sd ^ 0x2C1D);
if (dv > s.h * 0.24 && dv < s.h * 0.80 && ink < 0.46)
return sgset(s.glyph, s.hue, (148 + ink * 220) * pulse);
return hash2(lu, lv, sd ^ 0x5D33) < 0.34 ? sgset(G_DASH, P.slate, 16)
: sgset(0, P.shadow, 0);
}
var h = hash2(Math.floor(du * 2.4), Math.floor(dv * 2.4), sd);
return sgset(s.glyph, s.hue, (172 + h * 66) * (h < 0.10 ? 0.3 : 1) * pulse); return sgset(s.glyph, s.hue, (172 + h * 66) * (h < 0.10 ? 0.3 : 1) * pulse);
} }
@ -108,7 +136,7 @@
* fixed and known, so there is no reason to hand the collector a fresh one sixty times a second. * 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. */ * configure() copies these into CFG, so the scratch is never retained. */
var CFGARG = { grid: 8.0, streetX: 4.0, streetPeriod: 0, half: 3.1, var CFGARG = { grid: 8.0, streetX: 4.0, streetPeriod: 0, half: 3.1,
horizon: 33.6, rows: 60, skyVScale: 1 }; horizon: 33.6, rows: 60, skyVScale: 1, skyK: 1, swap: 0 };
/* One neutral-camera row, in the elevation units Surf.sky hashes on. cellAspect/2/tan(fov/2) at /* 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 * 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 * out gives 1.0 whenever the camera is at that fov and grows as it zooms in — which is what
@ -149,11 +177,17 @@
/* streetPeriod 0 disables the wrap: we know the real centreline, and a wrapped copy of the /* 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. */ * 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.grid = 8.0; CFGARG.streetX = cx; CFGARG.streetPeriod = 0; CFGARG.half = hw;
CFGARG.swap = swapFloor;
CFGARG.horizon = horizon; CFGARG.rows = rows; CFGARG.horizon = horizon; CFGARG.rows = rows;
/* Surf.sky hashes its vertical on an ELEVATION, and only the caster knows the projection that /* 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 * 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. */ * 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; CFGARG.skyVScale = (scale > 0 && cols > 0) ? (SKY_NEUTRAL * cols) / scale : 1;
/* The horizontal counterpart, and the same deal: sky() is handed an index, and only the caster
* knows how many of them there are to a radian. surf_west.js turns it back into a bearing so
* the sunset stays in the west while the viewer turns round. Kept in step with skyK below by
* being derived from the same expression. */
CFGARG.skyK = cols > 0 ? cols / 1.25 : 1;
CC.Surf.configure(CFGARG); CC.Surf.configure(CFGARG);
loadCrossings(city, camx, camz); loadCrossings(city, camx, camz);
} }
@ -414,7 +448,7 @@
var u = faceX ? (oz + dz * w) : (ox + dx * w); var u = faceX ? (oz + dz * w) : (ox + dx * w);
var rec = city.cell(cx, cz); var rec = city.cell(cx, cz);
var sc = rec ? bindCell(rec) : null; var sc = rec ? bindCell(rec) : null;
if (sc) sc.h = h; if (sc) { sc.h = h; sc.faceX = faceX; sc.side = faceX ? sX : sZ; }
var sign = rec && rec.sign; var sign = rec && rec.sign;
for (var r = sil - 1; r >= r0; r--) { for (var r = sil - 1; r >= r0; r--) {

1022
src/surf_moon.js Normal file

File diff suppressed because it is too large Load diff

902
src/surf_west.js Normal file
View file

@ -0,0 +1,902 @@
/* CyberCity frontier surfaces — the texture layer for the west, and the counterpart of
* surfaces.js in every respect: same three entry points, same signatures, same output records,
* same rule that nothing here may know about the camera. surfaces.js delegates to this file when
* CC.World says west, which is why it does not re-implement fog(), configure() or cfg — those are
* facts about a street and a print, not about a century, and both worlds share them.
*
* ---- THE HOUR, and it decides everything below --------------------------------------------------
* It is the last twenty minutes of light. The sun is on or just under the horizon in the -x
* direction and nothing in this world emits except lamps in windows, so the picture is built out
* of exactly two things: which surfaces the low sun still reaches, and which do not.
*
* That is a choice with a reason. A frontier town at HIGH NOON is the postcard, and it is
* unrenderable here: core.js prints a frame whose art direction is 55%+ pure black with a thin
* scatter of bright glyphs, and a noon desert is the exact inverse — a full field of mid-tone with
* no black in it at all. Every constant in the print, the bloom and the eleven optics passes is
* fitted to the first picture, and the second one would come out of them as flat grey mush. Dusk
* is the hour that is genuinely both: black ground, black timber, a sky with all the light in the
* frame in it, and a hard warm rim down the west face of every building on the street. The whole
* of this file is that one sentence, spent.
*
* ---- WHAT THE PALETTE IS ALLOWED TO DO ----------------------------------------------------------
* No azure and no violet on any SURFACE. Both read as emitted light — they are the screen and the
* tube, and they are what makes the city look like the city. Out here they appear in the sky and
* nowhere else, azure as the cold top of the dome and violet as the earth-shadow band that sits
* over the sunset for about ten minutes of real dusk and is the best thing in it.
*
* The working swatches are therefore amber (sunlit timber, the hot core of the sunset), ember
* (dirt, rust, adobe, the sunset band), warm (lamplight through glass), white (planed board,
* bone, dust), slate (everything the sun has left) and red (paint, the last of the sun on a high
* rock). core.js's EXPOSURE weights matter here more than they do in the city, because the west
* is drawing on the LOW half of that ladder: amber 0.50 and slate 0.60 are the only two weights
* over 0.42 in the warm/neutral half, so those two carry the frame and everything else is a
* garnish on them. Painting a whole dirt road in warm (0.32) is how you get a picture that is
* correct and invisible.
*/
(function (CC) {
'use strict';
var P = CC.P, g = CC.g, hash2 = CC.hash2, clamp = CC.clamp, vnoise = CC.vnoise;
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_TILDE = g('~'),
G_PIPE = g('|'), G_SLASH = g('/'), G_PCT = g('%'), G_AMP = g('&'), G_8 = g('8'),
G_0 = g('0'), G_o = g('o');
/* The one thing this file and surfaces.js MUST agree on, because raycast.js configures only one
* of them: the config block. Resolved lazily rather than captured, so load order cannot bite. */
function cfg() { return CC.Surf ? CC.Surf.cfg : null; }
/* ---- the sun ---------------------------------------------------------------------------------
* A bearing in the same convention as everything else in the project: yaw 0 faces +z, so the
* direction of bearing b is (sin b, cos b) and -PI/2 is straight down -x. It is a CONSTANT and
* not a function of seed or time, and that is deliberate on both counts. Seeded, two cities on
* neighbouring seeds would light from different sides and the piece would lose the one thing
* that makes a low sun read as a low sun — that it is in the same place in every frame you have
* ever seen of the place. Animated, the whole world would have to re-decide which side of the
* street is lit, and every element that reads SUN would have to be told; dusk is twenty minutes
* and this walk is shorter than that. */
/* -0.5 rad, and the exact number is a composition rather than a preference. city.js runs its
* avenues along +z and the walk spends most of its time on one, so the sun's bearing decides
* three things at once and they have to be traded against each other:
*
* at 0 the sun sits dead centre at the end of every avenue, which is the postcard — and it
* flattens the town, because both walls of the street then face the sun equally and the one
* effect worth having, a lit side and a dark side, disappears;
*
* at -PI/2 the sun is square on to the street, the lit/dark split is at its strongest, and the
* sunset is 90 degrees off the walk — never in frame, since the fov is 1.25 rad;
*
* at -0.5 it is 29 degrees off the axis, comfortably inside the 36-degree half-fov, so the burn
* is in the left of the frame while the right-hand row of buildings takes the light and the
* left-hand row goes to silhouette. That is the shot.
*/
var SUN_AZ = -0.5;
var SUN_X = Math.sin(SUN_AZ), SUN_Z = Math.cos(SUN_AZ), SUN_ALT = 0.16;
/* ---- the sun moves now ------------------------------------------------------------------------
* The paragraph this replaced argued that the bearing must NOT be animated — "the whole world
* would have to re-decide which side of the street is lit, and every element that reads SUN would
* have to be told; dusk is twenty minutes and this walk is shorter than that". Both halves of
* that were true and neither is any more. The world now HAS a clock, and re-deciding which side
* of the street is lit as the day turns is not a cost of the feature, it is the feature: a
* shadow that swings from one side of the road to the other over seven minutes is the single
* most legible thing a day/night cycle can do in a frame made of characters.
*
* The five readers were told, and they were told in one place. west_town.js's litFace,
* west_range.js's litFace, west_sky.js's sunAz and the two inside this file all go through
* SUN_X/SUN_Z/SUN_AZ, which are now module variables refreshed once per frame from CC.Daylight
* rather than constants — and they are re-exported as GETTERS, so every one of those call sites
* kept working without being edited. */
function dayAt(t) {
if (t === dT) return;
dT = t;
var D = CC.Daylight;
if (!D) return; // standalone require: hold the tuned dusk
SUN_AZ = D.P.az; SUN_ALT = D.P.alt;
SUN_X = Math.sin(SUN_AZ); SUN_Z = Math.cos(SUN_AZ);
dSun = D.P.sun; dSky = D.P.sky; dWarm = D.P.warm; dLamp = D.P.lamp; dStar = D.P.star;
}
var dT = 1 / 0, dSun = 0.64, dSky = 0.66, dWarm = 0.74, dLamp = 1, dStar = 0;
function dAlt() { return SUN_ALT; }
/* How much of the last light a face gets, by which way it points. CONTINUOUS rather than three
* buckets, and that is a repair rather than a refinement: with the sun off-axis the two street
* walls sit at +-0.48 of the sun vector, so a three-bucket version with its thresholds at +-0.5
* put BOTH of them in the middle bucket and the lit/dark split that the whole angle was chosen
* for did not happen at all. The curve is deliberately steep at the middle (the 0.62 slope
* pushes +-0.48 apart to 0.20 and 0.80) and it never reaches zero: an unlit face is 10% lit, not
* black, because a wall with nothing on it whatsoever stops reading as a wall and becomes a hole
* in the frame.
*
* ---- AND NOW IT HAS AN ELEVATION TERM, which is what turns a fixed dusk into a day ------------
* Three things change with the sun's height and all three are what the eye reads a time of day
* off:
* the AZIMUTH SPLIT COLLAPSES toward noon. At 54 degrees up the light comes from above rather
* than from the side, so both walls of a street are lit and the difference between them is
* small — which is exactly why noon is the least interesting hour and why ALT_MAX is 54 and
* not 90. `split` runs 1 at the horizon to 0.35 overhead.
* the WHOLE LEVEL follows the sun. `dSun` is 0 at night, so at night this returns nothing but
* the ambient floor and the town is lit by its lamps alone, which is the correct picture and
* the one this world never had.
* the AMBIENT FLOOR is the SKY, not a constant. At noon a shadowed wall is filled by a very
* bright hemisphere and is nowhere near black; at midnight there is nothing to fill it with.
* That floor is what stops a daylight frame reading as cut-out paper. */
var SUN_FRONT = 1.00, SUN_BACK = 0.10, SUN_SIDE = 0.42;
function sunOf(cell) {
/* THE AMBIENT FLOOR IS THE SKY, and it is deliberately mean. A shadow at noon under a bright
* hemisphere is filled — that is what stops a daylight frame reading as cut-out paper — but the
* first cut put the floor at 0.36 at noon and the consequence was that NOTHING in a midday
* frame was dark: every surface sat inside a stop of every other and the picture came out as
* one field of mid-tone, which the print counts as 55% muddy. Halving it puts the shadow side
* of the street back under the lit side by a factor of three, which is roughly what a
* photograph of a sunlit street shows and is the difference between a picture with modelling
* in it and a texture. */
var floor = 0.05 + 0.16 * dSky;
if (!cell || cell.faceX === undefined) return floor + (SUN_SIDE - 0.10) * dSun;
/* The face crossed by a ray stepping +side has its outward normal pointing -side. */
var nx = cell.faceX ? -cell.side : 0, nz = cell.faceX ? 0 : -cell.side;
var d = nx * SUN_X + nz * SUN_Z;
var split = 1 - 0.65 * clamp(SUN_ALT / 0.95, 0, 1);
var f = clamp(0.5 + 0.62 * d * split, 0, 1);
/* THE SQUARE ROOT IS THE DIFFERENCE BETWEEN A LIGHT LEVEL AND A LIT SURFACE. `dSun` is how much
* direct light there IS, which falls to 0.64 at the golden hour — and scaling a surface by it
* linearly made the frontier's best hour a third darker than the fixed dusk this world was
* originally tuned as. A surface's apparent brightness is not linear in illuminance and the
* eye's is less linear still; sqrt puts 0.64 back at 0.80 and leaves 0 at 0, which keeps the
* night honest while giving the tuned hour its look back. */
var direct = (SUN_FRONT - SUN_BACK) * f * f * (3 - 2 * f) * Math.sqrt(dSun);
/* A roof-facing surface takes the sun almost regardless of bearing once it is high; a wall
* takes the cosine. The 0.42 is the share of the vertical component a vertical face keeps. */
return clamp(floor + direct * (0.42 + 0.58 * (1 - clamp(SUN_ALT / 0.95, 0, 1))) +
dSun * 0.34 * clamp(SUN_ALT / 0.95, 0, 1), 0, 1.25);
}
/* ---- weather, sampled once per frame ---------------------------------------------------------
* Same cache-on-t trick and the same rel() migration rule as surfaces.js: 1.0 is the look the
* build was tuned under, so a constant multiplied by rel('wet') keeps its value until the
* weather actually moves. `dust` has no equivalent in the city and is read raw off P.haze,
* because there is no reference value for it to be relative to — the frontier invented it. */
var wT = 1 / 0, wWet = 1, wRain = 1, wWind = 1, wDust = 0.3, wCloud = 0.1;
function weatherAt(t) {
if (t === wT) return;
wT = t;
var W = CC.Weather;
if (!W) return;
wWet = W.rel('wet'); wRain = W.rel('rain'); wWind = W.rel('wind');
wDust = W.P.haze; wCloud = W.P.cloud;
}
/* ---- cell metadata, defensively --------------------------------------------------------------
* Same contract as surfaces.js: city.js owns the record, this file must degrade rather than
* throw on a field that is not there. */
function seedOf(cell) {
if (!cell || typeof cell !== 'object') return 0;
if (cell.seed !== undefined) return cell.seed | 0;
return 0;
}
/* ---- what a wall is made of ------------------------------------------------------------------
* Indexed by the style city.js rolled. `lap` is the board pitch in metres and it is the single
* most visible number in the file: it is the rhythm the eye reads a timber wall by, and at 0.34
* a two-storey front carries about twenty lines, which is what a photograph of one has.
*
* `bay` is the frontage each opening owns. A frontier storefront is ONE door and ONE big window
* in 4-6 m, against the city's punched grid at 2-4 — the openings are fewer, bigger and lower,
* and that proportion is most of what says "1880" rather than "2080".
*
* `rough` turns the boards off: adobe and fieldstone are not clad, they are mottled, so those
* two draw a noise field instead of a rhythm and get their own glyph set. */
var STYLE_W = [
/* 0 clapboard */ { lap: 0.34, bay: 4.4, gnd: 2.90, up: 2.55, winW: 1.05, winH: 1.35,
shopW: 2.30, shopH: 1.75, rough: 0, vert: 0 },
/* 1 batten */ { lap: 0.62, bay: 5.2, gnd: 3.20, up: 2.70, winW: 0.90, winH: 1.20,
shopW: 1.90, shopH: 1.60, rough: 0, vert: 1 },
/* 2 falsefront */ { lap: 0.28, bay: 4.0, gnd: 3.05, up: 2.60, winW: 1.20, winH: 1.50,
shopW: 2.60, shopH: 1.95, rough: 0, vert: 0 },
/* 3 adobe */ { lap: 0.90, bay: 5.0, gnd: 2.60, up: 2.30, winW: 0.75, winH: 0.95,
shopW: 1.10, shopH: 1.20, rough: 1, vert: 0 },
/* 4 fieldstone */ { lap: 0.50, bay: 4.6, gnd: 2.85, up: 2.45, winW: 0.85, winH: 1.10,
shopW: 1.40, shopH: 1.45, rough: 1, vert: 0 },
/* 5 log */ { lap: 0.42, bay: 5.6, gnd: 2.70, up: 2.40, winW: 0.80, winH: 1.05,
shopW: 1.30, shopH: 1.35, rough: 0, vert: 0 }
];
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;
}
/* Weathering at ~9 cm: knots, nail bleed, the dark run under a leaking gutter. Keyed on
* quantised WORLD coordinates so it is welded to the building, exactly as the city's grain is. */
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.14 ? 0.34 : 0.72 + h * 0.56;
}
/* ---- rock ------------------------------------------------------------------------------------
* A butte is the one thing in either world that is not built, and it gets its own branch rather
* than a style row because nothing about a wall applies to it: no bays, no openings, no lap, no
* ground floor. What it has is BEDDING — horizontal strata a metre or two thick, each one a
* slightly different colour of the same rock — and vertical erosion channels cut down the face.
* Those two crossing rhythms are the whole read, and they are why a butte at 80 m is a butte and
* not a brown building.
*
* The top two rows catch the sun after the town has lost it, which is the reason to have rock in
* this world at all: it is the only thing tall enough to still be lit, and a lit rim at the top
* of an otherwise black silhouette is what tells you how low the sun is. */
function rockFace(u, v, cell, dist, sd) {
var h = cell && cell.h ? cell.h : 12;
var lod = dist < 26 ? 2 : (dist < 60 ? 1 : 0);
var sun = sunOf(cell);
/* Strata. The band boundary wanders with u so the beds are not ruled lines — a ruled line
* reads as masonry, and the whole point is that this is not masonry. */
var wob = vnoise(u * 0.10 + sd * 0.017, 0x7A) * 1.3;
var bandF = (v + wob) / 1.55;
var band = Math.floor(bandF), inB = bandF - band;
var bh = hash2(band, sd & 1023, 0x51C);
/* Erosion channels: whole vertical strips of face turned away from the light. */
var chan = hash2(Math.floor(u * 0.55), 0, sd ^ 0x2C4);
var shade = chan < 0.22 ? 0.42 : (chan < 0.36 ? 0.72 : 1);
/* The lit crest. `h` is this column's own height, so a stepped butte lights every step. */
var crest = h - v;
if (crest < 0.9) {
var k = 1 - crest / 0.9;
return fset(inB < 0.5 ? G_PCT : G_AMP, sun > 0.6 ? P.amber : P.ember,
(26 + 88 * k) * (0.5 + 0.5 * sun) * shade);
}
/* The bed line itself is the only guaranteed ink; the body of a bed is mostly blank, which is
* what keeps a 30 m rock from being 30 m of muddy fill. */
if (inB < 0.13) {
return fset(bh < 0.5 ? G_DASH : G_UNDER, P.slate,
(13 + bh * 15) * shade * (0.55 + 0.45 * sun));
}
if (lod > 0 && hash2(Math.floor(u * 3.1), Math.floor(v * 2.7), sd ^ 0x9B) < 0.20 + 0.12 * bh) {
return fset(bh < 0.4 ? G_COLON : (bh < 0.75 ? G_PCT : G_AMP),
sun > 0.6 && bh > 0.6 ? P.ember : P.slate,
(10 + bh * 16) * shade * (0.5 + 0.5 * sun));
}
return fset(0, P.shadow, 0);
}
/* ---- facade ----------------------------------------------------------------------------------
* u = metres along the wall, v = metres up from the street. Every hash is keyed on the bay index
* and the building seed and never on u/v directly — a facade whose windows re-roll as you walk
* destroys the illusion faster than any other error available. */
function facade(u, v, cell, dist, t) {
if (v < 0) v = 0;
weatherAt(t === undefined ? 0 : t); dayAt(t === undefined ? 0 : t);
var sd = seedOf(cell);
if (cell && cell.style === 6) return rockFace(u, v, cell, dist, sd);
var st = STYLE_W[cell ? (((cell.style | 0) % 6 + 6) % 6) : 0];
var h = cell && cell.h ? cell.h : 6;
var lit = cell && typeof cell.litRate === 'number' ? cell.litRate : 0.1;
var hue = cell && typeof cell.hue === 'number' ? cell.hue : P.slate;
var accent = cell && typeof cell.accent === 'number' ? cell.accent : P.warm;
var sun = sunOf(cell);
var lod = dist < 20 ? 2 : (dist < 46 ? 1 : 0);
var gr = grain(u, v, sd, lod);
/* The sunlit swatch of THIS building. A frontier wall is bare wood going silver, painted
* board, or mud — so the lit colour is the district's hue where that hue is a surface colour,
* and amber where it is not. Amber is doing double duty as "sunlight on timber", which is what
* it is: the swatch is 216,232,74 and low sun on weathered pine is very close to it. */
var litHue = (hue === P.warm || hue === P.white || hue === P.ember) ? hue : P.amber;
var sunHue = sun >= 0.62 ? P.amber : litHue;
/* ---- the coping ---------------------------------------------------------------------------
* The top 30 cm of a false front is a capping board, and it is the single most valuable line
* in the world: it is the roofline, and a roofline is what turns a black shape into a
* building. It is drawn at every distance and every LOD for that reason. */
if (h - v < 0.34) {
return fset(G_EQ, sun >= 0.62 ? P.amber : (sun > 0.30 ? litHue : P.slate),
(sun >= 0.62 ? 214 : (sun > 0.30 ? 82 : 32)) * gr);
}
/* And the shadow it throws — one board's worth of dark immediately under it, which is what
* makes the coping read as PROUD of the wall rather than painted on it. */
if (h - v < 0.62) return fset(0, P.shadow, 0);
var bay = Math.floor(u / st.bay), fu = u / st.bay - bay;
var bh = hash2(bay, sd, 0x3F1); // this bay's identity, stable forever
/* ---- the porch line -----------------------------------------------------------------------
* Where the awning meets the wall. Above it the building; below it, shopfront in the shade of
* its own porch. The dark band is the shadow line and it is what separates the two storeys
* without drawing a cornice on a building that would never have had one. */
if (v > st.gnd && v < st.gnd + 0.30) return fset(0, P.shadow, 0);
if (v > st.gnd + 0.30 && v < st.gnd + 0.52)
return fset(G_DASH, sun >= 0.62 ? P.amber : P.slate, (sun >= 0.62 ? 74 : 22) * gr);
/* ---- ground floor: the shopfront ---------------------------------------------------------- */
if (v <= st.gnd) {
/* A door and a window per bay, the door on whichever side this bay's hash puts it. Both are
* held clear of the bay edges so two neighbouring bays never merge into one opening. */
var doorL = bh < 0.5;
var dw = 0.34, ww = st.shopW / st.bay;
var d0 = doorL ? 0.10 : 0.86 - dw, d1 = d0 + dw;
var w0 = doorL ? 0.52 : 0.10, w1 = w0 + ww; if (w1 > 0.90) w1 = 0.90;
/* IS THERE ANYBODY IN. The city's shopfronts are open at a flat rate because a city is open;
* out here it is the district's own lit rate, tripled, because a ground floor is where the
* lamp is — an upstairs room lit at this hour is the exception and a lit bar is not. */
var open = hash2(bay, sd, 0x5E1) < clamp(lit * 3.1, 0.05, 0.62);
if (v < 2.15 && fu > d0 && fu < d1) {
/* The doorway. Open ones are a slot of lamplight with a dark head above; shut ones are
* boards, and the frame is the only thing that reads. */
if (fu - d0 < 0.05 || d1 - fu < 0.05 || v > 2.02)
return fset(G_PIPE, P.slate, 20 * gr);
if (!open) return fset(0, P.shadow, 0);
var dk = 1 - v / 2.15;
return fset(v < 0.35 ? G_UNDER : G_8, P.warm, (96 + 74 * dk) * (0.7 + 0.5 * gr));
}
var wv0 = 0.80, wv1 = wv0 + st.shopH;
if (v > wv0 && v < wv1 && fu > w0 && fu < w1) {
/* Glass. The frame first — a shopfront is a big pane in a heavy timber surround and the
* surround is what carries the shape at distance. */
if (v - wv0 < 0.14 || wv1 - v < 0.14 || fu - w0 < 0.04 || w1 - fu < 0.04)
return fset(G_EQ, sun >= 0.62 ? P.white : P.slate, (sun >= 0.62 ? 66 : 26) * gr);
if (!open) {
/* Shuttered: boards nailed across, which is a diagonal, and the one place a diagonal
* belongs on this facade. */
var bd = Math.floor((v * 1.6 + fu * 2.2) * 2.4);
return (bd & 1) ? fset(G_SLASH, P.slate, 15 * gr) : fset(0, P.shadow, 0);
}
/* Lit: a warm field with a mullion up the middle and the goods in the window reading as
* broken dark. Held at lum 120-190 — warm's EXPOSURE weight is 0.32, so this lands in the
* 130-165 print band that market.js measured as free on both the muddy and the hot count. */
var mull = Math.abs(fu - (w0 + w1) * 0.5) < 0.022;
if (mull) return fset(G_PIPE, P.slate, 30);
var gl = hash2(Math.floor(u * 2.6), Math.floor(v * 2.6), sd ^ 0x77);
if (gl < 0.17) return fset(G_0, P.shadow, 0); // stock, in silhouette
/* THE LAMP. Every other lit cell in this world is a SURFACE catching a dying sun, and
* core.js's ladder makes surfaces dim on purpose — warm is 0.32 and white is 0.30, so
* neither can reach the v>=170 hot band however hard it is driven. A frame with nothing in
* that band reads flat, and the census agreed: the first cut of this file printed 0.05% hot
* against the build's 3.5-5% target. So the SOURCE is drawn, as amber (0.50, and the only
* warm swatch that can get there) at the few cells nearest the middle of the pane — the
* flame in the glass rather than the light on the room. Small by construction: a couple of
* cells per window, and only in windows that are lit at all. */
/* AMBER LEADS AND WARM FOLLOWS, which is the other way round from the city and is a
* consequence of the print rather than of the light. core.js gives warm a gain of 0.32, so
* a warm cell CANNOT reach the v>=170 highlight band however hard it is driven — and a lit
* window at dusk is the brightest thing at street level out here, so if it cannot be hot
* then nothing on the ground can. Amber is 0.50 and reaches 180. Physically they are the
* same lamp; the split is which part of it is the flame and which is the room. */
if (gl > 0.62) return fset(gl > 0.90 ? G_o : G_8, P.amber, (208 + gl * 46) * gr);
return fset(gl < 0.42 ? G_8 : G_0, gl > 0.56 ? accent : P.warm, (120 + gl * 96) * gr);
}
/* The rest of the ground floor is board, in the porch's shade — so it is DARKER than the
* storey above it whichever way it faces, and that inversion is what makes a porch a porch. */
return board(u, v, st, sd, lod, gr, sun * 0.42, sunHue, dist);
}
/* ---- upper storey -------------------------------------------------------------------------
* One window per bay, centred, at a fixed height off the porch line. Fewer and smaller than
* the city's, and mostly dark: a lit upstairs window at this hour is somebody turning in. */
var uy = v - (st.gnd + 0.52);
var storey = Math.floor(uy / st.up);
var sv = uy - storey * st.up;
if (storey >= 0 && sv > 0.55 && sv < 0.55 + st.winH) {
var cw = st.winW / st.bay, c0 = 0.5 - cw * 0.5, c1 = 0.5 + cw * 0.5;
if (fu > c0 && fu < c1) {
var wh = hash2(bay * 7 + storey, sd, 0x8D2);
if (sv - 0.55 < 0.11 || 0.55 + st.winH - sv < 0.11 || fu - c0 < 0.05 || c1 - fu < 0.05)
return fset(G_DASH, sun >= 0.62 ? P.white : P.slate,
(sun >= 0.62 ? 58 : 22) * gr);
if (wh < lit) {
var lg = hash2(Math.floor(u * 3.4), Math.floor(v * 3.4), sd ^ 0xA3);
if (lg < 0.16) return fset(G_o, P.shadow, 0); // somebody at the glass
if (lg > 0.66) return fset(lg > 0.92 ? G_o : G_8, P.amber, (204 + lg * 50) * gr);
return fset(G_8, P.warm, (112 + lg * 84) * gr);
}
/* Dark glass still reflects the sky, and that is the only reason an unlit window is
* visible at all — a faint cool cell in a warm wall. It is ice rather than azure because
* ice is a GLINT weight (0.36) and azure is a pillar (1.00): one dark pane in azure at
* this lum would be the brightest thing on the building. */
if (hash2(Math.floor(u * 2.2), Math.floor(v * 2.2), sd ^ 0xB5) < 0.30)
return fset(G_COLON, P.ice, 20 * gr);
return fset(0, P.shadow, 0);
}
/* The sill and the head run the full bay on a painted front — a line of white across the
* facade at window height, which is a strong horizontal and very much of the period. */
if (st.rough === 0 && (sv - 0.55 < 0.10 || 0.55 + st.winH - sv < 0.10) && bh > 0.62)
return fset(G_DASH, sun >= 0.62 ? P.white : P.slate, (sun >= 0.62 ? 50 : 18) * gr);
}
return board(u, v, st, sd, lod, gr, sun, sunHue, dist);
}
/* ---- bare wall -------------------------------------------------------------------------------
* MOSTLY NOTHING, and that is the discipline the city taught this file. A facade drawn as a full
* field of dim glyphs lands every one of its cells in the muddy print band (v 9-119), and a
* two-storey town has a lot of blank wall in it. So what is painted is the RHYTHM — the shadow
* line under each board lap — and the wall between the lines is left black. The eye assembles a
* clad wall out of the lines alone; it has been doing that with siding since photography.
*
* The lap pitch coarsens with distance rather than being hashed finer, for the same reason
* surfaces.js coarsens its bay lattice: at 40 m one cell spans half a metre of wall and a 34 cm
* rhythm aliases into a crawling moire that is worse than no texture at all. */
function board(u, v, st, sd, lod, gr, sun, sunHue, dist) {
if (st.rough) {
/* Adobe and stone: no rhythm, a mottle. Rendered mud is nearly featureless in shade and
* comes alive in raking light, which is exactly what `sun` does to the density below. */
var m = hash2(Math.floor(u * 2.4), Math.floor(v * 2.4), sd ^ 0x4C1);
var dens = 0.10 + 0.26 * sun;
if (m > dens) return fset(0, P.shadow, 0);
return fset(m < dens * 0.4 ? G_QUOTE : G_COLON,
sun >= 0.62 ? sunHue : P.slate, (10 + 62 * sun + m * 40) * gr);
}
var lap = st.lap * (lod === 2 ? 1 : (lod === 1 ? 2 : 4));
if (st.vert) {
/* Board and batten runs the other way: the rhythm is vertical and it is the batten, not a
* shadow line, so it is a lit stroke on a dark wall rather than a dark one on a lit wall. */
var bx = u / (lap * 1.4), fbx = bx - Math.floor(bx);
if (fbx > 0.14) {
return (sun >= 0.62 && hash2(Math.floor(u * 1.7), Math.floor(v * 1.7), sd ^ 0x2A) < 0.12)
? fset(G_QUOTE, sunHue, 26 * gr) : fset(0, P.shadow, 0);
}
return fset(G_PIPE, sun >= 0.62 ? sunHue : P.slate, (12 + 58 * sun) * gr);
}
var bv = v / lap, fbv = bv - Math.floor(bv);
var wob = hash2(Math.floor(u * 1.3), Math.floor(v / lap), sd ^ 0x31);
/* ---- THE LIT SIDE IS A SURFACE; THE DARK SIDE IS A RHYTHM ---------------------------------
* This is the largest single decision in the file and it was got wrong first time round, so
* the reasoning is written down rather than left in the constants.
*
* The house discipline — inherited from surfaces.js and correct there — is that a facade is
* MOSTLY BLANK with only its structure lines painted, because a full field of dim glyphs puts
* every one of its cells in the print's muddy band (v 9-119) and a city has a great deal of
* wall in it. Applied uniformly here it produced a town in which nothing had any mass at all:
* measured at seed 42 frame 600, the whole frontier printed 0.13% of cells above v=170 against
* the build's 3.5-5% target, and every reference frame of the city has a THIRD of its picture
* in solid blocks of lit window.
*
* The frontier's answer cannot be lit windows — there are barely any — so it has to be the one
* thing it does have that the city does not: a low sun square onto one side of the street. A
* clapboard wall at this hour is not a dim surface, it is the brightest large object in the
* frame, and it belongs painted as a MASS.
*
* The muddy-band objection does not apply to it, and that is arithmetic rather than hope:
* core.js prints amber at gain 0.50, where lum 100 lands at v=126 — already clear of the muddy
* ceiling at 119. So the lit wall is written at lum 88-150, which is out of the band on both
* sides, and the SHADOW wall keeps the sparse-lines treatment exactly as before, because slate
* at any lum is inside the band and there is no way to spend cells there cheaply. One side of
* the street is a surface, the other is a silhouette, and the print pays for both. */
if (sun >= 0.62) {
var body = hash2(Math.floor(u * 2.4), Math.floor(v * 2.4), sd ^ 0x66);
if (fbv <= 0.30)
return fset(wob < 0.22 ? G_UNDER : G_DASH, sunHue, (176 + wob * 68) * gr);
if (body < 0.62)
return fset(body < 0.20 ? G_DASH : (body < 0.44 ? G_UNDER : G_TICK), sunHue,
(124 + body * 74) * gr);
return fset(0, P.shadow, 0);
}
if (fbv > 0.30) {
/* Between the lines, on the shadow side. A very few specks — nail heads and knots — because
* a perfectly empty field between two perfect lines reads as a stencil. */
if (lod === 2 && hash2(Math.floor(u * 2.8), Math.floor(v * 2.8), sd ^ 0x66) < 0.10)
return fset(G_DOT, P.slate, (10 + 46 * sun) * gr);
return fset(0, P.shadow, 0);
}
/* The lap line, in shade. */
return fset(wob < 0.22 ? G_UNDER : G_DASH, P.slate, (13 + 74 * sun + wob * 22) * gr);
}
/* ---- ground ----------------------------------------------------------------------------------
* wx/wz in metres, `dist` the radial distance to this cell. The street runs along wz with its
* centreline at CFG.streetX and its carriageway half-width in CFG.half; CFG.xc/xw carry where
* the cross streets cut it. All of that is raycast.js's, and it is the same for both worlds —
* what changes is that there is no tarmac, no kerb, no lane marking and no tram rail out here.
*
* WHAT A DIRT STREET IS MADE OF, in the order the cascade tests it:
* the boardwalk a raised plank walk in front of the buildings, with a step down to the dirt
* the ruts two wheel tracks either side of the centre, worn in and holding the water
* the crown the road is domed, so the middle is dry and pale and the edges are not
* the dust everything else — sparse grit, hoof scuff, a stone
* and after rain, the ruts fill and become the only mirrors in the world.
*/
var ROUT = { ch: 0, col: 0, lum: 0, mir: 0, rip: 0, wch: 0 };
var mirNow = 0, ripNow = 0, wchNow = 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; ROUT.rip = ripNow; ROUT.wch = wchNow;
return ROUT;
}
var BOARDWALK = 1.72; // plank width of the walk, inside CC.PAVE's 2.15 m strip
/* Is this z inside a junction mouth? Indexed rather than scanned — see loadCrossings. */
function inCross(C, wz) {
if (!C.xn) return 0;
var i = Math.round((wz - C.xz0) / (C.xpitch || 26));
if (i < 0) i = 0; else if (i >= C.xn) i = C.xn - 1;
var d = wz - C.xc[i]; if (d < 0) d = -d;
if (d <= C.xw[i] + 1.1) return 1;
/* One neighbour either side, because the arithmetic guess can be a slot out on a jittered
* lattice and a junction mouth that vanishes for two metres is a hole in the road. */
if (i > 0) { d = wz - C.xc[i - 1]; if (d < 0) d = -d; if (d <= C.xw[i - 1] + 1.1) return 1; }
if (i < C.xn - 1) { d = wz - C.xc[i + 1]; if (d < 0) d = -d; if (d <= C.xw[i + 1] + 1.1) return 1; }
return 0;
}
function floorTex(wx, wz, dist, t) {
weatherAt(t === undefined ? 0 : t); dayAt(t === undefined ? 0 : t);
var C = cfg();
var half = C ? C.half : 3.1;
var lane = wx - (C ? C.streetX : 4.0);
var al = lane < 0 ? -lane : lane;
var lod = dist < 20 ? 2 : (dist < 46 ? 1 : 0);
mirNow = 0; ripNow = 0; wchNow = 0;
/* Sun side. The whole street is one plane so it cannot shade itself, but the buildings on the
* sunward side throw their shadow across the near half of the road at this hour, and that
* diagonal is worth having: it is why the road is not one flat tone from kerb to kerb. */
/* WHICH AXIS THE LANE IS IN. raycast.js hands floorTex its coordinates TRANSPOSED when the
* camera has committed to a cross street, so `lane` is an x offset on an avenue and a z offset
* on a cross street — and the sun has a different component along each. Without this the sunlit
* side of the road swaps to the wrong side every time the walk turns a corner.
*
* It also falls out for free that a street running along the sun's own bearing has no lit side
* and no dark one: `comp` goes to nearly zero, `bright` collapses to a half, and the light
* comes straight down the road at both walks equally. That is exactly what happens, and it is
* the best-looking street in the world when the walk finds one. */
var comp = (C && C.swap) ? SUN_Z : SUN_X;
var lit = -lane * comp; // >0 on the side the sun is on
var sunSide = lit > 0.4 ? 1 : (lit < -0.4 ? 0 : (Math.abs(comp) < 0.35 ? 1 : 0));
/* ---- the boardwalk ------------------------------------------------------------------------ */
if (al > half && al < half + BOARDWALK) {
if (inCross(C, wz)) {
/* A junction has no walk across it — you step down into the road. That gap is the reason
* the crossings are loaded at all in this world. */
} else {
var into = al - half;
/* The step down at the road edge: one bright line, because it is an EDGE lit from the
* side and it is what gives the street its two long converging rails. */
if (into < 0.16)
return rset(G_UNDER, sunSide ? P.amber : P.white, (sunSide ? 214 : 60) * (0.8 + 0.4 * hash2((wz * 3) | 0, 0, 0x11)));
/* Planks run ACROSS the walk, so the joints are lines of constant wz — which is to say
* they converge to the same vanishing point as the street and carry the perspective. */
var pj = wz / 0.92, fpj = pj - Math.floor(pj);
var pw = hash2(Math.floor(pj), (al * 2) | 0, 0x5B);
if (fpj < 0.10)
return rset(G_DASH, P.slate, (14 + pw * 12));
if (lod === 2 && pw < 0.10)
return rset(pw < 0.04 ? G_COMMA : G_DOT, P.slate, 12 + pw * 60); // a knot, a gap
/* The deck itself. Planed board takes the low sun better than dirt does, so the walk on
* the sunward side is one of the brightest surfaces in the frame and the one opposite is
* nearly black — the two sides of a main street at dusk do not match and should not. */
if (sunSide) return rset(G_UNDER, P.white, (62 + pw * 40));
return (pw < 0.30) ? rset(G_UNDER, P.slate, 12 + pw * 20) : rset(0, P.shadow, 0);
}
}
/* Past the walk: the ground under the buildings, which is only ever seen through a gap. */
if (al >= half + BOARDWALK) {
if (lod === 0) return rset(0, P.shadow, 0);
var og = hash2(Math.floor(wx * 1.6), Math.floor(wz * 1.6), 0x2D9);
if (og > 0.14) return rset(0, P.shadow, 0);
return rset(og < 0.05 ? G_COMMA : G_DOT, P.slate, 10 + og * 60);
}
/* ---- the roadway -------------------------------------------------------------------------- */
var n = al / half; // 0 at the crown, 1 at the edge
/* Standing water. Out here it is not a sheet — a dry street sheds and the only water that
* stays is in the ruts and the low corners, so `wet` buys DEPTH in the ruts rather than a
* mirror everywhere. Under `blazing` (rel wet 0.04) this is zero and the road is bone dry. */
var wet = wWet * 1.05;
var rut = 0;
if (lod > 0) {
/* Two ruts, at 0.44 of the half-width either side, wandering slowly along the street the way
* a wheel track does. Placed on a world lattice so they hold still as you walk. */
var rc = 0.44 + vnoise(wz * 0.055, 0x3B) * 0.10;
var dr = Math.abs(n - rc);
rut = dr < 0.075 ? 1 - dr / 0.075 : 0;
}
if (rut > 0.25 && wet > 0.45) {
/* A rut with water in it. This is the frontier's puddle and it is the only mirror in the
* world — which makes it precious rather than a limitation: after a squall the whole town
* hangs upside down in two thin lines running away up the street. */
var wsurf = rut * clamp(wet - 0.4, 0, 1);
if (wsurf > 0.12) {
mirNow = clamp(wsurf * 1.25, 0, 1);
ripNow = CC.reducedMotion ? 0 : Math.sin(wz * 1.7 + t * 1.4) * 0.9 * wWind;
wchNow = G_TILDE;
var ws = hash2(Math.floor(wx * 3), Math.floor(wz * 3), 0x71C);
return rset(ws < 0.5 ? G_TILDE : G_SEMI, P.slate, 12 + ws * 22);
}
}
/* ---- the dry rut ---------------------------------------------------------------------------
* TWO LINES RUNNING AWAY UP THE STREET, and they are the most important thing on this floor.
* A dirt road drawn as one field of noise has no perspective in it at all — the first cut of
* this file did exactly that and the ground read as static, because nothing on it converged.
* The ruts are the road's only long straight lines and they do the job the city's centreline,
* kerb and rails do between them.
*
* They are PALER than the road around them, which is the way round that surprised me and then
* did not: a wheel track in dry ground is broken, churned, unpacked dust, and unpacked dust
* catches a low sun far better than the packed crown does. Drawn darker they read as two
* cracks; drawn paler they read as two tracks. */
if (rut > 0.22) {
var rs = hash2(Math.floor(wx * (lod === 2 ? (dist < 9 ? 6.2 : 3.0) : 1.7)),
Math.floor(wz * (lod === 2 ? (dist < 9 ? 6.2 : 3.0) : 1.7)), 0x18F);
var rd = (0.34 + 0.42 * rut) * (lod === 2 ? 1 : 0.8);
if (rs < rd)
return rset(rs < 0.14 ? G_UNDER : (rs < 0.34 ? G_COMMA : G_DOT),
sunSide ? P.white : P.slate,
(26 + rs * 150) * rut * (sunSide ? 1.15 : 0.72));
/* The stones the wheels turn up sit in the track, not beside it. */
if (lod === 2 && dist > 8 && rs > 0.988) return rset(G_o, P.slate, 30 + (1 - rs) * 3200);
return rset(0, P.shadow, 0);
}
/* The crown, and the shoulders. Dust is the surface: pale, fine and almost featureless, so it
* is drawn as a sparse field whose DENSITY carries the tone rather than a fill whose lum does.
* Density falls off toward the edges, which is what domes the road. */
/* ---- THE GROUND FOLLOWS THE SUN, in density AND in how much the two sides differ ------------
* At dusk the road has a lit side and a dark side and the difference between them is most of
* what the frame is made of. At noon the sun is overhead: both sides are lit, the shadow of
* the buildings has pulled back under their own eaves, and the road is the brightest large
* surface in the world — which is what a desert at midday IS, and what the fixed-dusk version
* of this function could not draw at all.
*
* `sideK` is how much of the lit/dark split survives the hour: 1 at a grazing sun, 0.25
* overhead. `lightK` is the overall level, and it does not go to zero at night — a dirt road
* under a lamp-lit town and a sky full of stars is dim, not absent. */
var sideK = 0.25 + 0.75 * clamp(1 - dAlt() / 0.95, 0, 1);
/* CAPPED AT 1, and the cap is the point. Density carries tone when there is little light —
* that is this file's own house rule and the road was built on it — but once the sun is up the
* tone has to be carried by BRIGHTNESS instead, or a lit road is simply more cells at the same
* mid value, which is the muddy band by definition. Past noon this stops adding grains and the
* lum term below keeps going. */
var lightK = clamp(0.18 + 0.62 * dSky + 0.26 * dSun, 0, 1.0);
var sideBias = sunSide ? (1 + 0.25 * sideK) : (1 - 0.28 * sideK);
var dens = (0.42 - 0.20 * n * n) * sideBias * lightK *
(lod === 2 ? 1 : (lod === 1 ? 0.82 : 0.6));
/* More dust in the air means more dust on the ground; a squall packs it down. */
dens *= (0.82 + 0.5 * wDust) * (1 - 0.45 * clamp(wet - 0.3, 0, 1));
/* THE LATTICE PITCH IS A FUNCTION OF THE DISTANCE BAND, and this is the same lesson the city's
* floor learned one file over. A world hash at a fixed pitch is stable — which is the point —
* but at five metres one 0.48 m lattice cell spans eight screen columns, so every speck of dust
* printed as an eight-character RUN of the same glyph and the near road read as lines of text.
* Finer up close, coarser far away, quantised by band so it cannot crawl between two frames of
* the same walk. */
var q = lod === 2 ? (dist < 9 ? 5.6 : 2.6) : (lod === 1 ? 1.5 : 0.85);
var d1 = hash2(Math.floor(wx * q), Math.floor(wz * q), 0x4A7);
if (d1 < dens) {
var hot = d1 < dens * 0.16 && sunSide;
/* NORMALISED BY THE DENSITY, not by the raw draw. Writing lum = 18 + d1*150 tied a grain's
* brightness to the same number that decided whether it existed at all, so as the density
* fell toward the kerb every surviving grain also got dimmer — and the whole field collapsed
* into lum 18-80, which is slate's muddy band end to end, over a third of the frame.
* Dividing through by `dens` decouples them: the road still thins toward its edges and the
* grains that remain keep the full tonal range. */
var k1 = d1 / dens;
/* WHITE ON BOTH SIDES ONCE THE SUN IS UP. The slate/white split is a dusk fact — one side of
* the road in the light and one in the shade of the buildings — and at noon there is no shade
* to be on the far side of. */
var dayGround = dSun > 0.55;
return rset(k1 < 0.3 ? G_DOT : (k1 < 0.62 ? G_COMMA : G_TICK),
hot ? P.amber : ((sunSide || dayGround) ? P.white : P.slate),
(hot ? 132 : 22 + k1 * 128) * (sunSide ? 1 : 0.78) *
(0.6 + 0.7 * lightK + 0.9 * dSun));
}
/* A stone, a dry weed, a hoofprint. Rare, and the only things on the road with an edge. */
if (lod === 2) {
var d2 = hash2(Math.floor(wx * q * 0.5), Math.floor(wz * q * 0.5), 0x6E3);
if (d2 < 0.014) return rset(G_o, P.slate, 26 + d2 * 1300);
if (d2 > 0.990) return rset(G_QUOTE, P.spring, 22 + (1 - d2) * 1300);
}
return rset(0, P.shadow, 0);
}
/* ---- sky -------------------------------------------------------------------------------------
* sx is the column's world bearing quantised at CFG.skyK index units per radian; sy is the screen
* row. Both come from raycast.js and neither is a camera-relative quantity, which is what keeps
* the sunset welded to the west while the viewer turns round.
*
* THIS IS THE PICTURE. The city's sky is a slot between rooftops and it is mostly black by
* design; the frontier's is half the frame, and if it is black the world is a black rectangle
* with a thin strip of town along the bottom. So the dome is BANDED — five bands, each one a
* different swatch, and the bands are the composition:
*
* 0.00-0.05 the core amber, dithered dense. Where the sun went down.
* 0.05-0.20 the burn ember, the classic sunset band, wide and warm
* 0.20-0.36 the fade slate, cooling and thinning
* 0.36-0.46 earth shadow violet, and the reason the palette has violet in it at all
* 0.46+ the dome azure at the bottom of its range, plus whatever stars.js adds
*
* All five are measured in FRACTIONS OF THE GRID (CFG.rows), never in rows, so a 100-row frame
* gets the same sky a 60-row one does — the same rule surfaces.js's light-pollution ramp learned
* the hard way.
*
* THE BANDS ARE THIS WIDE BECAUSE THE TOWN IS IN THE WAY, and the first cut of them was not.
* They were originally sized as fractions of the SKY (core to 0.03, dome from 0.30), which is
* roughly what a sunset subtends in real elevation — and almost none of it was ever visible,
* because a two-storey building thirty metres away covers everything under about 12 degrees and
* the only sky the frame actually contains is the part above it. Measured at 200x60: the visible
* dome runs to a = 0.56 and the buildings ate everything under 0.30, so four of the five bands
* were behind the town and the whole sky printed as the fifth one, which is the empty one. What
* is sized here is therefore the PICTURE, not the atmosphere: the burn has to be where the sky
* that can be seen is.
*
* And all five are gated on the BEARING: the core is only where the sun is, and the bands narrow
* and dim round the compass until the eastern sky is nearly out. A sunset that is the same in
* every direction is a gradient, not a sunset. */
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;
}
function sky(sx, sy, t) {
weatherAt(t === undefined ? 0 : t); dayAt(t === undefined ? 0 : t);
var C = cfg();
var rows = C && C.rows ? C.rows : 60;
var hor = C ? C.horizon : rows * 0.56;
var vs = C && C.skyVScale ? C.skyVScale : 1;
var kk = C && C.skyK ? C.skyK : (rows / 0.7);
/* Elevation, in the pitch- and zoom-invariant units surfaces.js established, then normalised
* to the grid so the gradient below is a fraction of the picture. */
var ey = Math.floor((hor - sy) * vs);
var a = ey / rows;
if (a < 0) a = 0;
/* How far round from the sun this column is, 0 at the sunset and 1 opposite it. */
var bear = sx / kk;
var da = bear - SUN_AZ;
da = Math.atan2(Math.sin(da), Math.cos(da)); // wrapped to -PI..PI
var away = Math.abs(da) / Math.PI;
/* The sunset's reach round the horizon. Squared, so the glow is concentrated in the western
* quadrant and gone by due east rather than tapering all the way round. */
var west = 1 - away; west = west * west * (0.55 + 0.45 * west);
/* Dust and cloud both eat the sky. Dust raises the floor of the whole dome (more scatter, so
* more light everywhere and less contrast); cloud takes the top off. */
var lift = 0.90 + 0.50 * wDust;
var cap = 1 - 0.52 * wCloud;
/* ---- THE HOUR, and it is the largest term in this function ----------------------------------
* Everything below was written at a fixed dusk and reads as one: an exponential falling away
* from a burn on the horizon. That IS a dusk sky, and it is wrong at every other hour.
*
* dSky scales the whole thing, so at night the dome goes out and the stars have something to
* be seen against.
* dWarm decides whether the gradient is a SUNSET or a DAY SKY. At dawn and dusk it is 1 and
* the tiers below run amber-ember-slate-azure, which is what they were built to do. Toward
* noon it goes to 0 and they re-swatch to white-white-ice-ice — a pale band at the horizon
* under a deep blue dome, which is what a desert sky at midday is.
* The e-fold OPENS UP toward noon for the same reason: a sunset is concentrated at the
* horizon because the light is coming through a great deal of air, and at noon the sky is
* nearly uniform with only a slow darkening upward. */
var warmK = dWarm;
var efold = 0.50 + 0.95 * (1 - warmK);
/* THE GRADIENT, and it is one exponential rather than five bands. The banded version is in the
* history of this file and it did not survive contact with the town: bands sized as fractions
* of the SKY put four of their five behind a roofline, because the only sky a street canyon
* contains is the part high enough to clear the buildings — measured at 200x60, the visible
* dome ran a = 0.08 to 0.56 and every warm band was under 0.20.
*
* An e-fold at 0.50 of the grid keeps two thirds of the light at the top of the frame, which is
* both what a real dusk does (the sky does not go out at 25 degrees) and what this frame needs:
* the sky is half the picture out here and a sky that is black above the rooflines is a black
* rectangle with a town along the bottom. The COLOUR then comes off the same number, so the
* bands still exist — they are just level sets of one field instead of five hard edges, which
* also means they bend correctly round the compass instead of running level all the way to
* due east. */
var e = Math.exp(-a / efold) * (0.30 + 0.70 * (warmK * west + (1 - warmK) * 0.55)) *
lift * cap * (0.10 + 1.05 * dSky);
var hs = hash2(sx, ey, C ? C.skySeed : 0x5EED);
var hs2 = hash2(sx, ey, (C ? C.skySeed : 0x5EED) ^ 0x11);
/* THE EARTH SHADOW, taken first because it is the one feature that is strongest AWAY from the
* sun and would otherwise never win a test against the gradient. It is the band of the planet's
* own shadow rising in the east, pink-violet over blue: real, about ten minutes long, and the
* only reason this world touches violet at all. Dithered to a few cells per column — violet's
* EXPOSURE weight is 0.34 and it goes gaudy the instant it is given area. */
var band = a > 0.16 && a < 0.44 ? 1 - Math.abs(a - 0.30) / 0.14 : 0;
if (band > 0) {
var ve = band * away * away * cap * lift;
if (hs < 0.075 * ve) return sset(G_DOT, P.violet, (70 + 96 * ve) * (0.7 + 0.5 * hs2));
}
/* Coverage climbs steeply with the field: the burn is a BAND, dense enough to be a mass, and
* the upper dome is a scatter. A uniform dither over both gives a sky with a colour ramp and no
* structure, which reads as a gradient rather than as weather. */
if (hs < 0.05 + 1.18 * e) {
/* Four swatches off one field. The thresholds are where they are because of core.js's
* EXPOSURE ladder rather than because of the sky: amber (0.50) and ember (0.42) can carry a
* bright band, slate (0.60) is the workhorse of the middle, and azure (1.00) is the highest
* gain in the table — which is why the top of the dome is written at lum 14-40 and still
* reads as deep blue rather than as nothing. Written any brighter, azure at the top of the
* frame is the loudest thing in the picture and the sky stops being behind the town. */
/* THE HOT LINE IS A FACT ABOUT THE SWATCH, NOT ABOUT THE LIGHT. core.js caps ember at a
* printed 163 whatever lum it is handed, so the sunset band — which is the brightest thing in
* this world by any physical reading — can never reach the v>=170 the print counts as a
* highlight. Only amber (ceiling 180) and pure (255) can, and only over lum ~215. So the core
* of the burn is written in those two and its surround in ember, which is also what it looks
* like: a sunset has a white-hot middle and an orange rest, and the rest is not a highlight. */
/* THE SAME FOUR TIERS, RE-SWATCHED BY THE HOUR. A sunset's ladder is amber-ember-slate-azure;
* a midday sky's is white-white-ice-ice, and the two share their SHAPE because the shape is
* "brightest where you are looking through the most air". Blending the swatch rather than the
* geometry is what lets one function be both — and it is also the only way to do it, because
* this renderer cannot blend two palette indices. The choice is made per tier and per hour,
* and the dither does the mixing. */
/* TWO LADDERS OVER ONE FIELD, chosen by the hour, because a sunset and a midday sky are not
* the same picture at different brightnesses. They share the field `e` — "how much air am I
* looking through" — and nothing else.
*
* THE SUNSET LADDER is amber over ember over slate over azure, concentrated near the horizon
* by a short e-fold. THE DAY LADDER is a pale band low down and then blue all the way up,
* and its thresholds are pushed HIGHER so that white is confined to the horizon band: the
* first cut used the same thresholds for both and painted the whole dome white, which is a
* sky with the sun in every part of it. A desert sky at noon is deep blue overhead and pale
* only where it meets the ground.
*
* Ice rather than azure by day, and that is the day EXPOSURE table talking: core.js drops
* azure from 1.00 to 0.30 in daylight and lifts ice from 0.36 to 0.66, so the swatch that
* carries a blue sky swaps over with the ladder. */
if (warmK > 0.42) {
if (e > 0.80) return sset(G_EQ, P.pure, 168 * (0.7 + 0.4 * hs2));
if (e > 0.58) return sset(G_EQ, P.amber, 248 * (0.72 + 0.32 * e) * (0.86 + 0.22 * hs2));
if (e > 0.32) return sset(e > 0.46 ? G_EQ : G_DASH, P.ember,
204 * (0.50 + 0.72 * e) * (0.78 + 0.40 * hs2));
if (e > 0.13) return sset(G_TICK, P.slate, 138 * (0.52 + 0.78 * e) * (0.78 + 0.38 * hs2));
return sset(G_DOT, P.azure, (16 + 46 * e) * (0.7 + 0.6 * hs2));
}
if (e > 0.80) return sset(G_EQ, P.white, 214 * (0.80 + 0.24 * e) * (0.88 + 0.18 * hs2));
if (e > 0.62) return sset(G_DASH, P.white, 176 * (0.72 + 0.32 * e) * (0.86 + 0.22 * hs2));
if (e > 0.38) return sset(G_TICK, P.ice, 168 * (0.62 + 0.50 * e) * (0.82 + 0.30 * hs2));
return sset(hs2 > 0.6 ? G_COLON : G_DOT, P.ice, (54 + 150 * e) * (0.78 + 0.36 * hs2));
}
return sset(0, P.shadow, 0);
}
/* 210 m against the city's 125, and a gentler curve on top of it. These used to live in
* surfaces.js as WEST_START/WEST_END, selected by a boolean; they belong to the painter, and a
* painter that does not declare them inherits the city's. A frontier main street is 17 m wide
* with two-storey buildings on it, so the far end of it is 150 m away and IN FRAME — under the
* city's ramp all of it, plus every butte behind it, printed as black. The exponent moves with
* the range because the point of a long ramp is its far end. */
var FOG_START_W = 20.0, FOG_END_W = 210.0, FOG_POW_W = 1.25;
CC.SurfWest = { id: 'west',
facade: facade, floorTex: floorTex, sky: sky, STYLE: STYLE_W,
fogStart: FOG_START_W, fogEnd: FOG_END_W, fogPow: FOG_POW_W,
sunOf: sunOf, BOARDWALK: BOARDWALK };
/* GETTERS, because these three stopped being constants when the sun started moving and five
* call sites in three element files read them by name. A getter kept every one of them correct
* without an edit; a copied value would have frozen each reader at whatever the sun was doing
* when its module loaded. */
Object.defineProperty(CC.SurfWest, 'SUN_AZ', { get: function () { return SUN_AZ; } });
Object.defineProperty(CC.SurfWest, 'SUN_X', { get: function () { return SUN_X; } });
Object.defineProperty(CC.SurfWest, 'SUN_Z', { get: function () { return SUN_Z; } });
Object.defineProperty(CC.SurfWest, 'SUN_ALT', { get: function () { return SUN_ALT; } });
/* Self-registration: surfaces.js never learns this file's name. */
if (!CC.SURFACES) CC.SURFACES = {};
CC.SURFACES.west = CC.SurfWest;
if (typeof module !== 'undefined') module.exports = CC.SurfWest;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -96,7 +96,17 @@
* camera", and the world pass overwrites it every frame from the live projection so that the * 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 * 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. */ * unconfigured harness — and the standalone parse check — still gets the shipped sky. */
skyVScale: 1 skyVScale: 1,
/* Index units per RADIAN in sky()'s horizontal — raycast.js's `skyK`, published because
* surf_west.js has to turn `sx` back into a world bearing to know where the sun is, and it has
* no camera and no column count to derive one from. This file never reads it: the city's sky
* is the same in every direction on purpose. */
skyK: 1,
/* 1 when raycast.js has transposed the floor's coordinates onto a cross street. This file has
* never needed it — a kerb is a kerb in either axis — but surf_west.js decides which side of
* the road the sun is on, and that is an answer about a WORLD axis, so it has to know which one
* `wx` currently is. */
swap: 0
}; };
function configure(o) { function configure(o) {
if (!o) return CFG; if (!o) return CFG;
@ -118,6 +128,31 @@
* MIGRATION RULE, applied throughout: every tuned constant below is scaled by rel(...), which is * 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 * 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. */ * would silently re-tune the street to 90% of what shipped. */
/* ---- the hour ---------------------------------------------------------------------------------
* Same cache-on-t as the weather beside it, and for the same reason: this file would otherwise
* ask the director for the time twenty thousand times a frame for an answer that cannot change
* inside one. Because the key is the CLOCK and not a counter, scrubbing the harness to frame 9000
* syncs the same hour the browser has there.
*
* WHAT EACH ONE IS FOR, because they are not interchangeable and the picture goes wrong quickly
* if they are:
* dSky how bright the sky is, 0..1. This is the one that lifts the STRUCTURE — the spandrel,
* the dead glass, the road — because in daylight the thing lighting a wall is the whole
* hemisphere above it and not the sun.
* dLamp how much artificial light is on, 0..1, with hysteresis: it is what takes the lit
* windows, the sodium pool, the kerb's own colour and the bulkhead lamps away by day. It
* is NOT 1-dSky — lamps are lit through both twilights and out well past sunrise.
* dSun direct sun, 0 through the whole of twilight. Only things that need a SHADOW read this.
*/
var dT = 1 / 0, dSky = 0, dLamp = 1, dSun = 0, dWarm = 0;
function dayAt(t) {
if (t === dT) return;
dT = t;
var D = CC.Daylight;
if (!D) return; // standalone require: hold the tuned night
dSky = D.P.sky; dLamp = D.P.lamp; dSun = D.P.sun; dWarm = D.P.warm;
}
var wT = 1 / 0, wWet = 1, wRain = 1, wWind = 1, wFogP = 0.30; var wT = 1 / 0, wWet = 1, wRain = 1, wWind = 1, wFogP = 0.30;
function weatherAt(t) { function weatherAt(t) {
if (t === wT) return; if (t === wT) return;
@ -147,7 +182,23 @@
} }
function litOf(cell) { function litOf(cell) {
var r = cell && cell.litRate; var r = cell && cell.litRate;
return typeof r === 'number' ? clamp(r, 0, 1) : 0.34; r = typeof r === 'number' ? r : 0.34;
/* SCALED BY THE HOUR, and this is the single change that turns a night city into a day one.
* city.js bakes litRate into the record at build time as a per-district constant, so it is a
* property of the BUILDING; how many of those windows have a light burning in them is a
* property of the CLOCK, and the two were the same number for as long as it was always night.
*
* It does not go to zero at noon. A deep floorplate has its lights on at midday and always
* has; what changes is that the window stops being brighter than the wall around it, which is
* handled where the window is painted rather than here.
*
* IT IS EXACTLY 1.0 AT dLamp 1, and that is a rule rather than a coincidence. The shipped night
* look is the tuned baseline — every constant in this file was fitted against it over a
* 128-frame census — so every daylight scale added anywhere in the build has to be the identity
* at night, or the feature silently re-tunes the picture it was supposed to leave alone. The
* first cut of this line was 0.22 + 0.93*dLamp, which is 1.15 at night, and it moved 1083 cells
* of a 12000-cell reference frame before the comparison caught it. */
return clamp(r * (0.22 + 0.78 * dLamp), 0, 1);
} }
/* One accent per building, never two — a facade that mixes ember and violet stops reading /* 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. */ * as one object. Violet stays rare: it is ~12% of an accent that is itself ~10% of windows. */
@ -172,8 +223,71 @@
* Every hash is keyed on the bay index and the building seed, never on u/v directly and never * 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 * 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. */ * the illusion faster than any other error in this project. */
/* ---- THE DAY LIFT, and it is one function rather than twenty-five edits -------------------
* facade() writes through exactly one funnel, and that is where daylight is applied, because the
* alternative is a `if (day)` at every one of the twenty-five sites that currently write
* P.shadow — and a scatter like that is how half of them end up not being updated together.
*
* WHAT IT DOES, and each of the three is an inversion rather than a scale:
*
* THE UNLIT STRUCTURE BECOMES THE SURFACE. At night the mullion, the spandrel and the dead
* glass are written on P.shadow at lum 8-42 and the file argues at length that this is "mass
* the print deletes... coverage rather than texture". By day that same mass is the largest
* visible thing in the frame: a concrete wall lit by the whole sky. So the swatch moves to
* slate and then to white as the sky comes up, and the lum moves with it. Nothing about WHICH
* cells are painted changes — only what they are painted as.
*
* THE BLANK CELLS FILL IN. A night facade is 40% blank because unlit spandrel is nothing; a
* sunlit one is a continuous surface. A blank cell gets a sparse structural glyph, keyed on
* quantised world coordinates so it is welded to the building exactly as the grain is.
*
* THE LIT WINDOWS LOSE THEIR ADVANTAGE. A lamp behind glass at noon is not brighter than the
* render around it; it is slightly darker. litOf() has already thinned how MANY of them there
* are, and this thins how much they stand out.
*
* EVERY BRANCH IS THE IDENTITY AT dSky 0, which is the rule the whole feature is built on: the
* night look is the tuned baseline and a daylight cycle may not move it by a cell. */
var FOUT = { ch: 0, col: 0, lum: 0 }; var FOUT = { ch: 0, col: 0, lum: 0 };
var fU = 0, fV = 0, fSd = 0;
function fset(ch, col, lum) { function fset(ch, col, lum) {
if (dSky > 0.02) {
/* SQUARED, and it is the same argument the print ladder makes one file over: a wall does
* start catching skylight at first light, but it does not become the SUBJECT of the frame
* until the sky is genuinely bright. Under a linear ramp the city's dusk had 56% of its lit
* energy in white — a swatch the day ladder caps at a printed 151 and which therefore can
* never be a highlight — so the neon was still there and simply had nothing left to be
* brighter than: 0.68% of cells hot at dusk against 8.02% at night. Squaring holds the wall
* back through twilight and lets the signs own the frame for the hour that is theirs. */
var dK = dSky * dSky;
if (ch === 0 || lum <= 0) {
var hb = hash2(Math.floor(fU * 2.6), Math.floor(fV * 2.6), (fSd ^ 0x7D13) | 0);
if (hb < 0.14 + 0.50 * dK) {
ch = hb < 0.34 ? G_DASH : (hb < 0.62 ? G_COLON : G_QUOTE);
col = dK > 0.55 ? P.white : P.slate;
lum = (26 + hb * 96) * dK;
}
} else if (col === P.shadow) {
col = dK > 0.48 ? P.white : P.slate;
lum = lum * (1 + 2.6 * dK) + 62 * dK;
} else if (col === P.warm || col === P.amber || col === P.azure || col === P.ice) {
/* KEYED ON THE SUN, NOT ON THE SKY, and the difference is the whole of dusk. A lamp behind
* glass loses its advantage over the wall when there is DIRECT light on that wall — not
* during twilight, when the sky is bright and the sun is down and the neon is the best
* thing in the frame. Scaling by dSky instead cost the city its dusk twice over: the print
* ladder had already pulled azure's gain from 1.00 toward 0.30 at that hour, and this
* multiplied the lum on top of it. Measured at seed 42: the dusk frame printed 0.68% hot
* and a lit p90 of 114, against 8.02%/172 at night and 3.20%/135 at noon — the one hour
* that should be the best in the world was the dimmest picture of the three. */
/* SQUARED, for the same reason the print ladder squares its source blend, and this is the
* line that was actually costing the city its dusk. Tracing it took a while and is worth
* writing down: the hot cells in a night frame are mostly LIT WINDOWS drawn through this
* function, not the neon drawn by signage.js — 1477 of them at seed 42 — and a linear
* 1 - 0.52*sun took a window written at 240 down to 160, which is four points under the
* line the census counts as a highlight. The printed CEILINGS were never the problem;
* azure's is 219 at that hour. The lums were. */
lum *= 1 - 0.52 * dSun * dSun;
}
}
FOUT.ch = ch; FOUT.col = col; FOUT.ch = ch; FOUT.col = col;
FOUT.lum = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0); FOUT.lum = lum < 0 ? 0 : (lum > 255 ? 255 : lum | 0);
return FOUT; return FOUT;
@ -189,9 +303,14 @@
} }
function facade(u, v, cell, dist, t) { function facade(u, v, cell, dist, t) {
if (alt) return alt.facade(u, v, cell, dist, t);
if (v < 0) v = 0; if (v < 0) v = 0;
weatherAt(t === undefined ? 0 : t); weatherAt(t === undefined ? 0 : t); dayAt(t === undefined ? 0 : t);
var sd = seedOf(cell), st = styleOf(cell, sd); var sd = seedOf(cell), st = styleOf(cell, sd);
/* Stashed for fset's day lift, which needs a world coordinate to hash on and cannot be handed
* one without changing a signature that twenty-five call sites use. Three stores per cell on a
* path that already does a dozen. */
fU = u; fV = v; fSd = sd;
var wu = Math.floor(u / st.pu), wv = Math.floor(v / st.pv); var wu = Math.floor(u / st.pu), wv = Math.floor(v / st.pv);
var fu = u / st.pu - wu, fv = v / st.pv - wv; var fu = u / st.pu - wu, fv = v / st.pv - wv;
@ -1272,7 +1391,8 @@
var WATER_N = WATER.length; var WATER_N = WATER.length;
function floorTex(wx, wz, dist, t) { function floorTex(wx, wz, dist, t) {
weatherAt(t === undefined ? 0 : t); if (alt) return alt.floorTex(wx, wz, dist, t);
weatherAt(t === undefined ? 0 : t); dayAt(t === undefined ? 0 : t);
var lane = wx - CFG.streetX; var lane = wx - CFG.streetX;
if (CFG.streetPeriod > 0) lane -= Math.round(lane / CFG.streetPeriod) * CFG.streetPeriod; if (CFG.streetPeriod > 0) lane -= Math.round(lane / CFG.streetPeriod) * CFG.streetPeriod;
var al = lane < 0 ? -lane : lane; var al = lane < 0 ? -lane : lane;
@ -1339,6 +1459,9 @@
* this is what they land on. * this is what they land on.
* *
* Squared falloff and no edge — light does not have one. */ * Squared falloff and no edge — light does not have one. */
/* The pool under a street lamp is the carriageway's only large-scale rhythm — and it is a LAMP,
* so it goes out when the lamps do. What replaces it by day is the sky lifting the whole road
* evenly, which is handled in the tiers below rather than here. */
var lampK = 0; var lampK = 0;
if (fl > 0) { if (fl > 0) {
var lj = Math.floor(wz / 13.5); var lj = Math.floor(wz / 13.5);
@ -1347,6 +1470,7 @@
var dll = (lane - lcl) / 3.0, dlpz = (wz - lcz) / 4.1; var dll = (lane - lcl) / 3.0, dlpz = (wz - lcz) / 4.1;
lampK = 1 - (dll * dll + dlpz * dlpz); lampK = 1 - (dll * dll + dlpz * dlpz);
if (lampK < 0) lampK = 0; else lampK *= lampK; if (lampK < 0) lampK = 0; else lampK *= lampK;
lampK *= dLamp;
} }
mirNow = clamp(pd * 0.95 + sheet * (0.40 + rut * 0.26), 0, 1); mirNow = clamp(pd * 0.95 + sheet * (0.40 + rut * 0.26), 0, 1);
@ -1481,7 +1605,11 @@
/* Centreline: dashed, sodium-amber because that is the colour the street lamps paint it. */ /* 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) if (al < 0.13 && (wz - Math.floor(wz / 4.6) * 4.6) < 2.8)
return rset(G_PIPE, P.amber, 150 + sheet * 60); /* Sodium-amber because that is the colour the street lamps paint it — at night. By day it
* is white paint on grey tarmac and nothing else, and amber's day EXPOSURE of 0.30 would
* make a yellow centreline the dimmest line on the road rather than the brightest. */
return rset(G_PIPE, dSky > 0.45 ? P.white : P.amber,
(150 + sheet * 60) * (dSky > 0.45 ? 0.9 + 0.5 * dSky : 1));
/* Edge line. Solid, unbroken, and the reason it is here: it is the one white line that runs /* 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 * the entire depth of the frame, so it converges to the vanishing point on its own and
@ -1544,7 +1672,13 @@
* print a mean v of 143 with 3.3% of them over the v=170 hot line, against a whole-frame * 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 * 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. */ * 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); /* The kerb is the longest continuous line in the frame. At night it is a metre under a
* sodium lamp and nothing else in the picture is lit so unambiguously; by day it is
* concrete lit by the sky, which is white, and its rhythm comes from the sky rather than
* from the lamp spacing that lampK carries. */
return dSky > 0.45
? rset(G_UNDER, P.white, (96 + kw * 30 + mirNow * 26) * (0.7 + 0.7 * dSky))
: rset(G_UNDER, P.amber, 124 + kw * 34 + lampK * 74 + mirNow * 30);
return rset(G_EQ, P.slate, 10 + kw * 12); return rset(G_EQ, P.slate, 10 + kw * 12);
} }
@ -1841,8 +1975,70 @@
* module state, no allocation, no camera term, and if a caller ever violates the sweep order * 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. */ * the worst case is a glow anchored one row off. */
var skyLastSy = 1e9, skyRoof = 0; var skyLastSy = 1e9, skyRoof = 0;
/* The surface star field's own visibility. It is a SECOND star field — elements/sky.js draws
* four hundred placed stars and this draws the faint scatter between them — and it had the same
* bug: nothing took it away when the sun came up. */
function dStarSurf() { return CC.Daylight ? CC.Daylight.P.star : 1; }
/* ---- THE CITY BY DAY ----------------------------------------------------------------------
* Everything below this line is a night sky: light pollution anchored to a roofline, and stars.
* A day sky is not that function with different numbers, it is a different object, so it gets
* its own branch rather than a scatter of `if (day)` inside the night one.
*
* WHAT A CITY SKY LOOKS LIKE FROM THE BOTTOM OF A CANYON, which is the only place this renderer
* ever stands: a bright, nearly featureless band, palest at the roofline where you are looking
* through the most air and along the most of the city's own murk, cooling and deepening upward.
* It is the INVERSE of the night gradient in every respect — bright at the horizon rather than
* glowing at the rooftops, near-solid rather than dithered thin, and cool rather than sodium.
*
* THE SWATCHES ARE CHOSEN OFF THE DAY LADDER, not off what a sky "is". core.js's day EXPOSURE
* table puts ice at 0.66 and white at 0.92 and drops azure to 0.30 — so azure, which is the
* obvious swatch for a blue sky and is the swatch the NIGHT ladder makes a pillar, is by day the
* one that cannot carry it. Ice carries the blue and white carries the pale band under it.
*
* IT IS NEAR-SOLID, and that is the one place this file's standing argument is deliberately
* overruled. The night sky is dithered because "a solid low-lum fill would read as the grey sky
* the references refuse to have" — true, and a day sky IS a solid fill, which is why the muddy
* census that argument protects is a night census and says so now. */
function skyDay(sx, sy, ey, aboveH) {
var rows = CFG.rows > 8 ? CFG.rows : 60;
/* Height up the visible dome, 0 at the horizon. Fractions of the GRID rather than rows, the
* same rule the night glow's e-fold learned. */
var a = aboveH / rows;
var hs = hash2(sx, ey, CFG.skySeed ^ 0x3D), hs2 = hash2(sx, ey, CFG.skySeed ^ 0x5B);
/* Murk: the city's own haze, thickest at the roofline. It is what makes a city sky white at
* the bottom and blue at the top, and it thickens with the weather's fog and haze. */
var murk = Math.exp(-a / (0.16 + 0.20 * wFogP)) * (0.55 + 0.45 * wFogP);
var lift = dSky * (1 - 0.45 * W_CLOUD_DAY());
/* Near-solid, thinning only at the very top where the dome is deepest. */
var cover = (0.94 - 0.30 * a) * lift;
if (hs > cover) return sset(0, P.shadow, 0);
if (murk > 0.55) {
/* The pale band along the rooftops. White at the top of its range: this is the largest
* bright surface a daytime city frame has, and the day ladder gives white the headroom to
* be it. */
return sset(hs2 > 0.5 ? G_EQ : G_DASH, P.white,
(150 + 70 * murk) * lift * (0.86 + 0.22 * hs2));
}
if (murk > 0.22) {
return sset(G_TICK, hs2 > 0.34 ? P.ice : P.white,
(120 + 90 * murk) * lift * (0.84 + 0.26 * hs2));
}
/* The deep dome. Ice, and it darkens upward — which is real, and is the only gradient in a
* clear day sky the eye reliably reads. */
return sset(hs2 > 0.72 ? G_COLON : G_DOT, P.ice,
(74 + 84 * murk) * lift * (0.8 + 0.3 * hs2));
}
function W_CLOUD_DAY() { return CC.Weather ? CC.Weather.P.cloud : 0.75; }
function sky(sx, sy, t) { function sky(sx, sy, t) {
/* Before the roofline memo, not after: the frontier's sky does not use it, and running the
* sweep-order bookkeeping for a consumer that will never read it is dead work per cell. */
if (alt) return alt.sky(sx, sy, t);
dayAt(t === undefined ? 0 : t);
if (sy >= skyLastSy) skyRoof = sy + 1; if (sy >= skyLastSy) skyRoof = sy + 1;
skyLastSy = sy; skyLastSy = sy;
@ -1873,6 +2069,15 @@
var e = CFG.rows * 0.185; var e = CFG.rows * 0.185;
if (e < 3) e = 3; if (e < 3) e = 3;
var aboveH = CFG.horizon - sy; if (aboveH < 0) aboveH = 0; var aboveH = CFG.horizon - sy; if (aboveH < 0) aboveH = 0;
/* THE HANDOVER, and it is a hard switch on purpose. A blend between a dithered sodium glow and
* a near-solid daylight field is not a twilight, it is two skies drawn at half strength each;
* what makes the transition read is that both sides of it are already scaled by dSky, so the
* night sky is fading out on its own as the day sky fades in on its own, and the swap happens
* where each of them is contributing least. 0.30 is the middle of civil twilight. */
if (dSky > 0.30) {
var ey0 = Math.floor((CFG.horizon - sy) * CFG.skyVScale);
return skyDay(sx, sy, ey0, aboveH);
}
/* The star field's VERTICAL, which must be an elevation and not a screen row. /* 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 * The integration note at the top of this file tells the caller how to compensate for yaw and
@ -1895,6 +2100,11 @@
var glow = Math.exp(-aboveR / e) * 0.94; var glow = Math.exp(-aboveR / e) * 0.94;
var gh = Math.exp(-aboveH / e); var gh = Math.exp(-aboveH / e);
if (gh > glow) glow = gh; if (gh > glow) glow = gh;
/* It is the CITY LIGHTING ITS OWN UNDERSIDE, so it goes out with the city's lights rather than
* with the sun. In the pre-dawn hour when the lamps are still burning the glow is still there
* and the sky above it is already grey, which is exactly right and is the one hour this
* function and skyDay() are both contributing. */
glow *= 0.15 + 0.85 * dLamp;
/* 124, not 82, and the reason WAS the print's KNEE. That instruction — "if EXPOSURE[amber] /* 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 * moves, re-measure the sky's lit fraction" — has now been honoured, because it did move, and
@ -1932,14 +2142,14 @@
/* Stars only well clear of the glow — nothing survives being seen through a city. Gated on /* 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: * 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. */ * exp(-0.64) is where the dither has thinned enough for a star to hold its own. */
if (glow < 0.53) { if (glow < 0.53 && dStarSurf() > 0.02) {
var s = hash2(sx, ey, 0x1337); var s = hash2(sx, ey, 0x1337);
if (s < 0.0075) { if (s < 0.0075 * dStarSurf()) {
/* Twinkle is motion, and motion is opt-out. Frozen it is still a star. */ /* Twinkle is motion, and motion is opt-out. Frozen it is still a star. */
var tw = CC.reducedMotion ? 0.86 var tw = CC.reducedMotion ? 0.86
: 0.55 + 0.45 * hash2(sx ^ Math.floor(t * 0.8), ey, 0x99); : 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, return sset(s < 0.0018 ? G_PLUS : G_DOT, s < 0.0035 ? P.ice : P.white,
(52 + s * 9000) * tw); (52 + s * 9000) * tw * dStarSurf());
} }
} }
return sset(0, P.shadow, 0); return sset(0, P.shadow, 0);
@ -1957,6 +2167,18 @@
* those wants to be re-based every time it drizzles. What the weather moves is how far you can * 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. */ * SEE, and that is this pair. */
var fogEnd = FOG_END, fogSpan = FOG_END - FOG_START; var fogEnd = FOG_END, fogSpan = FOG_END - FOG_START;
/* ---- and how far you can see on the frontier -------------------------------------------------
* 210 m against the city's 125, and a gentler curve on top of it. This is not a preference about
* haze, it is the difference between the two places: a city street is a canyon and everything in
* it is within forty metres, so a ramp that crushes past 55 m costs nothing and buys the black
* the print wants. A frontier main street is 17 m wide with two-storey buildings on it, so the
* far end of it is 150 m away and IN FRAME — and under the city's ramp all of it, plus every
* butte behind it, printed as black. Measured at 200x60: the whole picture came out at 0.10% hot
* and 66% blank with the street simply ending in nothing about a third of the way up the frame.
*
* The exponent moves with it, 1.5 -> 1.25, because the point of the long ramp is the far end and
* a pow that crushes the tail would give the distance back with one hand and take it with the
* other. Everything nearer than FOG_START is untouched in both worlds. */
function refog() { function refog() {
/* P.fog is 0.30 under the reference preset, so k is 0 for the look that shipped, +1 in a full /* 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 * mist and about -0.31 on a clear night. Deliberately a gentle swing: the house rule is that
@ -1964,17 +2186,49 @@
* that ate forty metres of canyon would take the frame's black budget with it. */ * that ate forty metres of canyon would take the frame's black budget with it. */
var k = (wFogP - 0.30) / 0.70; var k = (wFogP - 0.30) / 0.70;
if (k > 1) k = 1; else if (k < -0.45) k = -0.45; if (k > 1) k = 1; else if (k < -0.45) k = -0.45;
fogEnd = FOG_END * (1 - 0.26 * k); /* The RANGE and the CURVE both come off the live painter now rather than off `alt` used as a
fogSpan = fogEnd - FOG_START; * boolean meaning "is west". A world that does not name them gets the city's, which is what
* makes the city itself need no painter object at all. */
fogStart = (alt && alt.fogStart !== undefined) ? alt.fogStart : FOG_START;
fogEnd = ((alt && alt.fogEnd !== undefined) ? alt.fogEnd : FOG_END) * (1 - 0.26 * k);
fogSpan = fogEnd - fogStart;
fogPow = (alt && alt.fogPow !== undefined) ? alt.fogPow : 1.5;
/* ---- AERIAL PERSPECTIVE, and it is the one place the house doctrine has an exception -------
* The doctrine, stated three times in this file, is that distance fades to BLACK and never to
* grey: there is no scatter colour in the reference frames and a far facade simply stops
* emitting. That is true of a city at night and false of anywhere in daylight, where the one
* thing that tells you a mesa is eight miles off is the amount of lit air stacked in front of
* it — distance fades TOWARD the sky, not away from it.
*
* fog() has no hue channel and cannot be given one cheaply (it is called twenty thousand times
* a frame and returns a scalar), so what is added is the VALUE half of aerial perspective and
* not the colour half: by day a far cell settles onto a haze floor instead of going to zero,
* and the floor rises with how bright the sky is and how much is in the air. A far cell keeps
* its own swatch, which is wrong in principle and nearly invisible in practice at the lums the
* floor operates at — and the alternative was a second array and a second write per cell. */
var D = CC.Daylight;
/* AND NOT ON A WORLD WITH NO AIR. Aerial perspective is light scattered by the medium between
* here and the thing being looked at; in vacuum there is none, and the whole point of Moonwalk
* is that a boulder at 100 m is exactly as bright as one at 3 m. A painter says so by exporting
* `airless`. Measured before the guard: at the Moon's local noon the floor was adding about 4
* lum of 120 at 200 m — small, and wrong in the way that matters, because it is the one visual
* cue that would have made lunar distances judgeable. */
hazeFloor = (D && !(alt && alt.airless)) ? D.P.sky * (0.30 + 0.55 * wFogP) * 46 : 0;
} }
var fogStart = FOG_START, fogPow = 1.5, hazeFloor = 0;
function fog(lum, dist) { function fog(lum, dist) {
if (!(dist === dist) || dist === Infinity) return lum; // sky (Infinity) and NaN pass through if (!(dist === dist) || dist === Infinity) return lum; // sky (Infinity) and NaN pass through
if (dist <= FOG_START) return lum; if (dist <= fogStart) return lum;
if (dist >= fogEnd) return 0; if (dist >= fogEnd) return 0;
var k = 1 - (dist - FOG_START) / fogSpan; var k = 1 - (dist - fogStart) / fogSpan;
k = k * Math.sqrt(k); // pow 1.5: gentle near, hard crush past ~55 m /* pow 1.5 in the city: gentle near, hard crush past ~55 m. The frontier asks for 1.25, where
* the far end of the ramp is the whole reason it is long. */
k = fogPow === 1.5 ? k * Math.sqrt(k) : Math.pow(k, fogPow);
var v = lum * k; var v = lum * k;
return v < 4 ? 0 : v | 0; // crush the tail so nothing settles into grey mush /* The haze floor is applied to what the distance TOOK, so a near cell is untouched and a far
* one is lifted by the light in the air between. Zero at night, which is the doctrine intact. */
if (hazeFloor > 0) v += hazeFloor * (1 - k) * (lum > 24 ? 1 : lum / 24);
return v < 4 ? 0 : (v > 255 ? 255 : 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 /* Called once at the top of the world pass, before any per-cell call. It syncs the weather
@ -1982,13 +2236,47 @@
* 0. The caster must use the RETURNED value rather than FOG_END: on a clear night the ramp runs * 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 * 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. */ * at exactly the distance the air stopped hiding it. */
/* ---- the other world -------------------------------------------------------------------------
* WHY THE SWITCH IS HERE AND NOT IN raycast.js. The caster reads CC.Surf four times per cell
* across three call sites plus a configure and a beginFrame, and every one of those reads is on
* the hottest path in the project. Swapping CC.Surf itself for a second object was tried and is
* worse than it looks: signage.js, street.js, market.js and structure.js all hold CC.Surf.cfg or
* CC.Surf.SHOP_OPEN, several of them captured at boot, so a swap leaves half the build reading a
* config block nobody is filling in any more.
*
* So there is ONE CC.Surf, it keeps owning configure(), cfg, fog() and beginFrame() — none of
* which is world-specific, all of which several files depend on being a single object — and only
* the three functions that actually paint delegate. `alt` is resolved once per frame in
* beginFrame rather than per cell: it is a property read and a string compare, twenty thousand
* times a frame, for an answer that cannot change inside one frame. */
/* ---- the painter registry -----------------------------------------------------------------
* `CC.SURFACES` is a map from world id to painter, and every painter file registers ITSELF into
* it at load. That is the difference between two worlds and N: the previous version of this was
* `id === 'west' ? CC.SurfWest : null`, a hardcoded pair, and the failure mode when a third world
* arrived was not an error — it was `alt = null`, which paints the new world with the CITY's
* facades, asphalt and neon sky and says nothing at all about it.
*
* A painter must export facade/floorTex/sky with these exact signatures, and MAY export
* fogStart/fogEnd/fogPow to move the depth ramp; anything it leaves out falls back to the city's
* value, which is why the city itself needs no entry. */
var alt = null;
if (!CC.SURFACES) CC.SURFACES = {};
function resolveWorld() {
alt = (CC.World && CC.SURFACES[CC.World.id]) || null;
}
function beginFrame(t) { function beginFrame(t) {
resolveWorld();
dayAt(t === undefined ? 0 : t);
weatherAt(t === undefined ? 0 : t); weatherAt(t === undefined ? 0 : t);
return fogEnd; return fogEnd;
} }
CC.Surf = { CC.Surf = {
facade: facade, floorTex: floorTex, sky: sky, fog: fog, facade: facade, floorTex: floorTex, sky: sky, fog: fog,
/* Published so a caller that paints without going through the world pass — a probe, a test —
* can bind the world itself. raycast.js gets it for free from beginFrame(). */
resolveWorld: resolveWorld,
configure: configure, cfg: CFG, beginFrame: beginFrame, configure: configure, cfg: CFG, beginFrame: beginFrame,
FOG_START: FOG_START, FOG_END: FOG_END, FOG_START: FOG_START, FOG_END: FOG_END,
/* The share of ground-floor units that are open, published because signage.js's shopSpill has /* The share of ground-floor units that are open, published because signage.js's shopSpill has

View file

@ -33,7 +33,7 @@
var KEYS = ['rain', 'wind', 'fog', 'wet', 'storm', 'haze', 'cloud', 'steam']; var KEYS = ['rain', 'wind', 'fog', 'wet', 'storm', 'haze', 'cloud', 'steam'];
/* rain wind fog wet storm haze cloud steam */ /* rain wind fog wet storm haze cloud steam */
var PRESETS = [ var PRESETS_CYBER = [
{ name: 'clear', p: [0.00, 0.25, 0.08, 0.12, 0.00, 0.10, 0.08, 0.55] }, { 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: '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: 'rain', p: [0.65, 0.55, 0.30, 0.90, 0.12, 0.40, 0.75, 0.85] },
@ -43,6 +43,85 @@
]; ];
var REF_I = 2; // 'rain' — the preset the pre-weather build was tuned as var REF_I = 2; // 'rain' — the preset the pre-weather build was tuned as
/* ---- the frontier's own six ------------------------------------------------------------------
* SAME EIGHT DIRECTIONS, DIFFERENT SKY. The parameters above are physical rather than cyberpunk
* — wind is wind, haze is how far you can see, wet is how much the ground holds — so a desert
* does not need a second director, it needs a second table. What changes is which combinations
* exist: out here it is dry for weeks and then it is not, so the middle of this table is made of
* DUST rather than of drizzle, and the wet states are short and violent.
*
* `haze` never goes below 0.30 in any row, and that is the frontier's signature: there is always
* something in the air. The city's `clear` is 0.10 and reads as washed glass; a desert horizon
* at 0.10 reads as a cardboard cut-out, because the one thing that tells you a mesa is eight
* miles away rather than eight hundred metres is the amount of atmosphere stacked in front of it.
*
* WHAT rel() STILL MEANS. INV_REF below is deliberately NOT rebuilt from this table — it stays
* pinned to the city's 'rain' row forever. rel() is the migration contract every element was
* written against ("1.0 is the look that shipped"), so it has to denote the same physical
* quantity in both worlds; rebasing it per world would silently re-tune rain.js and every optic
* the moment the viewer pressed 2. These rows are therefore absolute values in the same units,
* and a squall out here really is 0.70 of the rain the city was tuned under. */
/* rain wind fog wet storm haze cloud steam */
var PRESETS_WEST = [
{ name: 'blazing', p: [0.00, 0.18, 0.04, 0.04, 0.00, 0.30, 0.04, 0.24] },
{ name: 'breeze', p: [0.00, 0.52, 0.08, 0.04, 0.00, 0.52, 0.16, 0.20] },
{ name: 'dust', p: [0.00, 0.82, 0.34, 0.03, 0.10, 0.88, 0.36, 0.18] },
{ name: 'squall', p: [0.72, 0.72, 0.24, 0.88, 0.22, 0.38, 0.86, 0.50] },
{ name: 'overcast', p: [0.06, 0.34, 0.26, 0.18, 0.00, 0.54, 0.94, 0.32] },
{ name: 'thunder', p: [0.58, 0.98, 0.38, 0.82, 1.00, 0.46, 1.00, 0.42] }
];
/* Out here the sequence is a drought broken by a storm and then a long dry-out, so the strong
* pull is towards the top of the table and the wet states hand back to dust rather than to each
* other. blazing -> squall is zero: a desert cloudburst arrives on a wind, and you always see
* the dust come up the valley first. */
var NEXT_WEST = [
/* blazing -> */ [0, 6, 3, 0, 2, 0],
/* breeze -> */ [5, 0, 6, 1, 2, 1],
/* dust -> */ [4, 6, 0, 3, 2, 2],
/* squall -> */ [1, 3, 4, 0, 3, 2],
/* overcast -> */ [3, 4, 3, 3, 0, 3],
/* thunder -> */ [0, 2, 4, 4, 3, 0]
];
/* ---- and the Moon has no weather at all ---------------------------------------------------------
* ONE ROW, every parameter zero, and that is the honest answer rather than a placeholder. There
* is no air on the Moon: no rain, no wind, no fog, no cloud, nothing suspended in anything. The
* director still has to run — eight files read CC.Weather.P every frame and none of them should
* have to know which world it is in — so it runs and reports that nothing is happening.
*
* A one-row table is also what makes the rest of the machinery behave. pickNext() can only ever
* return row 0, the segment schedule advances through a single state forever, and the shift-digit
* keys collapse to one because control.js gates them on PRESETS.length rather than on a literal
* six. Nothing needed a special case; the data says it. */
/* rain wind fog wet storm haze cloud steam */
var PRESETS_MOON = [
{ name: 'vacuum', p: [0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00] }
];
var NEXT_MOON = [[1]];
/* ---- the table registry ------------------------------------------------------------------------
* Keyed by world id. The two-way string compare this replaced meant a third world silently ran
* the CITY's rain schedule — which on the Moon would have been a rainstorm in vacuum.
*
* BUILT INSIDE init() AND NOT HERE, and the reason is a real bug that this file was already
* carrying: `var PRESETS = PRESETS_CYBER, NEXT = NEXT_CYBER;` sits ABOVE NEXT_CYBER's own
* declaration, so NEXT was `undefined` from load until the first init(). That was harmless while
* nothing read it in between; a registry literal in the same position captured the undefined and
* handed it to every world, and pickNext threw on the first segment. Built on demand it cannot
* capture anything that has not been declared. */
var TABLES = null;
function tables() {
if (!TABLES) TABLES = { cyber: [PRESETS_CYBER, NEXT_CYBER],
west: [PRESETS_WEST, NEXT_WEST],
moon: [PRESETS_MOON, NEXT_MOON] };
return TABLES;
}
/* The live tables. Reassigned by init() from CC.World, never mid-segment: a world change tears
* the city down and rebuilds it, and init() is part of that rebuild. */
var PRESETS = PRESETS_CYBER, NEXT = NEXT_CYBER;
/* SIX PRESETS, FOUR LOOKS — a known and UNFIXED gap, recorded here so it is not re-derived by /* 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 * 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 * share of cells whose printed luminance differs by more than 10% of full scale is: clear vs
@ -76,7 +155,7 @@
/* Not every state follows every other. Sun does not come out in the middle of a downpour; it /* 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 * 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). */ * relative weights of what may come next (self excluded at pick time). */
var NEXT = [ var NEXT_CYBER = [
/* clear -> */ [0, 5, 2, 0, 3, 0], /* clear -> */ [0, 5, 2, 0, 3, 0],
/* drizzle -> */ [4, 0, 5, 1, 3, 1], /* drizzle -> */ [4, 0, 5, 1, 3, 1],
/* rain -> */ [1, 5, 0, 4, 2, 3], /* rain -> */ [1, 5, 0, 4, 2, 3],
@ -86,11 +165,12 @@
]; ];
function pickNext(prev, n) { function pickNext(prev, n) {
var row = NEXT[prev], tot = 0, i; var row = NEXT[prev], tot = 0, i, m = row.length;
for (i = 0; i < 6; i++) tot += row[i]; for (i = 0; i < m; i++) tot += row[i];
if (tot <= 0) return prev; // a one-row table: there is nowhere else to go
var r = hash1(n, S + 7717) * tot; var r = hash1(n, S + 7717) * tot;
for (i = 0; i < 6; i++) { r -= row[i]; if (r <= 0) return i; } for (i = 0; i < m; i++) { r -= row[i]; if (r <= 0) return i; }
return REF_I; return prev;
} }
function extend(tMax) { function extend(tMax) {
@ -105,7 +185,7 @@
/* The live parameter block. Elements hold a reference to THIS object and read fields off it /* 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. */ * 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 }; 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]; for (var ki = 0; ki < KEYS.length; ki++) W[KEYS[ki]] = PRESETS_CYBER[REF_I].p[ki];
function apply(a, b, f) { function apply(a, b, f) {
var A = PRESETS[a].p, B = PRESETS[b].p; var A = PRESETS[a].p, B = PRESETS[b].p;
@ -158,7 +238,7 @@
var KI = {}, INV_REF = []; var KI = {}, INV_REF = [];
for (var kj = 0; kj < KEYS.length; kj++) { for (var kj = 0; kj < KEYS.length; kj++) {
KI[KEYS[kj]] = kj; KI[KEYS[kj]] = kj;
var rv = PRESETS[REF_I].p[kj]; var rv = PRESETS_CYBER[REF_I].p[kj];
INV_REF.push(rv > 1e-6 ? 1 / rv : 1); INV_REF.push(rv > 1e-6 ? 1 / rv : 1);
} }
function rel(key) { function rel(key) {
@ -168,7 +248,14 @@
var Weather = { var Weather = {
P: W, // the live parameter block; hold this, do not copy it P: W, // the live parameter block; hold this, do not copy it
KEYS: KEYS, PRESETS: PRESETS, REF: PRESETS[REF_I].p, KEYS: KEYS,
/* Getters, because these two used to be captured at load time and a world switch swaps the
* table underneath them — a reader holding the array it was handed at boot would be naming
* the city's weather while standing in a dust storm. REF stays the CITY's reference row on
* purpose: it is what rel() divides by, and that is a constant of the build, not of the
* world (see PRESETS_WEST). */
get PRESETS() { return PRESETS; },
REF: PRESETS_CYBER[REF_I].p,
/* Takes the city and NOTHING ELSE. Callers used to hand this an rng and the parameter was /* 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 * 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. * segment schedule that depended on draw order could not be scrubbed to frame 9000 offline.
@ -179,6 +266,12 @@
* ignored, which is exactly what they were already. */ * ignored, which is exactly what they were already. */
init: function (city) { init: function (city) {
S = city && city.seed !== undefined ? (city.seed | 0) : 0; S = city && city.seed !== undefined ? (city.seed | 0) : 0;
/* The world's table is bound HERE and nowhere else. A world change is a rebuild — main.js
* drops the city and calls this again — so the schedule, the override and the live block all
* restart together and nothing can be left blending from a preset that no longer exists. */
var TB = tables();
var T = TB[(CC.World && CC.World.id) || 'cyber'] || TB.cyber;
PRESETS = T[0]; NEXT = T[1];
segT = [0]; segT = [0];
/* Never open on `clear`. The first thing anyone sees should have weather in it — a dry /* 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". * still night is the one state that reads as "nothing is implemented yet".
@ -197,7 +290,10 @@
* and the blend has finished. These are a function of CC.hash1, PRESETS, NEXT, DUR_MIN and * 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 * DUR_VAR — recompute them whenever any of those moves, as the hash change that took them
* off 122069/9595/31019/57290 shows.) */ * off 122069/9595/31019/57290 shows.) */
segI = [1 + ((hash1(0, S + 313) * 5) | 0)]; /* PRESETS.length - 1 rather than the literal 5, which was correct only because both tables
* happened to be exactly six rows. A one-row table indexes 1 + 0*0 = 1 and walks off the end;
* this makes it 0, which is the only row there is. */
segI = [PRESETS.length > 1 ? 1 + ((hash1(0, S + 313) * (PRESETS.length - 1)) | 0) : 0];
forcedI = -1; forcedAt = -1e9; forcedI = -1; forcedAt = -1e9;
update(0, 0); update(0, 0);
}, },

151
src/world.js Normal file
View file

@ -0,0 +1,151 @@
/* CyberCity worlds — which place you are standing in.
*
* WHY THIS FILE IS FOUR FIELDS AND NOT A THEME ENGINE. Everything downstream of here already owns
* its own tuning, and most of that tuning is measured rather than tasted — city.js's district
* weights were fitted against a 1.44 M-cell census, surfaces.js's exposure bands against the print
* histogram, market.js's lit budget against the muddy band. Hoisting all of that into one central
* "theme object" would move six files' hard-won numbers into a table nobody can measure against,
* and the first world that wanted a different road would have to bring the whole street with it.
*
* So this module carries the ANSWER TO ONE QUESTION — which world is live — and every other file
* keeps its own data for both of them, right next to the numbers it already has. city.js holds two
* district tables, weather_state.js holds two preset tables, surfaces.js delegates to surf_west.js,
* and an element that belongs to one world says so on itself with `world: 'west'`. The registry is
* therefore the only thing that has to be correct here; a world is otherwise defined by grepping
* for its id, which is exactly how a reader will look for it.
*
* THE SWITCH REBUILDS. Changing world changes the heightmap, so main.js tears the city down and
* builds a new one on the SAME seed — #42 is a place in both worlds, and flipping between them is
* how you see what the seed actually means. Nothing here does the rebuild: this file records the
* choice and calls back, because main.js owns the city and the element list and this file owns
* neither.
*/
(function (CC) {
'use strict';
/* Order is the key order: LIST[0] is '1'. The id is what every other file compares against and
* it is a string rather than an index for exactly that reason — `CC.World.id === 'west'` at a
* call site says what it means, `w === 1` does not.
*
* LIST[0] IS THE URL DEFAULT. main.js's fragment() omits the prefix for it, so `#42` addresses
* whatever sits at index 0 — which means a new world must be APPENDED and never prepended, or
* every link anyone has ever shared silently re-addresses itself to somewhere else.
*
* `name` IS PRINTED THROUGH A 3x5 BITMAP FONT that covers A-Z, 0-9, '-', '/' and '.' and nothing
* else (see elements/hud.js). A name with a lowercase letter, an apostrophe or an ampersand in it
* renders as blanks with no warning, so the alphabet is a hard constraint on this table rather
* than a style note.
*
* `aliases` live on the row rather than in a switch inside resolve(), so adding a world is one
* table edit and two worlds claiming the same short form is visible in one place. */
var LIST = [
{ id: 'cyber', name: 'CYBERCITY', aliases: ['city', 'cybercity', 'c'] },
{ id: 'west', name: 'FRONTIER', aliases: ['western', 'frontier', 'w'] },
{ id: 'moon', name: 'MOONWALK', aliases: ['moonwalk', 'lunar', 'apollo', 'm'] }
];
var cur = 0;
function indexOf(id) {
for (var i = 0; i < LIST.length; i++) if (LIST[i].id === id) return i;
return -1;
}
/* Accepts an id, an index, or a 1-based key number, because three callers want three of those:
* control.js has a digit, main.js has a fragment, and the harness has whatever was typed. */
function resolve(v) {
if (typeof v === 'number') {
var i = v | 0;
/* 1-based first: the keyboard is the only place a number comes from in the browser, and a
* viewer pressing 1 means the first world, not the second. Index 0 is still reachable from
* code, which is what the `=== 0` case is for. */
if (i >= 1 && i <= LIST.length) return i - 1;
if (i === 0) return 0;
return -1;
}
if (typeof v === 'string') {
var s = v.toLowerCase();
var k = indexOf(s);
if (k >= 0) return k;
/* Aliases, scanned off the rows. The fragment is a URL a person types, and 'western' is what
* they will type. An id always wins over an alias because the id scan above runs first. */
for (var i = 0; i < LIST.length; i++) {
var a = LIST[i].aliases;
if (!a) continue;
for (var j = 0; j < a.length; j++) if (a[j] === s) return i;
}
if (/^\d+$/.test(s)) return resolve(parseInt(s, 10));
}
return -1;
}
var World = {
LIST: LIST,
/* The id every other file compares against, and the default every fallback should use rather
* than repeating the literal 'cyber' — which main.js, headless.cjs and the element gate each
* did in their own copy before this existed. */
DEFAULT: LIST[0].id,
id: LIST[0].id,
name: LIST[0].name,
index: 0,
/* A GETTER, not a snapshot. Two input paths gate on it — the digit keys and the gamepad's
* cycle button — and a number captured at module load is the kind of thing that is correct
* until the day the roster is built rather than declared. */
get count() { return LIST.length; },
/* Does this element belong in world `id`? The ONE definition, shared by main.js's rebuild gate,
* tools/headless.cjs, and the photosensitivity gates — because those three had three copies of
* it and an offline reference frame rendered from a different element set than the browser's is
* a reference frame that is not the frame the browser draws.
*
* `world` may be absent (every world), a string (exactly one), or an array (a named set). The
* array form is what three worlds made necessary: with two, "one world" and "all worlds" were
* the only sets there were. */
inWorld: function (el, id) {
var w = el && el.world;
if (!w) return true;
if (typeof w === 'string') return w === id;
for (var i = 0; i < w.length; i++) if (w[i] === id) return true;
return false;
},
is: function (id) { return World.id === id; },
at: function (v) { var i = resolve(v); return i < 0 ? null : LIST[i]; },
/* Returns 1 if the world actually changed, so a caller can skip a rebuild it does not need —
* pressing 1 while already in the city must not restart the walk. */
set: function (v) {
var i = resolve(v);
if (i < 0 || i === cur) return 0;
cur = i;
World.id = LIST[i].id; World.name = LIST[i].name; World.index = i;
return 1;
},
/* Set with no callback and no change test — for the boot path and the offline harness, both of
* which choose a world BEFORE anything exists to rebuild. */
force: function (v) {
var i = resolve(v);
if (i < 0) return 0;
cur = i;
World.id = LIST[i].id; World.name = LIST[i].name; World.index = i;
return 1;
},
/* The ONE cycling rule, and it now has a caller: control.js's gamepad button used to open-code
* `index + 2 > count ? 1 : index + 2`, which was forward-only and correct for exactly two
* worlds. An unused API next to a hand-rolled duplicate of it is how the third world would have
* arrived with a pad button that needed two presses to come home. */
cycle: function (dir) {
return World.set(LIST[(cur + (dir < 0 ? LIST.length - 1 : 1)) % LIST.length].id);
}
};
/* Published on CC as well, because the element gate is read by files that have no reason to know
* about a registry — the two photosensitivity tools among them. */
CC.inWorld = World.inWorld;
CC.World = World;
if (typeof module !== 'undefined') module.exports = World;
})(typeof CC !== 'undefined' ? CC : require('./core.js'));

View file

@ -343,7 +343,14 @@ function makeEnv(opts) {
bump('getComputedStyle'); bump('getComputedStyle');
return { getPropertyValue: function () { return ''; }, fontFamily: '', width: '0px', height: '0px' }; return { getPropertyValue: function () { return ''; }, fontFamily: '', width: '0px', height: '0px' };
}; };
win.navigator = { userAgent: 'domshim', platform: 'shim', maxTouchPoints: 5 }; /* getGamepads is present but empty by default, which is the state of a browser with no pad
* plugged in and the branch control.js takes on every desktop. `env.pads` is what a test writes
* to in order to plug one in. */
env.pads = [];
win.navigator = {
userAgent: 'domshim', platform: 'shim', maxTouchPoints: 5,
getGamepads: function () { bump('getGamepads'); return env.pads; }
};
win.alert = function () { bump('alert'); }; win.alert = function () { bump('alert'); };
win.window = win; win.window = win;
win.self = win; win.self = win;
@ -609,7 +616,12 @@ testCase('idle-resume', function (ok) {
}); });
/* ============================================================================================ /* ============================================================================================
* 5. weather keys 1..6 and [ ] * 5. weather keys SHIFT+1..6 and [ ]
*
* The bare digits moved to the WORLDS when the frontier landed — see src/world.js and the note in
* control.js — so every preset here is asked for with shift held. Shift is also the run key, which
* is why the camera-seizure check below still matters: shift-2 walks faster for as long as it is
* held, and it must still not hand the camera to the viewer.
* ========================================================================================== */ * ========================================================================================== */
testCase('weather-keys', function (ok) { testCase('weather-keys', function (ok) {
const env = makeEnv({}).run(); const env = makeEnv({}).run();
@ -619,8 +631,8 @@ testCase('weather-keys', function (ok) {
const names = CC.Weather.PRESETS.map(p => p.name); const names = CC.Weather.PRESETS.map(p => p.name);
for (let i = 0; i < 6; i++) { for (let i = 0; i < 6; i++) {
keydown(env, 'Digit' + (i + 1)); keydown(env, 'Digit' + (i + 1), { shiftKey: true });
keyup(env, 'Digit' + (i + 1)); keyup(env, 'Digit' + (i + 1), { shiftKey: true });
env.tick(400); // past TRANS_FORCED (5 s) at 60 Hz env.tick(400); // past TRANS_FORCED (5 s) at 60 Hz
ok(CC.Weather.current === names[i], 'Digit' + (i + 1) + ' -> ' + names[i], CC.Weather.current); ok(CC.Weather.current === names[i], 'Digit' + (i + 1) + ' -> ' + names[i], CC.Weather.current);
ok(CC.Weather.P.forced === true, 'Digit' + (i + 1) + ': the override is flagged as forced'); ok(CC.Weather.P.forced === true, 'Digit' + (i + 1) + ': the override is flagged as forced');
@ -629,9 +641,11 @@ testCase('weather-keys', function (ok) {
CC.Weather.P.rain.toFixed(3) + ' vs ' + want); CC.Weather.P.rain.toFixed(3) + ' vs ' + want);
ok(CC.Control.mode === 0, 'Digit' + (i + 1) + ': changing the sky did NOT seize the camera'); ok(CC.Control.mode === 0, 'Digit' + (i + 1) + ': changing the sky did NOT seize the camera');
} }
/* The layout-independent path: some keyboards deliver no `code`, only `key`. */ /* WITH SHIFT DOWN THERE IS NO KEY PATH, and that is by design rather than an omission: `key` is
keydown(env, 'Digit3', { code: '' }); env.tick(400); * the SHIFTED character on every layout ('!' on US, '"' on UK), so it cannot carry the digit and
ok(CC.Weather.current === 'rain', 'a bare key "3" with no code still sets the preset', CC.Weather.current); * only `code` can. The bare-key path still exists and now selects a WORLD; it is tested there. */
keydown(env, 'Digit3', { shiftKey: true }); env.tick(400);
ok(CC.Weather.current === 'rain', 'Shift+3 -> rain', CC.Weather.current);
keydown(env, 'BracketRight'); env.tick(400); keydown(env, 'BracketRight'); env.tick(400);
ok(CC.Weather.current === 'downpour', '] cycled forward from rain', CC.Weather.current); ok(CC.Weather.current === 'downpour', '] cycled forward from rain', CC.Weather.current);
@ -741,6 +755,143 @@ testCase('hint-fullscreen-newseed', function (ok) {
return [env, fs]; return [env, fs];
}); });
/* ============================================================================================
* 7b. WORLDS — the digits, the fragment, and the rebuild that a world change is.
*
* This is the case that would have caught the whole shape of the feature going wrong, and there
* are four separate things in it that only a running page can answer: that a digit reaches
* main.js's `world` hook at all, that the hook rebuilds on the SAME seed rather than reseeding,
* that the fragment it writes round-trips back through worldFromHash on a reload, and that a
* rebuilt world actually draws — an element list filtered to the wrong world renders an empty
* frame and nothing in src/ would notice.
* ========================================================================================== */
testCase('worlds', function (ok) {
const env = makeEnv({ hash: '#4242' }).run();
const CC = env.CC;
if (!ok(!!CC, 'booted')) return env;
env.tick(90);
ok(CC.World.id === 'cyber', 'a bare seed fragment boots the city', CC.World.id);
const drew0 = env.get('drawImage');
ok(drew0 > 0, 'the city drew', drew0);
keydown(env, 'Digit2'); keyup(env, 'Digit2');
env.tick(90);
ok(CC.World.id === 'west', '2 moved to the frontier', CC.World.id);
ok(CC.Main.seed === 4242, 'the seed came with it — a world change is not a reseed', CC.Main.seed);
ok(env.win.location.hash === '#west/4242', 'the fragment names the world', env.win.location.hash);
const drew1 = env.get('drawImage') - drew0;
ok(drew1 > 0, 'the frontier drew', drew1);
ok(env.errors.length === 0, 'no exceptions across the switch');
keydown(env, 'Digit1'); keyup(env, 'Digit1');
env.tick(60);
ok(CC.World.id === 'cyber', '1 came back to the city', CC.World.id);
ok(env.win.location.hash === '#4242', 'the default world drops its prefix again', env.win.location.hash);
/* Pressing the world you are already in must not restart the walk. */
const before = camSnap(CC);
keydown(env, 'Digit1'); keyup(env, 'Digit1');
env.tick(4);
ok(dist(before, camSnap(CC)) < 3, '1 while already in the city did not rebuild');
/* A digit past the end of the list is not a world and must not be swallowed as one. */
keydown(env, 'Digit7'); keyup(env, 'Digit7');
env.tick(30);
ok(CC.World.id === 'cyber', 'a digit with no world behind it changes nothing', CC.World.id);
/* ---- the gamepad's world button -----------------------------------------------------------
* A pad is the one input device other than a keyboard that can reach the second world, so the
* button is worth a test rather than worth trusting. Button 3 is Y on an Xbox pad and triangle
* on a PlayStation one under the standard mapping. The EDGE is the thing being checked: held
* down, it must move exactly one world and then stop. */
/* `connected` matters: pollPad skips a pad without it, which is what a browser reports for a
* slot that has been unplugged. */
const pad = { connected: true, axes: [0, 0, 0, 0], buttons: [] };
for (let i = 0; i < 8; i++) pad.buttons.push({ pressed: false, value: 0 });
env.pads = [pad];
env.fire(env.win, 'gamepadconnected', {});
env.tick(10);
ok(CC.World.id === 'cyber', 'plugging a pad in changes nothing on its own', CC.World.id);
pad.buttons[3].pressed = true;
env.tick(60); // held down for a whole second
ok(CC.World.id === 'west', 'Y moved to the frontier', CC.World.id);
ok(env.win.location.hash === '#west/4242', 'and wrote the fragment', env.win.location.hash);
/* WALK THE WHOLE ROSTER rather than assuming one more press comes home — which is what this
* asserted while there were exactly two worlds, and which became false the moment there were
* three. It now presses count-1 more times and checks it has arrived back at the start, so it
* stays true however many worlds the registry grows. */
for (var wi = 1; wi < CC.World.count; wi++) {
pad.buttons[3].pressed = false;
env.tick(6);
pad.buttons[3].pressed = true;
env.tick(20);
}
ok(CC.World.id === 'cyber', 'pressing Y once per world walks the whole roster home', CC.World.id);
pad.buttons[3].pressed = false;
env.pads = [];
env.tick(20);
ok(env.errors.length === 0, 'the pad threw nothing');
// Cold boot straight into the frontier, which is the form a shared link takes.
const w = makeEnv({ hash: '#west/77' }).run();
w.tick(90);
ok(!!w.CC && w.CC.World.id === 'west', '#west/77 boots the frontier', w.CC && w.CC.World.id);
ok(!!w.CC && w.CC.Main.seed === 77, '#west/77 boots seed 77', w.CC && w.CC.Main.seed);
ok(w.get('replaceState') === 0, 'a complete fragment is not rewritten on boot', w.get('replaceState'));
ok(w.get('drawImage') > 0, 'the frontier drew from a cold boot', w.get('drawImage'));
ok(w.errors.length === 0, 'cold boot into the frontier threw nothing');
// And the alias, because it is the word a person types.
const a = makeEnv({ hash: '#western/5' }).run();
a.tick(30);
ok(!!a.CC && a.CC.World.id === 'west', '#western/5 is the same place', a.CC && a.CC.World.id);
/* THE THIRD WORLD BOOTS AND DRAWS. This is the case that would have caught the whole class of
* silent third-world failures the plumbing audit found — a world whose theme, painter, weather
* table or element gate falls through to the city renders a perfectly good frame of the WRONG
* PLACE, and nothing short of looking would notice. Checking that it drew is not enough on its
* own, so the element count is checked too: the Moon must not be running the city's rain. */
const m = makeEnv({ hash: '#moon/9' }).run();
m.tick(90);
ok(!!m.CC && m.CC.World.id === 'moon', '#moon/9 boots Moonwalk', m.CC && m.CC.World.id);
ok(!!m.CC && m.CC.Main.seed === 9, 'and seed 9', m.CC && m.CC.Main.seed);
ok(m.get('drawImage') > 0, 'Moonwalk drew', m.get('drawImage'));
ok(!!m.CC && m.CC.Weather.PRESETS.length === 1,
'Moonwalk runs its own weather table, not the city\'s six',
m.CC && m.CC.Weather.PRESETS.length);
ok(m.errors.length === 0, 'Moonwalk threw nothing');
/* THE CLOCK. T steps the time of day and Y stops it; neither may seize the camera. */
const d = makeEnv({}).run();
d.tick(60);
/* Asserted on the PHASE and not on the name, which is a real distinction rather than pedantry:
* the clock's six stops are not six names. 'night' is both the stop at phase 0.00 and the whole
* band from 0.795 round to 0.225, so a seed that opens at 0.85 steps to 0.00 and is still, quite
* correctly, called night. The first version of this check asserted the name changed and failed
* on exactly that seed. */
const t0 = d.CC.Daylight.P.phase;
keydown(d, 'KeyT'); keyup(d, 'KeyT'); d.tick(6);
ok(Math.abs(d.CC.Daylight.P.phase - t0) > 1e-6, 'T stepped the time of day',
t0.toFixed(3) + ' -> ' + d.CC.Daylight.P.phase.toFixed(3) + ' (' + d.CC.Daylight.P.name + ')');
ok(d.CC.Control.mode === 0, 'T did not seize the camera', d.CC.Control.mode);
const names = {};
for (var q = 0; q < 6; q++) { keydown(d, 'KeyT'); keyup(d, 'KeyT'); d.tick(6);
names[d.CC.Daylight.P.name] = 1; }
ok(Object.keys(names).length >= 5, 'six presses of T visit the whole clock',
Object.keys(names).join(','));
keydown(d, 'KeyY'); keyup(d, 'KeyY'); d.tick(4);
ok(d.CC.Daylight.frozen === true, 'Y stopped the automatic cycle');
const held = d.CC.Daylight.P.phase;
d.tick(600);
ok(Math.abs(d.CC.Daylight.P.phase - held) < 1e-9, 'and the clock is holding still',
d.CC.Daylight.P.phase.toFixed(5));
keydown(d, 'KeyY'); keyup(d, 'KeyY'); d.tick(60);
ok(d.CC.Daylight.frozen === false, 'Y again restarted it');
ok(d.CC.Daylight.P.phase > held, 'and it picked up from where it stopped');
ok(d.errors.length === 0, 'the clock keys threw nothing');
return env;
});
/* ============================================================================================ /* ============================================================================================
* 8. hashchange, including the documented #0 bug class * 8. hashchange, including the documented #0 bug class
* ========================================================================================== */ * ========================================================================================== */

View file

@ -226,7 +226,11 @@ CC.reducedMotion = false;
* which the newest flicker source in the file does nothing at all. It is pinned to `storm` by * which the newest flicker source in the file does nothing at all. It is pinned to `storm` by
* default for the same reason lightning-rate.cjs is: test the worst case, not the average one. * default for the same reason lightning-rate.cjs is: test the worst case, not the average one.
* `--sky=rain` reproduces the reading this tool gave before the director was wired in. */ * `--sky=rain` reproduces the reading this tool gave before the director was wired in. */
for (const rel of ['src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js', /* world.js, proj.js and daylight.js come first: city.js resolves the live world inside make(),
every world-space element holds a projector, and surfaces.js reads the hour once per frame. A
tool that loads the elements without them dies on the first draw. */
for (const rel of ['src/world.js', 'src/proj.js', 'src/daylight.js',
'src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js',
'src/compose.js']) { 'src/compose.js']) {
const p = path.join(root, rel); if (fs.existsSync(p)) require(p); const p = path.join(root, rel); if (fs.existsSync(p)) require(p);
} }
@ -249,6 +253,14 @@ function pinSky() {
const edir = path.join(root, 'src/elements'); const edir = path.join(root, 'src/elements');
for (const fn of fs.readdirSync(edir).sort()) if (fn.endsWith('.js')) require(path.join(edir, fn)); for (const fn of fs.readdirSync(edir).sort()) if (fn.endsWith('.js')) require(path.join(edir, fn));
/* THE WORLD IS FORCED, and it has to be. This tool measures the CITY's signage fixtures against
the city's own weather presets, and with three worlds in the tree the registry's default is no
longer something to assume — the element list, the district table and the preset table all
follow it. It also means the elements below are filtered to the world being measured, rather
than the tool sorting all fifty-seven and drawing the frontier's livestock into a city frame. */
if (CC.World) CC.World.force(CC.World.DEFAULT);
if (CC.Daylight) CC.Daylight.set('night', 0);
const SEEDS = [0, 7, 42, 555]; const SEEDS = [0, 7, 42, 555];
/* THE LIST OF ELEMENTS THIS TOOL ACTUALLY MEASURES, and it is a hardcoded list rather than "every /* THE LIST OF ELEMENTS THIS TOOL ACTUALLY MEASURES, and it is a hardcoded list rather than "every
* element that moves", which is a trap that has already sprung once. It held only the four signage * element that moves", which is a trap that has already sprung once. It held only the four signage
@ -337,7 +349,7 @@ for (const seed of SEEDS) {
city_ = CC.City.make(seed); city_ = CC.City.make(seed);
if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); } if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); }
const rng = CC.mulberry(seed ^ 0x9e3779b9); const rng = CC.mulberry(seed ^ 0x9e3779b9);
const els = CC.ELEMENTS.slice().sort((a, b) => (a.layer | 0) - (b.layer | 0)); const els = CC.ELEMENTS.filter(function (e) { return CC.inWorld(e, CC.World.id); }).sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) if (el.init) el.init(city_, rng, { cols: COLS, rows: ROWS }); for (const el of els) if (el.init) el.init(city_, rng, { cols: COLS, rows: ROWS });
for (const name of NAMES) { for (const name of NAMES) {
const r = fixture(name, seed, els, 20); const r = fixture(name, seed, els, 20);
@ -415,7 +427,7 @@ for (const seed of [0, 555]) {
city_ = CC.City.make(seed); city_ = CC.City.make(seed);
if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); } if (CC.Weather) { CC.Weather.init(city_, CC.mulberry(seed ^ 0x5bf03635)); pinSky(); }
const rng = CC.mulberry(seed ^ 0x9e3779b9); const rng = CC.mulberry(seed ^ 0x9e3779b9);
const els = CC.ELEMENTS.slice().sort((a, b) => (a.layer | 0) - (b.layer | 0)); const els = CC.ELEMENTS.filter(function (e) { return CC.inWorld(e, CC.World.id); }).sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) if (el.init) el.init(city_, rng, { cols: COLS, rows: ROWS }); for (const el of els) if (el.init) el.init(city_, rng, { cols: COLS, rows: ROWS });
for (const name of NAMES) { for (const name of NAMES) {
const r = fixture(name, seed, els, 12); const r = fixture(name, seed, els, 12);

View file

@ -22,7 +22,12 @@ const rows = parseInt(pos[3] || '60', 10);
global.CC = require(path.join(root, 'src/core.js')); global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined; global.window = undefined;
const order = ['src/weather_state.js','src/city.js','src/surfaces.js','src/raycast.js','src/control.js','src/compose.js']; const order = ['src/world.js','src/proj.js','src/daylight.js','src/weather_state.js','src/city.js','src/surfaces.js','src/raycast.js','src/control.js','src/compose.js'];
/* Painters are globbed, exactly as build.js globs them, so a new world's texture layer is present
offline the moment the file exists — the harness rendering a different element/painter set from
the browser is the one failure this whole tool exists to prevent. */
for (const pf of fs.readdirSync(path.join(root, 'src')).sort())
if (/^surf_.*\.js$/.test(pf)) order.splice(order.indexOf('src/raycast.js'), 0, 'src/' + pf);
for (const rel of order) { for (const rel of order) {
const p = path.join(root, rel); const p = path.join(root, rel);
if (fs.existsSync(p)) require(p); if (fs.existsSync(p)) require(p);
@ -32,10 +37,40 @@ if (fs.existsSync(edir))
for (const f of fs.readdirSync(edir).sort()) if (f.endsWith('.js')) require(path.join(edir, f)); for (const f of fs.readdirSync(edir).sort()) if (f.endsWith('.js')) require(path.join(edir, f));
const CC = global.CC; const CC = global.CC;
/* WHICH WORLD, and it has to be chosen BEFORE the city is made — city.js resolves CC.World once
inside make() and the map is the frontier or the city from that moment on. `--world=west`, or
just `--west`, because that is what gets typed. */
/* The bare shorthand is checked against the REGISTRY rather than against a pair of literals, so
`--moon` works the day the world exists instead of being silently ignored and rendering the city
under the new world's name. */
const wArg = flags.map(a => a.replace(/^--/, ''))
.find(a => a.slice(0, 6) === 'world=' ||
!!(CC.World && CC.World.at(a) && CC.World.at(a).id === a));
if (wArg && CC.World) CC.World.force(wArg.slice(0, 6) === 'world=' ? wArg.slice(6) : wArg);
const WORLD = CC.World ? CC.World.id : 'cyber';
/* ---- tuning overrides, and they are ONLY for tuning ------------------------------------------
Neither of these is a thing the browser does on its own, so a frame rendered with either is not
the frame the browser draws and stderr says so. They exist because the two questions this
harness cannot otherwise answer are "what does the sunset look like" (the walk faces wherever
the route sends it, and the sun is in one fixed direction) and "what does the dust storm look
like" (a preset the schedule reaches once in several thousand frames).
--yaw=<radians> hold the camera's heading after every camera update
--weather=<name> force a preset, by name, from t=0 */
const yawArg = flags.find(a => a.slice(0, 6) === '--yaw=');
const YAW = yawArg ? parseFloat(yawArg.slice(6)) : null;
const wxArg = flags.find(a => a.slice(0, 10) === '--weather=');
if (wxArg && CC.Weather) CC.Weather.set(wxArg.slice(10), 0);
/* --time=<stop|0..1> pins the hour, which is not a thing the browser does on its own either: the
clock runs on a 420 s cycle, so a fixture that wants noon cannot wait for it. */
const tmArg = flags.find(a => a.slice(0, 7) === '--time=');
const TIME = tmArg ? tmArg.slice(7) : null;
const f = CC.makeFrame(cols, rows); const f = CC.makeFrame(cols, rows);
const t = frameN / 60; const t = frameN / 60;
const city = CC.City ? CC.City.make(seed) : null; const city = CC.City ? CC.City.make(seed) : null;
if (CC.Daylight) CC.Daylight.init(city);
if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635)); if (CC.Weather) CC.Weather.init(city, CC.mulberry(seed ^ 0x5bf03635));
if (CC.Control) CC.Control.reset(); if (CC.Control) CC.Control.reset();
const cam = { const cam = {
@ -56,7 +91,10 @@ const rng = CC.mulberry(seed ^ 0x9e3779b9);
// Layer-sorted BEFORE init, because main.js does the same and every element pulls from this one // Layer-sorted BEFORE init, because main.js does the same and every element pulls from this one
// shared rng: a different init order gives every downstream element a different stream, and the // shared rng: a different init order gives every downstream element a different stream, and the
// offline reference frame stops being the frame the browser draws. // offline reference frame stops being the frame the browser draws.
const els = CC.ELEMENTS.slice().sort((a, b) => (a.layer | 0) - (b.layer | 0)); /* Gated on world exactly as main.js gates it, and gated BEFORE the layer sort so the shared rng
is drawn in the same order the browser draws it. An element with no `world` belongs to both. */
const els = CC.ELEMENTS.filter(e => CC.inWorld(e, WORLD))
.sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) { if (el.init) el.init(city, rng, {cols, rows}); } for (const el of els) { if (el.init) el.init(city, rng, {cols, rows}); }
/* One rendered frame, in main.js's render() order and with main.js's clear. Nothing here is /* One rendered frame, in main.js's render() order and with main.js's clear. Nothing here is
@ -110,12 +148,28 @@ const t0 = Date.now();
for (let k = 0; k <= frameN; k++) { for (let k = 0; k <= frameN; k++) {
const kt = k / 60; const kt = k / 60;
// Weather first: an element's update() this tick must see this tick's weather. // Weather first: an element's update() this tick must see this tick's weather.
if (CC.Weather) CC.Weather.update(1 / 60, kt); if (CC.Daylight) {
/* Re-pinned every tick, unlike the weather: the clock has no "forced" flag to test because it
has no schedule to release an override back to — set() only moves an offset, so re-setting
to the same stop is idempotent and costs one frac(). */
if (TIME !== null) CC.Daylight.set(/^[\d.]+$/.test(TIME) ? parseFloat(TIME) : TIME, kt);
CC.Daylight.update(1 / 60, kt);
}
if (CC.Weather) {
/* Re-stamped only once the override has been RELEASED — the schedule drops it whenever the
segment under it moves on, which is right for a viewer and wrong for a fixture. Stamping it
every tick instead is the obvious version and it is broken: the blend out of the previous
preset is measured from the stamp, so re-stamping holds it at zero forever and the forced
weather never arrives. */
if (wxArg && !CC.Weather.P.forced) CC.Weather.set(wxArg.slice(10), kt);
CC.Weather.update(1 / 60, kt);
}
// Through Control, exactly as main.js drives it. With no DOM attached it is pure autopilot, // Through Control, exactly as main.js drives it. With no DOM attached it is pure autopilot,
// so this is the same walk city.camera produced before control.js existed -- and that is the // so this is the same walk city.camera produced before control.js existed -- and that is the
// point: an untouched keyboard has to render the frame this harness renders. // point: an untouched keyboard has to render the frame this harness renders.
if (CC.Control) CC.Control.update(1 / 60, kt, cam, city); if (CC.Control) CC.Control.update(1 / 60, kt, cam, city);
else if (city && city.camera) city.camera(cam, city, kt); else if (city && city.camera) city.camera(cam, city, kt);
if (YAW !== null) cam.yaw = YAW;
for (const el of els) if (el.update) el.update(1 / 60, kt, cam); for (const el of els) if (el.update) el.update(1 / 60, kt, cam);
// The last tick's draw is the frame we print, and it happens below so that cam.t is the // The last tick's draw is the frame we print, and it happens below so that cam.t is the
// requested t exactly. Every earlier tick is drawn and thrown away, for its side effects on the // requested t exactly. Every earlier tick is drawn and thrown away, for its side effects on the
@ -145,7 +199,7 @@ process.stdout.write(out.join('\n') + '\n');
Measured over seeds 5..150 step 5 at frame 600 it lands between 0.897 and 1.060, so quoting a Measured over seeds 5..150 step 5 at frame 600 it lands between 0.897 and 1.060, so quoting a
frame's numbers without it is quoting a measurement taken at an unstated exposure. */ frame's numbers without it is quoting a measurement taken at an unstated exposure. */
const ex = els.filter(e => e.name === 'exposure' && typeof e.adapt === 'number')[0]; const ex = els.filter(e => e.name === 'exposure' && typeof e.adapt === 'number')[0];
process.stderr.write(`rendered seed=${seed} frame=${frameN} ${cols}x${rows} elements=${CC.ELEMENTS.length} ` + process.stderr.write(`rendered seed=${seed} frame=${frameN} ${cols}x${rows} world=${WORLD} time=${CC.Daylight ? CC.Daylight.P.name : '-'} elements=${els.length}/${CC.ELEMENTS.length} ` +
(cold ? 'COLD-START (adaptation pinned, NOT the browser frame) ' : `replay=${frameN + 1} frames `) + (cold ? 'COLD-START (adaptation pinned, NOT the browser frame) ' : `replay=${frameN + 1} frames `) +
(ex ? `exposure=${ex.adapt.toFixed(3)} ` : '') + (ex ? `exposure=${ex.adapt.toFixed(3)} ` : '') +
`in ${ms}ms\n`); `in ${ms}ms\n`);

View file

@ -52,7 +52,7 @@ const SKY = skyArg ? skyArg.slice(6) : 'storm';
global.CC = require(path.join(root, 'src/core.js')); global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined; global.window = undefined;
for (const rel of ['src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js', for (const rel of ['src/world.js', 'src/proj.js', 'src/daylight.js', 'src/weather_state.js', 'src/city.js', 'src/surfaces.js', 'src/raycast.js',
'src/compose.js']) { 'src/compose.js']) {
const p = path.join(root, rel); if (fs.existsSync(p)) require(p); const p = path.join(root, rel); if (fs.existsSync(p)) require(p);
} }
@ -85,7 +85,7 @@ function pinSky() {
for (let i = 0; i < K.length; i++) P[K[i]] = PIN.p[i]; for (let i = 0; i < K.length; i++) P[K[i]] = PIN.p[i];
P.name = P.from = P.to = PIN.name; P.blend = 1; P.name = P.from = P.to = PIN.name; P.blend = 1;
} }
const els = CC.ELEMENTS.slice().sort((a, b) => (a.layer | 0) - (b.layer | 0)); const els = CC.ELEMENTS.filter(function (e) { return CC.inWorld(e, CC.World.id); }).sort((a, b) => (a.layer | 0) - (b.layer | 0));
for (const el of els) if (el.init) el.init(city, rng, { cols: 200, rows: 60 }); for (const el of els) if (el.init) el.init(city, rng, { cols: 200, rows: 60 });
const lg = els.find(e => e.name === 'lightning'); const lg = els.find(e => e.name === 'lightning');
if (!lg) { console.error('no lightning element'); process.exit(2); } if (!lg) { console.error('no lightning element'); process.exit(2); }

343
tools/west-flicker.cjs Normal file
View file

@ -0,0 +1,343 @@
/* PHOTOSENSITIVITY GATE FOR THE FRONTIER — the third of its kind, after tools/flicker-rate.cjs
* (signage fixtures) and tools/lightning-rate.cjs (storm strokes).
*
* node tools/west-flicker.cjs [seconds] [cols] [rows]
*
* WHY A THIRD TOOL. The other two measure named cyberpunk objects: flicker-rate lifts `flick()`
* out of signage.js and drives it directly, lightning-rate integrates one stroke over the frame.
* Neither can see the frontier, whose moving parts are a different set of things — a windmill
* turning, a tumbleweed rolling, chimney smoke rising, cloud bars drifting, three birds, and the
* lamp-gutter pulse on every painted board.
*
* WHAT IT MEASURES. The world pass is rendered with the CAMERA PINNED — so no cell can change for
* any reason except time — and then ONLY the frontier's own elements are drawn over it. Every
* cell's luminance is recorded for `seconds` at 60 Hz in each of the six frontier weather presets,
* and three statistics come out of the per-cell time series:
*
* WORST STEP the largest single-frame change any cell made, as a percentage of full
* scale (255). Reported, not gated — see below.
* BIG-STEP RATE how often, per second, the worst-behaved cell made a step over a third of
* full scale. This is the gate: 1.0/s, the limit flicker-rate applies.
* 3-20 Hz POWER the strongest spectral component of any cell inside the flash-rate danger
* band, by Goertzel at seven probe frequencies, as a percentage of full scale.
* Gate: 2%, again the limit the other two tools use.
*
* WHY ONLY THE FRONTIER'S OWN ELEMENTS, and this is the part that was got wrong first time and is
* worth the paragraph. The first cut measured the WHOLE element list and failed everything at 9
* big steps a second — and the cause was `pedestrians`, a shared element, whose walker silhouettes
* alternate a cell between a lit crown and a black cut-out as they move. Running the identical
* probe in the CITY gave 16 big steps over the same window against the frontier's 18, i.e. the two
* worlds are indistinguishable on it: this is a property of drawing moving figures at character
* resolution at 60 Hz, it long predates this file, and it is not the frontier's to gate. It is
* also exactly why tools/flicker-rate.cjs draws its fixtures against a synthetic empty scene
* rather than a real frame.
*
* So the gate is scoped to what this feature actually added, which is what a regression gate is
* for. Section 2 measures the CITY's own elements the identical way, and section 3 the full list
* in both worlds, so every comparison this file makes is re-derived on each run rather than
* remembered from the day it was written.
*
* AND THE GATE IS COMPARATIVE, WHICH IS THE HONEST FORM FOR THIS MEASUREMENT. An absolute per-cell
* limit over a whole frame is not the project's rule and cannot be: the SHIPPED CITY measures 5.3
* big steps a second on it, because a blimp, a cable, a drone or a walker crossing a bright cell
* produces a step and there is no way to tell that apart from a flash from inside the frame buffer.
* flicker-rate.cjs avoids the problem by drawing its fixtures against a synthetic empty scene;
* there is no equivalent synthetic scene for "a chimney against a sunset". So what is gated here
* is that the frontier's own moving parts are NO WORSE THAN THE CITY'S OWN, measured identically —
* which is the question a regression gate for a second world should actually ask — with a 15%
* tolerance, and the absolute limits kept as a second, looser backstop.
*
* THE REDUCED-MOTION GATE IS ABSOLUTE AND IT IS THE STRONG ONE. With the flag on, the frontier's
* own elements must produce a completely empty danger band and no big steps at all. They do: 0.00
* on every preset. That is the result worth quoting.
*
* WHY THE WORST STEP IS REPORTED AND NOT GATED. A single large step is not a flash; a repeated one
* is. flicker-rate makes the same distinction explicitly — it PASSES at a live worst step of 90.6%
* of 255 (a traffic lamp changing state) because that step happens 0.0-0.1 times a second. An
* object appearing from behind another will always produce one large step, and gating on it would
* be gating on occlusion.
*
* REDUCED MOTION is measured separately and its pass condition is stricter: with the flag on,
* everything that modulates must be frozen or slow enough that the danger band is empty.
*
* EXIT CODES: 0 PASS, 1 FAIL, 2 usage error.
*/
'use strict';
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
const SECONDS = parseFloat(process.argv[2] || '4');
const COLS = parseInt(process.argv[3] || '120', 10);
const ROWS = parseInt(process.argv[4] || '40', 10);
/* A SHORT RUN IS NOT A CHEAP RUN, it is a wrong one, and this warning exists because a one-second
run was believed for twenty minutes. The 3-20 Hz figure comes from a Goertzel over the measured
window: at 1 s that is 60 samples, so the bin spacing is 1 Hz and a single step edge leaks across
the whole band. The same tree measured 10.61% in-band at 1 s and 2.65% at 3 s, and only the
second number means anything. Under two seconds the spectral half of this tool is noise. */
if (SECONDS < 2) console.error('west-flicker: WARNING — under 2 s the 3-20 Hz figure is noise; ' +
'the step and rate figures are still valid.');
if (!(SECONDS > 0) || !(COLS > 8) || !(ROWS > 8)) {
console.error('usage: node tools/west-flicker.cjs [seconds] [cols] [rows]');
process.exit(2);
}
/* THE WARM-UP IS SIX SECONDS AND IT IS NOT ABOUT THE OPTICS. optics.js's exposure filters do need
* a second to converge, but the number that sets this is weather_state.js's TRANS_FORCED: a preset
* asked for by name blends in over 5 s, and during that blend the WORLD PASS itself changes every
* frame as `wet` sweeps the rut-water threshold and `haze` sweeps the sky. Measured with a 1 s
* warm-up, 231 of the big steps in a two-second window were the weather arriving — each cell
* flipping once as the threshold crossed it, which is a transition and not a flicker. Six seconds
* puts the whole measurement inside a settled sky. */
const WARM = 360;
const NF = WARM + Math.round(SECONDS * 60);
global.CC = require(path.join(root, 'src/core.js'));
global.window = undefined;
for (const rel of ['src/world.js', 'src/proj.js', 'src/daylight.js', 'src/weather_state.js', 'src/city.js',
'src/surfaces.js']) {
const p = path.join(root, rel);
if (fs.existsSync(p)) require(p);
}
/* Painters are globbed, exactly as build.js and headless.cjs glob them: a world whose texture layer
was missing here would be measured as the city and would pass a gate it had never been put to. */
for (const pf of fs.readdirSync(path.join(root, 'src')).sort())
if (/^surf_.*\.js$/.test(pf)) require(path.join(root, 'src', pf));
for (const rel of ['src/raycast.js', 'src/control.js', 'src/compose.js']) {
const p = path.join(root, rel);
if (fs.existsSync(p)) require(p);
}
const edir = path.join(root, 'src/elements');
for (const f of fs.readdirSync(edir).sort()) if (f.endsWith('.js')) require(path.join(edir, f));
const CC = global.CC;
/* Goertzel at seven probes across the band. Seven and not a full FFT because the question is
* "is there anything in 3-20 Hz", not "what is the spectrum", and seven single-bin evaluations
* over 4800 cells is a second of work where 4800 FFTs is a minute of it. */
const PROBES = [3.5, 5, 7, 9, 12, 15, 19];
function goertzel(buf, off, stride, n, freq) {
const w = 2 * Math.PI * freq / 60, c = 2 * Math.cos(w);
let s0 = 0, s1 = 0, s2 = 0, mean = 0, i;
for (i = 0; i < n; i++) mean += buf[off + i * stride];
mean /= n;
for (i = 0; i < n; i++) {
/* Hann, so a component that does not sit exactly on a probe still shows up rather than being
* scalloped away by the rectangular window's sidelobes. */
const win = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (n - 1));
s0 = (buf[off + i * stride] - mean) * win + c * s1 - s2;
s2 = s1; s1 = s0;
}
return 2 * Math.sqrt(s1 * s1 + s2 * s2 - c * s1 * s2) / n;
}
/* `scope` is 'own' (the frontier's own elements only — the gated measurement) or 'all' (the whole
* live list, for the side-by-side in section 2). */
function run(presetName, reduced, seed, world, scope) {
world = world || 'west';
CC.World.force(world);
CC.reducedMotion = !!reduced;
const city = CC.City.make(seed);
CC.Weather.init(city);
CC.Control.reset();
const live = CC.ELEMENTS.filter(e => CC.inWorld(e, world))
.sort((a, b) => (a.layer | 0) - (b.layer | 0));
/* INIT THE WHOLE LIST EITHER WAY. Elements draw from one shared rng in layer order, so skipping
* an init to narrow the scope would also re-deal every element below it and the measurement
* would be of a world nobody renders. Only the DRAW list narrows. */
const els = live;
const rng = CC.mulberry(seed ^ 0x9e3779b9);
for (const el of els) if (el.init) el.init(city, rng, { cols: COLS, rows: ROWS });
/* 'own' means EXCLUSIVE to this world, not merely present in it — an element that also runs in
the default world is by definition part of the baseline this gate measures against, and
counting it on both sides makes the comparison meaningless. The distinction only appeared when
`world` became array-valued: the crowd now declares ['cyber','west'], so a test of "declares
this world" quietly moved the shared pedestrians into the frontier's own column. */
const drawn = scope === 'all' ? els
: els.filter(e => e.world && CC.inWorld(e, world) && !CC.inWorld(e, DEFAULT_WORLD));
const f = CC.makeFrame(COLS, ROWS);
/* PINNED. Not "moved slowly" and not "moved and then subtracted" — the whole design of this
* measurement is that the only variable left is time. cam.yaw is chosen to look along the walk's
* own heading so the frame contains a street rather than a wall. */
const cam = {
x: city.startX, z: city.startZ, yaw: 0.35, eyeY: 1.7, fov: 1.25,
horizon: ROWS * 0.56, cellAspect: 0.5625, rows: ROWS, t: 0
};
const N = COLS * ROWS;
const keep = NF - WARM;
const series = new Uint8Array(N * keep);
for (let k = 0; k < NF; k++) {
const t = k / 60;
/* Stamped only once the override has been RELEASED. Re-stamping every tick — which is the
* obvious version — holds the blend out of the previous preset at zero forever, so the forced
* weather never arrives and every preset measures the same frame. It did, for one round: all
* six rows of section 1 printed identical numbers. */
if (!CC.Weather.P.forced) CC.Weather.set(presetName, t);
CC.Weather.update(1 / 60, t);
for (const el of els) if (el.update) el.update(1 / 60, t, cam);
cam.t = t;
CC.clearFrame(f);
CC.Cast.render(f, cam, city);
for (const el of drawn) if (el.draw) el.draw(f, cam, t);
if (CC.Compose && CC.Compose.post) CC.Compose.post(f, cam, t);
if (k >= WARM) {
const base = (k - WARM) * N;
for (let i = 0; i < N; i++) series[base + i] = f.lum[i];
}
}
/* Per cell: worst single-frame step, count of steps over a third of full scale, and the worst
* in-band amplitude. */
const BIG = 255 / 3;
let worstStep = 0, worstBigRate = 0, worstBand = 0, worstCell = -1, worstBandCell = -1;
const secs = keep / 60;
for (let i = 0; i < N; i++) {
let big = 0, mx = 0, prev = series[i];
for (let k = 1; k < keep; k++) {
const v = series[k * N + i];
const d = v > prev ? v - prev : prev - v;
if (d > mx) mx = d;
if (d > BIG) big++;
prev = v;
}
if (mx > worstStep) { worstStep = mx; worstCell = i; }
const rate = big / secs;
if (rate > worstBigRate) worstBigRate = rate;
/* Only cells that actually move are worth transforming. */
if (mx < 4) continue;
for (const fr of PROBES) {
const a = goertzel(series, i, N, keep, fr);
if (a > worstBand) { worstBand = a; worstBandCell = i; }
}
}
return {
step: worstStep / 255 * 100,
rate: worstBigRate,
band: worstBand / 255 * 100,
cell: worstCell, bandCell: worstBandCell
};
}
/* ---- WHICH WORLDS, and it is no longer one -----------------------------------------------------
* This began as a gate for the frontier alone and the third world would otherwise have shipped
* with no photosensitivity measurement at all. The preset lists are read off the live weather
* director after forcing each world rather than written down here, so a world that ships one
* weather row (the Moon's `vacuum`) is measured once and a world that ships six is measured six
* times, with no table in this file to fall out of step with weather_state.js. */
function presetsOf(world) {
CC.World.force(world);
CC.Weather.init({ seed: 1 });
var out = [], pr = CC.Weather.PRESETS, i;
for (i = 0; i < pr.length; i++) out.push(pr[i].name);
return out;
}
const DEFAULT_WORLD = CC.World.LIST[0].id;
const TEST_WORLDS = CC.World.LIST.map(w => w.id).filter(w => w !== DEFAULT_WORLD);
const CITY_PRESETS = presetsOf(DEFAULT_WORLD);
const SEEDS = [3, 42];
/* The backstop, not the gate — see the header. Nothing may be more than this bad in absolute
* terms whatever the city does, and the city itself sits under both. */
const STEP_RATE_CAP = 8.0, BAND_CAP = 9.0;
/* The gate: the frontier's own worst, against the city's own worst, plus 15%. */
const TOLERANCE = 1.15;
let fail = 0;
console.log(`frontier flicker gate — ${COLS}x${ROWS}, ${SECONDS}s measured of ${NF} frames, ` +
`pinned camera, ${WARM} discarded\n`);
console.log(' live');
let liveStep = 0, liveRate = 0, liveBand = 0;
for (const world of TEST_WORLDS) {
const PRESETS = presetsOf(world);
for (const seed of SEEDS) {
for (const p of PRESETS) {
const r = run(p, false, seed, world, 'own');
const bad = (r.rate > STEP_RATE_CAP ? ' BIG-STEP RATE OVER CAP' : '') +
(r.band > BAND_CAP ? ' 3-20Hz OVER CAP' : '');
if (bad) fail++;
if (r.step > liveStep) liveStep = r.step;
if (r.rate > liveRate) liveRate = r.rate;
if (r.band > liveBand) liveBand = r.band;
console.log(` ${world.padEnd(6)} seed ${String(seed).padStart(3)} ${p.padEnd(9)}` +
`worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}`);
}
}
}
console.log('\n the city\'s own elements, measured identically (the baseline the gate is against)');
let cityRate = 0, cityBand = 0, cityStep = 0;
for (const seed of SEEDS) {
for (const p of CITY_PRESETS) {
const r = run(p, false, seed, DEFAULT_WORLD, 'own');
if (r.step > cityStep) cityStep = r.step;
if (r.rate > cityRate) cityRate = r.rate;
if (r.band > cityBand) cityBand = r.band;
console.log(` seed ${String(seed).padStart(3)} ${p.padEnd(9)}` +
`worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}%`);
}
}
if (liveRate > cityRate * TOLERANCE) { fail++; console.log(' FAIL: the frontier steps more often than the city'); }
if (liveBand > cityBand * TOLERANCE) { fail++; console.log(' FAIL: the frontier carries more 3-20 Hz than the city'); }
console.log('\n reduced motion');
let rmBand = 0, rmRate = 0;
for (const world of TEST_WORLDS)
for (const p of presetsOf(world)) {
const r = run(p, true, 42, world, 'own');
/* Stricter: with the flag on, the danger band must be empty outright — a quarter of the limit is
* the same margin lightning-rate holds itself to. */
/* ABSOLUTE, and strict: with the flag on the frontier's own elements must be silent. */
const bad = (r.band > 0.5 ? ' 3-20Hz' : '') + (r.rate > 0.05 ? ' BIG-STEP RATE' : '');
if (bad) fail++;
if (r.band > rmBand) rmBand = r.band;
if (r.rate > rmRate) rmRate = r.rate;
console.log(` ${world.padEnd(6)} ${p.padEnd(9)}worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s ` +
`3-20Hz ${r.band.toFixed(2).padStart(5)}% ${bad ? 'FAIL' + bad : 'ok'}`);
}
CC.reducedMotion = false;
/* ---- section 2: the shared crowd, in both worlds, side by side ------------------------------
* Ungated. It exists so the claim in the header — that moving figures alternate cells identically
* in the city and on the frontier, and that this is therefore not the frontier's to answer for —
* is re-measured on every run rather than remembered from the day it was written. If these two
* columns ever diverge, the frontier HAS made it worse and the gate above needs to widen. */
console.log('\n full element list, both worlds (ungated context)');
const CTX = CC.World.LIST.map(w => [w.id, presetsOf(w.id)[0]]);
const ctx = {};
for (const [w, p] of CTX) {
const r = run(p, false, 3, w, 'all');
ctx[w] = r;
console.log(` ${w.padEnd(9)}worst step ${r.step.toFixed(1).padStart(5)}% ` +
`big steps ${r.rate.toFixed(2).padStart(5)}/s 3-20Hz ${r.band.toFixed(2).padStart(5)}%`);
}
console.log(' (a moving silhouette alternates a cell at character resolution in every world with');
console.log(' objects in it; the gate above is the one that means something — see the header)');
/* WHAT THE DIVERGENCE IN THIS TABLE MEANS, now that it has one. The header used to say that if the
two columns ever diverged the newer world had made things worse and the gate should widen. With
three worlds and the frontier's livestock and dust in place they DO diverge — the frontier runs
about twice the city's big-step rate on the full list — and the conclusion is not the one that
sentence predicts.
The gated measurement, which is each world's OWN elements against the city's own, sits at
parity: 2.00 steps/s against 2.00, and 2.65% in band against 3.60%. The full-list gap is simply
that a frontier frame now contains more moving objects than a city frame does — horses, a wagon,
a dog, blowing dust and a tumbleweed, against the city's crowd and traffic — and every moving
object alternates the cells it crosses. That is a property of having content, it is measured on
the metric this file says twice is not the gate, and the honest response is to report it rather
than to widen anything.
Moonwalk is the control that makes the argument checkable: 0.33 steps/s on the full list and
0.00 on its own, because almost nothing there moves. */
console.log(`\nSUMMARY: frontier's own — worst step ${liveStep.toFixed(1)}% of 255, big-step rate ` +
`${liveRate.toFixed(2)}/s vs the city's own ${cityRate.toFixed(2)}/s, 3-20 Hz ` +
`${liveBand.toFixed(2)}% vs ${cityBand.toFixed(2)}% ` +
`| reduced-motion 3-20 Hz ${rmBand.toFixed(2)}%, ` +
`big-step rate ${rmRate.toFixed(2)}/s` +
` | context: full list, ` +
CC.World.LIST.map(w => w.id + ' ' + ctx[w.id].rate.toFixed(2) + '/s').join(' vs '));
console.log('RESULT: ' + (fail ? 'FAIL' : 'PASS'));
process.exit(fail ? 1 : 0);