{
  "name": "flying-traffic",
  "title": "FlyingTraffic",
  "type": "registry:component",
  "description": "Lanes of hovercars over a street, decks of lanes each way, every car placed by the world clock and `seed` so every viewer sees the same traffic. Three instanced draws however many cars; no colliders.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "FlyingTraffic.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { Dynamic, rng, skipMirrors, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  AdditiveBlending,\n  BoxGeometry,\n  type BufferGeometry,\n  Color,\n  DoubleSide,\n  Float32BufferAttribute,\n  type Group,\n  type InstancedMesh,\n  MeshBasicMaterial,\n  MeshStandardMaterial,\n  Object3D,\n  PlaneGeometry,\n} from 'three'\nimport { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'\nimport { emissiveColor, mid, useLadder } from './city/glow'\n\nexport interface FlyingTrafficProps {\n  /** The middle of the lanes [x, y, z] in units, at the height of the lowest one. Lanes run along local Z. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Deals out each car's lane, speed, paint and where on the lane it starts. */\n  seed?: number\n  /** How long the lanes are, in units. Cars leave one end and come in at the other, so make it\n   *  longer than the fog lets anyone see. */\n  length?: number\n  /** How many cars fly. */\n  cars?: number\n  /** Lanes side by side going each way. */\n  lanes?: number\n  /** How far apart lanes are, side to side, in units. */\n  spacing?: number\n  /** Heights of the decks of lanes above `position`, in units. */\n  levels?: number[]\n  /** Slowest and fastest a car flies, in units a second. */\n  speed?: [number, number]\n}\n\n/** What a car is painted, dark enough to read as a shape against the sky. */\nconst PAINTS = ['#16141c', '#1d1f22', '#2a120c', '#33363b', '#42464a']\n/** The light a car throws down under itself. */\nconst GLOWS = ['#ffa64d', '#ff6418', '#39ff88', '#b967ff', '#f4f6fb']\nconst HEAD = '#dfe8ff'\nconst TAIL = '#ff6418'\n\ninterface Car {\n  x: number\n  y: number\n  dir: 1 | -1\n  speed: number\n  offset: number\n  phase: number\n}\n\n/** A box with every vertex painted `color` (linear, may be over 1). */\nfunction lamp(\n  w: number,\n  h: number,\n  d: number,\n  x: number,\n  y: number,\n  z: number,\n  color: Color,\n): BufferGeometry {\n  const g = new BoxGeometry(w, h, d).translate(x, y, z)\n  const n = g.attributes.position.count\n  const paint = new Float32Array(n * 3)\n  for (let i = 0; i < n; i++) paint.set([color.r, color.g, color.b], i * 3)\n  g.setAttribute('color', new Float32BufferAttribute(paint, 3))\n  return g\n}\n\n/**\n * Lanes of hovercars over a street: decks of lanes going both ways, every car an instance in\n * three shared meshes (bodies, lamps, and the light under each). Where each car is comes\n * straight from the world clock and `seed`, so every player who shares the clock sees the same\n * traffic (contract §2), and nothing is simulated or sent.\n *\n * Three draws however many cars, left out of the world's mirrors. No colliders: the lanes are\n * meant to fly over anything a body can reach.\n */\nexport function FlyingTraffic({\n  position = [0, 40, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  length = 480,\n  cars = 28,\n  lanes = 2,\n  spacing = 7,\n  levels = [0, 9, 20],\n  speed = [16, 34],\n}: FlyingTrafficProps) {\n  const { unit, now = Date.now } = useWorld()\n  const ladder = useLadder()\n  const root = useRef<Group>(null)\n  const body = useRef<InstancedMesh>(null)\n  const lamps = useRef<InstancedMesh>(null)\n  const glow = useRef<InstancedMesh>(null)\n  const count = Math.max(0, Math.round(cars))\n  const [slow, fast] = speed\n  const decks = levels.join(',')\n\n  const fleet = useMemo<Car[]>(() => {\n    const r = rng(seed)\n    const heights = decks.split(',').map(Number)\n    return Array.from({ length: count }, () => {\n      const dir = r() < 0.5 ? 1 : -1\n      const lane = Math.floor(r() * Math.max(1, lanes))\n      return {\n        // Each way keeps to its own side, as a road does.\n        x: dir * (lane + 0.5) * spacing * unit,\n        y: (heights[Math.floor(r() * heights.length)] + (r() - 0.5) * 1.6) * unit,\n        dir,\n        speed: (slow + r() * (fast - slow)) * unit,\n        offset: r() * length * unit,\n        phase: r() * Math.PI * 2,\n      }\n    })\n  }, [seed, count, lanes, spacing, decks, slow, fast, length, unit])\n\n  const parts = useMemo(() => {\n    const u = unit\n    const shell = mergeGeometries([\n      new BoxGeometry(2.0 * u, 0.55 * u, 4.4 * u).translate(0, 0.5 * u, 0),\n      new BoxGeometry(1.8 * u, 0.3 * u, 0.9 * u).translate(0, 0.42 * u, 2.5 * u),\n      new BoxGeometry(1.7 * u, 0.5 * u, 2.0 * u).translate(0, 1.0 * u, -0.3 * u),\n    ])\n    const head = emissiveColor(HEAD, mid(ladder.lampLens))\n    const tail = emissiveColor(TAIL, mid(ladder.signFace))\n    const lights = mergeGeometries([\n      lamp(0.5 * u, 0.1 * u, 0.06 * u, 0.6 * u, 0.55 * u, 2.96 * u, head),\n      lamp(0.5 * u, 0.1 * u, 0.06 * u, -0.6 * u, 0.55 * u, 2.96 * u, head),\n      lamp(1.9 * u, 0.08 * u, 0.06 * u, 0, 0.66 * u, -2.22 * u, tail),\n    ])\n    const under = new PlaneGeometry(1.7 * u, 4.0 * u).rotateX(Math.PI / 2).translate(0, 0.2 * u, 0)\n    const paint = new MeshStandardMaterial({ color: '#ffffff', roughness: 0.32, metalness: 0.7 })\n    const lit = new MeshBasicMaterial({ vertexColors: true, toneMapped: false })\n    const cast = new MeshBasicMaterial({\n      color: '#ffffff',\n      transparent: true,\n      opacity: 0.9,\n      blending: AdditiveBlending,\n      depthWrite: false,\n      side: DoubleSide,\n      toneMapped: false,\n    })\n    return { shell, lights, under, paint, lit, cast }\n  }, [unit, ladder.lampLens, ladder.signFace])\n  useEffect(\n    () => () => {\n      for (const part of Object.values(parts)) part.dispose()\n    },\n    [parts],\n  )\n\n  // Paint and underglow are dealt once. Only where the cars are changes from frame to frame.\n  useEffect(() => {\n    const r = rng(seed + 7919)\n    const tint = new Color()\n    for (let i = 0; i < count; i++) {\n      body.current?.setColorAt(i, tint.set(PAINTS[Math.floor(r() * PAINTS.length)]))\n      glow.current?.setColorAt(\n        i,\n        emissiveColor(GLOWS[Math.floor(r() * GLOWS.length)], ladder.shopGlass[1]),\n      )\n    }\n    for (const mesh of [body.current, glow.current])\n      if (mesh?.instanceColor) mesh.instanceColor.needsUpdate = true\n  }, [seed, count, ladder.shopGlass, parts])\n\n  const at = useMemo(() => new Object3D(), [])\n  useFrame(() => {\n    const meshes = [body.current, lamps.current, glow.current]\n    if (!meshes[0] || !meshes[1] || !meshes[2]) return\n    const seconds = now() / 1000\n    const span = length * unit\n    for (let i = 0; i < fleet.length; i++) {\n      const car = fleet[i]\n      const along = (((car.offset + car.speed * seconds) % span) + span) % span\n      at.position.set(\n        car.x,\n        car.y + Math.sin(seconds * 0.7 + car.phase) * 0.25 * unit,\n        car.dir * (along - span / 2),\n      )\n      at.rotation.set(0, car.dir > 0 ? 0 : Math.PI, 0)\n      at.updateMatrix()\n      for (const mesh of meshes) mesh?.setMatrixAt(i, at.matrix)\n    }\n    for (const mesh of meshes) if (mesh) mesh.instanceMatrix.needsUpdate = true\n  })\n\n  // Cars overhead move every frame: a reflection of them would only trail.\n  useEffect(() => skipMirrors(root.current), [count])\n\n  if (count === 0) return null\n  return (\n    <Dynamic>\n      <group ref={root} position={position} rotation={rotation}>\n        <instancedMesh ref={body} args={[parts.shell, parts.paint, count]} frustumCulled={false} />\n        <instancedMesh ref={lamps} args={[parts.lights, parts.lit, count]} frustumCulled={false} />\n        <instancedMesh\n          ref={glow}\n          args={[parts.under, parts.cast, count]}\n          frustumCulled={false}\n          renderOrder={2}\n        />\n      </group>\n    </Dynamic>\n  )\n}\n\nFlyingTraffic.stream = false\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"
    }
  ]
}
