{
  "name": "cable-sag",
  "title": "CableSag",
  "type": "registry:component",
  "description": "A cable sagging across a street between two anchors: a parabola cut into straight pieces. Drawn by the world's shared facade-kit meshes. Decorative: no collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "CableSag.tsx",
      "content": "import { useWorld, type Vec3 } from '@runek/core'\nimport { cableSag } from './city/kitParts'\nimport { useKit } from './city/useKit'\n\nexport interface CableSagProps {\n  /** The near anchor [x, y, z] in units. The cable crosses along local +Z. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. Turn about Y to aim it across the street. */\n  rotation?: Vec3\n  /** Accepted for the component contract. This component has no seeded variation. */\n  seed?: number\n  /** Distance to the far anchor, in units. */\n  span?: number\n  /** How far the middle hangs below the straight line, in units. */\n  sag?: number\n  /** How much higher (or lower, when negative) the far anchor sits, in units. */\n  drop?: number\n  /** Straight pieces the curve is cut into. */\n  segments?: number\n  /** Cable thickness, in units. */\n  thickness?: number\n  /** Cable color. */\n  color?: string\n}\n\n/**\n * A cable sagging across a street between two anchors: a parabola cut into straight pieces.\n * Drawn by the world's shared kit meshes and left out of the world's mirrors. No collider.\n */\nexport function CableSag({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  span = 27,\n  sag = 1.4,\n  drop = 0,\n  segments = 8,\n  thickness = 0.04,\n  color = '#141110',\n}: CableSagProps) {\n  const { unit } = useWorld()\n  const ref = useKit(\n    (kit) =>\n      cableSag(kit, 0, 0, 0, span, {\n        sag: sag,\n        drop: drop,\n        segments: Math.max(2, Math.round(segments)),\n        thickness: thickness,\n        color,\n      }),\n    [span, sag, drop, segments, thickness, color],\n    [position, rotation, unit],\n  )\n  return <group ref={ref} position={position} rotation={rotation} scale={unit} />\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/kit.ts",
      "content": "// The facade kit's shared draw: every AC unit, pipe, cable, vent, awning, shutter, sign and\n// vending machine in a world is an instance in one of three InstancedMeshes, so a street full of\n// props costs three draws however many towers it has. A fourth holds the light those signs leave\n// on the ground.\n//\n// `near` holds the parts worth reflecting in the wet street (signs, tubes, awnings, shutters).\n// `small` holds the rest and is left out of the world's mirrors (`skipMirrors`).\n// `glyph` holds sign letters, cut from an atlas drawn in code at load from the world's fonts.\n// `splat` holds soft additive pools on the street in front of lit signs and door lamps. They are\n// not real lights: a shop's glow reads on the pavement without spending one of the world's few.\n//\n// Components describe their parts in local space with a KitBuilder (a pure function of props and\n// seed) and hand them to `useKit`, which registers them in world space with the scene's Kit.\n\nimport { skipMirrors } from '@runek/core'\nimport {\n  AdditiveBlending,\n  BoxGeometry,\n  Color,\n  DataTexture,\n  InstancedBufferAttribute,\n  InstancedMesh,\n  LinearFilter,\n  LinearMipmapLinearFilter,\n  type Material,\n  Matrix4,\n  PlaneGeometry,\n  RGBAFormat,\n  type Scene,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n  Vector3,\n} from 'three'\nimport { emissiveColor } from './glow'\nimport { FOG_FADE } from './haze'\nimport { towerUniforms } from './towerLight'\n\n/** Floats per box or glyph instance: a 4x4 matrix, then two vec4s. */\nexport const KIT_STRIDE = 24\n/** How a part is lit: matte under street light, or an emitter on a ladder rung. */\nexport const GLOW = { matte: 0, sign: 1, tube: 2, glass: 3 } as const\n/** Surface detail drawn by the box shader from the face's size in metres. */\nexport const DETAIL = {\n  none: 0,\n  slats: 1,\n  fan: 2,\n  vending: 3,\n  stripes: 4,\n  cage: 5,\n  panel: 6,\n} as const\n\nconst GLYPHS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.:'&/!?#\"\nconst ADVANCE: Record<string, number> = {\n  I: 0.42,\n  '1': 0.55,\n  '.': 0.34,\n  ':': 0.34,\n  \"'\": 0.3,\n  '!': 0.4,\n  ' ': 0.45,\n  M: 0.95,\n  W: 1.0,\n  '-': 0.6,\n  '+': 0.7,\n}\n/** Advance of one glyph, in letter heights. */\nexport const glyphAdvance = (ch: string) => ADVANCE[ch] ?? 0.8\n/** A glyph's quad side, in letter heights (the cap height fills half a cell). */\nconst GLYPH_QUAD = 2\n\nconst m4 = new Matrix4()\nconst m4b = new Matrix4()\nconst v3 = new Vector3()\n\n/** A box that stops a walker, in the component's local space. Upright, turned about Y only. */\nexport interface KitSolid {\n  /** Centre [x, y, z]. */\n  position: [number, number, number]\n  /** Half extents along the box's own X, Y and Z. */\n  half: [number, number, number]\n  /** Turn about Y, in radians. */\n  rotY: number\n}\n\n/** Collects a component's kit parts in its local space. */\nexport class KitBuilder {\n  near: number[] = []\n  small: number[] = []\n  glyph: number[] = []\n  splat: number[] = []\n  /** What a walker should bump into. The kit meshes do not read it: the component that owns the builder makes the colliders. */\n  solids: KitSolid[] = []\n  private frame = new Matrix4()\n  private stack: Matrix4[] = []\n\n  /** Enter a local frame at (x, y, z) turned `rotY` about Y. Parts added until `pop` sit in it. */\n  push(x: number, y: number, z: number, rotY = 0) {\n    this.stack.push(this.frame.clone())\n    this.frame.multiply(m4.makeRotationY(rotY).setPosition(x, y, z))\n    return this\n  }\n  pop() {\n    this.frame.copy(this.stack.pop() ?? new Matrix4())\n    return this\n  }\n\n  /**\n   * Mark a box centred at (x, y, z) of size (sx, sy, sz) in the current frame as solid. It draws\n   * nothing. Parts record their own (a vending machine's case), so a component that places them\n   * gets colliders that follow the same seeded layout as the instances.\n   */\n  solid(x: number, y: number, z: number, sx: number, sy: number, sz: number) {\n    const e = this.frame.elements\n    v3.set(x, y, z).applyMatrix4(this.frame)\n    this.solids.push({\n      position: [v3.x, v3.y, v3.z],\n      half: [sx / 2, sy / 2, sz / 2],\n      rotY: Math.atan2(e[8], e[0]),\n    })\n    return this\n  }\n\n  private write(\n    out: number[],\n    local: Matrix4,\n    color: string,\n    glow: number,\n    a: number,\n    b: number,\n    c: number,\n    d: number,\n  ) {\n    m4b.multiplyMatrices(this.frame, local)\n    const col = glow === GLOW.matte ? new Color(color) : emissiveColor(color, 1)\n    out.push(...m4b.elements, col.r, col.g, col.b, glow, a, b, c, d)\n  }\n\n  /**\n   * A box centred at (x, y, z) of size (sx, sy, sz). `glow` picks matte or a ladder rung, `t` the\n   * place along that rung (0 to 1), `detail` a surface pattern. `shear` leans the box: its top\n   * moves that far along local Z per metre of height (an awning's slope). `rise` lifts its far\n   * end: that many metres of height per metre of local Z (a cable's slope).\n   */\n  box(\n    small: boolean,\n    x: number,\n    y: number,\n    z: number,\n    sx: number,\n    sy: number,\n    sz: number,\n    color: string,\n    {\n      glow = GLOW.matte as number,\n      t = 0.5,\n      detail = DETAIL.none as number,\n      seed = 0,\n      rotY = 0,\n      shear = 0,\n      rise = 0,\n    } = {},\n  ) {\n    m4.makeRotationY(rotY).setPosition(x, y, z)\n    const s = new Matrix4().makeScale(sx, sy, sz)\n    if (shear) s.elements[6] = shear * sy // local Z gains shear per unit of local Y\n    if (rise) s.elements[9] = rise * sz // local Y gains rise per unit of local Z\n    m4.multiply(s)\n    this.write(small ? this.small : this.near, m4, color, glow, t, detail, seed, 0)\n    return this\n  }\n\n  /**\n   * Light left on the ground: a soft half disc lying flat at height y, its straight edge centred\n   * on (x, z) and running along local X for `sx`, reaching `sz` out along local +Z (away from\n   * the wall the light comes from). `t` is its place on the street-under-sign rung.\n   */\n  lightSplat(\n    x: number,\n    y: number,\n    z: number,\n    sx: number,\n    sz: number,\n    color: string,\n    { t = 0.5 } = {},\n  ) {\n    // A unit plane laid flat: its top edge (uv.y = 1) ends up on the -Z side, at the wall.\n    m4.makeRotationX(-Math.PI / 2)\n      .scale(v3.set(sx, sz, 1))\n      .setPosition(x, y, z + sz / 2)\n    this.write(this.splat, m4, color, GLOW.sign, t, 0, 0, 0)\n    return this\n  }\n\n  /** Width of `text` set at letter height `h`. */\n  static textWidth(text: string, h: number, tracking = 0.06) {\n    let w = 0\n    for (const ch of text) w += (glyphAdvance(ch) + tracking) * h\n    return w - tracking * h\n  }\n\n  /**\n   * A line of text centred on (x, y, z), facing local +Z after `rotY`, letters `h` tall.\n   * `outline` draws bent-tube letters, `body` uses the world's body font (stencil codes).\n   * `vertical` stacks the letters downward from y.\n   */\n  text(\n    text: string,\n    x: number,\n    y: number,\n    z: number,\n    h: number,\n    color: string,\n    {\n      glow = GLOW.sign as number,\n      t = 0.5,\n      rotY = 0,\n      outline = false,\n      body = false,\n      vertical = false,\n      tracking = 0.06,\n    } = {},\n  ) {\n    const q = h * GLYPH_QUAD\n    const channel = body ? 2 : outline ? 1 : 0\n    const width = vertical ? 0 : KitBuilder.textWidth(text, h, tracking)\n    let cursor = -width / 2\n    let row = 0\n    for (const ch of text.toUpperCase()) {\n      const adv = glyphAdvance(ch) * h\n      const index = GLYPHS.indexOf(ch)\n      if (index >= 0) {\n        const lx = vertical ? 0 : cursor + adv / 2\n        const ly = vertical ? -row * h * 1.28 : 0\n        m4.makeRotationY(rotY)\n        m4.multiply(new Matrix4().makeTranslation(lx, ly, 0)).multiply(\n          new Matrix4().makeScale(q, q, 1),\n        )\n        m4.elements[12] += x\n        m4.elements[13] += y\n        m4.elements[14] += z\n        this.write(this.glyph, m4, color, glow, t, index, channel, 0)\n      }\n      cursor += adv + tracking * h\n      if (ch !== ' ' || vertical) row++\n    }\n    return this\n  }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Glyph atlas\n\nconst ATLAS = 1024\nconst CELL = ATLAS / 8\nconst atlasData = new Uint8Array(ATLAS * ATLAS * 4)\nlet atlasTexture: DataTexture | null = null\nconst fontsAsked = new Set<string>()\n\nfunction drawAtlas(display: string, body: string) {\n  const canvas = document.createElement('canvas')\n  canvas.width = canvas.height = ATLAS\n  const ctx = canvas.getContext('2d', { willReadFrequently: true })\n  if (!ctx) return\n  const pass = (family: string, weight: number, stroke: boolean, channel: number) => {\n    ctx.clearRect(0, 0, ATLAS, ATLAS)\n    ctx.fillStyle = ctx.strokeStyle = 'white'\n    ctx.textAlign = 'center'\n    ctx.textBaseline = 'alphabetic'\n    ctx.lineJoin = ctx.lineCap = 'round'\n    // Size the font so a capital is exactly half a cell tall, whatever the face.\n    ctx.font = `${weight} 100px ${family}`\n    const cap = ctx.measureText('H').actualBoundingBoxAscent || 70\n    const px = (100 * CELL * 0.5) / cap\n    ctx.font = `${weight} ${px}px ${family}`\n    ctx.lineWidth = CELL * 0.05\n    for (let i = 0; i < GLYPHS.length; i++) {\n      const cx = (i % 8) * CELL + CELL / 2\n      const cy = Math.floor(i / 8) * CELL + CELL * 0.75\n      if (stroke) ctx.strokeText(GLYPHS[i], cx, cy)\n      else ctx.fillText(GLYPHS[i], cx, cy)\n    }\n    const img = ctx.getImageData(0, 0, ATLAS, ATLAS).data\n    for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + channel] = img[p * 4 + 3]\n  }\n  pass(display, 600, false, 0)\n  pass(display, 600, true, 1)\n  pass(body, 500, false, 2)\n  for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + 3] = 255\n  if (atlasTexture) atlasTexture.needsUpdate = true\n}\n\n/** The sign glyph atlas: R display fill, G display outline, B body fill. Redrawn when the world's fonts arrive. */\nexport function glyphAtlas(fonts?: { display?: string; body?: string }) {\n  const families = { display: 'sans-serif', body: 'monospace' }\n  if (!atlasTexture) {\n    atlasTexture = new DataTexture(atlasData, ATLAS, ATLAS, RGBAFormat)\n    atlasTexture.magFilter = LinearFilter\n    atlasTexture.minFilter = LinearMipmapLinearFilter\n    atlasTexture.generateMipmaps = true\n    if (typeof document !== 'undefined') drawAtlas(families.display, families.body)\n    atlasTexture.needsUpdate = true\n  }\n  if (typeof document === 'undefined' || typeof FontFace === 'undefined') return atlasTexture\n  const key = `${fonts?.display}|${fonts?.body}`\n  if (fonts && !fontsAsked.has(key)) {\n    fontsAsked.add(key)\n    const load = (name: string, url?: string) =>\n      url\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        : Promise.resolve(null)\n    void Promise.all([\n      load('runek-kit-display', fonts.display),\n      load('runek-kit-body', fonts.body),\n    ]).then(([d, b]) => {\n      if (d || b)\n        drawAtlas(d ? `${d}, sans-serif` : families.display, b ? `${b}, monospace` : families.body)\n    })\n  }\n  return atlasTexture\n}\n\n// ---------------------------------------------------------------------------------------------\n// Materials (WebGL). The WebGPU twins live in kitNode.ts.\n\n/** Uniforms the kit shares with every tower, plus its own night level. */\nexport const kitUniforms = {\n  ...towerUniforms,\n  uNight: { value: 1 },\n  tAtlas: { value: null as DataTexture | null },\n}\n\nconst PARS = /* glsl */ `\nuniform float uNight;\nuniform float uWallGain;\nuniform vec3 uGlow;\nuniform vec2 uSign;\nuniform vec2 uTube;\nuniform vec2 uShop;\nfloat rung(vec2 r, float t) { return r.x * pow(r.y / r.x, t); }\nfloat kitRung(float glow, float t) { return glow < 1.5 ? rung(uSign, t) : (glow < 2.5 ? rung(uTube, t) : rung(uShop, t)); }\n`\n\nconst BOX_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nvarying vec4 vColor;\nvarying vec4 vKit;\nvarying vec2 vUvM;\nvarying vec2 vFace;\nvarying vec3 vLN;\nvarying vec3 vWN;\nvarying float vWorldY;\n#include <fog_pars_vertex>\nvoid main() {\n  vColor = aColor; vKit = aKit; vLN = normal;\n  mat4 im = instanceMatrix;\n  vec3 s = vec3(length(im[0].xyz), length(im[1].xyz), length(im[2].xyz));\n  vec3 an = abs(normal);\n  vFace = an.x > 0.5 ? s.zy : (an.y > 0.5 ? s.xz : s.xy);\n  vUvM = uv * vFace;\n  vWN = normalize(mat3(modelMatrix) * mat3(im) * normal);\n  vec4 wp = modelMatrix * im * vec4(position, 1.0);\n  vWorldY = wp.y;\n  vec4 mvPosition = viewMatrix * wp;\n  gl_Position = projectionMatrix * mvPosition;\n  #include <fog_vertex>\n}`\n\nconst BOX_FRAG = /* glsl */ `\n${PARS}\nvarying vec4 vColor;\nvarying vec4 vKit;\nvarying vec2 vUvM;\nvarying vec2 vFace;\nvarying vec3 vLN;\nvarying vec3 vWN;\nvarying float vWorldY;\n#include <fog_pars_fragment>\nfloat pulseInt(float x, float a, float b) { return floor(x) * (b - a) + clamp(fract(x), a, b) - a; }\n// Box-filtered periodic pulse: coverage of [a, b] in each unit cell over a footprint w.\nfloat pulse(float x, float a, float b, float w) {\n  w = max(w, 1e-4);\n  return (pulseInt(x + 0.5 * w, a, b) - pulseInt(x - 0.5 * w, a, b)) / w;\n}\nfloat band(float x, float a, float b, float w) {\n  return clamp((min(x + 0.5 * w, b) - max(x - 0.5 * w, a)) / max(w, 1e-4), 0.0, 1.0);\n}\nvoid main() {\n  float glow = vColor.a, t = vKit.x, detail = vKit.y, sd = vKit.z;\n  vec2 m = vUvM, fw = fwidth(vUvM);\n  float side = 1.0 - step(0.5, abs(vLN.y));\n  float front = step(0.5, vLN.z);\n  float tone = 1.0;\n  if (detail > 0.5 && detail < 1.5) {\n    tone = mix(0.55, 1.0, pulse(m.y / 0.11, 0.0, 0.7, fw.y / 0.11)) * side + (1.0 - side);\n  } else if (detail < 2.5 && detail > 1.5) {\n    // An outdoor unit: a fan ring behind fins on the front, a seam round the case.\n    vec2 c = (m - vec2(vFace.x * 0.38, vFace.y * 0.5)) / (vFace.y * 0.4);\n    float disc = 1.0 - smoothstep(0.92, 1.0, length(c));\n    float fins = pulse(m.y / 0.045, 0.0, 0.5, fw.y / 0.045);\n    tone = mix(1.0, mix(0.25, 0.6, fins) * (0.6 + 0.4 * smoothstep(0.15, 0.3, length(c))), disc * front);\n    tone *= mix(1.0, 0.7, (1.0 - front) * side * band(m.y, vFace.y - 0.05, vFace.y, fw.y));\n  } else if (detail < 3.5 && detail > 2.5) {\n    // A vending window: rows of lit goods.\n    tone = mix(0.2, 1.0, pulse(m.y / 0.26, 0.12, 1.0, fw.y / 0.26) * pulse(m.x / 0.13, 0.2, 1.0, fw.x / 0.13));\n  } else if (detail < 4.5 && detail > 3.5) {\n    tone = mix(0.55, 1.0, pulse(m.x / 0.7, 0.0, 0.5, fw.x / 0.7));\n  } else if (detail < 5.5 && detail > 4.5) {\n    float wire = 1.0 - pulse(m.x / 0.09, 0.0, 0.8, fw.x / 0.09) * pulse(m.y / 0.09, 0.0, 0.8, fw.y / 0.09);\n    tone = mix(0.35, 1.3, wire);\n  } else if (detail > 5.5) {\n    float rim = 1.0 - band(m.x, 0.05, vFace.x - 0.05, fw.x) * band(m.y, 0.05, vFace.y - 0.05, fw.y);\n    tone = mix(1.0, 2.2, rim * (1.0 - step(0.5, abs(vLN.x))));\n  }\n  vec3 col;\n  if (glow < 0.5) {\n    // Matte: the wall's own unlit model, with a face shade so a box reads as a solid.\n    float shade = 0.72 + 0.28 * vWN.y + 0.1 * vWN.x;\n    col = vColor.rgb * mix(0.35, uWallGain, uNight) * shade * tone;\n    col += uGlow * exp(-max(vWorldY, 0.0) / 6.0) * uNight * (0.55 + 0.45 * shade) * min(tone, 1.0);\n  } else {\n    col = vColor.rgb * kitRung(glow, t) * tone * mix(0.12, 1.0, uNight);\n  }\n  gl_FragColor = vec4(col, 1.0);\n  #include <tonemapping_fragment>\n  #include <colorspace_fragment>\n  #include <fog_fragment>\n}`\n\nconst GLYPH_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nvarying vec4 vColor;\nvarying vec3 vKit;\nvarying vec2 vUv;\n#include <fog_pars_vertex>\nvoid main() {\n  vColor = aColor; vKit = aKit.xyz;\n  vec2 cell = vec2(mod(aKit.y, 8.0), floor(aKit.y / 8.0));\n  vUv = vec2(cell.x + uv.x, cell.y + 1.0 - uv.y) / 8.0;\n  vec4 mvPosition = viewMatrix * modelMatrix * instanceMatrix * vec4(position, 1.0);\n  gl_Position = projectionMatrix * mvPosition;\n  #include <fog_vertex>\n}`\n\nconst GLYPH_FRAG = /* glsl */ `\n${PARS}\nuniform sampler2D tAtlas;\nvarying vec4 vColor;\nvarying vec3 vKit;\nvarying vec2 vUv;\n#include <fog_pars_fragment>\nvoid main() {\n  vec3 tx = texture2D(tAtlas, vUv).rgb;\n  float a = vKit.z < 0.5 ? tx.r : (vKit.z < 1.5 ? tx.g : tx.b);\n  // Sharpen the edge when the atlas is magnified. Leave the mip's own coverage when it is not.\n  float texels = length(fwidth(vUv)) * ${ATLAS}.0;\n  float w = clamp(fwidth(a), 0.03, 0.5);\n  a = mix(smoothstep(0.5 - w, 0.5 + w, a), a, clamp(texels - 0.6, 0.0, 1.0));\n  if (a < 0.01) discard;\n  // Glow 0 is paint on a wall (stencil codes). Anything else is a lit letter on its rung.\n  vec3 col = vColor.a < 0.5 ? vColor.rgb * mix(0.35, uWallGain, uNight) + uGlow * uNight * 0.5 : vColor.rgb * kitRung(vColor.a, vKit.x) * mix(0.12, 1.0, uNight);\n  gl_FragColor = vec4(col, a);\n  #include <tonemapping_fragment>\n  #include <colorspace_fragment>\n  #include <fog_fragment>\n}`\n\nconst SPLAT_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nuniform float uNight;\nuniform vec2 uStreet;\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec3 vWorld;\nvoid main() {\n  vColor = aColor.rgb * uStreet.x * pow(uStreet.y / uStreet.x, aKit.x) * uNight;\n  vUv = uv;\n  vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);\n  vWorld = world.xyz;\n  gl_Position = projectionMatrix * viewMatrix * world;\n}`\n\n// Brightest at the foot of the wall, gone at the far edge. Added to the street, so it fades\n// with the fog range instead of mixing toward the fog color.\nconst SPLAT_FRAG = /* glsl */ `\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float d = length(vec2((vUv.x - 0.5) * 2.0, 1.0 - vUv.y));\n  float a = 1.0 - smoothstep(0.0, 1.0, d);\n  gl_FragColor = vec4(vColor * a * a * hazeFog(vWorld), 1.0);\n}`\n\nfunction glMaterials(): KitMaterialSet {\n  const fog = () => UniformsUtils.merge([UniformsLib.fog])\n  const box = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: BOX_VERT,\n    fragmentShader: BOX_FRAG,\n    fog: true,\n  })\n  const glyph = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: GLYPH_VERT,\n    fragmentShader: GLYPH_FRAG,\n    fog: true,\n    transparent: true,\n    depthWrite: false,\n  })\n  const splat = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: SPLAT_VERT,\n    fragmentShader: SPLAT_FRAG,\n    fog: true,\n    transparent: true,\n    blending: AdditiveBlending,\n    depthWrite: false,\n    // It lies a few centimetres over the street, which is not enough far away.\n    polygonOffset: true,\n    polygonOffsetFactor: -2,\n    polygonOffsetUnits: -4,\n  })\n  return { box, glyph, splat }\n}\n\n// ---------------------------------------------------------------------------------------------\n// The per-scene kit\n\ntype Slot = 'near' | 'small' | 'glyph' | 'splat'\nconst SLOTS: Slot[] = ['near', 'small', 'glyph', 'splat']\n\nexport interface KitMaterialSet {\n  box: Material\n  glyph: Material\n  splat: Material\n}\n\n/** Makes the kit's box, glyph and splat materials. WebGPU passes its node twins. */\nexport type KitMaterials = (atlas: DataTexture) => KitMaterialSet\n\nexport class Kit {\n  private entries = new Map<number, { parts: KitBuilder; world: Matrix4 }>()\n  private meshes: Partial<Record<Slot, InstancedMesh>> = {}\n  private materials: KitMaterialSet\n  private nextId = 1\n  private unskip = new Map<InstancedMesh, () => void>()\n  private queued = false\n  users = 0\n\n  constructor(\n    private scene: Scene,\n    make: KitMaterials | undefined,\n    atlas: DataTexture,\n  ) {\n    kitUniforms.tAtlas.value = atlas\n    this.materials = make ? make(atlas) : glMaterials()\n  }\n\n  add(parts: KitBuilder, world: Matrix4) {\n    const id = this.nextId++\n    this.entries.set(id, { parts, world: world.clone() })\n    this.queue()\n    return id\n  }\n  remove(id: number) {\n    this.entries.delete(id)\n    this.queue()\n  }\n  private queue() {\n    if (this.queued) return\n    this.queued = true\n    queueMicrotask(() => this.flush())\n  }\n\n  /** Rewrite the instance buffers from every registered component. */\n  private flush() {\n    this.queued = false\n    for (const slot of SLOTS) {\n      let count = 0\n      for (const e of this.entries.values()) count += e.parts[slot].length / KIT_STRIDE\n      let mesh = this.meshes[slot]\n      if (!mesh || mesh.instanceMatrix.count < count) {\n        if (mesh) this.drop(mesh)\n        if (count === 0) {\n          delete this.meshes[slot]\n          continue\n        }\n        mesh = this.meshes[slot] = this.make(slot, Math.ceil(count * 1.25) + 16)\n      }\n      const mat = mesh.instanceMatrix.array as Float32Array\n      const color = mesh.geometry.getAttribute('aColor') as InstancedBufferAttribute\n      const kit = mesh.geometry.getAttribute('aKit') as InstancedBufferAttribute\n      let i = 0\n      for (const e of this.entries.values()) {\n        const src = e.parts[slot]\n        for (let o = 0; o < src.length; o += KIT_STRIDE, i++) {\n          m4.fromArray(src, o)\n            .premultiply(e.world)\n            .toArray(mat, i * 16)\n          for (let k = 0; k < 4; k++) {\n            color.array[i * 4 + k] = src[o + 16 + k]\n            kit.array[i * 4 + k] = src[o + 20 + k]\n          }\n        }\n      }\n      mesh.count = count\n      mesh.instanceMatrix.needsUpdate = color.needsUpdate = kit.needsUpdate = true\n    }\n  }\n\n  private make(slot: Slot, capacity: number) {\n    const flat = slot === 'glyph' || slot === 'splat'\n    const geometry = flat ? new PlaneGeometry(1, 1) : new BoxGeometry(1, 1, 1)\n    geometry.setAttribute('aColor', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))\n    geometry.setAttribute('aKit', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))\n    const mesh = new InstancedMesh(\n      geometry,\n      flat ? this.materials[slot] : this.materials.box,\n      capacity,\n    )\n    mesh.name = `runek:kit:${slot}`\n    // Instances span the world, so one bound would never cull anything useful.\n    mesh.frustumCulled = false\n    mesh.matrixAutoUpdate = false\n    // Mirrors skip the small parts, and the light on the street they are themselves laid over.\n    if (slot === 'small' || slot === 'splat') this.unskip.set(mesh, skipMirrors(mesh))\n    if (slot === 'glyph') mesh.renderOrder = 2\n    if (slot === 'splat') mesh.renderOrder = 1\n    this.scene.add(mesh)\n    return mesh\n  }\n  private drop(mesh: InstancedMesh) {\n    this.unskip.get(mesh)?.()\n    this.unskip.delete(mesh)\n    this.scene.remove(mesh)\n    mesh.geometry.dispose()\n    mesh.dispose()\n  }\n  dispose() {\n    for (const slot of SLOTS) if (this.meshes[slot]) this.drop(this.meshes[slot])\n    this.meshes = {}\n    this.materials.box.dispose()\n    this.materials.glyph.dispose()\n    this.materials.splat.dispose()\n  }\n}\n\nconst kits = new WeakMap<Scene, Kit>()\n\n/** The scene's kit, made on first use. Pair every call with `releaseKit`. */\nexport function acquireKit(\n  scene: Scene,\n  make: KitMaterials | undefined,\n  fonts?: { display?: string; body?: string },\n) {\n  let kit = kits.get(scene)\n  if (!kit) {\n    kit = new Kit(scene, make, glyphAtlas(fonts))\n    kits.set(scene, kit)\n  }\n  kit.users++\n  return kit\n}\n\nexport function releaseKit(scene: Scene) {\n  const kit = kits.get(scene)\n  if (!kit || --kit.users > 0) return\n  // Wait a tick: a component that re-registers in the same commit keeps the kit alive.\n  queueMicrotask(() => {\n    if (kit.users > 0 || kits.get(scene) !== kit) return\n    kit.dispose()\n    kits.delete(scene)\n  })\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/kitParts.ts",
      "content": "// The facade kit's parts. Each function adds one prop to a KitBuilder in a wall frame: +X runs\n// along the wall to the viewer's right, +Y is up, +Z points out of the wall. (x, y, z) is where\n// the prop meets the wall. Tower calls these for its street faces, and each also backs a\n// standalone component of the same name.\n\nimport { DETAIL, GLOW, KitBuilder } from './kit'\n\nconst CASES = ['#8a8a84', '#75736c', '#9a9488', '#6b6f70']\nconst DARK = '#141110'\nconst STEEL = '#4a4844'\nconst RUST = '#5a4234'\n\n/** An outdoor AC unit on its bracket. `cage` wraps it in a wire cage. */\nexport function acUnit(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { seed = 0, cage = false } = {},\n) {\n  const tone = CASES[Math.floor(Math.abs(seed) * 97) % CASES.length]\n  if (cage) {\n    kit.box(true, x, y + 0.36, z + 0.24, 0.98, 0.72, 0.48, RUST, { detail: DETAIL.cage, seed })\n  } else {\n    kit.box(true, x, y + 0.33, z + 0.19, 0.82, 0.58, 0.34, tone, { detail: DETAIL.fan, seed })\n  }\n  kit.box(true, x, y + 0.02, z + 0.2, 0.9, 0.04, 0.4, DARK)\n  // The drain hose.\n  kit.box(true, x + 0.34, y - 0.4, z + 0.03, 0.03, 0.8, 0.03, DARK)\n}\n\n/** A pipe run with collars: up the wall from (x, y, z), or along it when `horizontal`. */\nexport function pipeRun(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  length: number,\n  { horizontal = false, radius = 0.06, color = STEEL } = {},\n) {\n  const t = radius * 2\n  if (horizontal) kit.box(true, x + length / 2, y, z + radius + 0.03, length, t, t, color)\n  else kit.box(true, x, y + length / 2, z + radius + 0.03, t, length, t, color)\n  const collars = Math.max(2, Math.round(length / 2.4))\n  for (let i = 0; i < collars; i++) {\n    const at = ((i + 0.5) * length) / collars\n    if (horizontal) kit.box(true, x + at, y, z + radius + 0.02, 0.07, t + 0.06, t + 0.05, DARK)\n    else kit.box(true, x, y + at, z + radius + 0.02, t + 0.06, 0.07, t + 0.05, DARK)\n  }\n}\n\n/** Height of a cable `t` of the way across (0 to 1): a parabola that drops `sag` at mid span and ends `drop` higher. */\nexport const cableY = (t: number, sag: number, drop = 0) => drop * t - 4 * sag * t * (1 - t)\n\n/** A cable sagging from the wall at (x, y, z) across `span` metres of street. */\nexport function cableSag(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  span: number,\n  { sag = 1.2, drop = 0, segments = 8, color = DARK, thickness = 0.04 } = {},\n) {\n  for (let i = 0; i < segments; i++) {\n    const t0 = i / segments\n    const t1 = (i + 1) / segments\n    const y0 = cableY(t0, sag, drop)\n    const y1 = cableY(t1, sag, drop)\n    const len = span / segments\n    kit.box(\n      true,\n      x,\n      y + (y0 + y1) / 2,\n      z + (t0 + t1) * 0.5 * span,\n      thickness,\n      thickness,\n      len,\n      color,\n      { rise: (y1 - y0) / len },\n    )\n  }\n}\n\n/** A louvred vent under a small hood. */\nexport function vent(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { width = 0.6, height = 0.45 } = {},\n) {\n  kit.box(true, x, y + height / 2, z + 0.04, width, height, 0.08, STEEL, { detail: DETAIL.slats })\n  kit.box(true, x, y + height + 0.03, z + 0.08, width + 0.08, 0.05, 0.16, DARK)\n}\n\n/** A sloped fabric awning hung at (x, y, z), `width` along the wall, with a valance. */\nexport function awning(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  width: number,\n  { depth = 1.3, drop = 0.45, color = '#5a2a1c', stripes = true } = {},\n) {\n  const detail = stripes ? DETAIL.stripes : DETAIL.none\n  kit.box(false, x, y - drop / 2, z + depth / 2, width, 0.05, depth, color, {\n    detail,\n    rise: -drop / depth,\n  })\n  kit.box(false, x, y - drop - 0.1, z + depth, width, 0.22, 0.03, color, { detail })\n  // The two arms that carry it.\n  for (const side of [-1, 1])\n    kit.box(\n      true,\n      x + side * (width / 2 - 0.05),\n      y - drop / 2 - 0.05,\n      z + depth / 2,\n      0.04,\n      0.04,\n      depth,\n      DARK,\n      { rise: -drop / depth },\n    )\n}\n\n/** A roller shutter in its housing. `open` is the share rolled up, 0 (down) to 1. */\nexport function rollerShutter(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  width: number,\n  height: number,\n  { open = 0, color = '#6e6a62' } = {},\n) {\n  const down = height * (1 - Math.min(1, Math.max(0, open)))\n  if (down > 0.05)\n    kit.box(false, x, y + height - down / 2, z + 0.05, width, down, 0.05, color, {\n      detail: DETAIL.slats,\n    })\n  kit.box(false, x, y + height + 0.1, z + 0.11, width + 0.12, 0.26, 0.22, STEEL)\n  for (const side of [-1, 1])\n    kit.box(\n      true,\n      x + side * (width / 2 + 0.03),\n      y + height / 2,\n      z + 0.05,\n      0.06,\n      height,\n      0.09,\n      STEEL,\n    )\n}\n\n/** The word a blade sign stacks: the longest word of a shop's name that has seven letters or fewer. */\nexport function bladeWord(name: string) {\n  const words = name.toUpperCase().split(' ')\n  let best = ''\n  for (const w of words) if (w.length <= 7 && w.length > best.length) best = w\n  return best || words[0].slice(0, 9)\n}\n\n/** A blade sign: a board standing out from the wall, its letters stacked and lit on both faces. (x, y, z) is the bottom of the board at the wall. */\nexport function bladeSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.55, color = '#ff6418', gap = 0.3, tube = true } = {},\n) {\n  const word = text.toUpperCase().replace(/ /g, '')\n  const step = letter * 1.28\n  const height = word.length * step + 0.3\n  const depth = letter * 1.15 + 0.3\n  const mid = z + gap + depth / 2\n  kit.box(false, x, y + height / 2, mid, 0.14, height, depth, DARK)\n  const top = y + height - 0.15 - step / 2\n  for (const side of [-1, 1]) {\n    kit.text(word, x + side * 0.085, top, mid, letter, color, {\n      vertical: true,\n      rotY: (side * Math.PI) / 2,\n      t: 0.45,\n    })\n  }\n  if (tube) {\n    for (const edge of [-1, 1])\n      kit.box(\n        false,\n        x,\n        y + height / 2,\n        mid + edge * (depth / 2 + 0.02),\n        0.05,\n        height,\n        0.05,\n        color,\n        { glow: GLOW.tube, t: 0.1 },\n      )\n  }\n  // Two arms back to the wall.\n  for (const at of [0.25, height - 0.25])\n    kit.box(true, x, y + at, z + gap / 2, 0.05, 0.05, gap, STEEL)\n}\n\n/** A vending machine standing against the wall: a matte case and a lit window of goods. The case is solid. */\nexport function vendingMachine(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { seed = 0, color = '#3a2f45', lamp = '#ffcf9a' } = {},\n) {\n  kit.box(true, x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72, color)\n  kit.solid(x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72)\n  kit.box(false, x - 0.06, y + 1.2, z + 0.73, 0.76, 1.02, 0.03, lamp, {\n    glow: GLOW.glass,\n    t: 0.35,\n    detail: DETAIL.vending,\n    seed,\n  })\n  kit.box(true, x - 0.06, y + 0.38, z + 0.73, 0.6, 0.2, 0.03, DARK)\n  kit.box(true, x + 0.4, y + 1.2, z + 0.73, 0.1, 0.7, 0.03, DARK)\n}\n\n/** A shop's name over its bay: lit letters on a dark board, or bare tube letters. `fit` is the most width it may take. */\nexport function fasciaSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.5, color = '#ffa64d', fit = 0, tube = false, board = true } = {},\n) {\n  let h = letter\n  const wide = KitBuilder.textWidth(text, h)\n  if (fit > 0 && wide + 0.4 > fit) h *= fit / (wide + 0.4)\n  const width = KitBuilder.textWidth(text, h)\n  if (board)\n    kit.box(false, x, y, z + 0.04, width + h * 0.9, h * 1.75, 0.08, DARK, { detail: DETAIL.panel })\n  kit.text(text, x, y, z + 0.1, h, color, {\n    outline: tube,\n    glow: tube ? GLOW.tube : GLOW.sign,\n    t: tube ? 0.12 : 0.5,\n  })\n  return width + h * 0.9\n}\n\n/** A drum lantern on a wall arm: the corner light of a tenement street. */\nexport function drumLantern(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { color = '#ffa64d', reach = 0.7 } = {},\n) {\n  const at = z + reach\n  for (const turn of [0, Math.PI / 4]) {\n    kit.box(false, x, y, at, 0.5, 0.78, 0.5, color, { glow: GLOW.sign, t: 0.25, rotY: turn })\n    kit.box(true, x, y + 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })\n    kit.box(true, x, y - 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })\n  }\n  kit.box(true, x, y + 0.55, z + reach / 2, 0.05, 0.05, reach, STEEL)\n}\n\n/** Big letters on an open frame, standing on a roof edge. (x, y, z) is the middle of the frame's foot. Returns its width. */\nexport function roofSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 1.8, color = '#ff6418', fit = 0 } = {},\n) {\n  let h = letter\n  const wide = KitBuilder.textWidth(text, h, 0.1)\n  if (fit > 0 && wide > fit) h *= fit / wide\n  const width = KitBuilder.textWidth(text, h, 0.1)\n  const base = y + 0.9\n  kit.text(text, x, base + h / 2, z + 0.08, h, color, { t: 0.75, tracking: 0.1 })\n  for (const rail of [0.12, 0.88])\n    kit.box(false, x, base + h * rail, z, width + 0.6, 0.07, 0.07, STEEL)\n  const posts = Math.max(2, Math.round(width / 3))\n  for (let i = 0; i < posts; i++) {\n    const px = x - width / 2 + (width * i) / (posts - 1)\n    kit.box(true, px, y + (0.9 + h) / 2, z - 0.06, 0.1, 0.9 + h, 0.1, STEEL)\n    kit.box(true, px, y + 0.5, z - 0.5, 0.07, 0.07, 0.95, STEEL, { rise: -0.9 })\n  }\n  return width\n}\n\n/** A stencilled code painted on the wall in the body font. */\nexport function stencilCode(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.3, color = '#a8a092' } = {},\n) {\n  kit.text(text, x, y, z + 0.012, letter, color, { glow: GLOW.matte, body: true, tracking: 0.12 })\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/useKit.ts",
      "content": "import { useThree } from '@react-three/fiber'\nimport { lazyModule, useNodeRenderer, useWorld } from '@runek/core'\nimport { type DependencyList, useLayoutEffect, useMemo, useRef } from 'react'\nimport type { Group } from 'three'\nimport { useLadder } from './glow'\nimport { acquireKit, KitBuilder, kitUniforms, releaseKit } from './kit'\nimport { applyTowerLight, nightFactor, towerLight } from './towerLight'\n\n// The kit's node (TSL) materials, loaded only under a node renderer.\nconst kitNodes = lazyModule(() => import('../nodes/kit'))\n\n/**\n * Register a component's kit parts with the scene's shared instanced meshes. `build` describes\n * the parts in local space and must be a pure function of `deps`. Attach the returned ref to a\n * group at the component's origin: its world matrix places the parts. `place` is any value that\n * changes when that group moves (the position and rotation props).\n */\nexport function useKit(build: (kit: KitBuilder) => void, deps: DependencyList, place: unknown) {\n  const parts = useMemo(() => {\n    const kit = new KitBuilder()\n    build(kit)\n    return kit\n  }, deps)\n  return useKitParts(parts, place)\n}\n\n/**\n * The same, for a component that built its own `KitBuilder` because it needs more than the\n * instances out of it (Tower reads `solids` to make its colliders). `parts` must be memoized.\n */\nexport function useKitParts(parts: KitBuilder, place: unknown) {\n  const ref = useRef<Group>(null)\n  const scene = useThree((s) => s.scene)\n  const nodes = useNodeRenderer() ? kitNodes() : null\n  const { fonts, time } = useWorld()\n  const ladder = useLadder()\n  const night = Math.round(nightFactor(time.hours) * 10) / 10\n\n  useLayoutEffect(() => applyTowerLight(ladder), [ladder])\n  useLayoutEffect(() => {\n    kitUniforms.uNight.value = night\n    towerLight.night = night\n  }, [night])\n  const placeKey = JSON.stringify(place)\n  useLayoutEffect(() => {\n    const group = ref.current\n    if (!group) return\n    group.updateWorldMatrix(true, false)\n    const kit = acquireKit(scene, nodes?.kitNodeMaterials, fonts)\n    const id = kit.add(parts, group.matrixWorld)\n    return () => {\n      kit.remove(id)\n      releaseKit(scene)\n    }\n  }, [parts, scene, nodes, fonts.display, fonts.body, placeKey])\n  return ref\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/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/towerLight.ts",
      "content": "// What lights a Tower at night, shared by its GLSL material and its TSL port: the lamp colors\n// behind windows and shopfronts (warm LED, sodium, mercury, phosphor violet and green, gas\n// neon), each at unit luminance, and the uniforms that put windows, shop\n// glass, trim, the lowest floors and the light a sign leaves on the street on the world's\n// luminance ladder.\n\nimport { Vector2 } from 'three'\nimport { DEFAULT_LADDER, emissiveColor, type Ladder, mid } from './glow'\n\n/** Lit windows: cumulative share, lamp. Most rooms are warm LED, then sodium, a few mercury, violet and green. */\nexport const WINDOW_LAMPS: [number, string][] = [\n  [0.6, '#ffcf9a'],\n  [0.86, '#ffa64d'],\n  [0.94, '#b8e8c8'],\n  [0.975, '#b967ff'],\n  [1, '#39ff88'],\n]\n\n/** Shopfront bays: cumulative share, lamp. Bays past the last share have their shutters down. */\nexport const SHOP_LAMPS: [number, string][] = [\n  [0.3, '#ffcf9a'],\n  [0.45, '#ffa64d'],\n  [0.52, '#39ff88'],\n  [0.58, '#b967ff'],\n  [0.62, '#ff6418'],\n]\n\n// The facade shader's integer hash (`pcg` and `h21` in towerFacade.ts), bit for bit, so the kit\n// can ask what the shader draws behind a bay's glass.\nfunction pcg(v: number) {\n  const state = (Math.imul(v, 747796405) + 2891336453) >>> 0\n  const word = Math.imul(((state >>> ((state >>> 28) + 4)) ^ state) >>> 0, 277803737) >>> 0\n  return ((word >>> 22) ^ word) >>> 0\n}\nfunction h21(x: number, y: number) {\n  const qx = (Math.floor(x) + 65536) >>> 0\n  const qy = (Math.floor(y) + 65536) >>> 0\n  return pcg((Math.imul(qx, 1664525) + pcg(qy)) >>> 0) / 4294967295\n}\n// The shader works in 32-bit floats: round the same way before a `floor` decides a cell.\nconst f = Math.fround\n\n/**\n * The lamp behind a lit shop bay's glass and where on the shop rung it sits (0 to 1), as the\n * facade shader draws it. `sd` is the tower's seed value, `fseed` the face's, `bay` the bay's\n * place along the face.\n */\nexport function shopLamp(sd: number, fseed: number, bay: number): { color: string; level: number } {\n  const last = SHOP_LAMPS[SHOP_LAMPS.length - 1]\n  const r = h21(bay, f(f(f(sd) * f(13.1)) + f(fseed))) * last[0]\n  return {\n    color: (SHOP_LAMPS.find(([share]) => r < share) ?? last)[1],\n    level: h21(bay + 3, f(f(sd) + f(f(fseed) * 5))),\n  }\n}\n\n/** Trim colors a tower may pick when its `trim` is unset: gas neon, phosphor green and violet, sodium, pump orange. */\nexport const TRIM_NEON = ['#ff6418', '#39ff88', '#b967ff', '#ffa64d', '#ff8a1f']\n\n/** A lamp color at unit luminance, as a GLSL literal. */\nexport function glslLamp(hex: string) {\n  const c = emissiveColor(hex, 1)\n  return `vec3(${c.r.toFixed(4)}, ${c.g.toFixed(4)}, ${c.b.toFixed(4)})`\n}\n\n/** GLSL for a cumulative lamp table: `vec3 name(float r)`, black past the last share. */\nexport function glslLampTable(name: string, table: [number, string][]) {\n  const body = table\n    .map(([share, hex]) => `if (r < ${share.toFixed(3)}) return ${glslLamp(hex)};`)\n    .join('\\n  ')\n  return `vec3 ${name}(float r) {\\n  ${body}\\n  return vec3(0.0);\\n}`\n}\n\n/** The ladder values a tower needs. The wall gain maps a wall color of luminance 0.04 to the bottom of the unlit-wall rung. */\nfunction lightFrom(ladder: Ladder) {\n  return {\n    window: new Vector2(ladder.windowLit[0], ladder.windowLit[1]),\n    shop: new Vector2(ladder.shopGlass[0], ladder.shopGlass[1]),\n    trim: mid(ladder.signFace),\n    sign: new Vector2(ladder.signFace[0], ladder.signFace[1]),\n    tube: new Vector2(ladder.tubeCore[0], ladder.tubeCore[1]),\n    street: new Vector2(ladder.streetUnderSign[0], ladder.streetUnderSign[1]),\n    wallGain: ladder.unlitWall[0] / 0.04,\n    glow: emissiveColor('#ffa64d', ladder.streetUnderSign[0] * 0.3),\n  }\n}\n\n/**\n * The light every tower and kit part is drawn under, one set for the page. The GLSL uniforms\n * below hold its vectors by reference, and the node twins (`nodes/city.ts`) read it each render,\n * so one write relights every tower under either renderer.\n */\nexport const towerLight = { ...lightFrom(DEFAULT_LADDER), night: 1 }\n\n/** Uniforms every tower ShaderMaterial shares by reference. */\nexport const towerUniforms = {\n  uWindow: { value: towerLight.window },\n  uShop: { value: towerLight.shop },\n  uTrim: { value: towerLight.trim },\n  uSign: { value: towerLight.sign },\n  uTube: { value: towerLight.tube },\n  uStreet: { value: towerLight.street },\n  uWallGain: { value: towerLight.wallGain },\n  uGlow: { value: towerLight.glow },\n}\n\n/** Put every tower on `ladder`. Cheap: it writes a handful of shared values. */\nexport function applyTowerLight(ladder: Ladder) {\n  const l = lightFrom(ladder)\n  towerLight.window.copy(l.window)\n  towerLight.shop.copy(l.shop)\n  towerLight.sign.copy(l.sign)\n  towerLight.tube.copy(l.tube)\n  towerLight.street.copy(l.street)\n  towerLight.glow.copy(l.glow)\n  towerLight.trim = towerUniforms.uTrim.value = l.trim\n  towerLight.wallGain = towerUniforms.uWallGain.value = l.wallGain\n}\n\n/** 0 at midday, 1 from late evening to early morning. */\nexport function nightFactor(hours: number) {\n  const fromNoon = Math.abs((((hours % 24) + 24) % 24) - 12) / 12 // 0 noon, 1 midnight\n  return Math.min(1, Math.max(0, (fromNoon - 0.35) / 0.3))\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/kit.ts",
      "content": "// The facade kit's materials as TSL node materials, for WebGPURenderer. Same lighting model as\n// the GLSL in city/kit.ts (matte parts under street light, emitters on their ladder rung, letters cut\n// from the glyph atlas, light splats added to the street). The per-kind surface detail (slats, fan grilles, awning stripes, cage\n// wire, vending rows) is skipped here: parts draw in their flat color.\n\nimport { AdditiveBlending, type DataTexture } from 'three'\nimport {\n  attribute,\n  exp,\n  float,\n  floor,\n  max,\n  mix,\n  mod,\n  normalWorld,\n  positionWorld,\n  pow,\n  select,\n  smoothstep,\n  texture,\n  uv,\n  vec2,\n} from 'three/tsl'\nimport { MeshBasicNodeMaterial, type Node } from 'three/webgpu'\nimport { towerNodeUniforms as U } from './city'\n\nconst rung = (r: Node<'vec2'>, t: Node<'float'>) => r.x.mul(pow(r.y.div(r.x), t))\nconst kitRung = (glow: Node<'float'>, t: Node<'float'>) =>\n  select(\n    glow.lessThan(1.5),\n    rung(U.sign, t),\n    select(glow.lessThan(2.5), rung(U.tube, t), rung(U.shop, t)),\n  )\n\nexport function kitNodeMaterials(atlas: DataTexture) {\n  const color = attribute<'vec4'>('aColor', 'vec4')\n  const kit = attribute<'vec4'>('aKit', 'vec4')\n  const dusk = mix(float(0.12), float(1), U.night)\n\n  const box = new MeshBasicNodeMaterial()\n  const shade = float(0.72).add(normalWorld.y.mul(0.28)).add(normalWorld.x.mul(0.1))\n  const matte = color.rgb\n    .mul(mix(float(0.35), U.wallGain, U.night))\n    .mul(shade)\n    .add(\n      U.glow\n        .mul(exp(max(positionWorld.y, 0).negate().div(6)))\n        .mul(U.night)\n        .mul(shade.mul(0.45).add(0.55)),\n    )\n  box.colorNode = select(\n    color.a.lessThan(0.5),\n    matte,\n    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),\n  )\n  box.fog = true\n\n  const glyph = new MeshBasicNodeMaterial()\n  const cell = vec2(mod(kit.y, 8), floor(kit.y.div(8)))\n  const at = vec2(cell.x.add(uv().x), cell.y.add(float(1).sub(uv().y))).div(8)\n  const tx = texture(atlas, at)\n  // Glow 0 is stencil paint: matte under the street light, like the wall it sits on.\n  const paint = color.rgb\n    .mul(mix(float(0.35), U.wallGain, U.night))\n    .add(U.glow.mul(U.night).mul(0.5))\n  glyph.colorNode = select(\n    color.a.lessThan(0.5),\n    paint,\n    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),\n  )\n  glyph.opacityNode = select(kit.z.lessThan(0.5), tx.r, select(kit.z.lessThan(1.5), tx.g, tx.b))\n  glyph.transparent = true\n  glyph.depthWrite = false\n  glyph.fog = true\n\n  // Light on the street: a half disc from the foot of the wall, added to what lies under it.\n  const splat = new MeshBasicNodeMaterial()\n  const reach = vec2(uv().x.sub(0.5).mul(2), float(1).sub(uv().y)).length()\n  const disc = float(1).sub(smoothstep(0, 1, reach))\n  splat.colorNode = color.rgb.mul(rung(U.street, kit.x)).mul(U.night).mul(disc.mul(disc))\n  splat.transparent = true\n  splat.blending = AdditiveBlending\n  splat.depthWrite = false\n  splat.fog = false\n  splat.polygonOffset = true\n  splat.polygonOffsetFactor = -2\n  splat.polygonOffsetUnits = -4\n  return { box, glyph, splat }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/city.ts",
      "content": "// The city's shared light as TSL uniforms, for the tower and kit node materials. They read\n// `towerLight` (city/towerLight.ts) each render, so the light a world sets reaches them without\n// a write of their own.\n\nimport { uniform } from 'three/tsl'\nimport { towerLight as T } from '../city/towerLight'\n\nexport const towerNodeUniforms = {\n  window: uniform(T.window),\n  shop: uniform(T.shop),\n  trim: uniform(T.trim).onRenderUpdate(() => T.trim),\n  sign: uniform(T.sign),\n  tube: uniform(T.tube),\n  street: uniform(T.street),\n  night: uniform(T.night).onRenderUpdate(() => T.night),\n  wallGain: uniform(T.wallGain).onRenderUpdate(() => T.wallGain),\n  glow: uniform(T.glow),\n}\n",
      "type": "registry:component"
    }
  ]
}
