{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "topography",
  "title": "Topography",
  "description": "Contour lines like a topographic map over slowly shifting terrain, from one WebGL2 shader.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-in-view"
  ],
  "files": [
    {
      "path": "registry/default/ui/topography.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useMemo, useRef, type ComponentProps, type Ref } from \"react\";\nimport { useInView } from \"@/registry/default/hooks/use-in-view\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\nconst VERTEX = `#version 300 es\nin vec2 a_position;\nvoid main() { gl_Position = vec4(a_position, 0.0, 1.0); }`;\n\n// A height field from layered gradient noise, cut into evenly spaced\n// levels. Each level is drawn where the field crosses it; fwidth turns the\n// distance to the level into pixels, so lines keep one width everywhere.\nconst FRAGMENT = `#version 300 es\nprecision highp float;\nuniform vec2 u_size;\nuniform float u_dpr;\nuniform float u_clock;\nuniform float u_scale;\nuniform float u_density;\nuniform float u_thickness;\nuniform float u_index;\nuniform float u_opacity;\nuniform vec4 u_color;\nuniform vec2 u_pointer;\nuniform float u_pull;\nout vec4 outColor;\n\nfloat hash(vec2 cell) {\n  return fract(sin(dot(cell, vec2(41.37, 289.13))) * 17853.217);\n}\n\n// The corner's random slope, followed from the corner to the point.\nfloat lean(vec2 cell, vec2 offset) {\n  float angle = 6.2831853 * hash(cell);\n  return dot(vec2(cos(angle), sin(angle)), offset);\n}\n\n// Gradient noise with quintic fades, roughly -0.7 to 0.7.\nfloat noise(vec2 p) {\n  vec2 cell = floor(p);\n  vec2 f = p - cell;\n  vec2 fade = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);\n  float bottom = mix(lean(cell, f), lean(cell + vec2(1.0, 0.0), f - vec2(1.0, 0.0)), fade.x);\n  float top = mix(lean(cell + vec2(0.0, 1.0), f - vec2(0.0, 1.0)), lean(cell + 1.0, f - 1.0), fade.x);\n  return mix(bottom, top, fade.y);\n}\n\n// Each layer is finer, fainter and turned, so the layers never line up.\nconst mat2 TURN = mat2(0.8776, 0.4794, -0.4794, 0.8776);\n\nfloat layered(vec2 p) {\n  float sum = 0.0;\n  float weight = 0.5;\n  for (int i = 0; i < 4; i++) {\n    sum += weight * noise(p);\n    p = TURN * p * 2.03 + vec2(1.7, -3.1);\n    weight *= 0.5;\n  }\n  return sum;\n}\n\nvoid main() {\n  // Pattern space counts CSS pixels from the centre, so the terrain keeps\n  // its size on any canvas and any screen density.\n  vec2 css = (gl_FragCoord.xy - 0.5 * u_size) / u_dpr;\n  vec2 p = css * mix(0.006, 0.0012, u_scale);\n  float t = 0.05 * u_clock;\n  // Two layers drifting apart make the hills change shape, not just slide.\n  float height = layered(p + vec2(t, -0.7 * t)) + 0.5 * layered(1.7 * p - vec2(0.4 * t, 0.9 * t) + 11.0);\n  // A soft hill under the pointer.\n  vec2 toPointer = (gl_FragCoord.xy - u_pointer) / u_dpr;\n  height += u_pull * 0.3 * exp(-dot(toPointer, toPointer) / 32400.0);\n\n  float level = height * mix(6.0, 40.0, u_density);\n  float f = fract(level);\n  float away = min(f, 1.0 - f) / max(fwidth(level), 1e-4);\n  float nearest = floor(level + 0.5);\n  bool major = u_index > 0.5 && mod(nearest + 0.5, u_index) < 1.0;\n  float radius = 0.5 * u_thickness * u_dpr * (major ? 1.8 : 1.0);\n  float line = 1.0 - smoothstep(radius - 0.5, radius + 0.5, away);\n  float strength = major || u_index < 0.5 ? 1.0 : 0.6;\n  float alpha = line * strength * u_opacity * u_color.a;\n  outColor = vec4(u_color.rgb * alpha, alpha);\n}`;\n\ninterface TopographySettings {\n  color: string;\n  density: number;\n  thickness: number;\n  indexEvery: number;\n  speed: number;\n  scale: number;\n  opacity: number;\n  pointer: boolean;\n}\n\n/** Any CSS colour, theme variables included, as 0–1 RGBA. */\nfunction resolveColor(color: string, probe: HTMLElement): [number, number, number, number] {\n  probe.style.color = color;\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = canvas.height = 1;\n  const context = canvas.getContext(\"2d\");\n  if (!context) return [0, 0, 0, 1];\n  context.fillStyle = getComputedStyle(probe).color;\n  context.fillRect(0, 0, 1, 1);\n  const [r = 0, g = 0, b = 0, a = 255] = context.getImageData(0, 0, 1, 1).data;\n  return [r / 255, g / 255, b / 255, a / 255];\n}\n\nfunction compile(gl: WebGL2RenderingContext) {\n  const program = gl.createProgram();\n  for (const [type, source] of [\n    [gl.VERTEX_SHADER, VERTEX],\n    [gl.FRAGMENT_SHADER, FRAGMENT],\n  ] as const) {\n    const shader = gl.createShader(type);\n    if (!shader) return null;\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    gl.attachShader(program, shader);\n    gl.deleteShader(shader);\n  }\n  gl.linkProgram(program);\n  return gl.getProgramParameter(program, gl.LINK_STATUS) ? program : null;\n}\n\nconst unit = (value: number) => Math.min(Math.max(value, 0), 1);\n\ninterface TopographyProps\n  extends Omit<ComponentProps<\"div\">, \"children\" | \"color\">, Partial<TopographySettings> {}\n\n/**\n * Contour lines like a topographic map, slowly shifting as the terrain\n * under them changes shape. It is one WebGL2 fragment shader; every\n * `indexEvery`-th line is drawn stronger, like the index lines on a survey\n * map. Put it inside a positioned element; it fills it. The colour can be a\n * theme variable and follows theme switches. With `pointer`, the terrain\n * rises gently under a mouse or pen. It is decorative and hidden from\n * screen readers, pauses off screen and in background tabs, draws one still\n * frame with `prefers-reduced-motion`, and falls back to CSS rings of the\n * same colour where WebGL2 is unavailable.\n *\n * @example\n * <section className=\"relative isolate overflow-hidden rounded-2xl p-12\">\n *   <Topography color=\"var(--primary)\" density={0.6} pointer />\n *   <h2 className=\"relative\">Uncharted waters</h2>\n * </section>\n */\nfunction Topography({\n  color = \"var(--muted-foreground)\",\n  density = 0.5,\n  thickness = 1,\n  indexEvery = 5,\n  speed = 0.3,\n  scale = 0.5,\n  opacity = 0.6,\n  pointer = false,\n  className,\n  style,\n  ref,\n  ...props\n}: TopographyProps) {\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const fallback = useRef<HTMLDivElement>(null);\n  const [observe, inView] = useInView<HTMLDivElement>({ rootMargin: \"100px\" });\n  const mergedRef = useMemo(() => mergeRefs(ref, observe), [ref, observe]);\n  const settings = useRef<TopographySettings>({\n    color,\n    density,\n    thickness,\n    indexEvery,\n    speed,\n    scale,\n    opacity,\n    pointer,\n  });\n  const visible = useRef(false);\n  const wake = useRef<() => void>(() => {});\n  const recolor = useRef<() => void>(() => {});\n\n  useEffect(() => {\n    const element = canvas.current;\n    const gl = element?.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: true });\n    if (!element || !gl) return;\n    const program = compile(gl);\n    if (!program) return;\n    const flat = fallback.current;\n    if (flat) flat.hidden = true;\n\n    const buffer = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n    // One triangle that covers the whole canvas.\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n    const position = gl.getAttribLocation(program, \"a_position\");\n    gl.enableVertexAttribArray(position);\n    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n    gl.useProgram(program);\n\n    const names = [\n      \"u_size\",\n      \"u_dpr\",\n      \"u_clock\",\n      \"u_scale\",\n      \"u_density\",\n      \"u_thickness\",\n      \"u_index\",\n      \"u_opacity\",\n      \"u_color\",\n      \"u_pointer\",\n      \"u_pull\",\n    ] as const;\n    const u = Object.fromEntries(\n      names.map((name) => [name, gl.getUniformLocation(program, name)])\n    ) as Record<(typeof names)[number], WebGLUniformLocation | null>;\n\n    const probe = document.createElement(\"span\");\n    probe.style.display = \"none\";\n    element.after(probe);\n    recolor.current = () => {\n      gl.uniform4fv(u.u_color, resolveColor(settings.current.color, probe));\n    };\n\n    let clock = 0;\n    let ratio = 1;\n    // The pointer, in canvas pixels from the bottom left, and how far the hill has risen.\n    const hill = { x: 0, y: 0, pull: 0, target: 0 };\n\n    const draw = () => {\n      const s = settings.current;\n      gl.uniform2f(u.u_size, element.width, element.height);\n      gl.uniform1f(u.u_dpr, ratio);\n      gl.uniform1f(u.u_clock, clock);\n      gl.uniform1f(u.u_scale, unit(s.scale));\n      gl.uniform1f(u.u_density, unit(s.density));\n      gl.uniform1f(u.u_thickness, Math.max(s.thickness, 0));\n      gl.uniform1f(u.u_index, Math.max(Math.round(s.indexEvery), 0));\n      gl.uniform1f(u.u_opacity, unit(s.opacity));\n      gl.uniform2f(u.u_pointer, hill.x, hill.y);\n      gl.uniform1f(u.u_pull, hill.pull);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n\n    const resize = () => {\n      ratio = Math.min(window.devicePixelRatio || 1, 2);\n      element.width = Math.max(1, Math.round(element.clientWidth * ratio));\n      element.height = Math.max(1, Math.round(element.clientHeight * ratio));\n      gl.viewport(0, 0, element.width, element.height);\n      draw();\n    };\n\n    const still = window.matchMedia?.(\"(prefers-reduced-motion: reduce)\");\n    const fine = window.matchMedia?.(\"(pointer: fine)\");\n    let frame = 0;\n    let last = 0;\n    const loop = (now: number) => {\n      frame = 0;\n      const live = visible.current && !still?.matches;\n      const moving = live && settings.current.speed !== 0;\n      const rising = live && Math.abs(hill.target - hill.pull) > 0.001;\n      const elapsed = last ? now - last : 0;\n      if (moving) clock += (elapsed / 1000) * settings.current.speed;\n      if (rising) hill.pull += (hill.target - hill.pull) * (1 - Math.exp(-elapsed / 250));\n      last = moving || rising ? now : 0;\n      draw();\n      if (moving || rising) frame = requestAnimationFrame(loop);\n    };\n    wake.current = () => {\n      if (!frame) frame = requestAnimationFrame(loop);\n    };\n\n    // The canvas lets pointer events through, so listen on its parent.\n    const host = element.parentElement?.parentElement;\n    const follow = (event: PointerEvent) => {\n      if (!settings.current.pointer || event.pointerType === \"touch\" || !fine?.matches) return;\n      if (still?.matches) return;\n      const bounds = element.getBoundingClientRect();\n      const x = event.clientX - bounds.left;\n      const y = event.clientY - bounds.top;\n      const inside = x >= 0 && y >= 0 && x <= bounds.width && y <= bounds.height;\n      hill.x = x * ratio;\n      hill.y = (bounds.height - y) * ratio;\n      hill.target = inside ? 1 : 0;\n      wake.current();\n    };\n    const release = () => {\n      hill.target = 0;\n      wake.current();\n    };\n    host?.addEventListener(\"pointermove\", follow, { passive: true });\n    host?.addEventListener(\"pointerleave\", release);\n\n    recolor.current();\n    resize();\n    const resizer = new ResizeObserver(resize);\n    resizer.observe(element);\n    const theme = new MutationObserver(() => {\n      recolor.current();\n      draw();\n    });\n    theme.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"style\", \"data-theme\"],\n    });\n    wake.current();\n\n    return () => {\n      cancelAnimationFrame(frame);\n      wake.current = () => {};\n      recolor.current = () => {};\n      host?.removeEventListener(\"pointermove\", follow);\n      host?.removeEventListener(\"pointerleave\", release);\n      resizer.disconnect();\n      theme.disconnect();\n      probe.remove();\n      gl.deleteBuffer(buffer);\n      gl.deleteProgram(program);\n      if (flat) flat.hidden = false;\n    };\n  }, []);\n\n  // Hand the latest settings to the loop and wake it for a fresh frame.\n  useEffect(() => {\n    settings.current = { color, density, thickness, indexEvery, speed, scale, opacity, pointer };\n    recolor.current();\n    visible.current = inView;\n    wake.current();\n  }, [color, density, thickness, indexEvery, speed, scale, opacity, pointer, inView]);\n\n  // Rings of the line colour, about as far apart as the shader's lines.\n  const gap = Math.round(40 - 30 * unit(density));\n  const width = Math.min(Math.max(thickness, 0.5), gap / 2);\n\n  return (\n    <div\n      ref={mergedRef}\n      aria-hidden=\"true\"\n      data-slot=\"topography\"\n      className={cn(\"pointer-events-none absolute inset-0 -z-10 overflow-hidden\", className)}\n      style={style}\n      {...props}\n    >\n      {/* Stands in for the shader where WebGL2 is unavailable. */}\n      <div\n        ref={fallback}\n        data-slot=\"topography-fallback\"\n        className=\"absolute inset-0\"\n        style={{\n          backgroundImage: `repeating-radial-gradient(circle at 30% 40%, transparent 0, transparent ${gap - width}px, ${color} ${gap - width}px, ${color} ${gap}px)`,\n          opacity: unit(opacity),\n        }}\n      />\n      <canvas ref={canvas} className=\"block size-full\" />\n    </div>\n  );\n}\n\nexport { Topography, type TopographyProps };\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "creative",
    "background"
  ],
  "type": "registry:ui"
}