{
  "name": "background-cubes-grid",
  "type": "registry:ui",
  "dependencies": [
    "three",
    "motion"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "files": [
    {
      "path": "components/ui/background-cubes-grid.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport * as THREE from \"three\";\nimport { EffectComposer } from \"three/examples/jsm/postprocessing/EffectComposer.js\";\nimport { RenderPass } from \"three/examples/jsm/postprocessing/RenderPass.js\";\nimport { ShaderPass } from \"three/examples/jsm/postprocessing/ShaderPass.js\";\nimport { OutputPass } from \"three/examples/jsm/postprocessing/OutputPass.js\";\nimport { RoundedBoxGeometry } from \"three/examples/jsm/geometries/RoundedBoxGeometry.js\";\nimport { useAnimationFrame, useReducedMotion } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------- */\n/* Isometric variant: a flat field of cubes that ripples under the pointer.   */\n/* -------------------------------------------------------------------------- */\n\nconst SIM_HZ = 120;\nconst STEP = 1 / SIM_HZ;\nconst BRUSH_RADIUS = 1.1;\nconst PUSH_PER_CELL = 0.16;\n\nexport type IsometricCubesProps = {\n  variant?: \"isometric\";\n  className?: string;\n  /** On-screen width of one tile, in CSS pixels. */\n  cellSize?: number;\n  /** Seam between cubes, as a fraction of a tile. */\n  gap?: number;\n  /** Top face color. */\n  topColor?: string;\n  /** Left side face color. */\n  leftColor?: string;\n  /** Right side face color. */\n  rightColor?: string;\n  /** Wave height, in tiles. */\n  amplitude?: number;\n  /** Wave speed, in tiles per second. */\n  speed?: number;\n  /** Fraction of wave energy kept per second, from 0 to 1. Lower values settle faster. */\n  damping?: number;\n  /** Drop random ripples when the pointer stops. */\n  idleRipples?: boolean;\n  /** Seconds the grid stays flat and still before random ripples start. */\n  idleDelay?: number;\n  /** Color of the light that follows the ripple. */\n  glowColor?: string;\n  /** Glow strength. Use 0 to turn it off. */\n  glow?: number;\n};\n\nconst isoVertexShader = `\n  attribute vec2 aOffset;\n  attribute float aHeight;\n  attribute float aGlow;\n  uniform float uAmplitude;\n  varying vec3 vNormal;\n  varying float vHeight;\n  varying float vGlow;\n  varying float vDepth;\n\n  void main() {\n    vec3 p = position;\n    p.xz += aOffset;\n    // Crests round off softly; troughs have no limit and sink deeper than crests rise.\n    // The two curves blend smoothly around zero, so cubes never change speed as they pass rest.\n    float x = aHeight;\n    vHeight = mix( x * 1.5, tanh( x ), smoothstep( -0.6, 0.6, x ) );\n    p.y += vHeight * uAmplitude;\n    vNormal = normal;\n    vGlow = aGlow;\n    vDepth = position.y;\n    gl_Position = projectionMatrix * modelViewMatrix * vec4( p, 1.0 );\n  }\n`;\n\nconst isoFragmentShader = `\n  uniform vec3 uTop;\n  uniform vec3 uLeft;\n  uniform vec3 uRight;\n  uniform vec3 uGlowColor;\n  uniform float uGlow;\n  varying vec3 vNormal;\n  varying float vHeight;\n  varying float vGlow;\n  varying float vDepth;\n\n  void main() {\n    bool isTop = vNormal.y > 0.5;\n    vec3 color = isTop ? uTop : ( abs( vNormal.x ) > 0.5 ? uLeft : uRight );\n    // Tops that sink below the surface pick up a little shade so the trough reads.\n    if ( isTop ) color = mix( color, uLeft, clamp( -vHeight, 0.0, 1.0 ) * 0.6 );\n\n    // Glow: tops get a soft tint; sides are lit hardest near the rim, like a box-shadow.\n    float glow = clamp( vGlow * uGlow, 0.0, 1.0 );\n    float falloff = isTop ? 0.2 : exp( vDepth * 1.6 ) * 0.6;\n    color = mix( color, uGlowColor, glow * falloff );\n\n    gl_FragColor = vec4( color, 1.0 );\n    #include <colorspace_fragment>\n  }\n`;\n\nfunction createIsometricScene(\n  canvas: HTMLCanvasElement,\n  container: HTMLDivElement,\n  options: Required<Omit<IsometricCubesProps, \"className\" | \"variant\">>,\n) {\n  const {\n    cellSize,\n    gap,\n    topColor,\n    leftColor,\n    rightColor,\n    amplitude,\n    speed,\n    damping,\n    idleRipples,\n    idleDelay,\n    glowColor,\n    glow,\n  } = options;\n\n  const c2 = Math.min((speed / SIM_HZ) ** 2, 0.5);\n  // Per-second rates. While the pointer moves (or auto mode runs), waves travel freely and a\n  // slow pull toward zero removes leftover offset. Once the pointer stops, both rates ramp up\n  // smoothly so the surface eases back into a flat, aligned grid without a sudden brake.\n  const flowDrag = -Math.log(Math.min(Math.max(damping, 1e-4), 1));\n  const settleDrag = -Math.log(0.02);\n  const flowPull = 0.8;\n  const settlePull = 3.5;\n  const SETTLE_AFTER = 0.15;\n  const SETTLE_RAMP = 0.8;\n  const FLAT = 0.004;\n\n  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });\n  renderer.setClearColor(topColor);\n  const scene = new THREE.Scene();\n\n  // True isometric view: camera on the (1, 1, 1) diagonal.\n  const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, -100, 100);\n  camera.position.set(10, 10, 10);\n  camera.lookAt(0, 0, 0);\n\n  const material = new THREE.ShaderMaterial({\n    vertexShader: isoVertexShader,\n    fragmentShader: isoFragmentShader,\n    uniforms: {\n      uAmplitude: { value: amplitude },\n      uTop: { value: new THREE.Color(topColor) },\n      uLeft: { value: new THREE.Color(leftColor) },\n      uRight: { value: new THREE.Color(rightColor) },\n      uGlowColor: { value: new THREE.Color(glowColor) },\n      uGlow: { value: glow },\n    },\n  });\n\n  let size = 0;\n  let height = new Float32Array(0);\n  let velocity = new Float32Array(0);\n  let lastHeight = new Float32Array(0);\n  let glowField = new Float32Array(0);\n  let geometry: THREE.InstancedBufferGeometry | null = null;\n  let heightAttribute: THREE.InstancedBufferAttribute | null = null;\n  let glowAttribute: THREE.InstancedBufferAttribute | null = null;\n  let mesh: THREE.Mesh | null = null;\n\n  const build = (count: number) => {\n    if (mesh) scene.remove(mesh);\n    geometry?.dispose();\n    size = count;\n    height = new Float32Array(size * size);\n    velocity = new Float32Array(size * size);\n    lastHeight = new Float32Array(size * size);\n    glowField = new Float32Array(size * size);\n\n    // Tall columns so deep troughs never expose the bottom of a cube.\n    const box = new THREE.BoxGeometry(1 - gap, 16, 1 - gap).translate(0, -8, 0);\n    geometry = new THREE.InstancedBufferGeometry();\n    geometry.index = box.index;\n    geometry.setAttribute(\"position\", box.getAttribute(\"position\"));\n    geometry.setAttribute(\"normal\", box.getAttribute(\"normal\"));\n\n    const offsets = new Float32Array(size * size * 2);\n    const half = (size - 1) / 2;\n    for (let i = 0; i < size; i++) {\n      for (let j = 0; j < size; j++) {\n        offsets[(i * size + j) * 2] = i - half;\n        offsets[(i * size + j) * 2 + 1] = j - half;\n      }\n    }\n    geometry.setAttribute(\"aOffset\", new THREE.InstancedBufferAttribute(offsets, 2));\n    heightAttribute = new THREE.InstancedBufferAttribute(new Float32Array(size * size), 1);\n    heightAttribute.setUsage(THREE.DynamicDrawUsage);\n    geometry.setAttribute(\"aHeight\", heightAttribute);\n    glowAttribute = new THREE.InstancedBufferAttribute(glowField, 1);\n    glowAttribute.setUsage(THREE.DynamicDrawUsage);\n    geometry.setAttribute(\"aGlow\", glowAttribute);\n    geometry.instanceCount = size * size;\n\n    mesh = new THREE.Mesh(geometry, material);\n    mesh.frustumCulled = false;\n    scene.add(mesh);\n  };\n\n  let awake = true;\n  const resize = () => {\n    const width = container.clientWidth;\n    const viewHeight = container.clientHeight;\n    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));\n    renderer.setSize(width, viewHeight, false);\n\n    // A tile's top face spans sqrt(2) world units across the screen.\n    const scale = cellSize / Math.SQRT2;\n    camera.left = -width / 2 / scale;\n    camera.right = width / 2 / scale;\n    camera.top = viewHeight / 2 / scale;\n    camera.bottom = -viewHeight / 2 / scale;\n    camera.updateProjectionMatrix();\n\n    const needed = Math.ceil(((width + viewHeight * 2) / cellSize) * 1.1) + 4;\n    if (needed > size) build(needed);\n    awake = true;\n  };\n\n  // Smooth Gaussian push into the velocity field, centred on a fractional grid position.\n  const brush = (gx: number, gz: number, strength: number, radius = BRUSH_RADIUS) => {\n    const reach = Math.ceil(radius * 3);\n    const inv = 1 / (2 * radius * radius);\n    const ci = Math.round(gx);\n    const cj = Math.round(gz);\n    for (let i = Math.max(1, ci - reach); i <= Math.min(size - 2, ci + reach); i++) {\n      for (let j = Math.max(1, cj - reach); j <= Math.min(size - 2, cj + reach); j++) {\n        const dx = i - gx;\n        const dz = j - gz;\n        velocity[i * size + j] -= strength * Math.exp(-(dx * dx + dz * dz) * inv);\n      }\n    }\n    awake = true;\n  };\n\n  const raycaster = new THREE.Raycaster();\n  const pointer = new THREE.Vector2();\n  const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);\n  const hit = new THREE.Vector3();\n  let target: { x: number; z: number } | null = null;\n  let brushAt: { x: number; z: number } | null = null;\n  let idleTime = 0;\n  let quietTime = 0;\n  let idleTimer = 0;\n  let autoMode = false;\n  let lastEnergy = 0;\n\n  // Listen on window so content placed above the canvas does not block ripples.\n  const onPointerMove = (e: PointerEvent) => {\n    const rect = container.getBoundingClientRect();\n    const nx = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n    const ny = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n    if (Math.abs(nx) > 1 || Math.abs(ny) > 1) {\n      target = null;\n      brushAt = null;\n      return;\n    }\n    pointer.set(nx, ny);\n    raycaster.setFromCamera(pointer, camera);\n    if (!raycaster.ray.intersectPlane(ground, hit)) return;\n    const half = (size - 1) / 2;\n    target = { x: hit.x + half, z: hit.z + half };\n    idleTime = 0;\n    quietTime = 0;\n    autoMode = false;\n  };\n\n  // Drag the brush along the path the pointer travelled since the last frame.\n  const applyPointer = () => {\n    if (!target) return;\n    if (!brushAt) {\n      brushAt = { ...target };\n      return;\n    }\n    const dx = target.x - brushAt.x;\n    const dz = target.z - brushAt.z;\n    const distance = Math.hypot(dx, dz);\n    if (distance < 0.01) return;\n    const samples = Math.ceil(distance / 0.35);\n    const push = (Math.min(distance, 3) * PUSH_PER_CELL) / samples;\n    for (let s = 1; s <= samples; s++) {\n      brush(brushAt.x + (dx * s) / samples, brushAt.z + (dz * s) / samples, push);\n    }\n    brushAt = { ...target };\n  };\n\n  const step = () => {\n    const ramp = autoMode ? 0 : Math.min(Math.max((idleTime - SETTLE_AFTER) / SETTLE_RAMP, 0), 1);\n    const s = ramp * ramp * (3 - 2 * ramp);\n    const keep = Math.exp(-(flowDrag + (settleDrag - flowDrag) * s) / SIM_HZ);\n    const relax = Math.exp(-(flowPull + (settlePull - flowPull) * s) / SIM_HZ);\n    lastHeight.set(height);\n    for (let i = 1; i < size - 1; i++) {\n      for (let j = 1; j < size - 1; j++) {\n        const k = i * size + j;\n        // Nine-point Laplacian: round wavefronts and no grid-aligned checkerboard noise.\n        const edges = height[k - 1] + height[k + 1] + height[k - size] + height[k + size];\n        const corners =\n          height[k - size - 1] + height[k - size + 1] + height[k + size - 1] + height[k + size + 1];\n        const laplacian = (4 * edges + corners - 20 * height[k]) / 6;\n        velocity[k] = (velocity[k] + c2 * laplacian) * keep;\n      }\n    }\n    for (let k = 0; k < height.length; k++) height[k] = (height[k] + velocity[k]) * relax;\n\n    // Glow eases toward the local wave energy: quick to light up, slow to fade.\n    for (let i = 1; i < size - 1; i++) {\n      for (let j = 1; j < size - 1; j++) {\n        const k = i * size + j;\n        const energy =\n          (Math.abs(height[k]) * 4 +\n            Math.abs(height[k - 1]) +\n            Math.abs(height[k + 1]) +\n            Math.abs(height[k - size]) +\n            Math.abs(height[k + size])) /\n          8;\n        glowField[k] += (energy - glowField[k]) * (energy > glowField[k] ? 0.08 : 0.015);\n      }\n    }\n  };\n\n  let accumulator = 0;\n  const update = (delta: number) => {\n    if (!heightAttribute || !glowAttribute) return;\n\n    idleTime += delta;\n    // Auto mode starts only after the grid has been flat and still for `idleDelay` seconds.\n    quietTime = !autoMode && idleTime > SETTLE_AFTER && lastEnergy < FLAT ? quietTime + delta : 0;\n    if (idleRipples && !autoMode && quietTime > idleDelay) autoMode = true;\n    if (autoMode) {\n      idleTimer += delta;\n      if (idleTimer > 1.8) {\n        idleTimer = 0;\n        const spread = size * 0.15;\n        brush(\n          size / 2 + (Math.random() - 0.5) * spread * 2,\n          size / 2 + (Math.random() - 0.5) * spread * 2,\n          0.28,\n          1.8,\n        );\n      }\n    } else {\n      idleTimer = 1.8;\n    }\n\n    applyPointer();\n    if (!awake) {\n      lastEnergy = 0;\n      return;\n    }\n\n    accumulator = Math.min(accumulator + delta, STEP * 8);\n    while (accumulator >= STEP) {\n      step();\n      accumulator -= STEP;\n    }\n\n    // Blend the last two simulation states so motion stays smooth at any refresh rate.\n    const alpha = accumulator / STEP;\n    const display = heightAttribute.array as Float32Array;\n    let wave = 0;\n    let light = 0;\n    for (let k = 0; k < height.length; k++) {\n      display[k] = lastHeight[k] + (height[k] - lastHeight[k]) * alpha;\n      wave = Math.max(wave, Math.abs(height[k]), Math.abs(velocity[k]) * 20);\n      light = Math.max(light, glowField[k]);\n    }\n    heightAttribute.needsUpdate = true;\n    glowAttribute.needsUpdate = true;\n    renderer.render(scene, camera);\n    lastEnergy = wave;\n    const energy = Math.max(wave, light);\n\n    // Stop rendering once the surface has settled; the next push wakes it up.\n    if (energy < 1e-4) awake = false;\n  };\n\n  const observer = new ResizeObserver(resize);\n  observer.observe(container);\n  window.addEventListener(\"pointermove\", onPointerMove);\n\n  const dispose = () => {\n    observer.disconnect();\n    window.removeEventListener(\"pointermove\", onPointerMove);\n    geometry?.dispose();\n    material.dispose();\n    renderer.dispose();\n  };\n\n  return { update, dispose };\n}\n\nfunction IsometricCubes({\n  className,\n  cellSize = 150,\n  gap = 0.025,\n  topColor = \"#fafaf9\",\n  leftColor = \"#e7e5e4\",\n  rightColor = \"#d6d3d1\",\n  amplitude = 0.7,\n  speed = 7,\n  damping = 0.08,\n  idleRipples = true,\n  idleDelay = 1.5,\n  glowColor = \"#a8a29e\",\n  glow = 0.5,\n}: IsometricCubesProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const updateRef = useRef<((delta: number) => void) | null>(null);\n  const reduceMotion = useReducedMotion();\n  const idle = idleRipples && !reduceMotion;\n\n  useEffect(() => {\n    if (!canvasRef.current || !containerRef.current) return;\n    const { update, dispose } = createIsometricScene(canvasRef.current, containerRef.current, {\n      cellSize,\n      gap,\n      topColor,\n      leftColor,\n      rightColor,\n      amplitude,\n      speed,\n      damping,\n      idleRipples: idle,\n      idleDelay,\n      glowColor,\n      glow,\n    });\n    updateRef.current = update;\n    return () => {\n      updateRef.current = null;\n      dispose();\n    };\n  }, [cellSize, gap, topColor, leftColor, rightColor, amplitude, speed, damping, idle, idleDelay, glowColor, glow]);\n\n  useAnimationFrame((_, delta) => {\n    updateRef.current?.(Math.min(delta / 1000, 0.1));\n  });\n\n  return (\n    <div\n      ref={containerRef}\n      aria-hidden\n      className={cn(\"absolute inset-0 overflow-hidden\", className)}\n      style={{ backgroundColor: topColor }}\n    >\n      <canvas ref={canvasRef} className=\"block h-full w-full\" />\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Perspective variant: a tilted 3D grid with glowing wave crests.            */\n/* -------------------------------------------------------------------------- */\n\nconst MAX_TRAIL = 128;\nconst CUBE_WIDTH = 0.72;\nconst CUBE_HEIGHT = 3;\nconst CAMERA_RADIUS = 12;\nconst ALPHA_RANGE = Math.PI * 0.03;\nconst BETA_RANGE = Math.PI * 0.05;\n\nconst PERSPECTIVE_WAVE = {\n  speed: 6.0,\n  frequency: 1.2,\n  width: 3.0,\n  jitter: 0.2,\n  fadeTime: 2.0,\n  trailSpacing: 0.1,\n  idleStrength: 0.8,\n};\n\nexport type PerspectiveCubesProps = {\n  variant: \"perspective\";\n  className?: string;\n  /** Number of cubes per side. */\n  gridSize?: number;\n  /** Space between cubes, in world units. */\n  gap?: number;\n  /** Cube color at rest. */\n  baseColor?: string;\n  /** Color of the wave crests. */\n  waveColor?: string;\n  /** Scene background and fog color. */\n  backgroundColor?: string;\n  /** Amount of light the crests emit. */\n  glow?: number;\n  /** Wave height. */\n  amplitude?: number;\n  /** Camera tilt from top-down, in radians. */\n  tilt?: number;\n  /** Start random waves when the pointer stops. */\n  idleRipples?: boolean;\n};\n\nconst VignetteRGBShiftShader = {\n  uniforms: {\n    tDiffuse: { value: null },\n    shiftAmount: { value: 0.004 },\n    vignetteRadius: { value: 0.35 },\n    vignetteSoftness: { value: 0.45 },\n  },\n  vertexShader: `\n    varying vec2 vUv;\n    void main() {\n      vUv = uv;\n      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n    }\n  `,\n  fragmentShader: `\n    uniform sampler2D tDiffuse;\n    uniform float shiftAmount;\n    uniform float vignetteRadius;\n    uniform float vignetteSoftness;\n    varying vec2 vUv;\n\n    void main() {\n      vec2 center = vec2(0.5);\n      float dist = distance(vUv, center);\n      vec2 dir = sign(vUv - center);\n      float vignetteFactor = smoothstep(vignetteRadius, vignetteRadius + vignetteSoftness, dist);\n      vec2 shift = dir * shiftAmount * vignetteFactor;\n      float r = texture2D(tDiffuse, vUv + shift).r;\n      float g = texture2D(tDiffuse, vUv).g;\n      float b = texture2D(tDiffuse, vUv - shift).b;\n      gl_FragColor = vec4(vec3(r, g, b) * (1.0 - vignetteFactor * 0.7), 1.0);\n    }\n  `,\n};\n\nconst overrideVertexShader = (vertexShader: string) =>\n  vertexShader\n    .replace(\n      \"#include <common>\",\n      `#include <common>\n      varying float vHeight;\n      attribute vec2 aOffset;\n      uniform sampler2D uTrailTexture;\n      uniform int       uTrailCount;\n      uniform float     uWaveSpeed;\n      uniform float     uWaveFreq;\n      uniform float     uWaveWidth;\n      uniform float     uFadeTime;\n      uniform float     uAmplitude;\n      uniform float     uJitter;\n      uniform float     uMaxHeight;\n\n      vec2 hash2( vec2 p ) {\n        p = vec2(\n          dot( p, vec2( 127.1, 311.7 ) ),\n          dot( p, vec2( 269.5, 183.3 ) )\n        );\n        return fract( sin( p ) * 43758.5453123 ) - 0.5;\n      }`,\n    )\n    .replace(\n      \"#include <begin_vertex>\",\n      `#include <begin_vertex>\n      vHeight = 0.0;\n      if ( position.y > 0.0 ) {\n        vec2 worldXZ = aOffset + hash2( aOffset ) * uJitter;\n        float waveHeight  = 0.0;\n        float totalWeight = 0.0;\n\n        for ( int i = 0; i < uTrailCount; i++ ) {\n          vec4 td = texture2D(\n            uTrailTexture,\n            vec2( ( float(i) + 0.5 ) / ${MAX_TRAIL}.0, 0.5 )\n          );\n          float dist    = length( worldXZ - td.rg );\n          float relDist = dist - uWaveSpeed * td.b;\n          float window  = exp( -( relDist * relDist ) / ( uWaveWidth * uWaveWidth ) );\n          float fade    = exp( -td.b / uFadeTime );\n          float atten   = 1.0 / ( 1.0 + dist * 0.1 );\n          float weight  = fade * window * atten * td.a;\n\n          waveHeight  += weight * cos( uWaveFreq * relDist );\n          totalWeight += weight;\n        }\n\n        waveHeight /= max( totalWeight, 1.0 );\n\n        float displacement = clamp( waveHeight * uAmplitude, -uMaxHeight, uMaxHeight );\n        transformed.y += displacement;\n        vHeight = displacement;\n      }`,\n    );\n\ntype TrailPoint = { x: number; z: number; age: number; distDelta: number };\n\ntype SceneOptions = Required<Omit<PerspectiveCubesProps, \"className\" | \"variant\">>;\n\nfunction createPerspectiveScene(\n  canvas: HTMLCanvasElement,\n  container: HTMLDivElement,\n  options: SceneOptions,\n) {\n  const { gridSize, gap, baseColor, waveColor, backgroundColor, glow, amplitude, tilt, idleRipples } =\n    options;\n  let width = container.clientWidth;\n  let height = container.clientHeight;\n  let pixelRatio = Math.min(window.devicePixelRatio, 2);\n\n  const scene = new THREE.Scene();\n  scene.background = new THREE.Color(backgroundColor);\n  scene.fog = new THREE.Fog(backgroundColor, 9, 26);\n\n  const camera = new THREE.PerspectiveCamera(40, width / height, 0.1, 200);\n  const mouse = new THREE.Vector2();\n  const lerpedMouse = new THREE.Vector2();\n  const updateCamera = (mx: number, my: number) => {\n    const alpha = tilt + my * ALPHA_RANGE;\n    const beta = mx * BETA_RANGE;\n    camera.position.set(\n      -CAMERA_RADIUS * Math.cos(alpha) * Math.sin(beta),\n      CAMERA_RADIUS * Math.cos(alpha) * Math.cos(beta),\n      CAMERA_RADIUS * Math.sin(alpha),\n    );\n    camera.up.set(0, 1, 0);\n    camera.lookAt(0, 0, 0);\n  };\n  updateCamera(0, 0);\n\n  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });\n  renderer.toneMapping = THREE.ACESFilmicToneMapping;\n  renderer.toneMappingExposure = 1.3;\n  renderer.shadowMap.enabled = true;\n  renderer.shadowMap.type = THREE.PCFShadowMap;\n  renderer.setSize(width, height, false);\n  renderer.setPixelRatio(pixelRatio);\n\n  const composer = new EffectComposer(renderer);\n  composer.addPass(new RenderPass(scene, camera));\n  composer.addPass(new ShaderPass(VignetteRGBShiftShader));\n  composer.addPass(new OutputPass());\n  composer.setSize(width, height);\n  composer.setPixelRatio(pixelRatio);\n\n  scene.add(new THREE.AmbientLight(\"#ffffff\", 0.35));\n  const keyLight = new THREE.DirectionalLight(\"#ffffff\", 3.0);\n  keyLight.position.set(-20, 12, -6);\n  keyLight.castShadow = true;\n  keyLight.shadow.mapSize.set(1024, 1024);\n  keyLight.shadow.radius = 6;\n  keyLight.shadow.camera.near = 0.1;\n  keyLight.shadow.camera.far = 60;\n  keyLight.shadow.camera.left = -22;\n  keyLight.shadow.camera.right = 22;\n  keyLight.shadow.camera.top = 22;\n  keyLight.shadow.camera.bottom = -22;\n  keyLight.shadow.bias = 0.0001;\n  scene.add(keyLight);\n  const rimLight = new THREE.DirectionalLight(waveColor, 1.2);\n  rimLight.position.set(12, 4, 10);\n  scene.add(rimLight);\n\n  const bounds = gridSize * (CUBE_WIDTH + gap);\n  const maxHeight = amplitude;\n\n  const trail: TrailPoint[] = [];\n  let lastPoint: { x: number; z: number } | null = null;\n  let timeSinceLastMove = 0;\n  let randomPointTimer = 0;\n  let isPlacingRandomPoints = idleRipples;\n\n  const trailData = new Float32Array(MAX_TRAIL * 4);\n  const trailTexture = new THREE.DataTexture(\n    trailData,\n    MAX_TRAIL,\n    1,\n    THREE.RGBAFormat,\n    THREE.FloatType,\n  );\n  trailTexture.needsUpdate = true;\n  const trailUniforms = {\n    uTrailTexture: { value: trailTexture },\n    uTrailCount: { value: 0 },\n    uFadeTime: { value: PERSPECTIVE_WAVE.fadeTime },\n  };\n\n  const rayPlane = new THREE.Mesh(\n    new THREE.PlaneGeometry(bounds, bounds),\n    new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, visible: false }),\n  );\n  rayPlane.rotation.x = -Math.PI / 2;\n  rayPlane.updateMatrixWorld(true);\n  const raycaster = new THREE.Raycaster();\n  const pointer = new THREE.Vector2();\n\n  const pushPoint = (point: TrailPoint) => {\n    if (trail.length >= MAX_TRAIL) trail.shift();\n    trail.push(point);\n  };\n\n  const waveUniforms = () => ({\n    ...trailUniforms,\n    uWaveSpeed: { value: PERSPECTIVE_WAVE.speed },\n    uWaveFreq: { value: PERSPECTIVE_WAVE.frequency },\n    uWaveWidth: { value: PERSPECTIVE_WAVE.width },\n    uAmplitude: { value: amplitude },\n    uJitter: { value: PERSPECTIVE_WAVE.jitter },\n    uMaxHeight: { value: maxHeight },\n  });\n\n  const count = gridSize * gridSize;\n  const geometry = new RoundedBoxGeometry(CUBE_WIDTH, CUBE_HEIGHT, CUBE_WIDTH, 2, 0.12);\n  const offsetAttribute = new THREE.InstancedBufferAttribute(\n    new Float32Array(count * 2),\n    2,\n  );\n  geometry.setAttribute(\"aOffset\", offsetAttribute);\n\n  const material = new THREE.MeshPhongMaterial({ color: 0xffffff, shininess: 60 });\n  material.onBeforeCompile = (shader) => {\n    Object.assign(shader.uniforms, waveUniforms(), {\n      uColorBase: { value: new THREE.Color(baseColor) },\n      uColorHigh: { value: new THREE.Color(waveColor) },\n      uGlow: { value: glow },\n    });\n    shader.vertexShader = overrideVertexShader(shader.vertexShader);\n    shader.fragmentShader = shader.fragmentShader\n      .replace(\n        \"#include <common>\",\n        `#include <common>\n        varying float vHeight;\n        uniform vec3  uColorBase;\n        uniform vec3  uColorHigh;\n        uniform float uMaxHeight;\n        uniform float uGlow;`,\n      )\n      .replace(\n        \"#include <color_fragment>\",\n        `#include <color_fragment>\n        float crest  = clamp( vHeight / uMaxHeight, 0.0, 1.0 );\n        float trough = clamp( -vHeight / uMaxHeight, 0.0, 1.0 );\n        diffuseColor.rgb = mix( uColorBase, uColorHigh, crest ) * ( 1.0 - trough * 0.6 );`,\n      )\n      .replace(\n        \"#include <emissivemap_fragment>\",\n        `#include <emissivemap_fragment>\n        totalEmissiveRadiance += uColorHigh * crest * crest * uGlow;`,\n      );\n  };\n\n  const depthMaterial = new THREE.MeshDepthMaterial();\n  depthMaterial.onBeforeCompile = (shader) => {\n    Object.assign(shader.uniforms, waveUniforms());\n    shader.vertexShader = overrideVertexShader(shader.vertexShader);\n  };\n\n  const mesh = new THREE.InstancedMesh(geometry, material, count);\n  mesh.customDepthMaterial = depthMaterial;\n  mesh.castShadow = true;\n  mesh.receiveShadow = true;\n  scene.add(mesh);\n\n  const dummy = new THREE.Object3D();\n  const spacing = CUBE_WIDTH + gap;\n  const gridOffset = ((gridSize - 1) * spacing) / 2;\n  for (let i = 0; i < gridSize; i++) {\n    for (let j = 0; j < gridSize; j++) {\n      const index = i * gridSize + j;\n      const x = i * spacing - gridOffset;\n      const z = j * spacing - gridOffset;\n      dummy.position.set(x, 0, z);\n      dummy.updateMatrix();\n      mesh.setMatrixAt(index, dummy.matrix);\n      offsetAttribute.setXY(index, x, z);\n    }\n  }\n  mesh.instanceMatrix.needsUpdate = true;\n  offsetAttribute.needsUpdate = true;\n\n  // Listen on window so content placed above the canvas does not block waves.\n  const onPointerMove = (e: PointerEvent) => {\n    const rect = container.getBoundingClientRect();\n    const nx = ((e.clientX - rect.left) / rect.width) * 2 - 1;\n    const ny = -((e.clientY - rect.top) / rect.height) * 2 + 1;\n    if (Math.abs(nx) > 1 || Math.abs(ny) > 1) return;\n    mouse.set(nx, ny);\n    pointer.set(nx, ny);\n\n    raycaster.setFromCamera(pointer, camera);\n    const hits = raycaster.intersectObject(rayPlane);\n    if (hits.length === 0) return;\n\n    const { x, z } = hits[0].point;\n    let distDelta = 0;\n    if (lastPoint) {\n      distDelta = Math.hypot(x - lastPoint.x, z - lastPoint.z);\n      if (distDelta < PERSPECTIVE_WAVE.trailSpacing) return;\n    }\n    pushPoint({ x, z, age: 0, distDelta });\n    lastPoint = { x, z };\n    timeSinceLastMove = 0;\n    isPlacingRandomPoints = false;\n    randomPointTimer = 0;\n  };\n\n  const resizeObserver = new ResizeObserver(() => {\n    width = container.clientWidth;\n    height = container.clientHeight;\n    pixelRatio = Math.min(window.devicePixelRatio, 2);\n    camera.aspect = width / height;\n    camera.updateProjectionMatrix();\n    renderer.setSize(width, height, false);\n    renderer.setPixelRatio(pixelRatio);\n    composer.setSize(width, height);\n    composer.setPixelRatio(pixelRatio);\n  });\n  resizeObserver.observe(container);\n  window.addEventListener(\"pointermove\", onPointerMove);\n\n  const update = (delta: number) => {\n    lerpedMouse.x += (mouse.x - lerpedMouse.x) * 0.04;\n    lerpedMouse.y += (mouse.y - lerpedMouse.y) * 0.04;\n    updateCamera(lerpedMouse.x, lerpedMouse.y);\n\n    const expiry = PERSPECTIVE_WAVE.fadeTime * 4;\n    for (let i = trail.length - 1; i >= 0; i--) {\n      trail[i].age += delta;\n      if (trail[i].age > expiry) trail.splice(i, 1);\n    }\n\n    timeSinceLastMove += delta;\n    if (idleRipples && timeSinceLastMove >= 3.0 && !isPlacingRandomPoints) {\n      isPlacingRandomPoints = true;\n      randomPointTimer = 0;\n    }\n    if (isPlacingRandomPoints) {\n      randomPointTimer += delta;\n      if (randomPointTimer >= 1.5) {\n        pushPoint({\n          x: (Math.random() * 0.5 - 0.25) * bounds,\n          z: (Math.random() * 0.5 - 0.25) * bounds,\n          age: 0,\n          distDelta: PERSPECTIVE_WAVE.idleStrength + Math.random() * 0.2,\n        });\n        randomPointTimer = 0;\n      }\n    }\n\n    const live = Math.min(trail.length, MAX_TRAIL);\n    if (live > 0 || trailUniforms.uTrailCount.value > 0) {\n      for (let i = 0; i < live; i++) {\n        trailData.set(\n          [trail[i].x, trail[i].z, trail[i].age, trail[i].distDelta],\n          i * 4,\n        );\n      }\n      trailTexture.needsUpdate = true;\n      trailUniforms.uTrailCount.value = live;\n    }\n\n    composer.render();\n  };\n\n  const dispose = () => {\n    resizeObserver.disconnect();\n    window.removeEventListener(\"pointermove\", onPointerMove);\n    geometry.dispose();\n    material.dispose();\n    depthMaterial.dispose();\n    rayPlane.geometry.dispose();\n    rayPlane.material.dispose();\n    trailTexture.dispose();\n    composer.dispose();\n    renderer.dispose();\n  };\n\n  return { update, dispose };\n}\n\nfunction PerspectiveCubes({\n  className,\n  gridSize = 44,\n  gap = 0.08,\n  baseColor = \"#2a2a30\",\n  waveColor = \"#ff6a2b\",\n  backgroundColor = \"#0b0b0d\",\n  glow = 0.9,\n  amplitude = 0.5,\n  tilt = 0.7,\n  idleRipples = true,\n}: PerspectiveCubesProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const updateRef = useRef<((delta: number) => void) | null>(null);\n  const reduceMotion = useReducedMotion();\n  const idle = idleRipples && !reduceMotion;\n\n  useEffect(() => {\n    if (!canvasRef.current || !containerRef.current) return;\n    const { update, dispose } = createPerspectiveScene(canvasRef.current, containerRef.current, {\n      gridSize,\n      gap,\n      baseColor,\n      waveColor,\n      backgroundColor,\n      glow,\n      amplitude,\n      tilt,\n      idleRipples: idle,\n    });\n    updateRef.current = update;\n    return () => {\n      updateRef.current = null;\n      dispose();\n    };\n  }, [gridSize, gap, baseColor, waveColor, backgroundColor, glow, amplitude, tilt, idle]);\n\n  useAnimationFrame((_, delta) => {\n    updateRef.current?.(Math.min(delta / 1000, 0.1));\n  });\n\n  return (\n    <div\n      ref={containerRef}\n      aria-hidden\n      className={cn(\"absolute inset-0 overflow-hidden\", className)}\n      style={{ backgroundColor }}\n    >\n      <canvas ref={canvasRef} className=\"block h-full w-full outline-none\" />\n    </div>\n  );\n}\n\nexport type BackgroundCubesGridProps = IsometricCubesProps | PerspectiveCubesProps;\n\nexport const BackgroundCubesGrid = (props: BackgroundCubesGridProps) =>\n  props.variant === \"perspective\" ? <PerspectiveCubes {...props} /> : <IsometricCubes {...props} />;\n",
      "type": "registry:ui",
      "target": "components/ui/background-cubes-grid.tsx"
    }
  ],
  "author": "Manu Arora <hi@manuarora.in>",
  "title": "Background Cubes Grid"
}