component
WetStreet
A rain-soaked asphalt street with kerbs: puddles from world-space noise and in the gutters, darkened glossy asphalt, lane, edge and centre paint, zebras at crossings, and reflections from the world's shared mirror, full in standing water and faint on damp asphalt. A mounted `Rain` rings the puddles and dries and soaks the street with its weather. Decorative: no collider.
⌖ Explore the library in 3D → · View as Markdown
Add it
npx @runek/cli add wet-street
Pulls @runek/core@^0.18.0, three@^0.184.0.
Use it
import { WetStreet } from './runek/WetStreet'
<WetStreet position={[0, 0, 0]} length={24} width={9} puddles={0.6} seed={1} />
Or as a node in a world file (worlds as data):
{ "type": "WetStreet", "props": { "position": [0, 0, 0], "length": 24, "width": 9, "puddles": 0.6, "seed": 1 } }
Props
| Prop | Type | Default | Description |
|---|---|---|---|
length |
number |
12 |
Length along local Z, in units. |
width |
number |
7 |
Width along local X, kerb to kerb, in units. |
color |
color |
Asphalt color; defaults to the palette’s stone. |
|
kerbColor |
color |
Kerb color; defaults to the palette’s floor (the pavement). |
|
wetness |
number |
0.85 |
How wet the street is when the weather has soaked it, 0 (dry) to 1 (soaked). |
puddles |
number |
0.5 |
How much of the street stands in puddles then, 0 to 1. |
markings |
boolean |
true |
Paint lane and edge lines, and a zebra at each crossing. |
paint |
color |
"#ece6da" |
Lane, edge and zebra paint. |
centrePaint |
color |
"#c98a3e" |
The centre line. |
crossings |
StreetCrossing[] |
[] |
Cross streets: no kerbs, lines or gutters inside them, a zebra either side. At most four. |
position |
[x, y, z] |
[0, 0, 0] |
Position [x, y, z] in units (1 unit = 1 m, Y-up). |
rotation |
[x, y, z] |
[0, 0, 0] |
Euler rotation [x, y, z] in radians. |
seed |
number |
0 |
Seed for the deterministic variation: same seed, same result. |
StreetCrossing
| Prop | Type | Default | Description |
|---|---|---|---|
at |
number |
required | |
width |
number |
required |
Registry manifest
registry manifest /r/components/wet-street.json Self-contained JSON: inlined source plus resolved dependencies, exactly whatrunek add wet-street fetches.
Browse the whole catalog in the gallery →.
Source (2 files)
WetStreet.tsx
import {
type MirrorSurface,
useMaterial,
useMirrorMaterial,
useNodeRenderer,
useWorld,
type WorldComponentProps,
} from '@runek/core'
import { useMemo } from 'react'
import {
BoxGeometry,
BufferGeometry,
Color,
Float32BufferAttribute,
type WebGLProgramParametersWithUniforms,
} from 'three'
import { RAIN_PERIOD, rainUniforms } from './city/weather'
/** Where a cross street meets this one: its centre along this street, and its width, in units. */
export interface StreetCrossing {
at: number
width: number
}
export interface WetStreetProps extends WorldComponentProps {
/** Length along local Z, in units. */
length?: number
/** Width along local X, kerb to kerb, in units. */
width?: number
/** Asphalt color; defaults to the palette's `stone`. */
color?: string
/** Kerb color; defaults to the palette's `floor` (the pavement). */
kerbColor?: string
/** How wet the street is when the weather has soaked it, 0 (dry) to 1 (soaked). */
wetness?: number
/** How much of the street stands in puddles then, 0 to 1. */
puddles?: number
/** Paint lane and edge lines, and a zebra at each crossing. */
markings?: boolean
/** Lane, edge and zebra paint. */
paint?: string
/** The centre line. */
centrePaint?: string
/** Cross streets: no kerbs, lines or gutters inside them, a zebra either side. At most four. */
crossings?: StreetCrossing[]
}
/** Most crossings one street can hold. */
const MAX_CROSSINGS = 4
/**
* A wet asphalt street with kerbs, laid in the XZ plane just above the ground, straight along
* local Z: a `Road` that reads as rain-soaked. Puddles collect from a world-space noise field
* and in the gutters, wet asphalt darkens and turns glossy (Lagarde's porosity model), paint
* stays drier, and the deck reflects the street through the world's shared mirror for its
* height: fully in standing water, faintly on damp asphalt. While a `Rain` is mounted, drops ring
* the puddles, more of them the harder it rains, and the weather it follows dries the street and
* its puddles out and soaks them again. Streets that cross should share a `seed`: their puddles
* then match where they overlap. Decorative, like `Road`: it owns no collider.
*
* The puddles, paint and rain rings are `WebGLRenderer` only. Under `WebGPURenderer` the deck is
* damp asphalt with an even, faint reflection.
*/
export function WetStreet({
position = [0, 0, 0],
rotation = [0, 0, 0],
seed = 0,
length = 12,
width = 7,
color,
kerbColor,
wetness = 0.85,
puddles = 0.5,
markings = true,
paint = '#ece6da',
centrePaint = '#c98a3e',
crossings = NO_CROSSINGS,
}: WetStreetProps) {
const { unit, palette } = useWorld()
const node = useNodeRenderer()
const L = length * unit
const W = width * unit
const kerbW = 0.18 * unit
const kerbH = 0.12 * unit
const kerb = useMaterial({ slot: 'concrete', color: kerbColor ?? palette.floor, roughness: 0.85 })
const cutKey = JSON.stringify(crossings)
const cuts = useMemo(
() =>
crossings
.slice(0, MAX_CROSSINGS)
.map((c) => ({ at: c.at * unit, half: (c.width * unit) / 2 })),
[cutKey, unit],
)
const deck = useMemo(() => deckGeometry(W, L), [W, L])
const kerbs = useMemo(() => kerbSegments(L, cuts), [L, cuts])
const surface = useMemo(
() =>
streetSurface({ wetness, puddles, markings, paint, centrePaint, seed, half: W / 2, cuts }),
[wetness, puddles, markings, paint, centrePaint, seed, W, cuts],
)
// Under WebGPU there is no wet layer to darken the asphalt, so the look does it, as `Road` does.
const asphalt = color ?? palette.stone
const deckColor = useMemo(
() =>
node ? `#${new Color(asphalt).multiplyScalar(1 - 0.45 * wetness).getHexString()}` : asphalt,
[node, asphalt, wetness],
)
const deckMaterial = useMirrorMaterial(
{ slot: 'asphalt', color: deckColor, roughness: node ? 1 - 0.7 * wetness : 0.85, metalness: 0 },
node ? 0.25 * wetness : 1,
surface,
)
const edge = W / 2 - kerbW / 2
return (
<group position={[position[0], position[1] + 0.03 * unit, position[2]]} rotation={rotation}>
<mesh geometry={deck} material={deckMaterial} receiveShadow />
{[edge, -edge].map((x) =>
kerbs.map(([z, len]) => (
<mesh
key={`${x}:${z}`}
material={kerb}
position={[x, kerbH / 2, z]}
geometry={kerbGeometry(kerbW, kerbH, len)}
receiveShadow
/>
)),
)}
</group>
)
}
const NO_CROSSINGS: StreetCrossing[] = []
/** A flat deck with street coordinates (across, along) in meters, which survive batching. */
function deckGeometry(w: number, l: number) {
const g = new BufferGeometry()
const x = w / 2
const z = l / 2
g.setAttribute(
'position',
new Float32BufferAttribute([-x, 0, z, x, 0, z, x, 0, -z, -x, 0, -z], 3),
)
g.setAttribute('normal', new Float32BufferAttribute([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], 3))
g.setAttribute('uv', new Float32BufferAttribute([0, 0, 1, 0, 1, 1, 0, 1], 2))
g.setAttribute('aStreet', new Float32BufferAttribute([-x, z, x, z, x, -z, -x, -z], 2))
g.setIndex([0, 1, 2, 0, 2, 3])
return g
}
/** Kerb runs as [centre z, length], broken where cross streets come in. */
function kerbSegments(l: number, cuts: { at: number; half: number }[]): [number, number][] {
const gaps = cuts.map((c) => [c.at - c.half, c.at + c.half] as const).sort((a, b) => a[0] - b[0])
const out: [number, number][] = []
let from = -l / 2
for (const [a, b] of gaps) {
if (a > from + 0.01) out.push([(from + Math.min(a, l / 2)) / 2, Math.min(a, l / 2) - from])
from = Math.max(from, b)
}
if (l / 2 > from + 0.01) out.push([(from + l / 2) / 2, l / 2 - from])
return out
}
const kerbCache = new Map<string, BoxGeometry>()
function kerbGeometry(w: number, h: number, l: number) {
const key = `${w}:${h}:${l.toFixed(3)}`
let g = kerbCache.get(key)
if (!g) {
g = new BoxGeometry(w, h, l)
kerbCache.set(key, g)
}
return g
}
interface StreetLook {
wetness: number
puddles: number
markings: boolean
paint: string
centrePaint: string
seed: number
half: number
cuts: { at: number; half: number }[]
}
/** The street's own shader edits over the mirror material, and how strongly each pixel reflects:
* standing water fully, damp asphalt faintly. One program for every street. */
function streetSurface(look: StreetLook): MirrorSurface {
const v3 = (hex: string) => new Color(hex)
const cuts = Array.from({ length: MAX_CROSSINGS }, (_, i) => look.cuts[i] ?? { at: 1e6, half: 0 })
const uniforms = {
uWet: { value: look.wetness },
uPuddles: { value: look.puddles },
uSeed: { value: [((look.seed * 17.31) % 97) + 11.7, ((look.seed * 7.13) % 89) + 3.1] },
uHalf: { value: look.half },
uCuts: { value: cuts.flatMap((c) => [c.at, c.half]) },
uMarkings: { value: look.markings ? 1 : 0 },
uPaint: { value: v3(look.paint) },
uCentre: { value: v3(look.centrePaint) },
}
return {
key: 'wetstreet',
strength: 'streetPuddle + ( 1.0 - streetPuddle ) * streetWet * streetGloss * 0.35',
compile(shader: WebGLProgramParametersWithUniforms) {
Object.assign(shader.uniforms, uniforms, rainUniforms)
shader.vertexShader = shader.vertexShader
.replace('#include <common>', `#include <common>\n${VERT_PARS}`)
.replace('#include <project_vertex>', `#include <project_vertex>\n${VERT_MAIN}`)
shader.fragmentShader = shader.fragmentShader
.replace('#include <common>', `#include <common>\n${FRAG_PARS}`)
.replace('#include <map_fragment>', `#include <map_fragment>\n${ALBEDO}`)
.replace(
'#include <roughnessmap_fragment>',
`#include <roughnessmap_fragment>\n${ROUGHNESS}`,
)
.replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>\n${RIPPLES}`)
.replace(
'#include <lights_fragment_maps>',
'#include <lights_fragment_maps>\nradiance *= streetGloss;',
)
.replace(
'#include <lights_fragment_end>',
'#include <lights_fragment_end>\nreflectedLight.directSpecular *= streetGloss;',
)
},
}
}
const VERT_PARS = /* glsl */ `
attribute vec2 aStreet;
varying vec2 vStreet;
varying vec3 vStreetWorld;
`
const VERT_MAIN = /* glsl */ `
vStreet = aStreet;
vStreetWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;
`
const FRAG_PARS = /* glsl */ `
varying vec2 vStreet;
varying vec3 vStreetWorld;
uniform float uMarkings;
uniform vec3 uPaint;
uniform vec3 uCentre;
uniform float uWet;
uniform float uPuddles;
uniform vec2 uSeed;
uniform float uHalf;
uniform vec2 uCuts[${MAX_CROSSINGS}];
float streetHash( vec2 p ) { return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 ); }
float streetNoise( vec2 p ) {
vec2 i = floor( p ), f = fract( p );
vec2 u = f * f * ( 3.0 - 2.0 * f );
return mix( mix( streetHash( i ), streetHash( i + vec2( 1.0, 0.0 ) ), u.x ), mix( streetHash( i + vec2( 0.0, 1.0 ) ), streetHash( i + vec2( 1.0, 1.0 ) ), u.x ), u.y );
}
// Coverage of [a, b] over a pixel footprint w: a box-filtered band, so lines never shimmer.
float streetBand( float x, float a, float b, float w ) {
return clamp( ( min( x + 0.5 * w, b ) - max( x - 0.5 * w, a ) ) / max( w, 1e-4 ), 0.0, 1.0 );
}
float streetPulseInt( float x, float a, float b ) { return floor( x ) * ( b - a ) + clamp( fract( x ), a, b ) - a; }
float streetPulse( float x, float a, float b, float w ) {
w = max( w, 1e-4 );
return ( streetPulseInt( x + 0.5 * w, a, b ) - streetPulseInt( x - 0.5 * w, a, b ) ) / w;
}
uniform float uRainTime;
uniform float uRain;
uniform float uWetness;
// The slope a raindrop's ring gives the water: one drop at a time in each cell of a grid, at a
// new spot in the cell each time. Rates in eighths keep every cell in step with the rain clock's wrap.
// The harder it rains, the more of the cells take a drop: about one in twelve in a drizzle, over half in heavy rain.
vec2 streetRipple( vec2 p, float cell, float shift ) {
vec2 q = p / cell + shift;
vec2 id = floor( q );
vec2 f = q - id;
float rate = 0.875 + floor( streetHash( id + shift ) * 5.0 ) * 0.125;
float t = uRainTime * rate + floor( streetHash( id + 41.7 ) * 17.0 );
float turn = mod( floor( t ), rate * ${RAIN_PERIOD.toFixed(1)} );
float life = fract( t );
vec2 c = 0.3 + 0.4 * vec2( streetHash( id + turn * 0.37 + 3.1 ), streetHash( id + turn * 0.71 + 7.9 ) );
float fires = step( 1.0 - 0.55 * uRain, streetHash( id + turn * 1.31 + 1.7 ) );
vec2 d = f - c;
float dist = length( d ) + 1e-4;
float x = ( dist - 0.3 * life ) * 14.0;
float fade = 1.0 - life;
return ( d / dist ) * ( -2.0 * x * exp( -x * x ) ) * fade * fade * fires;
}
`
// Paint first (it decides where water stands), then puddles and wetness.
const ALBEDO = /* glsl */ `
float streetPaint = 0.0;
float streetInCross = 0.0;
float streetZebra = 0.0;
float streetZebraZone = 0.0;
{
vec2 sp = vStreet;
vec2 sfw = fwidth( sp );
for ( int i = 0; i < ${MAX_CROSSINGS}; i++ ) {
vec2 c = uCuts[i];
streetInCross = max( streetInCross, streetBand( sp.y, c.x - c.y, c.x + c.y, sfw.y ) );
float near = streetBand( abs( sp.y - c.x ), c.y + 1.0, c.y + 4.5, sfw.y );
streetZebraZone = max( streetZebraZone, near );
streetZebra = max( streetZebra, near * streetPulse( sp.x / 1.0, 0.0, 0.5, sfw.x ) * step( abs( sp.x ), uHalf - 0.6 ) );
}
if ( uMarkings > 0.5 ) {
float ax = abs( sp.x );
float edgeLine = streetBand( ax, uHalf - 0.5, uHalf - 0.38, sfw.x );
float lane = uHalf >= 6.0 ? streetBand( ax, uHalf * 0.5 - 0.06, uHalf * 0.5 + 0.06, sfw.x ) * streetPulse( sp.y / 9.0, 0.0, 0.33, sfw.y / 9.0 ) : 0.0;
float centre = streetBand( ax, 0.08, 0.2, sfw.x );
float open = 1.0 - streetInCross;
float lanes = open * ( 1.0 - streetZebraZone );
float bone = max( edgeLine * open + lane * lanes, streetZebra );
diffuseColor.rgb = mix( diffuseColor.rgb, uPaint * 0.55, bone );
diffuseColor.rgb = mix( diffuseColor.rgb, uCentre * 0.55, centre * lanes );
streetPaint = max( bone, centre * lanes );
}
}
vec2 streetW = vStreetWorld.xz + uSeed;
float streetBig = streetNoise( streetW / 7.0 ) * 0.6 + streetNoise( streetW / 3.1 ) * 0.3 + streetNoise( streetW / 1.3 ) * 0.1;
float streetFine = streetNoise( streetW / 1.7 + 17.0 );
// Camber: water runs to the gutters, except inside a crossing where there are none.
float streetGutter = smoothstep( uHalf - 1.4, uHalf - 0.2, abs( vStreet.x ) ) * ( 1.0 - streetInCross );
float streetLevel = streetBig + streetGutter * 0.22;
// The weather fills the street and dries it again. Standing water goes first, drawing back to
// the low spots and the gutters, and the damp in the asphalt goes after it.
float streetStand = smoothstep( 0.1, 0.6, uWetness );
float streetEdge = 0.74 - uPuddles * 0.2 + ( 1.0 - streetStand ) * 0.3;
float streetPuddle = smoothstep( streetEdge, streetEdge + 0.03, streetLevel ) * ( 1.0 - streetPaint * 0.8 ) * smoothstep( 0.0, 0.15, streetStand );
float streetWet = clamp( uWet * uWetness * mix( 0.35, 1.0, smoothstep( 0.3, 0.68, streetFine ) ), 0.0, 1.0 );
// Wet asphalt is full of grain and tyre polish, so outside the puddles it gives back only part
// of what a mirror (or a lamp) would, in patches. Standing water reflects fully.
float streetGloss = mix( mix( 0.2, 0.5, streetFine ), 1.0, streetPuddle );
// Wet porous asphalt darkens (Lagarde), standing water darkens it further.
diffuseColor.rgb *= mix( 1.0, mix( 1.0, 0.25, 0.5 ), streetWet );
diffuseColor.rgb *= mix( 1.0, 0.55, streetPuddle );
`
// Rain rings on standing water. They fade out where a pixel is wider than a ring, so far
// puddles hold still and never shimmer.
const RIPPLES = /* glsl */ `
vec2 streetRfw = fwidth( vStreetWorld.xz );
float streetRings = ( 1.0 - smoothstep( 0.03, 0.1, max( streetRfw.x, streetRfw.y ) ) ) * smoothstep( 0.0, 0.08, uRain ) * streetPuddle;
if ( streetRings > 0.0 ) {
vec2 slope = streetRipple( vStreetWorld.xz, 0.7, 0.0 ) + streetRipple( vStreetWorld.xz, 1.1, 13.7 );
normal = normalize( normal + ( viewMatrix * vec4( -slope.x, 0.0, -slope.y, 0.0 ) ).xyz * streetRings * 0.4 );
}
`
const ROUGHNESS = /* glsl */ `
roughnessFactor = mix( roughnessFactor, 0.06, streetWet * 0.6 );
roughnessFactor = mix( roughnessFactor, 0.4, streetPaint * ( 1.0 - streetPuddle ) );
roughnessFactor = mix( roughnessFactor, 0.025, streetPuddle );
` city/weather.ts
// The weather: what falls, how hard the wind blows and how wet the ground is, as a pure function
// of a clock. Hand `weatherAt` the same Unix time on two machines and both get the same weather,
// so players who share a clock share the sky with nothing sent between them.
//
// Also here, the uniforms `Rain` and `WetStreet` share. `Rain` drives them from the weather it is
// given and the street only listens.
//
// No three.js, React or Runek in this file, so a HUD can import it without pulling in the 3D code.
export type WeatherKind = 'dry' | 'windy' | 'drizzle' | 'light-rain' | 'heavy-rain' | 'snow'
interface WeatherRow {
/** How likely a spell is to be this kind, against the other rows. Any positive numbers. */
odds: number
/** A spell lasts between these, in minutes. Keep the shorter one well above `WEATHER_TIMING.blend`. */
minutes: readonly [number, number]
/** How hard it rains, 0 to 1: how many streaks fall, how fast and how long they are, how loud it is. */
rain: number
/** How hard it snows, 0 to 1. */
snow: number
/** The steady wind is somewhere between these, in units a second. Each spell picks its own speed and heading. */
wind: readonly [number, number]
/** How far gusts swing the wind around that speed: 0.4 is 40% either way. */
gust: number
/** How wet the ground ends up if the spell lasts, 0 (dry) to 1 (soaked). */
wet: number
}
/**
* The tuning table: one row for each kind of weather. Change the mix of weather here.
*
* `odds` are relative (these add up to 100, so they read as percentages of spells, not of time:
* a kind with long spells fills more of the night than its odds say). The same kind never comes
* twice in a row.
*/
export const WEATHER: Record<WeatherKind, WeatherRow> = {
dry: { odds: 28, minutes: [5, 12], rain: 0, snow: 0, wind: [0.4, 1.6], gust: 0.3, wet: 0 },
windy: { odds: 14, minutes: [3, 7], rain: 0, snow: 0, wind: [7, 11], gust: 0.45, wet: 0 },
drizzle: {
odds: 16,
minutes: [4, 9],
rain: 0.15,
snow: 0,
wind: [0.5, 2.5],
gust: 0.3,
wet: 0.6,
},
'light-rain': {
odds: 20,
minutes: [4, 10],
rain: 0.45,
snow: 0,
wind: [1, 3.5],
gust: 0.35,
wet: 0.85,
},
'heavy-rain': { odds: 12, minutes: [3, 6], rain: 1, snow: 0, wind: [3, 7], gust: 0.5, wet: 1 },
snow: { odds: 10, minutes: [5, 10], rain: 0, snow: 0.85, wind: [0.5, 2.5], gust: 0.3, wet: 0.5 },
}
/** The clocks behind the table, in seconds unless they say otherwise. */
export const WEATHER_TIMING = {
/** One spell eases into the next over this long, so nothing pops. */
blend: 45,
/** Heavy rain soaks dry ground in about this long. Lighter weather takes longer. */
soak: 40,
/** Wet ground loses about two thirds of its water in this long once the rain stops. */
dry: 480,
/** The same in a wind, which dries a street faster. */
dryWindy: 200,
/** How far back the ground remembers, in minutes. Several times `dry`, or wetness steps. */
memoryMinutes: 40,
/** The schedule is dealt in blocks this long, in minutes. A spell never runs across two blocks. */
blockMinutes: 120,
/** Changes every spell at once: a different night of weather for the same clock. */
seed: 2047,
}
export const WEATHER_KINDS = Object.keys(WEATHER) as WeatherKind[]
export interface WeatherState {
/** The kind of weather this is. Halfway through a change it becomes the new one. */
kind: WeatherKind
/** How hard it rains now, 0 to 1. */
rain: number
/** How hard it snows now, 0 to 1. */
snow: number
/** The wind now, gusts and all, in units a second along x and z. */
wind: { x: number; z: number }
/** The length of `wind`. */
speed: number
/** How wet the ground is, 0 to 1. It lags the rain: streets stay wet for a while after it stops. */
wetness: number
}
/** A state to hand to `weatherAt` as `out`, so a caller that asks every frame makes no garbage. */
export function makeWeather(): WeatherState {
return { kind: 'dry', rain: 0, snow: 0, wind: { x: 0, z: 0 }, speed: 0, wetness: 0 }
}
/** Short names `?weather=` also takes. */
const ALIASES: Record<string, WeatherKind> = {
clear: 'dry',
wind: 'windy',
light: 'light-rain',
rain: 'light-rain',
heavy: 'heavy-rain',
storm: 'heavy-rain',
}
/** The kind a word names, or null when it names none. */
export function parseWeatherKind(word: string | null | undefined): WeatherKind | null {
if (!word) return null
const w = word.trim().toLowerCase()
if (w in WEATHER) return w as WeatherKind
return ALIASES[w] ?? null
}
// The schedule --------------------------------------------------------------------------------
interface Spell {
kind: WeatherKind
/** Unix ms. */
start: number
end: number
rain: number
snow: number
/** The steady wind, before gusts. */
wx: number
wz: number
gust: number
wet: number
/** Seconds for the ground to take this spell's water up, and to let it go. */
soak: number
dry: number
}
const BLOCK_MS = WEATHER_TIMING.blockMinutes * 60_000
const BLEND_MS = WEATHER_TIMING.blend * 1000
const MEMORY_MS = WEATHER_TIMING.memoryMinutes * 60_000
/** A block never ends on a spell shorter than this: the one before runs on to the end instead. */
const SHORTEST_MS = Math.max(
2 * BLEND_MS,
Math.min(...WEATHER_KINDS.map((k) => WEATHER[k].minutes[0])) * 60_000,
)
/** A small seeded generator, so the same block deals the same spells on every machine. */
function seeded(seed: number): () => number {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
function pick(r: () => number, not: WeatherKind | null): WeatherKind {
let total = 0
for (const k of WEATHER_KINDS) if (k !== not) total += WEATHER[k].odds
let at = r() * total
let last = WEATHER_KINDS[0]
for (const k of WEATHER_KINDS) {
if (k === not) continue
last = k
at -= WEATHER[k].odds
if (at < 0) return k
}
return last
}
const blocks = new Map<number, Spell[]>()
/** The spells of one block, end to end. Dealt from the block's number alone, so any block can be asked for on its own. */
function spellsOf(block: number): Spell[] {
const known = blocks.get(block)
if (known) return known
const r = seeded(Math.imul(block, 0x9e3779b1) ^ WEATHER_TIMING.seed)
const from = block * BLOCK_MS
const spells: Spell[] = []
let t = 0
let prev: WeatherKind | null = null
while (t < BLOCK_MS) {
const kind = pick(r, prev)
const row = WEATHER[kind]
let length = (row.minutes[0] + r() * (row.minutes[1] - row.minutes[0])) * 60_000
if (BLOCK_MS - (t + length) < SHORTEST_MS) length = BLOCK_MS - t
const heading = r() * Math.PI * 2
const speed = row.wind[0] + r() * (row.wind[1] - row.wind[0])
// No two spells of a kind are quite alike: each falls a little harder or softer than the table says.
const strength = 0.85 + r() * 0.3
const rain = Math.min(1, row.rain * strength)
const snow = Math.min(1, row.snow * strength)
spells.push({
kind,
start: from + t,
end: from + t + length,
rain,
snow,
wx: Math.cos(heading) * speed,
wz: Math.sin(heading) * speed,
gust: row.gust,
wet: row.wet,
soak: WEATHER_TIMING.soak / (0.25 + 0.75 * Math.max(rain, snow * 0.3)),
dry: kind === 'windy' ? WEATHER_TIMING.dryWindy : WEATHER_TIMING.dry,
})
t += length
prev = kind
}
if (blocks.size > 6) blocks.clear()
blocks.set(block, spells)
return spells
}
// The state at one moment ---------------------------------------------------------------------
const clamp01 = (v: number) => Math.min(1, Math.max(0, v))
const smooth = (v: number) => {
const x = clamp01(v)
return x * x * (3 - 2 * x)
}
const mix = (a: number, b: number, k: number) => a + (b - a) * k
/** What falls eases out in the first part of a change and in over the last, so rain is nearly gone before snow starts. */
const fall = (from: number, to: number, x: number) =>
mix(from, to, to < from ? smooth(x / 0.6) : smooth((x - 0.4) / 0.6))
const TURN = Math.PI * 2
/** Lay gusts over a steady wind. Slow sums of sines of the clock, so every player feels the same gust. */
function blow(out: WeatherState, wx: number, wz: number, gust: number, unixMs: number) {
const t = unixMs / 1000
const swell =
0.5 * Math.sin((t * TURN) / 23.1) +
0.3 * Math.sin((t * TURN) / 9.7 + 1.3) +
0.2 * Math.sin((t * TURN) / 4.3 + 4.1)
const veer = 0.6 * gust * Math.sin((t * TURN) / 37 + 2.2)
const scale = Math.max(0.15, 1 + gust * swell)
const cos = Math.cos(veer) * scale
const sin = Math.sin(veer) * scale
out.wind.x = wx * cos - wz * sin
out.wind.z = wx * sin + wz * cos
out.speed = Math.hypot(out.wind.x, out.wind.z)
}
/** Carry the ground's wetness through the spells of one block that fall inside its memory. -1 means nothing yet. */
function soakThrough(spells: Spell[], since: number, now: number, wet: number): number {
for (const s of spells) {
if (s.end <= since || s.start > now) continue
if (wet < 0) wet = s.wet
const seconds = (Math.min(s.end, now) - Math.max(s.start, since)) / 1000
wet = s.wet + (wet - s.wet) * Math.exp(-seconds / (s.wet > wet ? s.soak : s.dry))
}
return wet
}
/**
* The weather at a moment, from the clock alone. `unixMs` is Unix time in milliseconds: hand it
* the clock the players share. Pure: the same time always gives the same weather, whenever and
* wherever it is asked. Pass `out` to have it filled in place.
*/
export function weatherAt(unixMs: number, out: WeatherState = makeWeather()): WeatherState {
const block = Math.floor(unixMs / BLOCK_MS)
const today = spellsOf(block)
const before = spellsOf(block - 1)
let i = today.length - 1
while (i > 0 && today[i].start > unixMs) i--
const cur = today[i]
const prev = i > 0 ? today[i - 1] : before[before.length - 1]
const x = clamp01((unixMs - cur.start) / BLEND_MS)
const k = smooth(x)
out.kind = x < 0.5 ? prev.kind : cur.kind
out.rain = fall(prev.rain, cur.rain, x)
out.snow = fall(prev.snow, cur.snow, x)
blow(out, mix(prev.wx, cur.wx, k), mix(prev.wz, cur.wz, k), mix(prev.gust, cur.gust, k), unixMs)
const since = unixMs - MEMORY_MS
out.wetness = clamp01(soakThrough(today, since, unixMs, soakThrough(before, since, unixMs, -1)))
return out
}
/**
* One kind of weather that never changes, as if its spell had always been: for `?weather=`, tests
* and screenshots. The wind still gusts with the clock.
*/
export function steadyWeather(
kind: WeatherKind,
unixMs: number,
out: WeatherState = makeWeather(),
): WeatherState {
const row = WEATHER[kind]
const speed = (row.wind[0] + row.wind[1]) / 2
out.kind = kind
out.rain = row.rain
out.snow = row.snow
blow(out, speed * 0.894, speed * 0.447, row.gust, unixMs)
out.wetness = row.wet
return out
}
// What `Rain` and `WetStreet` share -----------------------------------------------------------
/**
* The rain clock wraps to 0 after this many seconds. Every speed and rate that reads the clock
* is picked so its motion repeats exactly at the wrap, and nothing jumps.
*/
export const RAIN_PERIOD = 160
/**
* Read by the streaks, splashes and flakes in `Rain` and by every `WetStreet`. With no `Rain`
* mounted they stay as they are here: no rings, and streets as wet as their own props say.
*/
export const rainUniforms = {
/** Seconds of weather so far, wrapped at `RAIN_PERIOD`. */
uRainTime: { value: 0 },
/** How hard rain rings the puddles, 0 (still water) to 1 (heavy rain). */
uRain: { value: 0 },
/** How wet the weather has left the ground, 0 to 1. It scales each street's own `wetness` and `puddles`. */
uWetness: { value: 1 },
}