{
  "name": "street-lamp",
  "title": "StreetLamp",
  "type": "registry:component",
  "description": "A street lamp on an arm: a pole, a hot lens at the world's lamp luminance level, a haze cone under the head and a soft pool of light on the street, every lamp's cone and pool sharing two instanced draws. The real light comes from the world's light pool. One thin collider for the pole.",
  "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": "StreetLamp.tsx",
      "content": "import { CuboidCollider, RigidBody } from '@react-three/rapier'\nimport {\n  lazyModule,\n  useLight,\n  useLuminance,\n  useMaterial,\n  useNodeRenderer,\n  useWorld,\n  type Vec3,\n} from '@runek/core'\nimport { useMemo } from 'react'\nimport { BoxGeometry, CylinderGeometry, Matrix4, PlaneGeometry } from 'three'\nimport { emissiveColor, glowMaterial, mid, useLadder } from './city/glow'\nimport { coneMaterial, poolMaterial } from './city/haze'\nimport { useInstances } from './city/instances'\n\n// The haze's node (TSL) materials, loaded only under a node renderer.\nconst hazeNodes = lazyModule(() => import('./nodes/haze'))\n\nexport interface StreetLampProps {\n  /** Base of the pole [x, y, z] in units. The arm reaches along local +X. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Accepted for the component contract; this component has no seeded variation. */\n  seed?: number\n  /** Pole height to the arm, in units. */\n  height?: number\n  /** How far the arm reaches out from the pole, in units. */\n  arm?: number\n  /** Lamp color. A cool white by default: the city lights its streets like day. */\n  color?: string\n  /** Pole, arm and head color. Defaults to the world palette's `metal`. */\n  poleColor?: string\n  /** Candela toward the street, when the world lends this lamp a real light. */\n  intensity?: number\n  /** Ask the world's light pool for a real light. The lens, cone and pool glow either way. */\n  light?: boolean\n  /** Draw the haze cone under the head. */\n  cone?: boolean\n  /** Peak luminance of the haze cone (scene-linear), times the world's `lamp` level. */\n  haze?: number\n  /** Draw the soft pool on the street under the head, for lamps the pool has no light for. */\n  pool?: boolean\n  /** Radius of that pool, in units. */\n  poolRadius?: number\n  /** What the pool lies on. `ground` is the world's ground, for a lamp on a pavement whose arm\n   *  reaches out over the street below it. `base` is whatever the lamp itself stands on: a plaza,\n   *  a lawn, a roof. */\n  poolOn?: 'ground' | 'base'\n}\n\n/**\n * A street lamp on an arm: a pole, a hot lens at the world's `lamp` luminance level, a haze cone\n * under the head, and a soft pool on the street. The real light comes only from the world's\n * light pool (`useLight`), which lends it to the lamps that matter most to the view; every other\n * lamp still reads through its lens, cone, pool, bloom and fog. The pool fades in with distance\n * so it does not double the real light on the nearest lamps. One thin collider for the pole.\n */\nexport function StreetLamp({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  height = 8,\n  arm = 2.4,\n  color = '#dfe8ff',\n  poleColor,\n  intensity = 350,\n  light = true,\n  cone = true,\n  haze = 0.06,\n  pool = true,\n  poolRadius = 6,\n  poolOn = 'ground',\n}: StreetLampProps) {\n  const { unit, palette, ground } = useWorld()\n  const ladder = useLadder()\n  const lamp = useLuminance().lamp\n  const nodes = useNodeRenderer() ? hazeNodes() : null\n  const h = height * unit\n  const a = arm * unit\n  const metal = useMaterial({\n    slot: 'metal.painted',\n    color: poleColor ?? palette.metal,\n    roughness: 0.55,\n    metalness: 0.15,\n  })\n  const lens = glowMaterial(color, mid(ladder.lampLens))\n  const lit = haze * lamp\n  const coneMat = useMemo(() => {\n    const c = emissiveColor(color, lit)\n    return nodes ? nodes.coneNodeMaterial(c) : coneMaterial(c)\n  }, [color, lit, nodes])\n  const poolMat = useMemo(() => {\n    const c = emissiveColor(color, ladder.streetUnderSign[0])\n    return nodes\n      ? nodes.poolNodeMaterial(c, 20 * unit, 45 * unit)\n      : poolMaterial(c, 20 * unit, 45 * unit)\n  }, [color, ladder.streetUnderSign, unit, nodes])\n  const emitter = useLight({ color, intensity, distance: 26 * unit, decay: 2 }, light)\n  const coneH = h - 0.3 * unit\n  // The pool lies a little above the world's ground (the street), whatever the base height, or\n  // a little above what the lamp stands on.\n  const poolY = poolOn === 'base' ? 0.045 * unit : ground + 0.045 * unit - position[1]\n  // Every lamp's cone is an instance in one mesh and every pool in another (`useInstances`):\n  // both are see-through, so static batching leaves them alone, and a city lit by a hundred\n  // lamps would be two hundred draws of haze.\n  const coneAt = useMemo(\n    () => (cone ? [new Matrix4().makeTranslation(a, h - 0.25 * unit - coneH / 2, 0)] : []),\n    [cone, a, h, coneH, unit],\n  )\n  const poolAt = useMemo(\n    () => (pool ? [new Matrix4().makeRotationX(-Math.PI / 2).setPosition(a, poolY, 0)] : []),\n    [pool, a, poolY],\n  )\n  const place = [position, rotation]\n  const root = useInstances(\n    `lamp-cone:${coneMat.name}:${coneH}`,\n    () => ({ geometry: coneGeometry(coneH, unit), material: coneMat, renderOrder: 2 }),\n    coneAt,\n    null,\n    place,\n  )\n  const pools = useInstances(\n    `lamp-pool:${poolMat.name}:${poolRadius}`,\n    () => ({ geometry: plane(poolRadius * 2 * unit), material: poolMat, renderOrder: 1 }),\n    poolAt,\n    null,\n    place,\n  )\n\n  return (\n    <group ref={root} position={position} rotation={rotation}>\n      <group ref={pools} />\n      <RigidBody type=\"fixed\" colliders={false}>\n        <CuboidCollider args={[0.1 * unit, h / 2, 0.1 * unit]} position={[0, h / 2, 0]} />\n      </RigidBody>\n      <mesh position={[0, h / 2, 0]} material={metal} geometry={poleGeometry(h, unit)} />\n      <mesh\n        position={[a / 2, h - 0.1 * unit, 0]}\n        material={metal}\n        geometry={box(a, 0.1 * unit, 0.12 * unit)}\n      />\n      <mesh\n        position={[a, h - 0.12 * unit, 0]}\n        material={metal}\n        geometry={box(0.8 * unit, 0.16 * unit, 0.36 * unit)}\n      />\n      <mesh\n        position={[a, h - 0.21 * unit, 0]}\n        material={lens}\n        geometry={box(0.62 * unit, 0.02 * unit, 0.24 * unit)}\n      />\n      <object3D ref={emitter.ref} position={[a, h - 0.45 * unit, 0]} />\n    </group>\n  )\n}\n\n// Shared geometry: lamps along a street repeat the same few shapes.\nconst geometries = new Map<string, BoxGeometry | CylinderGeometry | PlaneGeometry>()\nfunction cached<G extends BoxGeometry | CylinderGeometry | PlaneGeometry>(\n  key: string,\n  make: () => G,\n): G {\n  let g = geometries.get(key) as G | undefined\n  if (!g) {\n    g = make()\n    geometries.set(key, g)\n  }\n  return g\n}\nconst box = (w: number, h: number, d: number) =>\n  cached(`box:${w}:${h}:${d}`, () => new BoxGeometry(w, h, d))\nconst poleGeometry = (h: number, unit: number) =>\n  cached(`pole:${h}:${unit}`, () => new CylinderGeometry(0.07 * unit, 0.11 * unit, h, 12))\nconst coneGeometry = (h: number, unit: number) =>\n  cached(`cone:${h}:${unit}`, () => new CylinderGeometry(0.25 * unit, 3.4 * unit, h, 24, 1, true))\nconst plane = (size: number) => cached(`plane:${size}`, () => new PlaneGeometry(size, size))\n\nStreetLamp.groundSitting = true\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/haze.ts",
      "content": "// Additive light that is not a real light: a lamp's haze cone and the pool it leaves on the\n// street. One shared material per color and strength: a GLSL ShaderMaterial here, and its TSL\n// twin for WebGPURenderer in nodes/haze.ts. Both work on instanced and merged geometry: they read\n// only `uv`, normals and world positions.\n//\n// Additive light must fade into fog rather than mix toward it (mixing would add the fog color\n// wherever the cone is), so they attenuate by the scene's linear fog range themselves.\n\nimport {\n  AdditiveBlending,\n  type Color,\n  DoubleSide,\n  type Material,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n} from 'three'\n\nconst HAZE_VERT = /* glsl */ `\nvarying vec3 vN;\nvarying vec3 vV;\nvarying vec2 vUv;\nvarying vec3 vWorld;\nvoid main() {\n  // Lamps share one instanced mesh for their cones and one for their pools (StreetLamp.tsx), so\n  // each instance brings its own place and turn.\n  #ifdef USE_INSTANCING\n    vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);\n    vec3 n = mat3(instanceMatrix) * normal;\n  #else\n    vec4 world = modelMatrix * vec4(position, 1.0);\n    vec3 n = normal;\n  #endif\n  vec4 mv = viewMatrix * world;\n  vN = normalize(normalMatrix * n);\n  vV = normalize(-mv.xyz);\n  vUv = uv;\n  vWorld = world.xyz;\n  gl_Position = projectionMatrix * mv;\n}`\n\n// The scene's linear fog range sets how far additive light carries, whatever fog chunk is in use.\nexport const FOG_FADE = /* glsl */ `\nuniform float fogNear;\nuniform float fogFar;\nfloat hazeFog(vec3 world) {\n  #ifdef USE_FOG\n    return 1.0 - 0.94 * smoothstep(fogNear, fogFar, distance(world, cameraPosition));\n  #else\n    return 1.0;\n  #endif\n}`\n\n// Brightest where the cone is seen side on through its middle, falling to nothing at the top.\nconst CONE_FRAG = /* glsl */ `\nuniform vec3 uColor;\nvarying vec3 vN;\nvarying vec3 vV;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float facing = pow(abs(dot(normalize(vN), normalize(vV))), 1.5);\n  float fall = vUv.y * vUv.y;\n  gl_FragColor = vec4(uColor * facing * fall * hazeFog(vWorld), 1.0);\n}`\n\n// A soft disc on the ground. It doubles in strength with distance, because near lamps usually\n// hold a real light from the pool, which lights the street itself.\nconst POOL_FRAG = /* glsl */ `\nuniform vec3 uColor;\nuniform vec2 uFade;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float r = length(vUv - 0.5) * 2.0;\n  float disc = (1.0 - smoothstep(0.0, 1.0, r));\n  disc *= disc;\n  float far = mix(0.5, 1.0, smoothstep(uFade.x, uFade.y, distance(vWorld, cameraPosition)));\n  gl_FragColor = vec4(uColor * disc * far * hazeFog(vWorld), 1.0);\n}`\n\nconst cache = new Map<string, Material>()\n\nexport function additive<M extends Material>(m: M): M {\n  m.transparent = true\n  m.blending = AdditiveBlending\n  m.depthWrite = false\n  return m\n}\n\n/** The haze cone under a lamp head, in `color` (linear, already scaled to its luminance). */\nexport function coneMaterial(color: Color): Material {\n  const key = `cone:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}`\n  let m = cache.get(key)\n  if (!m) {\n    m = new ShaderMaterial({\n      vertexShader: HAZE_VERT,\n      fragmentShader: CONE_FRAG,\n      uniforms: UniformsUtils.merge([UniformsLib.fog, { uColor: { value: color.clone() } }]),\n      side: DoubleSide,\n      fog: true,\n    })\n    m.name = `runek:haze:${key}`\n    cache.set(key, additive(m))\n  }\n  return m\n}\n\n/** The pool a lamp leaves on the street, faded in between `near` and `far` meters from the eye. */\nexport function poolMaterial(color: Color, near: number, far: number): Material {\n  const key = `pool:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}:${near}:${far}`\n  let m = cache.get(key)\n  if (!m) {\n    m = new ShaderMaterial({\n      vertexShader: HAZE_VERT,\n      fragmentShader: POOL_FRAG,\n      uniforms: UniformsUtils.merge([\n        UniformsLib.fog,\n        { uColor: { value: color.clone() }, uFade: { value: [near, far] } },\n      ]),\n      fog: true,\n    })\n    m.polygonOffset = true\n    m.polygonOffsetFactor = -2\n    m.polygonOffsetUnits = -4\n    m.name = `runek:haze:${key}`\n    cache.set(key, additive(m))\n  }\n  return m\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/instances.ts",
      "content": "// Shared instanced meshes for small parts a world repeats hundreds of times and that static\n// batching cannot merge: anything see-through. Runek's batcher leaves transparent meshes alone,\n// so every window pane and every soft shell round a neon tube was a draw of its own.\n//\n// A pool is one `InstancedMesh` in the scene for one kind of part (one geometry, one material).\n// Components hand it the places of their parts in the world and take them back when they\n// unmount. Parts are still: a component gives its places again when it moves. However many\n// parts there are, a pool is one draw, and it is never frustum culled.\n\nimport { useThree } from '@react-three/fiber'\nimport { skipMirrors } from '@runek/core'\nimport { type RefObject, useLayoutEffect, useMemo, useRef } from 'react'\nimport {\n  type BufferGeometry,\n  type Color,\n  type Group,\n  InstancedMesh,\n  type Material,\n  Matrix4,\n  type Scene,\n} from 'three'\n\ninterface Parts {\n  matrices: Matrix4[]\n  /** One color for every part of this owner, when the pool colors its instances. */\n  color: Color | null\n}\n\n/** What a pool is made of, asked for once when the first part of its kind turns up. */\nexport interface PoolLook {\n  geometry: BufferGeometry\n  material: Material\n  /** Draw order among see-through things. */\n  renderOrder?: number\n  /** Leave the pool out of the world's mirrors (`skipMirrors`). */\n  skipMirrors?: boolean\n}\n\nclass Pool {\n  private mesh: InstancedMesh | null = null\n  private unskip: (() => void) | null = null\n  private readonly owners = new Map<object, Parts>()\n  private queued = false\n\n  constructor(\n    private readonly scene: Scene,\n    private readonly name: string,\n    private readonly look: PoolLook,\n  ) {}\n\n  /** Give `owner`'s parts their places in the world, replacing any it had. */\n  set(owner: object, matrices: Matrix4[], color: Color | null) {\n    this.owners.set(owner, { matrices, color })\n    this.queue()\n  }\n\n  drop(owner: object) {\n    if (this.owners.delete(owner)) this.queue()\n  }\n\n  /** Many components mount in one commit: write the buffers once, after all of them. */\n  private queue() {\n    if (this.queued) return\n    this.queued = true\n    queueMicrotask(() => {\n      this.queued = false\n      this.write()\n    })\n  }\n\n  private write() {\n    let total = 0\n    for (const parts of this.owners.values()) total += parts.matrices.length\n    let mesh = this.mesh\n    if (!mesh || mesh.instanceMatrix.count < total) {\n      // Room for half as many again, so a few more parts do not mean a new buffer.\n      if (mesh) {\n        this.unskip?.()\n        this.scene.remove(mesh)\n        mesh.dispose()\n      }\n      mesh = new InstancedMesh(\n        this.look.geometry,\n        this.look.material,\n        Math.max(16, Math.ceil(total * 1.5)),\n      )\n      mesh.name = `runek:pool:${this.name}`\n      mesh.frustumCulled = false\n      mesh.renderOrder = this.look.renderOrder ?? 0\n      this.unskip = this.look.skipMirrors ? skipMirrors(mesh) : null\n      this.scene.add(mesh)\n      this.mesh = mesh\n    }\n    let i = 0\n    for (const parts of this.owners.values()) {\n      for (const matrix of parts.matrices) {\n        mesh.setMatrixAt(i, matrix)\n        if (parts.color) mesh.setColorAt(i, parts.color)\n        i++\n      }\n    }\n    mesh.count = total\n    mesh.instanceMatrix.needsUpdate = true\n    if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n  }\n}\n\nconst pools = new WeakMap<Scene, Map<string, Pool>>()\n\n/** The pool named `name` in `scene`, made from `look()` the first time it is asked for. */\nfunction poolFor(scene: Scene, name: string, look: () => PoolLook): Pool {\n  let named = pools.get(scene)\n  if (!named) {\n    named = new Map()\n    pools.set(scene, named)\n  }\n  let pool = named.get(name)\n  if (!pool) {\n    pool = new Pool(scene, name, look())\n    named.set(name, pool)\n  }\n  return pool\n}\n\n/**\n * Put a component's parts in the pool named `name`. `local` is each part's matrix in the\n * component's own frame and must be memoized. Attach the returned ref to a group at the\n * component's origin: its world matrix places the parts. `place` is any value that changes when\n * that group moves (its position and rotation props). `color` tints every part of this\n * component, for a pool whose material is white.\n */\nexport function useInstances(\n  name: string,\n  look: () => PoolLook,\n  local: Matrix4[],\n  color: Color | null,\n  place: unknown,\n): RefObject<Group | null> {\n  const ref = useRef<Group>(null)\n  const scene = useThree((s) => s.scene)\n  const owner = useMemo(() => ({}), [])\n  useLayoutEffect(() => {\n    const group = ref.current\n    if (!group || !local.length) return\n    const pool = poolFor(scene, name, look)\n    group.updateWorldMatrix(true, false)\n    pool.set(\n      owner,\n      local.map((m) => new Matrix4().multiplyMatrices(group.matrixWorld, m)),\n      color,\n    )\n    return () => pool.drop(owner)\n    // `look` is only read when the pool is first made.\n  }, [scene, name, local, color, place, owner])\n  return ref\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/haze.ts",
      "content": "// The TSL twins of city/haze.ts, for WebGPURenderer: a lamp's haze cone and the pool it leaves\n// on the street, additive and faded out by distance instead of fog.\n\nimport { type Color, DoubleSide, type Material } from 'three'\nimport {\n  abs,\n  cameraPosition,\n  distance,\n  float,\n  mix,\n  normalView,\n  positionViewDirection,\n  positionWorld,\n  pow,\n  smoothstep,\n  uniform,\n  uv,\n  vec2,\n} from 'three/tsl'\nimport { MeshBasicNodeMaterial } from 'three/webgpu'\nimport { additive } from '../city/haze'\n\nconst cache = new Map<string, Material>()\n\n/** The haze cone under a lamp head, in `color` (linear, already scaled to its luminance). */\nexport function coneNodeMaterial(color: Color): Material {\n  const key = `cone:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}`\n  let m = cache.get(key)\n  if (!m) {\n    const n = new MeshBasicNodeMaterial()\n    const facing = pow(abs(normalView.dot(positionViewDirection)), 1.5)\n    n.colorNode = uniform(color.clone()).mul(facing).mul(uv().y.mul(uv().y))\n    n.fog = false\n    n.side = DoubleSide\n    n.name = `runek:haze:${key}`\n    m = additive(n)\n    cache.set(key, m)\n  }\n  return m\n}\n\n/** The pool a lamp leaves on the street, faded in between `near` and `far` meters from the eye. */\nexport function poolNodeMaterial(color: Color, near: number, far: number): Material {\n  const key = `pool:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}:${near}:${far}`\n  let m = cache.get(key)\n  if (!m) {\n    const n = new MeshBasicNodeMaterial()\n    const r = uv().sub(vec2(0.5)).length().mul(2)\n    const disc = float(1).sub(smoothstep(0, 1, r))\n    const fade = mix(0.5, 1, smoothstep(near, far, distance(positionWorld, cameraPosition)))\n    n.colorNode = uniform(color.clone()).mul(disc.mul(disc)).mul(fade)\n    n.fog = false\n    n.polygonOffset = true\n    n.polygonOffsetFactor = -2\n    n.polygonOffsetUnits = -4\n    n.name = `runek:haze:${key}`\n    m = additive(n)\n    cache.set(key, m)\n  }\n  return m\n}\n",
      "type": "registry:component"
    }
  ]
}
