{
  "name": "billboard",
  "title": "Billboard",
  "type": "registry:component",
  "description": "A board that runs ads as data: one or two lines of lettering in the world's display font beside a mark drawn in code that moves with the world clock (steam off a bowl, a watch's hands, a cell filling), cut to the next every `hold` seconds through torn strips. Its picture is redrawn only while near the camera. Lit at the world's screen luminance level. Decorative: no collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Billboard.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { useMaterial, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport {\n  BoxGeometry,\n  CanvasTexture,\n  Color,\n  type Group,\n  LinearFilter,\n  MeshBasicMaterial,\n  PlaneGeometry,\n  SRGBColorSpace,\n  Vector3,\n} from 'three'\nimport { fontFamily } from './city/fontFace'\nimport { useLadder } from './city/glow'\nimport { hash2 } from './city/hash'\n\n/** The moving mark an ad draws beside its words, or `none` to set the words in the middle. */\nexport type BillboardMark = 'bowl' | 'battery' | 'watch' | 'plus' | 'dial' | 'clock' | 'none'\n\n/** One ad: big lettering, a smaller line, a mark that moves with the clock, and its colors. */\nexport interface BillboardAd {\n  /** One or two lines of big lettering. */\n  lines: string[]\n  /** A smaller line under them. */\n  tagline?: string\n  /** The mark beside the words. */\n  mark?: BillboardMark\n  /** The board's background. */\n  background?: string\n  /** The first line and the mark. */\n  color?: string\n  /** The second line, the tagline and the mark's highlights. */\n  accent?: string\n}\n\nexport interface BillboardProps {\n  /** The middle of the lit face [x, y, z] in units. It faces local +Z. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Shifts which ad is up when, so two boards side by side do not change together. */\n  seed?: number\n  /** The lit face, [width, height] in units. */\n  size?: [number, number]\n  /** The ads it runs, in order, round and round. Sample ads when unset. */\n  ads?: BillboardAd[]\n  /** Seconds each ad stays up. */\n  hold?: number\n  /** `wall` hangs it on a wall behind it. `posts` stands it on two legs, `stand` units tall. */\n  mount?: 'wall' | 'posts'\n  /** Height of the legs under a board on posts, in units. */\n  stand?: number\n  /** Frame and leg color. Defaults to the world palette's `metal`. */\n  frameColor?: string\n}\n\n/** The ads a board runs when given none: made-up shops, one of each mark. */\nexport const SAMPLE_ADS: BillboardAd[] = [\n  {\n    lines: ['NIGHT', 'NOODLE'],\n    tagline: 'ONE BOWL ALL NIGHT',\n    mark: 'bowl',\n    background: '#2a120c',\n    color: '#ffa64d',\n    accent: '#ff6418',\n  },\n  {\n    lines: ['CELL', 'CHARGE'],\n    tagline: 'POWER WHEN YOU NEED IT',\n    mark: 'battery',\n    background: '#1d1f22',\n    color: '#ece6da',\n    accent: '#ff8a1f',\n  },\n  {\n    lines: ['TIME', 'KEEPER'],\n    tagline: 'WATCHES MENDED',\n    mark: 'watch',\n    background: '#16141c',\n    color: '#e9e3f5',\n    accent: '#7a3cff',\n  },\n  {\n    lines: ['CLEAR+'],\n    tagline: 'SEE BETTER TONIGHT',\n    mark: 'plus',\n    background: '#16141c',\n    color: '#b8c4ff',\n    accent: '#e9e3f5',\n  },\n  {\n    lines: ['CHROME', 'WORKS'],\n    mark: 'dial',\n    background: '#1b1a1f',\n    color: '#e8e0d4',\n    accent: '#c47a4e',\n  },\n  {\n    lines: ['CITY', 'TRANSIT'],\n    tagline: 'EVERY TEN MINUTES',\n    mark: 'clock',\n    background: '#f4f6fb',\n    color: '#3d5bff',\n    accent: '#3d5bff',\n  },\n  {\n    lines: ['MIND THE GAP'],\n    tagline: 'PLEASE STAND CLEAR',\n    mark: 'none',\n    background: '#3d5bff',\n    color: '#f4f6fb',\n    accent: '#f4f6fb',\n  },\n]\n\n/** The picture is drawn at this size and at most this often. */\nconst W = 512\nconst H = 288\nconst REDRAWS_A_SECOND = 10\n/** Past this many units from the camera the picture holds still. */\nconst REACH = 140\n\ntype Mark = (g: CanvasRenderingContext2D, t: number, color: string, accent: string) => void\n\n/** `words` at `px` or smaller, so they fit in `room` pixels. */\nfunction text(\n  g: CanvasRenderingContext2D,\n  words: string,\n  x: number,\n  y: number,\n  px: number,\n  room: number,\n  color: string,\n  face: string,\n  weight = 600,\n) {\n  g.font = `${weight} ${px}px ${face}`\n  const wide = g.measureText(words).width\n  if (wide > room) g.font = `${weight} ${(px * room) / wide}px ${face}`\n  g.fillStyle = color\n  g.fillText(words, x, y)\n}\n\n// Each mark is a few strokes that move with the clock, centred at (W * 0.24, H * 0.5). None of\n// it is an image.\nconst MARKS: Record<Exclude<BillboardMark, 'none'>, Mark> = {\n  // A bowl in profile, and what rises off it.\n  bowl(g, t, color, accent) {\n    g.fillStyle = accent\n    g.beginPath()\n    g.arc(W * 0.24, H * 0.56, H * 0.28, 0, Math.PI)\n    g.fill()\n    g.strokeStyle = color\n    g.lineWidth = 5\n    for (let k = 0; k < 3; k++) {\n      g.beginPath()\n      for (let y = 0; y < H * 0.3; y += 4)\n        g.lineTo(W * (0.18 + k * 0.06) + Math.sin(y * 0.08 + t * 3 + k) * 8, H * 0.5 - y)\n      g.stroke()\n    }\n  },\n  // A cell with a charge notch, filling.\n  battery(g, t, color, accent) {\n    const x = W * 0.09\n    const y = H * 0.3\n    const w = W * 0.3\n    const h = H * 0.4\n    g.strokeStyle = color\n    g.lineWidth = 8\n    g.strokeRect(x, y, w, h)\n    g.fillStyle = color\n    g.fillRect(x + w, y + h * 0.3, W * 0.025, h * 0.4)\n    g.fillStyle = accent\n    g.fillRect(x + 10, y + 10, (w - 20) * ((t % 6) / 6), h - 20)\n  },\n  // A watch face with its hour and minute hands, keeping the time.\n  watch(g, t, color, accent) {\n    g.save()\n    g.translate(W * 0.24, H * 0.5)\n    g.strokeStyle = accent\n    g.lineWidth = 8\n    g.beginPath()\n    g.arc(0, 0, H * 0.3, 0, Math.PI * 2)\n    g.stroke()\n    g.strokeStyle = color\n    g.lineCap = 'round'\n    for (const [rate, long, wide] of [\n      [1 / 3600, 0.24, 6],\n      [1 / 43200, 0.15, 9],\n    ] as const) {\n      const a = t * rate * Math.PI * 2 - Math.PI / 2\n      g.lineWidth = wide\n      g.beginPath()\n      g.moveTo(0, 0)\n      g.lineTo(Math.cos(a) * H * long, Math.sin(a) * H * long)\n      g.stroke()\n    }\n    g.restore()\n  },\n  // A rounded square with a plus at its centre, breathing.\n  plus(g, t, color) {\n    const side = H * 0.42 * (1 + 0.06 * Math.sin(t * 2.4))\n    g.strokeStyle = color\n    g.lineWidth = 9\n    g.beginPath()\n    g.roundRect(W * 0.24 - side / 2, H * 0.5 - side / 2, side, side, side * 0.24)\n    g.stroke()\n    g.beginPath()\n    g.moveTo(W * 0.24 - side * 0.22, H * 0.5)\n    g.lineTo(W * 0.24 + side * 0.22, H * 0.5)\n    g.moveTo(W * 0.24, H * 0.5 - side * 0.22)\n    g.lineTo(W * 0.24, H * 0.5 + side * 0.22)\n    g.stroke()\n  },\n  // An engraved ring with a minute track, turning.\n  dial(g, t, _color, accent) {\n    g.save()\n    g.translate(W * 0.24, H * 0.5)\n    g.rotate(t * 0.15)\n    g.strokeStyle = accent\n    g.lineWidth = 5\n    g.beginPath()\n    g.arc(0, 0, H * 0.3, 0, Math.PI * 2)\n    g.stroke()\n    g.lineWidth = 2.5\n    for (let k = 0; k < 60; k++) {\n      const a = (k / 60) * Math.PI * 2\n      const inner = H * (k % 5 === 0 ? 0.22 : 0.255)\n      g.beginPath()\n      g.moveTo(Math.cos(a) * inner, Math.sin(a) * inner)\n      g.lineTo(Math.cos(a) * H * 0.28, Math.sin(a) * H * 0.28)\n      g.stroke()\n    }\n    g.restore()\n  },\n  // A ring with a notch at twelve, and a hand sweeping it once a minute.\n  clock(g, t, color) {\n    g.strokeStyle = color\n    g.lineWidth = 16\n    g.beginPath()\n    g.arc(W * 0.24, H * 0.5, H * 0.3, -Math.PI / 2 + 0.22, Math.PI * 1.5 - 0.22)\n    g.stroke()\n    g.lineWidth = 6\n    g.beginPath()\n    g.moveTo(W * 0.24, H * 0.5)\n    const a = ((t % 60) / 60) * Math.PI * 2 - Math.PI / 2\n    g.lineTo(W * 0.24 + Math.cos(a) * H * 0.22, H * 0.5 + Math.sin(a) * H * 0.22)\n    g.stroke()\n  },\n}\n\n/** Draw `ad` at `t` seconds on the world clock. */\nfunction drawAd(g: CanvasRenderingContext2D, ad: BillboardAd, t: number, face: string) {\n  const color = ad.color ?? '#f4f6fb'\n  const accent = ad.accent ?? color\n  g.fillStyle = ad.background ?? '#16141c'\n  g.fillRect(0, 0, W, H)\n  const mark = ad.mark ?? 'none'\n  const [first = '', second] = ad.lines\n  if (mark === 'none') {\n    g.textAlign = 'center'\n    text(g, first, W * 0.5, H * (second ? 0.38 : 0.5), H * 0.15, W * 0.9, color, face)\n    if (second) text(g, second, W * 0.5, H * 0.58, H * 0.15, W * 0.9, accent, face)\n    if (ad.tagline) text(g, ad.tagline, W * 0.5, H * 0.8, H * 0.065, W * 0.9, accent, face, 500)\n    g.textAlign = 'left'\n    return\n  }\n  MARKS[mark](g, t, color, accent)\n  const x = W * 0.46\n  const room = W * 0.5\n  if (second) {\n    text(g, first, x, H * 0.42, H * 0.21, room, color, face)\n    text(g, second, x, H * 0.64, H * 0.21, room, accent, face)\n    if (ad.tagline) text(g, ad.tagline, x, H * 0.84, H * 0.075, room, color, face, 500)\n  } else {\n    text(g, first, x, H * 0.46, H * 0.21, room, color, face)\n    if (ad.tagline) text(g, ad.tagline, x, H * 0.66, H * 0.085, room, accent, face, 500)\n  }\n}\n\n/**\n * A billboard that runs ads, each a line or two of lettering beside a mark drawn in code that\n * moves with the clock (a bowl's steam, a watch's hands, a cell filling), cut one to the next\n * every `hold` seconds. Ads are data, so a world writes its own. Which ad is up, and where its\n * hands and steam are, come from the world clock and `seed`, so every player reads the same\n * board. `Screen` is the still one.\n *\n * The picture is a 512 by 288 canvas redrawn ten times a second, and only while the camera is\n * within 140 units: one texture upload each time, one draw for the face and one for the frame.\n * Its white is lit at the world's `screen` luminance level, as a `Screen`'s is. Lettering is in\n * the world's display font (contract §4). No collider.\n */\nexport function Billboard({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  size = [7.2, 4.05],\n  ads = SAMPLE_ADS,\n  hold = 9,\n  mount = 'wall',\n  stand = 5,\n  frameColor,\n}: BillboardProps) {\n  const { unit, fonts, palette, now = Date.now } = useWorld()\n  const ladder = useLadder()\n  const [w, h] = [size[0] * unit, size[1] * unit]\n  const frame = useMaterial({ color: frameColor ?? palette.metal, roughness: 0.6, metalness: 0.3 })\n  const [face, setFace] = useState('sans-serif')\n  useEffect(() => {\n    let live = true\n    if (fonts.display)\n      void fontFamily(fonts.display).then((name) => {\n        if (live && name) setFace(`${name}, sans-serif`)\n      })\n    return () => {\n      live = false\n    }\n  }, [fonts.display])\n\n  const screen = useMemo(() => {\n    if (typeof document === 'undefined') return null\n    const canvas = document.createElement('canvas')\n    canvas.width = W\n    canvas.height = H\n    const g = canvas.getContext('2d')\n    if (!g) return null\n    const map = new CanvasTexture(canvas)\n    map.colorSpace = SRGBColorSpace\n    map.minFilter = map.magFilter = LinearFilter\n    map.generateMipmaps = false\n    const material = new MeshBasicMaterial({ map, toneMapped: false })\n    return { g, map, material }\n  }, [])\n  useEffect(\n    () => () => {\n      screen?.map.dispose()\n      screen?.material.dispose()\n    },\n    [screen],\n  )\n  useEffect(() => {\n    screen?.material.color.copy(new Color('#ffffff').multiplyScalar(ladder.shopGlass[1]))\n  }, [screen, ladder.shopGlass])\n\n  const list = ads.length ? ads : SAMPLE_ADS\n  const drawn = useRef({ at: -1, slot: -1, face: '' })\n  const where = useMemo(() => new Vector3(), [])\n  const anchor = useRef<Group>(null)\n  useFrame(({ camera }) => {\n    if (!screen || !anchor.current) return\n    const seconds = now() / 1000 + hash2(seed, 1) * hold\n    const slot = Math.floor(seconds / hold)\n    const d = drawn.current\n    const changed = slot !== d.slot || face !== d.face\n    if (!changed) {\n      if (seconds - d.at < 1 / REDRAWS_A_SECOND) return\n      if (anchor.current.getWorldPosition(where).distanceTo(camera.position) > REACH * unit) return\n    }\n    drawn.current = { at: seconds, slot, face }\n    const g = screen.g\n    g.setTransform(1, 0, 0, 1, 0, 0)\n    g.textAlign = 'left'\n    g.textBaseline = 'middle'\n    g.lineCap = 'butt'\n    drawAd(g, list[((slot % list.length) + list.length) % list.length], seconds, face)\n    // The cut: for a quarter of a second the new picture comes in torn into strips.\n    const into = seconds - slot * hold\n    if (into < 0.25) {\n      for (let k = 0; k < 6; k++) {\n        const y = Math.floor(hash2(slot, k) * H)\n        const tall = 8 + Math.floor(hash2(slot + 5, k) * 28)\n        const shift = (hash2(slot + 9, k) - 0.5) * 120 * (1 - into / 0.25)\n        g.drawImage(g.canvas, 0, y, W, tall, shift, y, W, tall)\n      }\n    }\n    screen.map.needsUpdate = true\n  })\n\n  if (!screen) return null\n  const edge = 0.14 * unit\n  const deep = 0.22 * unit\n  return (\n    <group ref={anchor} position={position} rotation={rotation}>\n      <mesh\n        position={[0, 0, -deep / 2 - 0.01 * unit]}\n        material={frame}\n        geometry={box(w + edge * 2, h + edge * 2, deep)}\n        castShadow\n      />\n      <mesh material={screen.material} geometry={plane(w, h)} />\n      {mount === 'posts' &&\n        ([-1, 1] as const).map((side) => (\n          <mesh\n            key={side}\n            position={[side * w * 0.32, -h / 2 - (stand * unit) / 2, -deep / 2]}\n            material={frame}\n            geometry={box(0.24 * unit, stand * unit, 0.24 * unit)}\n            castShadow\n          />\n        ))}\n    </group>\n  )\n}\n\nconst boxes = new Map<string, BoxGeometry>()\nfunction box(w: number, h: number, d: number) {\n  const key = `${w.toFixed(3)}:${h.toFixed(3)}:${d.toFixed(3)}`\n  let g = boxes.get(key)\n  if (!g) {\n    g = new BoxGeometry(w, h, d)\n    boxes.set(key, g)\n  }\n  return g\n}\nconst planes = new Map<string, PlaneGeometry>()\nfunction plane(w: number, h: number) {\n  const key = `${w.toFixed(3)}:${h.toFixed(3)}`\n  let g = planes.get(key)\n  if (!g) {\n    g = new PlaneGeometry(w, h)\n    planes.set(key, g)\n  }\n  return g\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/fontFace.ts",
      "content": "// Font files a component draws its own lettering from (a neon tube, a billboard), loaded once\n// each under a family name of their own. The files are the world's declared fonts (contract §4):\n// nothing here ships a font.\n\nconst families = new Map<string, Promise<string | null>>()\n\n/** Loads a font file and gives back the CSS family name it now has, or null if it would not load. */\nexport function fontFamily(url: string): Promise<string | null> {\n  let asked = families.get(url)\n  if (!asked) {\n    const name = `runek-face-${families.size}`\n    asked =\n      typeof FontFace === 'undefined' || typeof document === 'undefined'\n        ? Promise.resolve(null)\n        : new FontFace(name, `url(${url})`).load().then(\n            (f) => {\n              ;(document.fonts as unknown as { add(face: FontFace): void }).add(f)\n              return `\"${name}\"`\n            },\n            () => null,\n          )\n    families.set(url, asked)\n  }\n  return asked\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"
    }
  ]
}
