{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "iso-lattice",
  "title": "Iso Lattice",
  "description": "A hex lattice of glowing tiles that builds solid isometric figures, one over the last, from the floor up. Follows light and dark.",
  "files": [
    {
      "path": "registry/iso-lattice/iso-lattice.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useRef } from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport type IsoLatticeTheme = \"light\" | \"dark\" | \"auto\"\n\n/** The figures the lattice can light up, all drawn in isometric. */\nexport type IsoLatticeShape = \"cube\" | \"steps\" | \"pillars\" | \"coil\"\n\nexport type IsoLatticeOptions = {\n  /**\n   * Figures to cycle through, in order. One figure holds still.\n   * Default `[\"cube\", \"steps\", \"pillars\", \"coil\"]`.\n   */\n  shapes?: IsoLatticeShape[]\n  /** Seconds each figure holds before the next one builds. Default `4`. */\n  interval?: number\n  /** Tile color, any CSS hex. Omit to follow the theme. */\n  color?: string\n  /** Figure size as a share of the shorter side, 0.2–1. Default `0.6`. */\n  size?: number\n  /** Distance between lattice tiles in CSS px, 4–24. Default `8`. */\n  spacing?: number\n  /** Halo behind the figure, 0–1. `0` turns it off. Default `0.6`. */\n  glow?: number\n  /** Speed of the glint and the shimmer. Default `1`. */\n  speed?: number\n  /** A faint isometric floor grid under the figure. Default `true`. */\n  floor?: boolean\n  /** The pointer lights the lattice like a lamp. Default `true`. */\n  interactive?: boolean\n  /**\n   * Palette mode. Default `auto` follows shadcn / next-themes\n   * (`html.dark` class) so light and dark swap with the site theme.\n   */\n  theme?: IsoLatticeTheme\n  /** Fires whenever resolved dark mode changes. */\n  onThemeChange?: (dark: boolean) => void\n}\n\nexport type IsoLatticeInstance = {\n  setOptions: (options: Partial<IsoLatticeOptions>) => void\n  destroy: () => void\n}\n\n/** Warm amber that glows on a dark page. */\nexport const DARK_COLOR = \"#FFB25B\"\n/** A burnt orange that holds its contrast on paper. */\nexport const LIGHT_COLOR = \"#C2560C\"\n\nexport const SHAPES: IsoLatticeShape[] = [\"cube\", \"steps\", \"pillars\", \"coil\"]\nexport const DEFAULT_INTERVAL = 4\nexport const DEFAULT_SIZE = 0.6\nexport const DEFAULT_SPACING = 8\nexport const DEFAULT_GLOW = 0.6\nexport const DEFAULT_SPEED = 1\n\n/** How long one figure takes to build over the last, in seconds. */\nconst MORPH_SECONDS = 1.6\n/** Each figure is drawn once into a square mask this many pixels wide. */\nconst MASK = 512\n/** Half the width of the mask in figure units; a figure's radius is 1. */\nconst EXTENT = 1.6\nconst COS30 = Math.cos(Math.PI / 6)\n\nconst VERT = `\nattribute vec2 a_position;\nvoid main() {\n  gl_Position = vec4(a_position, 0.0, 1.0);\n}\n`\n\nconst FRAG = `\nprecision highp float;\n\nuniform vec2 u_resolution;\nuniform vec2 u_center;\nuniform float u_radius;\nuniform float u_spacing;\nuniform float u_pixel;\n// Red is the figure, green its blurred halo, blue the floor grid.\nuniform sampler2D u_maskA;\nuniform sampler2D u_maskB;\nuniform float u_progress;\nuniform float u_time;\nuniform float u_sweep;\nuniform float u_glow;\nuniform float u_floor;\nuniform vec2 u_mouse;\nuniform float u_pointer;\nuniform float u_dark;\nuniform vec3 u_color;\nuniform vec3 u_deep;\nuniform vec3 u_hot;\n\nconst float SQ3 = 1.7320508;\nconst float EXTENT = ${EXTENT.toFixed(2)};\n\n// Dave Hoskins' hash: no sin(), so it stays stable on mobile GPUs.\nfloat hash(vec2 p) {\n  vec3 p3 = fract(vec3(p.xyx) * 0.1031);\n  p3 += dot(p3, p3.yzx + 33.33);\n  return fract((p3.x + p3.y) * p3.z);\n}\n\nvec2 toUv(vec2 q) {\n  return vec2(q.x, -q.y) / (2.0 * EXTENT) + 0.5;\n}\n\nvec2 sampleShape(vec2 q, float k) {\n  vec2 uv = toUv(q);\n  return mix(texture2D(u_maskA, uv).rg, texture2D(u_maskB, uv).rg, k);\n}\n\n// Whether a whole tile fits on the figure: its four tips, pulled in a touch,\n// must all land on it. A cell whose centre is inside but whose tips are not\n// would poke past the silhouette as a ragged half-lit column.\nfloat fits(sampler2D mask, vec2 q, vec2 tip) {\n  float c = 1.0;\n  c = min(c, texture2D(mask, toUv(q + vec2(tip.x, 0.0))).r);\n  c = min(c, texture2D(mask, toUv(q - vec2(tip.x, 0.0))).r);\n  c = min(c, texture2D(mask, toUv(q + vec2(0.0, tip.y))).r);\n  c = min(c, texture2D(mask, toUv(q - vec2(0.0, tip.y))).r);\n  return step(0.08, c);\n}\n\nvoid main() {\n  vec2 frag = gl_FragCoord.xy;\n\n  // Hex lattice in vertical columns, so its rows run at 30 degrees, the\n  // same angles as an isometric edge. Each pixel finds its nearest cell.\n  vec2 p = frag - 0.5 * u_resolution;\n  vec2 period = vec2(SQ3, 1.0) * u_spacing;\n  vec2 a = mod(p, period) - 0.5 * period;\n  vec2 b = mod(p - 0.5 * period, period) - 0.5 * period;\n  vec2 off = dot(a, a) < dot(b, b) ? a : b;\n  vec2 cell = p - off;\n  vec2 id = floor(cell / (0.5 * period) + 0.5);\n\n  vec2 cellPx = cell + 0.5 * u_resolution;\n  vec2 q = (cellPx - u_center) / u_radius;\n\n  // The next figure builds from the floor up: each cell turns over when the\n  // build front passes its height, give or take a little.\n  float rise = clamp((q.y + 1.3) / 2.6, 0.0, 1.0);\n  float delay = 0.62 * rise + 0.08 * hash(id);\n  float k = smoothstep(0.0, 1.0, clamp((u_progress - delay) / 0.3, 0.0, 1.0));\n  vec3 shapeA = texture2D(u_maskA, toUv(q)).rgb;\n  vec3 shapeB = texture2D(u_maskB, toUv(q)).rgb;\n  // The mask's soft outline would leave half-strength specks along every\n  // edge; a cell is either on the figure or off it, and only when the whole\n  // tile (at full size, so the call never depends on brightness) fits.\n  vec2 tip = vec2(1.0, 1.0 / SQ3) * u_spacing * 0.866 * 0.84 * 0.85 / u_radius;\n  shapeA.r *= smoothstep(0.12, 0.26, shapeA.r) * fits(u_maskA, q, tip);\n  shapeB.r *= smoothstep(0.12, 0.26, shapeB.r) * fits(u_maskB, q, tip);\n  float m = mix(shapeA.r, shapeB.r, k);\n  // The build front burns brighter as it passes.\n  float flare = 4.0 * k * (1.0 - k) * max(shapeA.r, shapeB.r);\n\n  // A level band of light rises through the figure, then rests.\n  float glint = exp(-pow((q.y - u_sweep) / 0.14, 2.0));\n  float shimmer = 0.93 + 0.07 * sin(u_time * (1.1 + 1.6 * hash(id + 7.1)) + 6.2832 * hash(id + 3.7));\n\n  // The pointer is a lamp: it raises the bare lattice and the figure under it.\n  vec2 lamp = (cellPx - u_mouse) / (150.0 * u_pixel);\n  float lit = exp(-dot(lamp, lamp)) * u_pointer;\n\n  // Size follows only what the figure is, so tiles never pulse in and out;\n  // the shimmer, the glint and the build front change light, not size.\n  float floorLevel = shapeA.b * u_floor;\n  float body = max(m, floorLevel) + lit * (0.14 + 0.3 * m);\n  float level = max(m * shimmer * (1.0 + 0.6 * glint) + 0.7 * flare, floorLevel);\n  level += lit * (0.14 + 0.45 * m);\n\n  // Each cell is an isometric diamond; at full strength neighbours meet, so\n  // lit faces read as solid tiles and dim ones break into a dotted grain.\n  float fill = clamp(body, 0.0, 1.0);\n  float w = u_spacing * 0.866 * mix(0.2, 0.84, sqrt(fill));\n  float n = abs(off.x) + abs(off.y) * SQ3;\n  float dotA = 1.0 - smoothstep(w - 0.9, w + 0.9, n);\n  dotA *= smoothstep(0.015, 0.08, body);\n  dotA *= mix(0.35, 1.0, smoothstep(0.0, 0.7, clamp(level, 0.0, 1.0)));\n  vec3 dotC = mix(u_deep, u_color, smoothstep(0.0, 0.8, level));\n  dotC = mix(dotC, u_hot, smoothstep(0.85, 1.6, level));\n\n  // Halo: the blurred figure where this pixel sits, plus a broad wash.\n  vec2 qp = (frag - u_center) / u_radius;\n  float halo = sampleShape(qp, u_progress).g;\n  float wash = exp(-dot(qp, qp) * 0.8);\n  float glowA = u_glow * (halo * mix(0.18, 0.5, u_dark) + wash * mix(0.04, 0.16, u_dark));\n  // Interleaved gradient noise, half a step, so the dark falloff never bands.\n  float ign = fract(52.9829189 * fract(dot(frag, vec2(0.06711056, 0.00583715))));\n  glowA = clamp(glowA + (ign - 0.5) / 255.0, 0.0, 1.0);\n\n  // Dot over halo, premultiplied for a transparent canvas.\n  float outA = dotA + glowA * (1.0 - dotA);\n  vec3 outC = dotC * dotA + u_color * glowA * (1.0 - dotA);\n  gl_FragColor = vec4(outC, outA);\n}\n`\n\ntype Ctx = CanvasRenderingContext2D\ntype Point = [number, number]\n\n/** Isometric projection: x runs down-right, z down-left, y straight up. */\nfunction iso(x: number, y: number, z: number): Point {\n  return [(x - z) * COS30, y - (x + z) * 0.5]\n}\n\nfunction gray(level: number) {\n  const v = Math.round(clamp(level, 0, 1) * 255)\n  return `rgb(${v},${v},${v})`\n}\n\nfunction polyline(ctx: Ctx, points: Point[], close = false) {\n  ctx.beginPath()\n  points.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y)))\n  if (close) ctx.closePath()\n}\n\nfunction stroke(ctx: Ctx, points: Point[], level: number, width: number) {\n  polyline(ctx, points)\n  ctx.strokeStyle = gray(level)\n  ctx.lineWidth = width\n  ctx.stroke()\n}\n\nfunction fill(ctx: Ctx, points: Point[], level: number) {\n  polyline(ctx, points, true)\n  ctx.fillStyle = gray(level)\n  ctx.fill()\n}\n\n/** Every figure stands on this floor. */\nconst FLOOR = -0.4\n\n/**\n * A solid box lit from above: bright top, half-lit left, shaded right, with\n * the near edges picked out. Draw far boxes first; nearer ones cover them.\n */\nfunction box(ctx: Ctx, [x0, x1]: Point, [y0, y1]: Point, [z0, z1]: Point) {\n  ctx.globalCompositeOperation = \"source-over\"\n  // Butt caps: a round cap pokes past the corner as a stray tile.\n  ctx.lineCap = \"butt\"\n  ctx.lineJoin = \"round\"\n  fill(\n    ctx,\n    [iso(x1, y1, z1), iso(x0, y1, z1), iso(x0, y0, z1), iso(x1, y0, z1)],\n    0.6\n  )\n  fill(\n    ctx,\n    [iso(x1, y1, z1), iso(x1, y1, z0), iso(x1, y0, z0), iso(x1, y0, z1)],\n    0.42\n  )\n  fill(\n    ctx,\n    [iso(x1, y1, z1), iso(x1, y1, z0), iso(x0, y1, z0), iso(x0, y1, z1)],\n    0.78\n  )\n  stroke(ctx, [iso(x0, y1, z1), iso(x1, y1, z1), iso(x1, y1, z0)], 1, 0.035)\n  stroke(ctx, [iso(x1, y1, z1), iso(x1, y0, z1)], 0.7, 0.035)\n}\n\n/** One solid cube, a unit tall. */\nfunction drawCube(ctx: Ctx) {\n  box(ctx, [-0.5, 0.5], [FLOOR, FLOOR + 1], [-0.5, 0.5])\n}\n\n/** Four steps climbing away from the viewer. */\nfunction drawSteps(ctx: Ctx) {\n  for (let i = 3; i >= 0; i--) {\n    const near = 0.5 - i * 0.25\n    box(ctx, [-0.5, 0.5], [FLOOR, FLOOR + (i + 1) * 0.25], [near - 0.25, near])\n  }\n}\n\n/** A three-by-three bar chart; heights are fixed so it reads as data. */\nfunction drawPillars(ctx: Ctx) {\n  const heights = [\n    [0.35, 0.6, 1],\n    [0.55, 0.85, 0.45],\n    [0.9, 0.3, 0.65],\n  ]\n  const cells: Array<[number, number, number]> = []\n  for (let i = 0; i < 3; i++) {\n    for (let j = 0; j < 3; j++) {\n      cells.push([(i - 1) * 0.34, (j - 1) * 0.34, heights[i]![j]!])\n    }\n  }\n  // Painter's order: the far corner of the grid first.\n  cells.sort((a, b) => a[0] + a[1] - (b[0] + b[1]))\n  const half = 0.13\n  for (const [x, z, height] of cells) {\n    box(\n      ctx,\n      [x - half, x + half],\n      [FLOOR, FLOOR + height],\n      [z - half, z + half]\n    )\n  }\n}\n\n/** A coil rising off the floor; the near side of each turn is the bright one. */\nfunction drawCoil(ctx: Ctx) {\n  ctx.globalCompositeOperation = \"source-over\"\n  ctx.lineCap = \"round\"\n  const turns = 3.5\n  const steps = 280\n  const radius = 0.5\n  const points: Array<[Point, number]> = []\n  for (let i = 0; i <= steps; i++) {\n    const t = (i / steps) * turns * Math.PI * 2\n    const x = radius * Math.cos(t)\n    const z = radius * Math.sin(t)\n    const y = FLOOR + 0.06 + (i / steps) * 0.92\n    points.push([iso(x, y, z), x + z])\n  }\n  polyline(ctx, ellipse(radius + 0.1, FLOOR), true)\n  ctx.strokeStyle = gray(0.22)\n  ctx.lineWidth = 0.04\n  ctx.stroke()\n  // Far half first, then the near half over it.\n  for (const near of [false, true]) {\n    for (let i = 1; i < points.length; i++) {\n      const [a, depth] = points[i - 1]!\n      const [b] = points[i]!\n      if (depth > 0 !== near) continue\n      stroke(ctx, [a, b], near ? 1 : 0.38, 0.085)\n    }\n  }\n}\n\n/** A flat circle on the floor plane, as a projected outline. */\nfunction ellipse(radius: number, y: number): Point[] {\n  const out: Point[] = []\n  for (let i = 0; i < 96; i++) {\n    const t = (i / 96) * Math.PI * 2\n    out.push(iso(radius * Math.cos(t), y, radius * Math.sin(t)))\n  }\n  return out\n}\n\n/** A faint floor tile with a coarse grid, the same under every figure. */\nfunction drawFloor(ctx: Ctx) {\n  const r = 0.8\n  ctx.globalCompositeOperation = \"source-over\"\n  fill(\n    ctx,\n    [\n      iso(r, FLOOR, r),\n      iso(r, FLOOR, -r),\n      iso(-r, FLOOR, -r),\n      iso(-r, FLOOR, r),\n    ],\n    0.05\n  )\n  for (let i = -2; i <= 2; i++) {\n    const v = (i / 2) * r\n    // Wide enough that every grid line lands on a full row of cells.\n    stroke(ctx, [iso(v, FLOOR, -r), iso(v, FLOOR, r)], 0.15, 0.07)\n    stroke(ctx, [iso(-r, FLOOR, v), iso(r, FLOOR, v)], 0.15, 0.07)\n  }\n}\n\nconst DRAW: Record<IsoLatticeShape, (ctx: Ctx) => void> = {\n  cube: drawCube,\n  steps: drawSteps,\n  pillars: drawPillars,\n  coil: drawCoil,\n}\n\n/** Box-blurs by halving and growing back, where `ctx.filter` is missing. */\nfunction softBlur(source: HTMLCanvasElement, into: Ctx) {\n  let current = source\n  for (let size = MASK / 2; size >= MASK / 16; size /= 2) {\n    const next = document.createElement(\"canvas\")\n    next.width = next.height = size\n    const ctx = next.getContext(\"2d\")!\n    ctx.imageSmoothingQuality = \"high\"\n    ctx.drawImage(current, 0, 0, size, size)\n    current = next\n  }\n  into.imageSmoothingQuality = \"high\"\n  into.drawImage(current, 0, 0, MASK, MASK)\n}\n\n// Figures don't depend on color or theme, so every instance shares them.\nconst maskCache = new Map<IsoLatticeShape, Uint8Array>()\n\n/** A black square canvas set up in figure units: y up, origin centered. */\nfunction figureCanvas(draw: (ctx: Ctx) => void) {\n  const canvas = document.createElement(\"canvas\")\n  canvas.width = canvas.height = MASK\n  const ctx = canvas.getContext(\"2d\", { willReadFrequently: true })!\n  ctx.fillStyle = \"#000\"\n  ctx.fillRect(0, 0, MASK, MASK)\n  const unit = MASK / (2 * EXTENT)\n  ctx.setTransform(unit, 0, 0, -unit, MASK / 2, MASK / 2)\n  draw(ctx)\n  ctx.setTransform(1, 0, 0, 1, 0, 0)\n  return { canvas, ctx }\n}\n\nlet floorPixels: Uint8ClampedArray | null = null\n\n/**\n * Draws a figure once: red is the crisp figure, green a soft halo, blue the\n * floor grid (the same in every mask, so it never changes in a build).\n */\nfunction renderMask(shape: IsoLatticeShape): Uint8Array {\n  const cached = maskCache.get(shape)\n  if (cached) return cached\n\n  const { canvas: sharp, ctx } = figureCanvas(DRAW[shape])\n  floorPixels ??= figureCanvas(drawFloor).ctx.getImageData(\n    0,\n    0,\n    MASK,\n    MASK\n  ).data\n\n  const soft = document.createElement(\"canvas\")\n  soft.width = soft.height = MASK\n  const sctx = soft.getContext(\"2d\", { willReadFrequently: true })!\n  sctx.fillStyle = \"#000\"\n  sctx.fillRect(0, 0, MASK, MASK)\n  if (typeof sctx.filter === \"string\") {\n    sctx.filter = `blur(${MASK / 36}px)`\n    sctx.drawImage(sharp, 0, 0)\n  } else {\n    softBlur(sharp, sctx)\n  }\n\n  const a = ctx.getImageData(0, 0, MASK, MASK).data\n  const b = sctx.getImageData(0, 0, MASK, MASK).data\n  const out = new Uint8Array(MASK * MASK * 4)\n  for (let i = 0; i < out.length; i += 4) {\n    out[i] = a[i]!\n    out[i + 1] = b[i]!\n    out[i + 2] = floorPixels[i]!\n    out[i + 3] = 255\n  }\n  maskCache.set(shape, out)\n  return out\n}\n\nfunction isDev() {\n  return (\n    typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n  )\n}\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, value))\n}\n\nfunction numberOr(value: unknown, fallback: number, min: number, max: number) {\n  if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback\n  return clamp(value, min, max)\n}\n\nfunction hexToRgb(hex: string): [number, number, number] {\n  const h = hex.replace(\"#\", \"\").trim()\n  const full =\n    h.length === 3\n      ? h\n          .split(\"\")\n          .map((c) => c + c)\n          .join(\"\")\n      : h.padEnd(6, \"0\").slice(0, 6)\n  const n = Number.parseInt(full, 16)\n  if (Number.isNaN(n)) return [1, 0.7, 0.36]\n  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]\n}\n\nfunction mixRgb(\n  a: [number, number, number],\n  b: [number, number, number],\n  t: number\n): [number, number, number] {\n  return [\n    a[0] + (b[0] - a[0]) * t,\n    a[1] + (b[1] - a[1]) * t,\n    a[2] + (b[2] - a[2]) * t,\n  ]\n}\n\nfunction shapesOf(value: unknown): IsoLatticeShape[] {\n  if (!Array.isArray(value)) return SHAPES\n  const valid = value.filter((s): s is IsoLatticeShape => s in DRAW)\n  return valid.length ? valid : SHAPES\n}\n\n/** Resolves shadcn / next-themes dark mode (`attribute=\"class\"` → `html.dark`). */\nexport function isDarkTheme(): boolean {\n  if (typeof document === \"undefined\") return false\n  const root = document.documentElement\n  if (root.classList.contains(\"dark\")) return true\n  if (root.classList.contains(\"light\")) return false\n  const dataTheme = root.getAttribute(\"data-theme\")\n  if (dataTheme === \"dark\") return true\n  if (dataTheme === \"light\") return false\n  return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n}\n\nexport function resolveDark(theme: IsoLatticeTheme): boolean {\n  if (theme === \"dark\") return true\n  if (theme === \"light\") return false\n  return isDarkTheme()\n}\n\nfunction compile(gl: WebGLRenderingContext, type: number, source: string) {\n  const shader = gl.createShader(type)\n  if (!shader) return null\n  gl.shaderSource(shader, source)\n  gl.compileShader(shader)\n  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n    if (isDev()) {\n      console.warn(\n        \"IsoLattice: shader failed to compile\\n\",\n        gl.getShaderInfoLog(shader)\n      )\n    }\n    gl.deleteShader(shader)\n    return null\n  }\n  return shader\n}\n\n/**\n * A lattice of isometric tiles that lights up solid figures (a cube, a\n * staircase, a bar chart, a coil) on a faint floor grid, and builds each\n * one over the last from the floor up. A level glint rises through the\n * figure, and the pointer lights the lattice like a lamp. Transparent, theme-aware; pauses\n * off-screen and in hidden tabs; holds the first figure still under\n * `prefers-reduced-motion`. Recovers from a lost WebGL context.\n */\nexport function createIsoLattice(\n  canvas: HTMLCanvasElement,\n  initial: IsoLatticeOptions = {}\n): IsoLatticeInstance | null {\n  let options: IsoLatticeOptions = {\n    floor: true,\n    interactive: true,\n    theme: \"auto\",\n    ...initial,\n  }\n\n  const mouse = { x: 0, y: 0 }\n  const target = { x: 0, y: 0 }\n  // The lamp eases in and out, so leaving the canvas never snaps it off.\n  let lamp = 0\n  let lampTarget = 0\n  let dark = resolveDark(options.theme ?? \"auto\")\n  options.onThemeChange?.(dark)\n\n  const gl = canvas.getContext(\"webgl\", {\n    alpha: true,\n    premultipliedAlpha: true,\n    antialias: false,\n    depth: false,\n    stencil: false,\n    powerPreference: \"high-performance\",\n  })\n  if (!gl) return null\n\n  type Loc = WebGLUniformLocation | null\n  let vs: WebGLShader | null = null\n  let fs: WebGLShader | null = null\n  let program: WebGLProgram | null = null\n  let buf: WebGLBuffer | null = null\n  let textures = new Map<IsoLatticeShape, WebGLTexture>()\n  const u: Record<string, Loc> = {}\n\n  const texture = (shape: IsoLatticeShape) => {\n    const existing = textures.get(shape)\n    if (existing) return existing\n    const tex = gl.createTexture()!\n    gl.bindTexture(gl.TEXTURE_2D, tex)\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n    gl.texImage2D(\n      gl.TEXTURE_2D,\n      0,\n      gl.RGBA,\n      MASK,\n      MASK,\n      0,\n      gl.RGBA,\n      gl.UNSIGNED_BYTE,\n      renderMask(shape)\n    )\n    textures.set(shape, tex)\n    return tex\n  }\n\n  // Builds every GL resource. Runs at startup and again when the browser\n  // restores a lost context, since the old objects die with it.\n  const initGl = () => {\n    vs = compile(gl, gl.VERTEX_SHADER, VERT)\n    fs = compile(gl, gl.FRAGMENT_SHADER, FRAG)\n    if (!vs || !fs) {\n      if (vs) gl.deleteShader(vs)\n      if (fs) gl.deleteShader(fs)\n      return false\n    }\n\n    program = gl.createProgram()\n    if (!program) {\n      gl.deleteShader(vs)\n      gl.deleteShader(fs)\n      return false\n    }\n    gl.attachShader(program, vs)\n    gl.attachShader(program, fs)\n    gl.linkProgram(program)\n    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n      if (isDev()) {\n        console.warn(\n          \"IsoLattice: program failed to link\\n\",\n          gl.getProgramInfoLog(program)\n        )\n      }\n      gl.deleteProgram(program)\n      gl.deleteShader(vs)\n      gl.deleteShader(fs)\n      return false\n    }\n    gl.useProgram(program)\n\n    buf = gl.createBuffer()\n    gl.bindBuffer(gl.ARRAY_BUFFER, buf)\n    gl.bufferData(\n      gl.ARRAY_BUFFER,\n      new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),\n      gl.STATIC_DRAW\n    )\n    const loc = gl.getAttribLocation(program, \"a_position\")\n    gl.enableVertexAttribArray(loc)\n    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0)\n    gl.viewport(0, 0, canvas.width, canvas.height)\n\n    const linked = program\n    for (const name of [\n      \"resolution\",\n      \"center\",\n      \"radius\",\n      \"spacing\",\n      \"pixel\",\n      \"maskA\",\n      \"maskB\",\n      \"progress\",\n      \"time\",\n      \"sweep\",\n      \"glow\",\n      \"floor\",\n      \"mouse\",\n      \"pointer\",\n      \"dark\",\n      \"color\",\n      \"deep\",\n      \"hot\",\n    ]) {\n      u[name] = gl.getUniformLocation(linked, `u_${name}`)\n    }\n    gl.uniform1i(u.maskA!, 0)\n    gl.uniform1i(u.maskB!, 1)\n    textures = new Map()\n    return true\n  }\n  if (!initGl()) return null\n\n  let pixel = 1\n  /**\n   * Sizes the canvas to its parent; true when the backing store changed.\n   * Assigning the same size still clears the canvas, so it only assigns on\n   * a real change.\n   */\n  const resize = () => {\n    const parent = canvas.parentElement\n    if (!parent) return false\n    const w = parent.clientWidth\n    const h = parent.clientHeight\n    if (w <= 0 || h <= 0) return false\n    pixel = Math.min(window.devicePixelRatio || 1, 2)\n    const width = Math.max(1, Math.floor(w * pixel))\n    const height = Math.max(1, Math.floor(h * pixel))\n    if (canvas.width === width && canvas.height === height) return false\n    canvas.width = width\n    canvas.height = height\n    canvas.style.width = `${w}px`\n    canvas.style.height = `${h}px`\n    gl.viewport(0, 0, canvas.width, canvas.height)\n    wake()\n    return true\n  }\n\n  let colorKey = \"\"\n  const syncColor = () => {\n    const hex = options.color || (dark ? DARK_COLOR : LIGHT_COLOR)\n    const key = `${hex}|${dark}`\n    if (key === colorKey) return\n    colorKey = key\n    const base = hexToRgb(hex)\n    const white: [number, number, number] = [1, 1, 1]\n    const black: [number, number, number] = [0, 0, 0]\n    // Dim dots sink toward the page; hot dots move away from it.\n    const deep = mixRgb(base, dark ? black : white, 0.55)\n    const hot = mixRgb(base, dark ? white : black, dark ? 0.62 : 0.5)\n    gl.uniform3fv(u.color!, base)\n    gl.uniform3fv(u.deep!, deep)\n    gl.uniform3fv(u.hot!, hot)\n    gl.uniform1f(u.dark!, dark ? 1 : 0)\n  }\n\n  // Which figure is showing, and how far the morph to the next one has got.\n  let shapes = shapesOf(options.shapes)\n  let index = 0\n  let held = 0\n  let progress = 0\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  let onScreen = true\n  let raf = 0\n  let destroyed = false\n  let lost = false\n  let last = 0\n  let clock = 0\n\n  const moving = () =>\n    onScreen && !mqReduce.matches && document.visibilityState !== \"hidden\"\n\n  function wake() {\n    // An observer callback can still arrive after destroy.\n    if (raf || destroyed || lost) return\n    last = performance.now()\n    raf = requestAnimationFrame(tick)\n  }\n\n  /** Draws in place now, without advancing; the tick carries on if live. */\n  function redraw() {\n    if (destroyed || lost) return\n    cancelAnimationFrame(raf)\n    raf = 0\n    last = performance.now()\n    tick(last)\n  }\n\n  const advance = (dt: number) => {\n    if (shapes.length < 2) {\n      progress = 0\n      return\n    }\n    if (\n      progress > 0 ||\n      held >= numberOr(options.interval, DEFAULT_INTERVAL, 0.5, 60)\n    ) {\n      progress += dt / MORPH_SECONDS\n      if (progress >= 1) {\n        index = (index + 1) % shapes.length\n        progress = 0\n        held = 0\n      }\n    } else {\n      held += dt\n    }\n  }\n\n  // An arrow, not a declaration, so TypeScript keeps `gl` narrowed inside.\n  const tick = (now: number) => {\n    raf = 0\n    if (lost) return\n    const dt = Math.min(0.1, Math.max(0, (now - last) / 1000))\n    last = now\n    const live = moving()\n    const speed = numberOr(options.speed, DEFAULT_SPEED, 0, 4)\n    if (live) {\n      clock += dt * speed\n      advance(dt)\n    }\n    // Under reduced motion the first figure holds, with no lamp.\n    const still = mqReduce.matches\n    if (still) {\n      index = 0\n      progress = 0\n    }\n\n    const ease = 1 - Math.exp(-dt * 6)\n    mouse.x += (target.x - mouse.x) * ease\n    mouse.y += (target.y - mouse.y) * ease\n    lamp += (lampTarget - lamp) * (1 - Math.exp(-dt * 3))\n\n    syncColor()\n    const w = canvas.width\n    const h = canvas.height\n    const radius =\n      (numberOr(options.size, DEFAULT_SIZE, 0.2, 1) * Math.min(w, h)) / 2\n    const pointer = options.interactive === false || still ? 0 : lamp\n    // The figure stays put: any drift would slide it across the lattice and\n    // make the tiles along its edges blink.\n    const cx = w / 2\n    const cy = h / 2\n\n    gl.activeTexture(gl.TEXTURE0)\n    gl.bindTexture(gl.TEXTURE_2D, texture(shapes[index % shapes.length]!))\n    gl.activeTexture(gl.TEXTURE1)\n    gl.bindTexture(gl.TEXTURE_2D, texture(shapes[(index + 1) % shapes.length]!))\n\n    gl.uniform2f(u.resolution!, w, h)\n    gl.uniform2f(u.center!, cx, cy)\n    gl.uniform1f(u.radius!, radius)\n    gl.uniform1f(\n      u.spacing!,\n      numberOr(options.spacing, DEFAULT_SPACING, 4, 24) * pixel\n    )\n    gl.uniform1f(u.pixel!, pixel)\n    gl.uniform1f(u.progress!, progress)\n    gl.uniform1f(u.time!, clock)\n    // The glint rises through the figure, then rests above it a while.\n    gl.uniform1f(u.sweep!, still ? -9 : -1.6 + 4.2 * ((clock / 4.2) % 1))\n    gl.uniform1f(u.glow!, numberOr(options.glow, DEFAULT_GLOW, 0, 1))\n    gl.uniform1f(u.floor!, options.floor === false ? 0 : 1)\n    gl.uniform2f(u.mouse!, mouse.x, mouse.y)\n    gl.uniform1f(u.pointer!, pointer)\n    gl.clearColor(0, 0, 0, 0)\n    gl.clear(gl.COLOR_BUFFER_BIT)\n    gl.drawArrays(gl.TRIANGLES, 0, 6)\n\n    const settling = Math.abs(lampTarget - lamp) > 0.002\n    if (live || (settling && !still)) raf = requestAnimationFrame(tick)\n  }\n\n  // A GPU reset, a driver update or too many live contexts can drop ours.\n  // preventDefault asks the browser to restore it; until then gl is off limits.\n  const onLost = (e: Event) => {\n    e.preventDefault()\n    lost = true\n    cancelAnimationFrame(raf)\n    raf = 0\n    vs = fs = program = buf = null\n    textures = new Map()\n  }\n  const onRestored = () => {\n    if (destroyed || !initGl()) return\n    lost = false\n    // Uniforms reset with the context, so the colors go up again.\n    colorKey = \"\"\n    wake()\n  }\n  canvas.addEventListener(\"webglcontextlost\", onLost)\n  canvas.addEventListener(\"webglcontextrestored\", onRestored)\n\n  // Resizing cleared the canvas; draw now, or it shows blank for a frame.\n  const ro = new ResizeObserver(() => {\n    if (resize()) redraw()\n  })\n  if (canvas.parentElement) ro.observe(canvas.parentElement)\n  const io = new IntersectionObserver(([entry]) => {\n    onScreen = entry?.isIntersecting ?? true\n    wake()\n  })\n  io.observe(canvas)\n  const onVisibility = () => wake()\n  document.addEventListener(\"visibilitychange\", onVisibility)\n  const onReduce = () => wake()\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  const syncTheme = () => {\n    const next = resolveDark(options.theme ?? \"auto\")\n    if (next === dark) return\n    dark = next\n    options.onThemeChange?.(dark)\n    wake()\n  }\n  const mo = new MutationObserver(syncTheme)\n  mo.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: [\"class\", \"data-theme\", \"style\"],\n  })\n  const mqDark = window.matchMedia(\"(prefers-color-scheme: dark)\")\n  mqDark.addEventListener(\"change\", syncTheme)\n\n  const onMove = (e: PointerEvent) => {\n    if (options.interactive === false) return\n    const rect = canvas.getBoundingClientRect()\n    if (rect.width <= 0 || rect.height <= 0) return\n    const x = (e.clientX - rect.left) / rect.width\n    const y = 1 - (e.clientY - rect.top) / rect.height\n    const inside = x >= 0 && x <= 1 && y >= 0 && y <= 1\n    if (inside) {\n      // The first touch puts the lamp where the pointer is, not at a corner.\n      if (lamp < 0.01) {\n        mouse.x = x * canvas.width\n        mouse.y = y * canvas.height\n      }\n      target.x = x * canvas.width\n      target.y = y * canvas.height\n    }\n    const next = inside ? 1 : 0\n    if (next !== lampTarget) {\n      lampTarget = next\n      wake()\n    }\n  }\n  const onLeave = () => {\n    lampTarget = 0\n    wake()\n  }\n  window.addEventListener(\"pointermove\", onMove, { passive: true })\n  document.documentElement.addEventListener(\"pointerleave\", onLeave)\n\n  resize()\n  wake()\n\n  return {\n    setOptions(next) {\n      options = { ...options, ...next }\n      const nextShapes = shapesOf(options.shapes)\n      if (nextShapes.join() !== shapes.join()) {\n        shapes = nextShapes\n        index = 0\n        held = 0\n        progress = 0\n      }\n      syncTheme()\n      wake()\n    },\n    destroy() {\n      destroyed = true\n      cancelAnimationFrame(raf)\n      raf = 0\n      ro.disconnect()\n      io.disconnect()\n      mo.disconnect()\n      document.removeEventListener(\"visibilitychange\", onVisibility)\n      mqReduce.removeEventListener(\"change\", onReduce)\n      mqDark.removeEventListener(\"change\", syncTheme)\n      window.removeEventListener(\"pointermove\", onMove)\n      document.documentElement.removeEventListener(\"pointerleave\", onLeave)\n      canvas.removeEventListener(\"webglcontextlost\", onLost)\n      canvas.removeEventListener(\"webglcontextrestored\", onRestored)\n      for (const tex of textures.values()) gl.deleteTexture(tex)\n      textures.clear()\n      gl.deleteProgram(program)\n      gl.deleteShader(vs)\n      gl.deleteShader(fs)\n      gl.deleteBuffer(buf)\n      // Free the GPU context once the canvas has left the page; browsers cap\n      // live contexts at about 16. A canvas still in the page (a React\n      // Strict Mode replay) keeps it, so a new engine can reuse it.\n      const lose = gl.getExtension(\"WEBGL_lose_context\")\n      queueMicrotask(() => {\n        if (!canvas.isConnected && !gl.isContextLost()) lose?.loseContext()\n      })\n    },\n  }\n}\n\nexport type IsoLatticeProps = Omit<IsoLatticeOptions, \"onThemeChange\"> & {\n  className?: string\n}\n\n/**\n * A lattice of glowing isometric tiles that builds solid figures, one over\n * the last, from the floor up. Transparent; theme-aware.\n */\nexport function IsoLattice({\n  className,\n  shapes = SHAPES,\n  interval = DEFAULT_INTERVAL,\n  color,\n  size = DEFAULT_SIZE,\n  spacing = DEFAULT_SPACING,\n  glow = DEFAULT_GLOW,\n  speed = DEFAULT_SPEED,\n  floor = true,\n  interactive = true,\n  theme = \"auto\",\n}: IsoLatticeProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null)\n  const instanceRef = useRef<IsoLatticeInstance | null>(null)\n\n  useEffect(() => {\n    const canvas = canvasRef.current\n    if (!canvas) return\n    instanceRef.current = createIsoLattice(canvas, {\n      shapes,\n      interval,\n      color,\n      size,\n      spacing,\n      glow,\n      speed,\n      floor,\n      interactive,\n      theme,\n    })\n    return () => {\n      instanceRef.current?.destroy()\n      instanceRef.current = null\n    }\n    // Engine reads live options via setOptions; mount once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  useEffect(() => {\n    instanceRef.current?.setOptions({\n      shapes,\n      interval,\n      color,\n      size,\n      spacing,\n      glow,\n      speed,\n      floor,\n      interactive,\n      theme,\n    })\n  }, [\n    shapes,\n    interval,\n    color,\n    size,\n    spacing,\n    glow,\n    speed,\n    floor,\n    interactive,\n    theme,\n  ])\n\n  return (\n    <div\n      data-slot=\"iso-lattice\"\n      aria-hidden\n      className={cn(\n        \"pointer-events-none absolute inset-0 overflow-hidden\",\n        className\n      )}\n    >\n      <canvas ref={canvasRef} className=\"absolute inset-0 size-full\" />\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/iso-lattice.tsx"
    }
  ],
  "type": "registry:ui"
}