{
  "name": "steam-vent",
  "title": "SteamVent",
  "type": "registry:component",
  "description": "Steam off a manhole or out of a wall vent: soft puffs that rise, spread, lean and thin away, each a pure function of the world clock and `seed`. One instanced draw, plus the lid. Decorative: no collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "SteamVent.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { Dynamic, skipMirrors, useMaterial, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  AdditiveBlending,\n  Color,\n  CylinderGeometry,\n  DataTexture,\n  type InstancedMesh,\n  LinearFilter,\n  MeshBasicMaterial,\n  Object3D,\n  PlaneGeometry,\n  RGBAFormat,\n  TorusGeometry,\n} from 'three'\nimport { emissiveColor, useLadder } from './city/glow'\nimport { hash2 } from './city/hash'\n\nexport interface SteamVentProps {\n  /** Where the steam comes out [x, y, z] in units: the middle of a manhole, or the mouth of a wall vent. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Sets each puff apart from the next, and this vent from every other. */\n  seed?: number\n  /** How many puffs are in the air at once. */\n  puffs?: number\n  /** How high a puff rises before it is gone, in units. */\n  rise?: number\n  /** How far a puff has spread by then, in units. */\n  spread?: number\n  /** Seconds a puff takes to rise and thin out. */\n  period?: number\n  /** Steam color: it takes the color of the light around it. */\n  color?: string\n  /** How thick it is, 0 (nothing) to 1. */\n  strength?: number\n  /** Draw the manhole it comes from: a dark lid with a rim, `radius` across. */\n  grate?: boolean\n  /** Radius of the lid and of the column of steam at its foot, in units. */\n  radius?: number\n}\n\nlet soft: DataTexture | null = null\n/** One soft round puff, drawn in code: white, with alpha falling off from the middle. */\nfunction puffTexture(): DataTexture {\n  if (soft) return soft\n  const N = 64\n  const data = new Uint8Array(N * N * 4)\n  for (let y = 0; y < N; y++) {\n    for (let x = 0; x < N; x++) {\n      const r = Math.hypot(x - (N - 1) / 2, y - (N - 1) / 2) / (N / 2)\n      const a = Math.max(0, 1 - r)\n      const v = Math.round(255 * a * a * (3 - 2 * a))\n      data.set([v, v, v, 255], (y * N + x) * 4)\n    }\n  }\n  soft = new DataTexture(data, N, N, RGBAFormat)\n  soft.magFilter = soft.minFilter = LinearFilter\n  soft.needsUpdate = true\n  return soft\n}\n\n/**\n * Steam off a manhole or out of a kitchen vent: a column of soft puffs that rise, spread, lean a\n * little and thin away. Each puff's place is a pure function of the world clock and `seed`, so\n * every player sees the same plume and nothing is simulated.\n *\n * One instanced draw of quads that face the camera, left out of the world's mirrors, plus the lid\n * when `grate` is set. The steam is added light a little brighter than an unlit wall, so it shows\n * where a lamp or a sign is behind it and barely at all against the dark. No collider.\n */\nexport function SteamVent({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  puffs = 14,\n  rise = 3.2,\n  spread = 1.1,\n  period = 4.5,\n  color = '#c9d2e6',\n  strength = 1,\n  grate = true,\n  radius = 0.42,\n}: SteamVentProps) {\n  const { unit, palette, now = Date.now } = useWorld()\n  const ladder = useLadder()\n  const mesh = useRef<InstancedMesh>(null)\n  const count = Math.max(1, Math.round(puffs))\n  const quad = useMemo(() => new PlaneGeometry(1, 1), [])\n  const material = useMemo(\n    () =>\n      new MeshBasicMaterial({\n        map: puffTexture(),\n        transparent: true,\n        blending: AdditiveBlending,\n        depthWrite: false,\n        toneMapped: false,\n      }),\n    [],\n  )\n  useEffect(\n    () => () => {\n      quad.dispose()\n      material.dispose()\n    },\n    [quad, material],\n  )\n  const lid = useMaterial({\n    slot: 'metal.bare',\n    color: palette.metal,\n    roughness: 0.7,\n    metalness: 0.4,\n  })\n  // A puff at its thickest: a little over an unlit wall, so a column of them reads as haze.\n  const tone = useMemo(\n    () => emissiveColor(color, ladder.unlitWall[1] * 1.0 * Math.min(1, Math.max(0, strength))),\n    [color, ladder.unlitWall, strength],\n  )\n\n  useEffect(() => skipMirrors(mesh.current), [])\n\n  const at = useMemo(() => new Object3D(), [])\n  const tint = useMemo(() => new Color(), [])\n  useFrame(({ camera }) => {\n    const m = mesh.current\n    if (!m) return\n    const seconds = now() / 1000\n    const parent = m.parent\n    for (let i = 0; i < count; i++) {\n      const life = (((seconds / period + hash2(seed, i)) % 1) + 1) % 1\n      // Which time round this puff is on, so each one takes a path of its own.\n      const round = Math.floor(seconds / period + hash2(seed, i))\n      const lean = (hash2(seed * 7 + i, round) - 0.5) * 2\n      const turn = hash2(seed * 11 + i, round) * Math.PI * 2\n      const out = (radius * 0.6 + spread * 0.5 * life) * unit\n      at.position.set(\n        Math.cos(turn) * out * 0.5 + lean * life * life * 0.5 * unit,\n        rise * unit * life ** 0.8,\n        Math.sin(turn) * out * 0.5,\n      )\n      // Face the camera, whatever the vent's own turn.\n      at.quaternion.copy(camera.quaternion)\n      if (parent) at.quaternion.premultiply(parent.getWorldQuaternion(scratch).invert())\n      at.scale.setScalar((radius * 1.6 + spread * life) * unit)\n      at.updateMatrix()\n      m.setMatrixAt(i, at.matrix)\n      // Thin at the mouth, thickest a third of the way up, gone at the top.\n      const fade = Math.min(1, life * 5) * (1 - life) ** 1.5\n      m.setColorAt(i, tint.copy(tone).multiplyScalar(fade))\n    }\n    m.instanceMatrix.needsUpdate = true\n    if (m.instanceColor) m.instanceColor.needsUpdate = true\n  })\n\n  return (\n    <group position={position} rotation={rotation}>\n      {grate && (\n        <>\n          <mesh\n            position={[0, 0.012 * unit, 0]}\n            material={lid}\n            geometry={lidGeometry(radius * unit, unit)}\n            receiveShadow\n          />\n          <mesh\n            position={[0, 0.02 * unit, 0]}\n            rotation={[Math.PI / 2, 0, 0]}\n            material={lid}\n            geometry={rimGeometry(radius * unit, unit)}\n          />\n        </>\n      )}\n      <Dynamic>\n        <instancedMesh\n          ref={mesh}\n          args={[quad, material, count]}\n          frustumCulled={false}\n          renderOrder={3}\n        />\n      </Dynamic>\n    </group>\n  )\n}\n\nconst scratch = new Object3D().quaternion\n\nconst lids = new Map<string, CylinderGeometry>()\nfunction lidGeometry(radius: number, unit: number) {\n  const key = `${radius.toFixed(3)}:${unit}`\n  let g = lids.get(key)\n  if (!g) {\n    g = new CylinderGeometry(radius, radius, 0.024 * unit, 24)\n    lids.set(key, g)\n  }\n  return g\n}\nconst rims = new Map<string, TorusGeometry>()\nfunction rimGeometry(radius: number, unit: number) {\n  const key = `${radius.toFixed(3)}:${unit}`\n  let g = rims.get(key)\n  if (!g) {\n    g = new TorusGeometry(radius * 1.06, 0.03 * unit, 6, 28)\n    rims.set(key, g)\n  }\n  return g\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/hash.ts",
      "content": "/** A number in [0, 1) from two integers: the same on every machine, with no state. */\nexport function hash2(a: number, b: number): number {\n  let h = Math.imul(a | 0, 0x9e3779b1) ^ Math.imul(b | 0, 0x85ebca6b)\n  h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d)\n  h = Math.imul(h ^ (h >>> 12), 0x297a2d39)\n  return ((h ^ (h >>> 15)) >>> 0) / 4294967296\n}\n",
      "type": "registry:component"
    }
  ]
}
