{
  "name": "hologram",
  "title": "Hologram",
  "type": "registry:component",
  "description": "A plaza centrepiece: a pedestal, a beam of light with scan lines climbing it, and in it a wire cage turning round three rings that keep time (once a minute, once an hour, once every `round` seconds) off the world clock. The pedestal has a cylinder collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@react-three/rapier@^2.2.0",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Hologram.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { CylinderCollider, RigidBody } from '@react-three/rapier'\nimport {\n  Dynamic,\n  lazyModule,\n  skipMirrors,\n  useLight,\n  useMaterial,\n  useNodeRenderer,\n  useWorld,\n  type Vec3,\n} from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  AdditiveBlending,\n  CylinderGeometry,\n  DoubleSide,\n  EdgesGeometry,\n  type Group,\n  IcosahedronGeometry,\n  LineBasicMaterial,\n  type Material,\n  ShaderMaterial,\n  TorusGeometry,\n} from 'three'\nimport { emissiveColor, glowMaterial, mid, useLadder } from './city/glow'\n\n// The beam's node (TSL) material, loaded only under a node renderer.\nconst hologramNodes = lazyModule(() => import('./nodes/hologram'))\n\nexport interface HologramProps {\n  /** The middle of the pedestal's foot [x, y, z] in units. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Accepted for the component contract. Every hologram keeps the same time. */\n  seed?: number\n  /** Radius of the pedestal, in units. */\n  radius?: number\n  /** How high the middle of the figure hangs over the pedestal's foot, in units. */\n  height?: number\n  /** Radius of the figure, in units. */\n  size?: number\n  /** The beam and the figure's cage, lit at the world's `sign` and `tube` levels. */\n  color?: string\n  /** The rings that keep time. */\n  accent?: string\n  /** Seconds the slow ring takes to go round once: a district's power round, say. */\n  round?: number\n  /** Ask the world's light pool for a real light at the figure. */\n  light?: boolean\n}\n\nconst BEAM_VERT = /* glsl */ `\nvarying vec2 vUv;\nvoid main() {\n  vUv = uv;\n  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}`\n\n// Scan lines climbing a cone of light that thins toward the top.\nconst BEAM_FRAG = /* glsl */ `\nuniform vec3 uColor;\nuniform float uTime;\nvarying vec2 vUv;\nvoid main() {\n  float lines = 0.6 + 0.4 * step(0.5, fract(vUv.y * 40.0 - uTime * 2.0));\n  gl_FragColor = vec4(uColor * (1.0 - vUv.y) * lines, 1.0);\n}`\n\n/**\n * A hologram on a pedestal: a beam of light up from a ring, and in it a cage that turns slowly\n * round three rings that keep time. The fast ring goes round once a minute, the middle one once\n * an hour and the slow one once every `round` seconds, all read off the world clock, so it is a\n * clock anyone in the city can check and every player sees it at the same angle.\n *\n * The pedestal is lit, solid and has a collider. The light parts are unlit, at the world's\n * luminance levels, left out of the world's mirrors, and drawn inside a `<Dynamic>`. Under\n * `WebGPURenderer` the beam has no scan lines.\n */\nexport function Hologram({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  radius = 1.6,\n  height = 6.5,\n  size = 2.2,\n  color = '#3d5bff',\n  accent = '#f4f6fb',\n  round = 1440,\n  light = true,\n}: HologramProps) {\n  const { unit, palette, now = Date.now } = useWorld()\n  const ladder = useLadder()\n  const nodes = useNodeRenderer() ? hologramNodes() : null\n  const r = radius * unit\n  const s = size * unit\n  const base = 0.5 * unit\n  const beamH = (height + size * 0.6) * unit - base\n\n  const metal = useMaterial({ color: palette.metal, roughness: 0.35, metalness: 0.7 })\n  const rim = glowMaterial(color, mid(ladder.tubeCore))\n  const ringMinute = glowMaterial(accent, ladder.signFace[1])\n  const ringHour = glowMaterial(accent, mid(ladder.signFace))\n  const ringRound = glowMaterial(color, ladder.signFace[1])\n  const time = useMemo(() => ({ value: 0 }), [])\n  const made = useMemo(() => {\n    const tone = emissiveColor(color, ladder.shopGlass[0])\n    let beam: Material\n    if (nodes) {\n      beam = nodes.beamNodeMaterial(tone)\n    } else {\n      beam = new ShaderMaterial({\n        vertexShader: BEAM_VERT,\n        fragmentShader: BEAM_FRAG,\n        uniforms: { uColor: { value: tone.clone() }, uTime: time },\n      })\n    }\n    beam.transparent = true\n    beam.blending = AdditiveBlending\n    beam.depthWrite = false\n    beam.side = DoubleSide\n    const cage = new LineBasicMaterial({\n      color: emissiveColor(color, ladder.signFace[0]),\n      toneMapped: false,\n    })\n    const core = new LineBasicMaterial({\n      color: emissiveColor(accent, mid(ladder.signFace)),\n      toneMapped: false,\n    })\n    return {\n      beam,\n      cage,\n      core,\n      pedestal: new CylinderGeometry(r, r * 1.15, base, 40),\n      rim: new TorusGeometry(r * 1.02, 0.03 * unit, 8, 64),\n      cone: new CylinderGeometry(r * 0.62, r * 0.94, beamH, 40, 1, true),\n      shell: new EdgesGeometry(new IcosahedronGeometry(s, 1)),\n      heart: new EdgesGeometry(new IcosahedronGeometry(s * 0.4, 0)),\n      ring: [1.5, 1.26, 1.02].map((k) => new TorusGeometry(s * k, 0.022 * unit, 6, 120)),\n    }\n  }, [nodes, color, accent, ladder.shopGlass, ladder.signFace, time, r, s, base, beamH, unit])\n  useEffect(\n    () => () => {\n      for (const part of [\n        made.beam,\n        made.cage,\n        made.core,\n        made.pedestal,\n        made.rim,\n        made.cone,\n        made.shell,\n        made.heart,\n        ...made.ring,\n      ]) {\n        part.dispose()\n      }\n    },\n    [made],\n  )\n\n  const figure = useRef<Group>(null)\n  const cage = useRef<Group>(null)\n  const core = useRef<Group>(null)\n  const minute = useRef<Group>(null)\n  const hour = useRef<Group>(null)\n  const slow = useRef<Group>(null)\n  // It turns: hidden from mirrors, so a reflection never shows it a frame behind.\n  useEffect(() => skipMirrors(figure.current), [])\n  const emitter = useLight({ color, intensity: 220, distance: 22 * unit, decay: 2 }, light)\n\n  useFrame(() => {\n    const seconds = now() / 1000\n    time.value = seconds % 1000\n    const turn = Math.PI * 2\n    if (cage.current) cage.current.rotation.set(seconds * 0.05, seconds * 0.11, 0)\n    if (core.current) core.current.rotation.set(seconds * -0.3, seconds * 0.45, 0)\n    // Three rings, each tilted its own way and turning about the upright at its own rate.\n    if (minute.current) minute.current.rotation.y = ((seconds % 60) / 60) * turn\n    if (hour.current) hour.current.rotation.y = ((seconds % 3600) / 3600) * turn\n    if (slow.current) slow.current.rotation.y = ((seconds % round) / round) * turn\n  })\n\n  return (\n    <group position={position} rotation={rotation}>\n      <RigidBody type=\"fixed\" colliders={false}>\n        <CylinderCollider args={[base / 2, r]} position={[0, base / 2, 0]} />\n      </RigidBody>\n      <mesh\n        position={[0, base / 2, 0]}\n        material={metal}\n        geometry={made.pedestal}\n        castShadow\n        receiveShadow\n      />\n      <Dynamic>\n        <group ref={figure}>\n          <mesh\n            position={[0, base + 0.02 * unit, 0]}\n            rotation={[Math.PI / 2, 0, 0]}\n            material={rim}\n            geometry={made.rim}\n          />\n          <mesh\n            position={[0, base + beamH / 2, 0]}\n            material={made.beam}\n            geometry={made.cone}\n            renderOrder={2}\n          />\n          <group position={[0, height * unit, 0]}>\n            <group ref={cage}>\n              <lineSegments geometry={made.shell} material={made.cage} />\n            </group>\n            <group ref={core}>\n              <lineSegments geometry={made.heart} material={made.core} />\n            </group>\n            <group ref={minute}>\n              <mesh\n                rotation={[Math.PI / 2 - 0.5, 0, 0]}\n                material={ringMinute}\n                geometry={made.ring[2]}\n              />\n            </group>\n            <group ref={hour}>\n              <mesh\n                rotation={[Math.PI / 2 + 0.35, 0, 0.6]}\n                material={ringHour}\n                geometry={made.ring[1]}\n              />\n            </group>\n            <group ref={slow}>\n              <mesh\n                rotation={[Math.PI / 2 + 0.12, 0, -0.3]}\n                material={ringRound}\n                geometry={made.ring[0]}\n              />\n            </group>\n            <object3D ref={emitter.ref} />\n          </group>\n        </group>\n      </Dynamic>\n    </group>\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": "nodes/hologram.ts",
      "content": "// Hologram's beam as a TSL node material, for WebGPURenderer: the cone of light thinning toward\n// the top, without the scan lines the GLSL draws.\n\nimport type { Color } from 'three'\nimport { float, uniform, uv } from 'three/tsl'\nimport { MeshBasicNodeMaterial } from 'three/webgpu'\n\nexport function beamNodeMaterial(tone: Color) {\n  const material = new MeshBasicNodeMaterial()\n  material.colorNode = uniform(tone.clone()).mul(float(1).sub(uv().y))\n  material.fog = false\n  return material\n}\n",
      "type": "registry:component"
    }
  ]
}
