{
  "name": "rain",
  "title": "Rain",
  "type": "registry:component",
  "description": "The weather over a whole world, drawn only around the camera: rain streaks and splashes, snowflakes, and rings on every `WetStreet`'s puddles, as hard as a `weather` function says (`weatherAt` gives the weather as a pure function of a clock). It stays out from under roofs through a depth map of the still world drawn from above in its first seconds. WebGLRenderer only.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Rain.tsx",
      "content": "import { useFrame, useThree } from '@react-three/fiber'\nimport {\n  DYNAMIC_KEY,\n  rng,\n  scenePass,\n  skipMirrors,\n  useNodeRenderer,\n  useWorld,\n  type Vec3,\n} from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  AdditiveBlending,\n  BufferAttribute,\n  BufferGeometry,\n  type Camera,\n  type Color,\n  DepthTexture,\n  DoubleSide,\n  Group,\n  InstancedBufferAttribute,\n  InstancedBufferGeometry,\n  LineSegments,\n  Mesh,\n  NearestFilter,\n  type Object3D,\n  OrthographicCamera,\n  Points,\n  RedFormat,\n  type Scene,\n  ShaderMaterial,\n  type Texture,\n  UnsignedByteType,\n  UnsignedShortType,\n  Vector2,\n  Vector3,\n  Vector4,\n  type WebGLRenderer,\n  WebGLRenderTarget,\n} from 'three'\nimport { along, emissiveColor, useLadder } from './city/glow'\nimport { RAIN_PERIOD, rainUniforms, type WeatherState } from './city/weather'\n\n// The weather is the rain's own: a world that mounts `Rain` reads what it does from here too.\nexport type { WeatherKind, WeatherState } from './city/weather'\nexport {\n  makeWeather,\n  parseWeatherKind,\n  RAIN_PERIOD,\n  steadyWeather,\n  WEATHER,\n  WEATHER_KINDS,\n  weatherAt,\n} from './city/weather'\n\n/** The part of a `WeatherState` the rain draws from. */\nexport type RainWeather = Pick<WeatherState, 'rain' | 'snow' | 'wind' | 'wetness'>\n\nexport interface RainProps {\n  /** Accepted for the component contract. Rain follows the camera, so it has no place of its own. */\n  position?: Vec3\n  /** Accepted for the component contract. */\n  rotation?: Vec3\n  /** Seeds where each streak, splash and flake starts. */\n  seed?: number\n  /** Streaks in the air around the camera when it rains its hardest. Lighter rain draws fewer. */\n  streaks?: number\n  /** Splashes on the ground around the camera in the heaviest rain, 0 for none. */\n  splashes?: number\n  /** Snowflakes in the air around the camera when it snows its hardest, 0 for none. */\n  flakes?: number\n  /** Ring the puddles of every `WetStreet`. */\n  ripples?: boolean\n  /**\n   * The weather now, asked every frame: `weatherAt` on a clock, most often. Left out, it rains\n   * hard and steadily and the streets stay soaked. JSX only.\n   */\n  weather?: () => RainWeather\n  /** The part of the world rain can fall on, [minX, minZ, maxX, maxZ] in units. Outside it, rain falls through everything. */\n  bounds?: readonly [number, number, number, number]\n  /** Texels along each side of the cover map, which records the highest surface over every spot. */\n  cover?: number\n  /** The lowest anything falls, in units: the surface of a sea, which no cover map holds since\n   *  water is not a still part of the world. Rain ends there and splashes on it, inside the\n   *  bounds and out. Unset, there is no such floor. */\n  floor?: number\n  /** Rain color. A cool grey by default, lit as if by the street. */\n  color?: string\n  /** Called with the GPU bytes the cover map holds, and with 0 when it is let go. JSX only. */\n  onMemory?: (bytes: number) => void\n}\n\nconst DEFAULT_BOUNDS = [-160, -160, 160, 160] as const\n\n/**\n * The weather over the whole world, drawn only around the camera: streaks of rain in the air,\n * splashes where they land, rings on the puddles of every `WetStreet`, and snowflakes. Mount it\n * once inside `<World>`.\n *\n * What falls follows `weather`. Rain from a drizzle (a few short, slow streaks) to a downpour\n * (all of them, long and fast), slanted by the wind and its gusts. Snow as slow flakes that\n * sway and drift. In dry weather nothing is drawn at all. It also tells every `WetStreet` how\n * hard the puddles are ringed and how wet the ground is.\n *\n * It stays out from under roofs. Shortly after mounting it draws the still parts of the world\n * once from straight above into a depth map (the cover map), and a streak dies where it meets\n * the highest surface over its spot, so an awning, a canopy or a ceiling keeps the ground under\n * it dry, and snow stays out the same way. Anything inside a `<Dynamic>` is left out of that\n * map. The map is drawn a few times in the first seconds to catch parts that arrive late, then\n * never again.\n *\n * Streaks, splashes and flakes are a draw call each, only while there are any to draw: two in\n * rain, one in snow, all three for the moments rain turns to snow, none when it is dry. They\n * stay out of the world's mirrors. The cover map is the one extra scene render, a few times in\n * the first seconds and never again, inside `scenePass()`.\n *\n * `WebGLRenderer` only: under `WebGPURenderer` it draws nothing.\n */\nexport function Rain(props: RainProps) {\n  return useNodeRenderer() ? null : <Fall {...props} />\n}\n\nRain.stream = false\n\n/** Seconds after mounting at which the cover map is drawn. The later ones catch parts that build over several frames. */\nconst BAKE_AT = [0.3, 1.0, 2.2]\n\n/** With no `weather` it rains as it always did: hard, on a light steady wind, on soaked streets. */\nconst STEADY: RainWeather = { rain: 1, snow: 0, wind: { x: 0.8, z: 0.4 }, wetness: 1 }\n\nfunction Fall({\n  seed = 0,\n  streaks = 8000,\n  splashes = 400,\n  flakes = 4000,\n  ripples = true,\n  weather,\n  bounds = DEFAULT_BOUNDS,\n  cover = 2048,\n  floor,\n  color = '#aab0bd',\n  onMemory,\n}: RainProps) {\n  const { unit } = useWorld()\n  const ladder = useLadder()\n  const gl = useThree((s) => s.gl) as WebGLRenderer\n  const scene = useThree((s) => s.scene) as Scene\n  const camera = useThree((s) => s.camera)\n  const [minX, minZ, maxX, maxZ] = bounds\n\n  const map = useMemo(\n    () => new CoverMap(minX * unit, minZ * unit, maxX * unit, maxZ * unit, cover, unit),\n    [minX, minZ, maxX, maxZ, cover, unit],\n  )\n  const schedule = useRef({ t: 0, next: 0 })\n  useEffect(() => {\n    schedule.current = { t: 0, next: 0 }\n    return () => {\n      map.dispose()\n      onMemory?.(0)\n    }\n  }, [map, onMemory])\n\n  // Lit as if by the street: rain shows where light is, and this is the light most of it has.\n  const rain = useMemo(\n    () =>\n      buildRain({\n        seed,\n        streaks,\n        splashes,\n        flakes,\n        unit,\n        streak: emissiveColor(color, along(ladder.streetUnderSign, 0.2)),\n        splash: emissiveColor(color, along(ladder.streetUnderSign, 0.35)),\n        // Snow is white where rain is clear, so the same street light shows more of it.\n        flake: emissiveColor(SNOW_COLOR, along(ladder.streetUnderSign, 0.4)),\n        map,\n      }),\n    [seed, streaks, splashes, flakes, unit, color, ladder.streetUnderSign, map],\n  )\n  useEffect(() => () => rain.dispose(), [rain])\n\n  // A reflection of a streak is too faint to pay for.\n  useEffect(() => skipMirrors(rain.group), [rain])\n\n  // Without a `Rain` the streets go back to what their own props say: still water, as wet as they were built.\n  useEffect(\n    () => () => {\n      rainUniforms.uRain.value = 0\n      rainUniforms.uWetness.value = 1\n    },\n    [],\n  )\n\n  useFrame((_, delta) => {\n    // A long frame (a tab coming back) moves the rain a tenth of a second, not the whole gap.\n    const dt = Math.min(delta, 0.1)\n    rainUniforms.uRainTime.value = (rainUniforms.uRainTime.value + dt) % RAIN_PERIOD\n    const now = weather ? weather() : STEADY\n    rainUniforms.uRain.value = ripples ? Math.min(1, Math.max(0, now.rain)) : 0\n    rainUniforms.uWetness.value = now.wetness\n    rain.step(dt, now)\n    const s = schedule.current\n    s.t += dt\n    if (s.next < BAKE_AT.length && s.t >= BAKE_AT[s.next]) {\n      s.next++\n      const first = !map.ready\n      map.bake(gl, scene, camera, rain.group)\n      if (first) onMemory?.(map.bytes)\n    }\n    // Nothing falls until the map says where the roofs are.\n    rain.cover.value = map.ready ? map.depth : null\n    rain.floor.value = floor === undefined ? NO_FLOOR : floor * unit\n    rain.group.visible = map.ready\n  })\n\n  return <primitive object={rain.group} />\n}\n\n/**\n * The highest surface over every spot of a rectangle of the world, as a depth map drawn from\n * straight above. Sixteen bits of depth over the camera's range puts a surface within a\n * centimetre of where it is.\n */\nclass CoverMap {\n  readonly target: WebGLRenderTarget\n  readonly depth: DepthTexture\n  readonly camera: OrthographicCamera\n  /** (minX, maxZ, 1 / sizeX, 1 / sizeZ): turns a world xz into the map's uv. */\n  readonly box: Vector4\n  /** (camera height, near, far - near, half a texel in uv): turns a depth into a world height. */\n  readonly range: Vector4\n  readonly bytes: number\n  ready = false\n\n  constructor(minX: number, minZ: number, maxX: number, maxZ: number, size: number, unit: number) {\n    const sizeX = maxX - minX\n    const sizeZ = maxZ - minZ\n    const top = 400 * unit\n    const near = unit\n    const far = top + 40 * unit\n    this.depth = new DepthTexture(size, size, UnsignedShortType)\n    this.target = new WebGLRenderTarget(size, size, {\n      format: RedFormat,\n      type: UnsignedByteType,\n      minFilter: NearestFilter,\n      magFilter: NearestFilter,\n      generateMipmaps: false,\n      depthBuffer: true,\n    })\n    this.target.depthTexture = this.depth\n    // One byte of color (unused, a target must have one) and two of depth for each texel.\n    this.bytes = size * size * 3\n    // Looking straight down with -Z up the image: u runs along +X and v along -Z.\n    this.camera = new OrthographicCamera(-sizeX / 2, sizeX / 2, sizeZ / 2, -sizeZ / 2, near, far)\n    this.camera.position.set((minX + maxX) / 2, top, (minZ + maxZ) / 2)\n    this.camera.up.set(0, 0, -1)\n    this.camera.lookAt((minX + maxX) / 2, 0, (minZ + maxZ) / 2)\n    this.camera.updateProjectionMatrix()\n    this.camera.updateMatrixWorld()\n    this.box = new Vector4(minX, maxZ, 1 / sizeX, 1 / sizeZ)\n    this.range = new Vector4(top, near, far - near, 0.5 / size)\n  }\n\n  /** Draw the map: the scene as `viewer` sees it, less `skip` and everything that moves. */\n  bake(gl: WebGLRenderer, scene: Scene, viewer: Camera, skip: Object3D) {\n    const hidden: Object3D[] = []\n    const hide = (o: Object3D) => {\n      if (!o.visible) return\n      if (o === skip || o.userData[DYNAMIC_KEY]) {\n        o.visible = false\n        hidden.push(o)\n        return\n      }\n      for (const child of o.children) hide(child)\n    }\n    hide(scene)\n    this.camera.layers.mask = viewer.layers.mask\n    const target = gl.getRenderTarget()\n    const auto = gl.shadowMap.autoUpdate\n    const needs = gl.shadowMap.needsUpdate\n    // The shadow maps are for the viewer's camera. Leave them be.\n    gl.shadowMap.autoUpdate = false\n    gl.shadowMap.needsUpdate = false\n    gl.setRenderTarget(this.target)\n    gl.clear(true, true, true)\n    scenePass(() => gl.render(scene, this.camera))\n    gl.setRenderTarget(target)\n    gl.shadowMap.autoUpdate = auto\n    gl.shadowMap.needsUpdate = needs\n    for (const o of hidden) o.visible = true\n    this.ready = true\n  }\n\n  dispose() {\n    this.target.dispose()\n    this.depth.dispose()\n  }\n}\n\n// The box of rain around the camera, in units. Streaks wrap inside it, so the camera never\n// walks out of the rain. `BELOW` is how far under the camera they still fall, for a view down\n// from a roof.\nconst BOX = 64\nconst HEIGHT = 40\nconst BELOW = 10\n/** Streak speeds in the heaviest rain's range, in units a second, in steps that fall a whole number of box heights over `RAIN_PERIOD`. */\nconst SPEED = { min: 22, steps: 41, step: 0.25 }\n/** A streak is as long as the rain moves in this many seconds: the blur of one exposure. */\nconst EXPOSURE = 0.03\n/**\n * What the rain's strength (0 to 1) does to a streak, as [in a drizzle, in a downpour]: how fast\n * it falls against `SPEED`, how long its exposure is against `EXPOSURE`, and how bright it is.\n * How many streaks fall goes straight with the strength.\n */\nconst STREAK = { speed: [0.45, 1.1], exposure: [0.7, 1.3], light: [0.55, 1] } as const\n/** Splashes thin out a little faster than streaks as the rain eases: their count goes with the strength to this power. */\nconst SPLASH_EASE = 1.3\n// Snow has a smaller box of its own, since a flake past 12 units is too small to see, and a\n// small box keeps the flakes there are close together.\nconst SNOW_BOX = 24\nconst SNOW_HEIGHT = 16\nconst SNOW_BELOW = 6\n/** Flake speeds, in units a second, in steps that fall a whole number of snow box heights over `RAIN_PERIOD`. */\nconst SNOW_SPEED = { min: 0.9, steps: 13, step: SNOW_HEIGHT / RAIN_PERIOD }\n/** The wind's drift wraps here, in units: a whole number of both boxes, so neither sees the wrap. */\nconst DRIFT_SPAN = BOX * SNOW_BOX\n/** How far a flake swings side to side as it falls, in units, and how wide the largest is. */\nconst SNOW_SWAY = 0.35\nconst SNOW_SIZE = { min: 0.02, max: 0.045 }\nconst SNOW_COLOR = '#dfe6f2'\n/** Splashes wrap inside a square of this side around the camera, in units. */\nconst AREA = 36\n\nconst f = (n: number) => n.toFixed(4)\n\n/** Where the floor is when a world has none: under anything a cover map could hold. */\nconst NO_FLOOR = -1000\n\nconst COVER_PARS = /* glsl */ `\nuniform sampler2D tCover;\nuniform float uFloor;\nuniform vec4 uCoverBox;\nuniform vec4 uCoverDepth;\nvec2 coverUv( vec2 xz ) { return vec2( ( xz.x - uCoverBox.x ) * uCoverBox.z, ( uCoverBox.y - xz.y ) * uCoverBox.w ); }\nfloat coverAt( vec2 uv ) { return uCoverDepth.x - ( uCoverDepth.y + texture2D( tCover, uv ).r * uCoverDepth.z ); }\nbool coverOutside( vec2 uv ) { return uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0; }\n// The height of the highest surface over a spot, or far below the world outside the map.\nfloat coverHeight( vec2 xz ) {\n  vec2 uv = coverUv( xz );\n  return max( coverOutside( uv ) ? -1000.0 : coverAt( uv ), uFloor );\n}\n// The same over the four nearest texels, so a streak beside a wall ends at the roof line and not in the wall.\nfloat coverShelter( vec2 xz ) {\n  vec2 uv = coverUv( xz );\n  if ( coverOutside( uv ) ) return uFloor;\n  float h = uCoverDepth.w;\n  return max( uFloor, max( max( coverAt( uv + vec2( -h, -h ) ), coverAt( uv + vec2( h, -h ) ) ), max( coverAt( uv + vec2( -h, h ) ), coverAt( uv + vec2( h, h ) ) ) ) );\n}\n`\n\nconst streakVert = (unit: number) => /* glsl */ `\nuniform float uFall;\nuniform vec2 uDrift;\nuniform vec2 uWind;\nuniform vec3 uStreak;\nuniform vec3 uCam;\nattribute float aEnd;\nattribute float aSpeed;\nvarying float vA;\n${COVER_PARS}\nvoid main() {\n  // Fall and drift, wrapped into the box around the camera. The fall has a clock of its own that\n  // runs slow in a drizzle, and the drift is how far the wind has carried everything so far.\n  vec3 w;\n  w.y = uCam.y + mod( position.y - uFall * aSpeed - uCam.y + ${f(BELOW * unit)}, ${f(HEIGHT * unit)} ) - ${f(BELOW * unit)};\n  w.x = uCam.x + mod( position.x + uDrift.x - uCam.x + ${f((BOX / 2) * unit)}, ${f(BOX * unit)} ) - ${f((BOX / 2) * unit)};\n  w.z = uCam.z + mod( position.z + uDrift.y - uCam.z + ${f((BOX / 2) * unit)}, ${f(BOX * unit)} ) - ${f((BOX / 2) * unit)};\n  // Both ends ask about the head, so a streak goes out whole when its head meets a surface.\n  float alive = step( coverShelter( w.xz ), w.y );\n  // The tail trails back along the way the drop is moving, so wind slants the streak.\n  vec3 velocity = vec3( uWind.x, -aSpeed * uStreak.x, uWind.y );\n  w -= velocity * ( aEnd * ${f(EXPOSURE)} * uStreak.y );\n  float d = distance( w, uCam );\n  // Bright at the head, faint at the tail. Gone right at the lens and again where the box ends.\n  vA = uStreak.z * ( 1.0 - aEnd * 0.8 ) * smoothstep( ${f(0.5 * unit)}, ${f(3 * unit)}, d ) * ( 1.0 - smoothstep( ${f(18 * unit)}, ${f((BOX / 2) * unit)}, d ) ) * alive;\n  gl_Position = projectionMatrix * viewMatrix * vec4( w, 1.0 );\n}`\n\n// No tone mapping here: like the haze, rain is added to the linear image and the post stack grades it.\nconst STREAK_FRAG = /* glsl */ `\nuniform vec3 uColor;\nvarying float vA;\nvoid main() {\n  gl_FragColor = vec4( uColor * vA, 1.0 );\n}`\n\n// A flake is one point: it falls slowly, swings from side to side and rides the same drift as the\n// rain. The swing turns a whole number of times over the rain clock, so the wrap is seamless.\nconst flakeVert = (unit: number) => /* glsl */ `\nuniform float uRainTime;\nuniform vec2 uDrift;\nuniform float uPixels;\nuniform vec3 uCam;\nattribute vec4 aFlake;\nvarying float vA;\n${COVER_PARS}\nvoid main() {\n  vec2 sway = vec2( sin( aFlake.y + uRainTime * aFlake.z ), cos( aFlake.y * 1.7 + uRainTime * aFlake.z ) ) * ${f(SNOW_SWAY * unit)};\n  vec3 w;\n  w.y = uCam.y + mod( position.y - uRainTime * aFlake.x - uCam.y + ${f(SNOW_BELOW * unit)}, ${f(SNOW_HEIGHT * unit)} ) - ${f(SNOW_BELOW * unit)};\n  w.x = uCam.x + mod( position.x + uDrift.x + sway.x - uCam.x + ${f((SNOW_BOX / 2) * unit)}, ${f(SNOW_BOX * unit)} ) - ${f((SNOW_BOX / 2) * unit)};\n  w.z = uCam.z + mod( position.z + uDrift.y + sway.y - uCam.z + ${f((SNOW_BOX / 2) * unit)}, ${f(SNOW_BOX * unit)} ) - ${f((SNOW_BOX / 2) * unit)};\n  float alive = step( coverShelter( w.xz ), w.y );\n  vec4 mv = viewMatrix * vec4( w, 1.0 );\n  float d = length( mv.xyz );\n  // As wide on screen as it would be at its distance. Under a pixel it stays a pixel and fades instead.\n  float px = aFlake.w * uPixels / max( -mv.z, 1e-3 );\n  gl_PointSize = clamp( px, 1.0, 12.0 );\n  vA = min( px, 1.0 ) * smoothstep( ${f(0.4 * unit)}, ${f(1.5 * unit)}, d ) * ( 1.0 - smoothstep( ${f(SNOW_BOX * 0.3 * unit)}, ${f((SNOW_BOX / 2) * unit)}, d ) ) * alive;\n  gl_Position = projectionMatrix * mv;\n}`\n\nconst FLAKE_FRAG = /* glsl */ `\nuniform vec3 uColor;\nvarying float vA;\nvoid main() {\n  float r = length( gl_PointCoord - 0.5 ) * 2.0;\n  gl_FragColor = vec4( uColor * ( 1.0 - smoothstep( 0.35, 1.0, r ) ) * vA, 1.0 );\n}`\n\n// Each splash is two quads: a ring that spreads flat on the surface, and a short spurt that\n// stands up and turns to face the camera. When its time is up it starts again somewhere else.\nconst splashVert = (unit: number) => /* glsl */ `\nuniform float uRainTime;\nuniform vec3 uCam;\nattribute vec4 aSeed;\nvarying vec2 vP;\nvarying float vPart;\nvarying float vLife;\nvarying float vFade;\n${COVER_PARS}\nvoid main() {\n  // Rates in eighths, so each splash's count of lives over the rain clock is whole and the wrap is seamless.\n  float rate = 1.5 + floor( aSeed.z * 12.0 ) * 0.125;\n  float t = uRainTime * rate + floor( aSeed.w * 61.0 );\n  float life = fract( t );\n  float turn = mod( floor( t ), rate * ${f(RAIN_PERIOD)} );\n  vec2 spot = fract( aSeed.xy + turn * vec2( 0.618034, 0.754878 ) ) * ${f(AREA * unit)};\n  vec2 xz = uCam.xz + mod( spot - uCam.xz + ${f((AREA / 2) * unit)}, ${f(AREA * unit)} ) - ${f((AREA / 2) * unit)};\n  float ground = coverHeight( xz );\n  vec3 w = vec3( xz.x, ground, xz.y );\n  float d = distance( w, uCam );\n  if ( position.z < 0.5 ) {\n    float radius = ( 0.02 + ( 0.07 + 0.06 * aSeed.z ) * sqrt( life ) ) * ${f(unit)};\n    w.xz += position.xy * radius;\n    w.y += ${f(0.02 * unit)};\n  } else {\n    vec2 toCam = normalize( uCam.xz - xz + 1e-4 );\n    float rise = ( 0.04 + 0.08 * aSeed.x ) * sin( min( life * 3.0, 1.0 ) * 3.14159 ) * ${f(unit)};\n    w.xz += vec2( -toCam.y, toCam.x ) * position.x * ${f(0.025 * unit)};\n    w.y += ${f(0.02 * unit)} + position.y * rise;\n  }\n  vP = position.xy;\n  vPart = position.z;\n  vLife = life;\n  vFade = ( 1.0 - smoothstep( ${f(AREA * 0.3 * unit)}, ${f(AREA * 0.5 * unit)}, d ) ) * smoothstep( ${f(0.3 * unit)}, ${f(1.5 * unit)}, d ) * step( -500.0, ground );\n  gl_Position = projectionMatrix * viewMatrix * vec4( w, 1.0 );\n}`\n\nconst SPLASH_FRAG = /* glsl */ `\nuniform vec3 uColor;\nvarying vec2 vP;\nvarying float vPart;\nvarying float vLife;\nvarying float vFade;\nvoid main() {\n  float a;\n  if ( vPart < 0.5 ) {\n    float r = length( vP );\n    float fade = 1.0 - vLife;\n    a = smoothstep( 0.7, 0.88, r ) * ( 1.0 - smoothstep( 0.88, 1.0, r ) ) * fade * fade;\n  } else {\n    // A sliver, widest at the foot, gone by the time the ring has spread.\n    float width = 1.0 - vP.y * 0.8;\n    a = ( 1.0 - smoothstep( width * 0.4, width, abs( vP.x ) ) ) * ( 1.0 - smoothstep( 0.0, 0.4, vLife ) );\n  }\n  gl_FragColor = vec4( uColor * a * vFade, 1.0 );\n}`\n\ninterface RainParts {\n  seed: number\n  streaks: number\n  splashes: number\n  flakes: number\n  unit: number\n  streak: Color\n  splash: Color\n  flake: Color\n  map: CoverMap\n}\n\nconst wrap = (v: number, span: number) => ((v % span) + span) % span\nconst between = (range: readonly [number, number], k: number) =>\n  range[0] + (range[1] - range[0]) * k\n\nfunction buildRain({\n  seed,\n  streaks,\n  splashes,\n  flakes,\n  unit,\n  streak,\n  splash,\n  flake,\n  map,\n}: RainParts) {\n  const r = rng(seed)\n  const group = new Group()\n  group.name = 'runek:rain'\n  group.visible = false\n  const disposables: { dispose(): void }[] = []\n  const cover = { value: null as Texture | null }\n  const floor = { value: NO_FLOOR }\n  const eye = { value: new Vector3() }\n  // The streaks' own clock, how far the wind has carried everything, the wind now, and what the\n  // rain's strength makes of a streak (speed, exposure, light).\n  const fall = { value: 0 }\n  const drift = { value: new Vector2() }\n  const wind = { value: new Vector2() }\n  const streakLook = { value: new Vector3(1, 1, 1) }\n  // Screen pixels a world length of 1 covers at a distance of 1, for sizing flakes.\n  const pixels = { value: 1 }\n  const size = new Vector2()\n  const shared = {\n    uRainTime: rainUniforms.uRainTime,\n    uCam: eye,\n    tCover: cover,\n    uFloor: floor,\n    uCoverBox: { value: map.box },\n    uCoverDepth: { value: map.range },\n  }\n  // Read the eye from whichever camera is about to draw, so the rain never trails the view.\n  const follow = (gl: WebGLRenderer, _scene: unknown, camera: Camera) => {\n    eye.value.setFromMatrixPosition(camera.matrixWorld)\n    const target = gl.getRenderTarget()\n    const height = target ? target.height : gl.getDrawingBufferSize(size).y\n    pixels.value = height * 0.5 * camera.projectionMatrix.elements[5]\n  }\n  const additive = (material: ShaderMaterial) => {\n    material.transparent = true\n    material.blending = AdditiveBlending\n    material.depthWrite = false\n    disposables.push(material)\n    return material\n  }\n  const place = (object: Object3D) => {\n    // The box follows the camera in the shader, so there is no still bound to cull by.\n    object.frustumCulled = false\n    object.renderOrder = 6\n    object.onBeforeRender = follow as Object3D['onBeforeRender']\n    // Nothing is drawn until the weather asks for it.\n    object.visible = false\n    group.add(object)\n  }\n\n  let lines: LineSegments | null = null\n  let splashMesh: Mesh<InstancedBufferGeometry> | null = null\n  let points: Points | null = null\n\n  if (streaks > 0) {\n    const position = new Float32Array(streaks * 6)\n    const end = new Float32Array(streaks * 2)\n    const speed = new Float32Array(streaks * 2)\n    for (let i = 0; i < streaks; i++) {\n      const x = r() * BOX * unit\n      const y = r() * HEIGHT * unit\n      const z = r() * BOX * unit\n      const fall = (SPEED.min + Math.floor(r() * SPEED.steps) * SPEED.step) * unit\n      position.set([x, y, z, x, y, z], i * 6)\n      end.set([0, 1], i * 2)\n      speed.set([fall, fall], i * 2)\n    }\n    const geometry = new BufferGeometry()\n    geometry.setAttribute('position', new BufferAttribute(position, 3))\n    geometry.setAttribute('aEnd', new BufferAttribute(end, 1))\n    geometry.setAttribute('aSpeed', new BufferAttribute(speed, 1))\n    disposables.push(geometry)\n    const material = additive(\n      new ShaderMaterial({\n        vertexShader: streakVert(unit),\n        fragmentShader: STREAK_FRAG,\n        uniforms: {\n          ...shared,\n          uFall: fall,\n          uDrift: drift,\n          uWind: wind,\n          uStreak: streakLook,\n          uColor: { value: streak },\n        },\n      }),\n    )\n    lines = new LineSegments(geometry, material)\n    lines.name = 'runek:rain:streaks'\n    place(lines)\n  }\n\n  if (splashes > 0) {\n    const geometry = new InstancedBufferGeometry()\n    // (x, y) is the corner and z says which quad: 0 the flat ring, 1 the upright spurt.\n    const corners = [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0, -1, 0, 1, 1, 0, 1, -1, 1, 1, 1, 1, 1]\n    geometry.setAttribute('position', new BufferAttribute(new Float32Array(corners), 3))\n    geometry.setIndex([0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7])\n    const seeds = new Float32Array(splashes * 4)\n    for (let i = 0; i < seeds.length; i++) seeds[i] = r()\n    geometry.setAttribute('aSeed', new InstancedBufferAttribute(seeds, 4))\n    geometry.instanceCount = splashes\n    disposables.push(geometry)\n    const material = additive(\n      new ShaderMaterial({\n        vertexShader: splashVert(unit),\n        fragmentShader: SPLASH_FRAG,\n        uniforms: { ...shared, uColor: { value: splash } },\n        side: DoubleSide,\n      }),\n    )\n    material.polygonOffset = true\n    material.polygonOffsetFactor = -2\n    material.polygonOffsetUnits = -4\n    splashMesh = new Mesh(geometry, material)\n    splashMesh.name = 'runek:rain:splashes'\n    place(splashMesh)\n  }\n\n  if (flakes > 0) {\n    const position = new Float32Array(flakes * 3)\n    const flakeSeeds = new Float32Array(flakes * 4)\n    for (let i = 0; i < flakes; i++) {\n      position.set([r() * SNOW_BOX * unit, r() * SNOW_HEIGHT * unit, r() * SNOW_BOX * unit], i * 3)\n      // Fall speed, where in its swing it starts, how fast it swings (a whole number of turns over the rain clock), and its width.\n      flakeSeeds.set(\n        [\n          (SNOW_SPEED.min + Math.floor(r() * SNOW_SPEED.steps) * SNOW_SPEED.step) * unit,\n          r() * Math.PI * 2,\n          ((20 + Math.floor(r() * 40)) * Math.PI * 2) / RAIN_PERIOD,\n          (SNOW_SIZE.min + r() * (SNOW_SIZE.max - SNOW_SIZE.min)) * unit,\n        ],\n        i * 4,\n      )\n    }\n    const geometry = new BufferGeometry()\n    geometry.setAttribute('position', new BufferAttribute(position, 3))\n    geometry.setAttribute('aFlake', new BufferAttribute(flakeSeeds, 4))\n    disposables.push(geometry)\n    const material = additive(\n      new ShaderMaterial({\n        vertexShader: flakeVert(unit),\n        fragmentShader: FLAKE_FRAG,\n        uniforms: { ...shared, uDrift: drift, uPixels: pixels, uColor: { value: flake } },\n      }),\n    )\n    points = new Points(geometry, material)\n    points.name = 'runek:rain:flakes'\n    place(points)\n  }\n\n  return {\n    group,\n    cover,\n    floor,\n    /** Move the weather on by `dt` seconds and draw as much of it as `now` asks for. */\n    step(dt: number, now: RainWeather) {\n      const rain = Math.min(1, Math.max(0, now.rain))\n      const snow = Math.min(1, Math.max(0, now.snow))\n      const speed = between(STREAK.speed, rain)\n      // Wrapped like the rain clock, and for the same reason: every streak speed repeats over it.\n      fall.value = (fall.value + dt * speed) % RAIN_PERIOD\n      const span = DRIFT_SPAN * unit\n      drift.value.set(\n        wrap(drift.value.x + now.wind.x * unit * dt, span),\n        wrap(drift.value.y + now.wind.z * unit * dt, span),\n      )\n      wind.value.set(now.wind.x * unit, now.wind.z * unit)\n      streakLook.value.set(speed, between(STREAK.exposure, rain), between(STREAK.light, rain))\n      // Every part starts at a random spot, so the first few of them are as evenly spread as all of them.\n      if (lines) {\n        const count = Math.round(streaks * rain)\n        lines.geometry.setDrawRange(0, count * 2)\n        lines.visible = count > 0\n      }\n      if (splashMesh) {\n        const count = Math.round(splashes * rain ** SPLASH_EASE)\n        splashMesh.geometry.instanceCount = count\n        splashMesh.visible = count > 0\n      }\n      if (points) {\n        const count = Math.round(flakes * snow)\n        points.geometry.setDrawRange(0, count)\n        points.visible = count > 0\n      }\n    },\n    dispose() {\n      for (const d of disposables) d.dispose()\n    },\n  }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/glow.ts",
      "content": "// How bright each kind of city emitter is, as a ladder of rungs, each the lowest and highest\n// luminance that kind may have, so a sign face is a sign face whatever its hue and a lamp lens\n// always outshines it. The rungs are face values scaled by the world's luminance levels\n// (`useLuminance()`): sign faces by `sign`, tube cores by `tube`, lamp lenses by `lamp`, and lit\n// glass (windows, shopfronts, ad boards, and the light they leave on the pavement) by `screen`.\n// At every level's default of 1 the brightest rungs sit around 1, so they read without bloom; a\n// world with bloom raises `sign`, `tube` and `lamp` to make them bloom.\n//\n// Emissive colors are normalized to unit luminance and then scaled onto a rung, so the hue of a\n// color never changes how bright it reads.\n\nimport {\n  DEFAULT_LUMINANCE,\n  glowLook,\n  type MaterialLook,\n  materialKey,\n  retainMaterial,\n  sharedMaterial,\n  useLuminance,\n  type WorldLuminance,\n} from '@runek/core'\nimport { useMemo } from 'react'\nimport { Color, type Material } from 'three'\n\n/** A rung of the ladder: the lowest and highest luminance that kind of emitter may have. */\nexport type Rung = readonly [number, number]\n\nexport interface Ladder {\n  /** A night sky dome lit from below by a city. Face value. */\n  skyDome: Rung\n  /** A wall with no lamp on it. Face value. */\n  unlitWall: Rung\n  /** Pavement lit by the glass and signs above it. */\n  streetUnderSign: Rung\n  /** A lit room seen through its window from the street. */\n  windowLit: Rung\n  /** Lit shopfront glass, and the white of an ad board. */\n  shopGlass: Rung\n  /** Sign faces and lit letters. */\n  signFace: Rung\n  /** The core of a neon tube. */\n  tubeCore: Rung\n  /** A street lamp's lens seen from below. */\n  lampLens: Rung\n}\n\nconst scale = (r: Rung, k: number): Rung => [r[0] * k, r[1] * k]\n\n/** The rungs at every luminance level's face value (1). */\nexport const FACE_LADDER: Ladder = {\n  skyDome: [0.018, 0.055],\n  unlitWall: [0.02, 0.05],\n  streetUnderSign: [0.1, 0.5],\n  windowLit: [0.15, 0.6],\n  shopGlass: [0.4, 1.2],\n  signFace: [0.6, 1.6],\n  tubeCore: [0.6, 1.7],\n  lampLens: [0.67, 1.5],\n}\n\n/** The ladder for a world's luminance levels. */\nexport function ladderFor(l: WorldLuminance): Ladder {\n  const f = FACE_LADDER\n  return {\n    skyDome: f.skyDome,\n    unlitWall: f.unlitWall,\n    streetUnderSign: scale(f.streetUnderSign, l.screen),\n    windowLit: scale(f.windowLit, l.screen),\n    shopGlass: scale(f.shopGlass, l.screen),\n    signFace: scale(f.signFace, l.sign),\n    tubeCore: scale(f.tubeCore, l.tube),\n    lampLens: scale(f.lampLens, l.lamp),\n  }\n}\n\n/** The ladder at the default levels. */\nexport const DEFAULT_LADDER: Ladder = ladderFor(DEFAULT_LUMINANCE)\n\n/** The world's ladder, from its luminance levels. */\nexport function useLadder(): Ladder {\n  const { screen, sign, tube, lamp, flame } = useLuminance()\n  return useMemo(\n    () => ladderFor({ screen, sign, tube, lamp, flame }),\n    [screen, sign, tube, lamp, flame],\n  )\n}\n\n/** The typical value of a rung: the geometric middle, since luminance is perceived on a log scale. */\nexport function mid(rung: Rung): number {\n  return Math.sqrt(rung[0] * rung[1])\n}\n\n/** A point along a rung, 0 at its bottom and 1 at its top, spaced evenly on a log scale. */\nexport function along(rung: Rung, t: number): number {\n  return rung[0] * (rung[1] / rung[0]) ** t\n}\n\n/** Relative luminance (Rec. 709) of a linear color. */\nexport function luminanceOf(c: Color): number {\n  return 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b\n}\n\n/** `hex` at unit luminance times `luminance`, as a linear (HDR) color. */\nexport function emissiveColor(hex: string, luminance: number): Color {\n  const c = new Color(hex)\n  return c.multiplyScalar(luminance / Math.max(1e-4, luminanceOf(c)))\n}\n\n/** A shared look's material, kept for the life of the page: city emitters come back often. */\nfunction kept(look: MaterialLook): Material {\n  const key = materialKey(look)\n  const material = sharedMaterial(look, key)\n  if (!material.userData.kept) {\n    material.userData.kept = true\n    retainMaterial(key)\n  }\n  return material\n}\n\n/**\n * The shared unlit material for an emitter of color `hex` at `luminance`, through core's\n * `glowLook`, so it batches with every other part of that look. Read-only.\n */\nexport function glowMaterial(hex: string, luminance: number, opacity = 1): Material {\n  return kept(\n    glowLook(\n      emissiveColor(hex, 1),\n      luminance,\n      opacity < 1 ? { transparent: true, opacity, depthWrite: false } : undefined,\n    ),\n  )\n}\n\n/**\n * The shared unlit material for picture content on a lit board: `hex` keeps its own value and\n * is scaled so that white would shine at `white`. Dark backgrounds stay dark, bright text and\n * shapes glow.\n */\nexport function screenMaterial(hex: string, white: number): Material {\n  return kept(glowLook(hex, white))\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/weather.ts",
      "content": "// The weather: what falls, how hard the wind blows and how wet the ground is, as a pure function\n// of a clock. Hand `weatherAt` the same Unix time on two machines and both get the same weather,\n// so players who share a clock share the sky with nothing sent between them.\n//\n// Also here, the uniforms `Rain` and `WetStreet` share. `Rain` drives them from the weather it is\n// given and the street only listens.\n//\n// No three.js, React or Runek in this file, so a HUD can import it without pulling in the 3D code.\n\nexport type WeatherKind = 'dry' | 'windy' | 'drizzle' | 'light-rain' | 'heavy-rain' | 'snow'\n\ninterface WeatherRow {\n  /** How likely a spell is to be this kind, against the other rows. Any positive numbers. */\n  odds: number\n  /** A spell lasts between these, in minutes. Keep the shorter one well above `WEATHER_TIMING.blend`. */\n  minutes: readonly [number, number]\n  /** How hard it rains, 0 to 1: how many streaks fall, how fast and how long they are, how loud it is. */\n  rain: number\n  /** How hard it snows, 0 to 1. */\n  snow: number\n  /** The steady wind is somewhere between these, in units a second. Each spell picks its own speed and heading. */\n  wind: readonly [number, number]\n  /** How far gusts swing the wind around that speed: 0.4 is 40% either way. */\n  gust: number\n  /** How wet the ground ends up if the spell lasts, 0 (dry) to 1 (soaked). */\n  wet: number\n}\n\n/**\n * The tuning table: one row for each kind of weather. Change the mix of weather here.\n *\n * `odds` are relative (these add up to 100, so they read as percentages of spells, not of time:\n * a kind with long spells fills more of the night than its odds say). The same kind never comes\n * twice in a row.\n */\nexport const WEATHER: Record<WeatherKind, WeatherRow> = {\n  dry: { odds: 28, minutes: [5, 12], rain: 0, snow: 0, wind: [0.4, 1.6], gust: 0.3, wet: 0 },\n  windy: { odds: 14, minutes: [3, 7], rain: 0, snow: 0, wind: [7, 11], gust: 0.45, wet: 0 },\n  drizzle: {\n    odds: 16,\n    minutes: [4, 9],\n    rain: 0.15,\n    snow: 0,\n    wind: [0.5, 2.5],\n    gust: 0.3,\n    wet: 0.6,\n  },\n  'light-rain': {\n    odds: 20,\n    minutes: [4, 10],\n    rain: 0.45,\n    snow: 0,\n    wind: [1, 3.5],\n    gust: 0.35,\n    wet: 0.85,\n  },\n  'heavy-rain': { odds: 12, minutes: [3, 6], rain: 1, snow: 0, wind: [3, 7], gust: 0.5, wet: 1 },\n  snow: { odds: 10, minutes: [5, 10], rain: 0, snow: 0.85, wind: [0.5, 2.5], gust: 0.3, wet: 0.5 },\n}\n\n/** The clocks behind the table, in seconds unless they say otherwise. */\nexport const WEATHER_TIMING = {\n  /** One spell eases into the next over this long, so nothing pops. */\n  blend: 45,\n  /** Heavy rain soaks dry ground in about this long. Lighter weather takes longer. */\n  soak: 40,\n  /** Wet ground loses about two thirds of its water in this long once the rain stops. */\n  dry: 480,\n  /** The same in a wind, which dries a street faster. */\n  dryWindy: 200,\n  /** How far back the ground remembers, in minutes. Several times `dry`, or wetness steps. */\n  memoryMinutes: 40,\n  /** The schedule is dealt in blocks this long, in minutes. A spell never runs across two blocks. */\n  blockMinutes: 120,\n  /** Changes every spell at once: a different night of weather for the same clock. */\n  seed: 2047,\n}\n\nexport const WEATHER_KINDS = Object.keys(WEATHER) as WeatherKind[]\n\nexport interface WeatherState {\n  /** The kind of weather this is. Halfway through a change it becomes the new one. */\n  kind: WeatherKind\n  /** How hard it rains now, 0 to 1. */\n  rain: number\n  /** How hard it snows now, 0 to 1. */\n  snow: number\n  /** The wind now, gusts and all, in units a second along x and z. */\n  wind: { x: number; z: number }\n  /** The length of `wind`. */\n  speed: number\n  /** How wet the ground is, 0 to 1. It lags the rain: streets stay wet for a while after it stops. */\n  wetness: number\n}\n\n/** A state to hand to `weatherAt` as `out`, so a caller that asks every frame makes no garbage. */\nexport function makeWeather(): WeatherState {\n  return { kind: 'dry', rain: 0, snow: 0, wind: { x: 0, z: 0 }, speed: 0, wetness: 0 }\n}\n\n/** Short names `?weather=` also takes. */\nconst ALIASES: Record<string, WeatherKind> = {\n  clear: 'dry',\n  wind: 'windy',\n  light: 'light-rain',\n  rain: 'light-rain',\n  heavy: 'heavy-rain',\n  storm: 'heavy-rain',\n}\n\n/** The kind a word names, or null when it names none. */\nexport function parseWeatherKind(word: string | null | undefined): WeatherKind | null {\n  if (!word) return null\n  const w = word.trim().toLowerCase()\n  if (w in WEATHER) return w as WeatherKind\n  return ALIASES[w] ?? null\n}\n\n// The schedule --------------------------------------------------------------------------------\n\ninterface Spell {\n  kind: WeatherKind\n  /** Unix ms. */\n  start: number\n  end: number\n  rain: number\n  snow: number\n  /** The steady wind, before gusts. */\n  wx: number\n  wz: number\n  gust: number\n  wet: number\n  /** Seconds for the ground to take this spell's water up, and to let it go. */\n  soak: number\n  dry: number\n}\n\nconst BLOCK_MS = WEATHER_TIMING.blockMinutes * 60_000\nconst BLEND_MS = WEATHER_TIMING.blend * 1000\nconst MEMORY_MS = WEATHER_TIMING.memoryMinutes * 60_000\n/** A block never ends on a spell shorter than this: the one before runs on to the end instead. */\nconst SHORTEST_MS = Math.max(\n  2 * BLEND_MS,\n  Math.min(...WEATHER_KINDS.map((k) => WEATHER[k].minutes[0])) * 60_000,\n)\n\n/** A small seeded generator, so the same block deals the same spells on every machine. */\nfunction seeded(seed: number): () => number {\n  let a = seed >>> 0\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0\n    let t = a\n    t = Math.imul(t ^ (t >>> 15), t | 1)\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n  }\n}\n\nfunction pick(r: () => number, not: WeatherKind | null): WeatherKind {\n  let total = 0\n  for (const k of WEATHER_KINDS) if (k !== not) total += WEATHER[k].odds\n  let at = r() * total\n  let last = WEATHER_KINDS[0]\n  for (const k of WEATHER_KINDS) {\n    if (k === not) continue\n    last = k\n    at -= WEATHER[k].odds\n    if (at < 0) return k\n  }\n  return last\n}\n\nconst blocks = new Map<number, Spell[]>()\n\n/** 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. */\nfunction spellsOf(block: number): Spell[] {\n  const known = blocks.get(block)\n  if (known) return known\n  const r = seeded(Math.imul(block, 0x9e3779b1) ^ WEATHER_TIMING.seed)\n  const from = block * BLOCK_MS\n  const spells: Spell[] = []\n  let t = 0\n  let prev: WeatherKind | null = null\n  while (t < BLOCK_MS) {\n    const kind = pick(r, prev)\n    const row = WEATHER[kind]\n    let length = (row.minutes[0] + r() * (row.minutes[1] - row.minutes[0])) * 60_000\n    if (BLOCK_MS - (t + length) < SHORTEST_MS) length = BLOCK_MS - t\n    const heading = r() * Math.PI * 2\n    const speed = row.wind[0] + r() * (row.wind[1] - row.wind[0])\n    // No two spells of a kind are quite alike: each falls a little harder or softer than the table says.\n    const strength = 0.85 + r() * 0.3\n    const rain = Math.min(1, row.rain * strength)\n    const snow = Math.min(1, row.snow * strength)\n    spells.push({\n      kind,\n      start: from + t,\n      end: from + t + length,\n      rain,\n      snow,\n      wx: Math.cos(heading) * speed,\n      wz: Math.sin(heading) * speed,\n      gust: row.gust,\n      wet: row.wet,\n      soak: WEATHER_TIMING.soak / (0.25 + 0.75 * Math.max(rain, snow * 0.3)),\n      dry: kind === 'windy' ? WEATHER_TIMING.dryWindy : WEATHER_TIMING.dry,\n    })\n    t += length\n    prev = kind\n  }\n  if (blocks.size > 6) blocks.clear()\n  blocks.set(block, spells)\n  return spells\n}\n\n// The state at one moment ---------------------------------------------------------------------\n\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v))\nconst smooth = (v: number) => {\n  const x = clamp01(v)\n  return x * x * (3 - 2 * x)\n}\nconst mix = (a: number, b: number, k: number) => a + (b - a) * k\n/** What falls eases out in the first part of a change and in over the last, so rain is nearly gone before snow starts. */\nconst fall = (from: number, to: number, x: number) =>\n  mix(from, to, to < from ? smooth(x / 0.6) : smooth((x - 0.4) / 0.6))\n\nconst TURN = Math.PI * 2\n\n/** Lay gusts over a steady wind. Slow sums of sines of the clock, so every player feels the same gust. */\nfunction blow(out: WeatherState, wx: number, wz: number, gust: number, unixMs: number) {\n  const t = unixMs / 1000\n  const swell =\n    0.5 * Math.sin((t * TURN) / 23.1) +\n    0.3 * Math.sin((t * TURN) / 9.7 + 1.3) +\n    0.2 * Math.sin((t * TURN) / 4.3 + 4.1)\n  const veer = 0.6 * gust * Math.sin((t * TURN) / 37 + 2.2)\n  const scale = Math.max(0.15, 1 + gust * swell)\n  const cos = Math.cos(veer) * scale\n  const sin = Math.sin(veer) * scale\n  out.wind.x = wx * cos - wz * sin\n  out.wind.z = wx * sin + wz * cos\n  out.speed = Math.hypot(out.wind.x, out.wind.z)\n}\n\n/** Carry the ground's wetness through the spells of one block that fall inside its memory. -1 means nothing yet. */\nfunction soakThrough(spells: Spell[], since: number, now: number, wet: number): number {\n  for (const s of spells) {\n    if (s.end <= since || s.start > now) continue\n    if (wet < 0) wet = s.wet\n    const seconds = (Math.min(s.end, now) - Math.max(s.start, since)) / 1000\n    wet = s.wet + (wet - s.wet) * Math.exp(-seconds / (s.wet > wet ? s.soak : s.dry))\n  }\n  return wet\n}\n\n/**\n * The weather at a moment, from the clock alone. `unixMs` is Unix time in milliseconds: hand it\n * the clock the players share. Pure: the same time always gives the same weather, whenever and\n * wherever it is asked. Pass `out` to have it filled in place.\n */\nexport function weatherAt(unixMs: number, out: WeatherState = makeWeather()): WeatherState {\n  const block = Math.floor(unixMs / BLOCK_MS)\n  const today = spellsOf(block)\n  const before = spellsOf(block - 1)\n  let i = today.length - 1\n  while (i > 0 && today[i].start > unixMs) i--\n  const cur = today[i]\n  const prev = i > 0 ? today[i - 1] : before[before.length - 1]\n  const x = clamp01((unixMs - cur.start) / BLEND_MS)\n  const k = smooth(x)\n  out.kind = x < 0.5 ? prev.kind : cur.kind\n  out.rain = fall(prev.rain, cur.rain, x)\n  out.snow = fall(prev.snow, cur.snow, x)\n  blow(out, mix(prev.wx, cur.wx, k), mix(prev.wz, cur.wz, k), mix(prev.gust, cur.gust, k), unixMs)\n  const since = unixMs - MEMORY_MS\n  out.wetness = clamp01(soakThrough(today, since, unixMs, soakThrough(before, since, unixMs, -1)))\n  return out\n}\n\n/**\n * One kind of weather that never changes, as if its spell had always been: for `?weather=`, tests\n * and screenshots. The wind still gusts with the clock.\n */\nexport function steadyWeather(\n  kind: WeatherKind,\n  unixMs: number,\n  out: WeatherState = makeWeather(),\n): WeatherState {\n  const row = WEATHER[kind]\n  const speed = (row.wind[0] + row.wind[1]) / 2\n  out.kind = kind\n  out.rain = row.rain\n  out.snow = row.snow\n  blow(out, speed * 0.894, speed * 0.447, row.gust, unixMs)\n  out.wetness = row.wet\n  return out\n}\n\n// What `Rain` and `WetStreet` share -----------------------------------------------------------\n\n/**\n * The rain clock wraps to 0 after this many seconds. Every speed and rate that reads the clock\n * is picked so its motion repeats exactly at the wrap, and nothing jumps.\n */\nexport const RAIN_PERIOD = 160\n\n/**\n * Read by the streaks, splashes and flakes in `Rain` and by every `WetStreet`. With no `Rain`\n * mounted they stay as they are here: no rings, and streets as wet as their own props say.\n */\nexport const rainUniforms = {\n  /** Seconds of weather so far, wrapped at `RAIN_PERIOD`. */\n  uRainTime: { value: 0 },\n  /** How hard rain rings the puddles, 0 (still water) to 1 (heavy rain). */\n  uRain: { value: 0 },\n  /** How wet the weather has left the ground, 0 to 1. It scales each street's own `wetness` and `puddles`. */\n  uWetness: { value: 1 },\n}\n",
      "type": "registry:component"
    }
  ]
}
