# Integrate `Caustics` from Motion Garden

You are helping me add the **Caustics** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Caustics
- **Category:** Backgrounds
- **Summary:** Light through moving water. The filaments are the zero crossings of a noise field folded back on itself, not its peaks — which is why they stay thin and hard-edged at any brightness instead of blooming into blobs. The lattice is periodic, so the flow offset wraps and the motion never coarsens over a long session.
- **Reference:** https://motion-garden.netlify.app/components/caustics
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add ogl
```

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/caustics/caustics.tsx`

```tsx
"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Renderer, Program, Mesh, Triangle } from "ogl";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

interface CausticsProps {
  scale?: number;
  speed?: number;
  depth?: number;
  ripple?: number;
  refraction?: number;
  brightness?: number;
  pointerInfluence?: number;
  inkColor?: string;
  glowColor?: string;
  backgroundColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const PERIOD = 32;

const hexToRgb01 = (hex: string): [number, number, number] => {
  const h = hex.replace("#", "");
  const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
  const n = parseInt(full, 16);
  if (Number.isNaN(n) || full.length !== 6) return [1, 1, 1];
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const supportsWebGL2 = () => {
  try {
    return !!document.createElement("canvas").getContext("webgl2");
  } catch {
    return false;
  }
};

const vertex = `#version 300 es
in vec2 position;
void main() { gl_Position = vec4(position, 0.0, 1.0); }`;

const fragment = `#version 300 es
precision highp float;
out vec4 fragColor;

uniform vec2  uResolution;
uniform float uDpr;
uniform vec2  uDriftA;
uniform vec2  uDriftB;
uniform float uScale;
uniform float uDepth;
uniform float uRipple;
uniform float uRefraction;
uniform float uBrightness;
uniform vec2  uPointer;
uniform float uPointerInfluence;
uniform vec3  uInk;
uniform vec3  uGlow;
uniform vec3  uBg;

#define PERIOD 32.0
#define MAX_DEPTH 5

// Lattice hash, wrapped to PERIOD so the whole field tiles on that boundary.
// The sin-based hash is the universally portable one; its exact values differ a
// little between GPUs, which is invisible here because nothing depends on a
// specific cell being a specific brightness.
float hash(vec2 cell) {
  cell = mod(cell, PERIOD);
  return fract(sin(dot(cell, vec2(127.1, 311.7))) * 43758.5453123);
}

float noise(vec2 p) {
  vec2 i = floor(p);
  vec2 f = fract(p);
  // Smoothstep interpolant — a linear one leaves the lattice visible as a grid
  // of creases, which reads as fabric rather than as water.
  vec2 u = f * f * (3.0 - 2.0 * f);
  return mix(
    mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x),
    mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
    u.y
  );
}

// One sheet of light: warp, then fold. Order matters — folding first and warping
// the result smears the filaments instead of bending them.
float sheet(vec2 p, vec2 drift, float warp) {
  vec2 q = p + drift;
  vec2 w = vec2(noise(q + vec2(1.7, 9.2)), noise(q + vec2(8.3, 2.8)));
  float n = noise(q + (w - 0.5) * warp);
  return 1.0 - abs(2.0 * n - 1.0);
}

void main() {
  vec2 res = uResolution / uDpr;
  vec2 uv = (gl_FragCoord.xy / uDpr) / res;
  // Aspect-corrected about the centre, so the cells stay square and the pattern
  // does not stretch when the container does.
  vec2 p = (uv - 0.5) * vec2(res.x / max(res.y, 1.0), 1.0) * uScale;
  p += uPointer * uPointerInfluence * 0.6;

  int depth = int(uDepth);
  float sum = 0.0;
  float total = 0.0;
  for (int i = 0; i < MAX_DEPTH; i++) {
    if (i >= depth) break;
    float step_ = float(i + 1);
    // Frequency climbs geometrically, contribution falls at the same rate, so
    // adding an octave adds detail without adding overall brightness.
    float freq = pow(1.73, float(i));
    float weight = 1.0 / freq;
    // Alternating between two drift vectors decorrelates the octaves. Both are
    // integer multiples of a wrapped offset, so both still tile.
    vec2 drift = (i - (i / 2) * 2 == 0) ? uDriftA * step_ : uDriftB * step_;
    sum += sheet(p * freq, drift, uRefraction) * weight;
    total += weight;
  }

  float light = pow(clamp(sum / max(total, 1e-4), 0.0, 1.0), uRipple) * uBrightness;

  // Two-stop ramp rather than one: the body of a filament and its core are
  // different colours in the real thing, and a single mix toward one bright
  // colour flattens the network into a wire diagram.
  vec3 color = mix(uBg, uInk, clamp(light, 0.0, 1.0));
  color = mix(color, uGlow, clamp(light - 1.0, 0.0, 1.0));

  fragColor = vec4(color, 1.0);
}`;

const Caustics = memo(
  ({
    scale = 4,
    speed = 0.35,
    depth = 3,
    ripple = 3.2,
    refraction = 0.85,
    brightness = 1.35,
    pointerInfluence = 1,
    inkColor = "#a855f7",
    glowColor = "#e9d5ff",
    backgroundColor = "#08050e",
    paused = false,
    reducedMotion = false,
    className,
  }: CausticsProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const glRef = useRef<WebGLRenderingContext | WebGL2RenderingContext | null>(null);

    const [fallback, setFallback] = useState(false);

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused || reducedMotion,
      dpr: "auto",
      onResize: (metrics) => measureRef.current?.(metrics),
      onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
      gl: () => glRef.current,
    });

    const live = useRef({
      scale, speed, depth, ripple, refraction,
      brightness, pointerInfluence, inkColor, glowColor, backgroundColor,
    });
    live.current = {
      scale, speed, depth, ripple, refraction,
      brightness, pointerInfluence, inkColor, glowColor, backgroundColor,
    };

    const pointer = useRef({ x: 0, y: 0, tx: 0, ty: 0 });

    useEffect(() => {
      const container = containerRef.current;
      if (fallback || !container) return;
      if (!supportsWebGL2()) {
        setFallback(true);
        return;
      }

      const renderer = new Renderer({
        webgl: 2,
        alpha: false,
        antialias: false,
        powerPreference: "high-performance",
        dpr: Math.min(window.devicePixelRatio || 1, 2),
      });
      const gl = renderer.gl;
      glRef.current = gl;

      const canvas = gl.canvas as HTMLCanvasElement;
      canvas.style.display = "block";
      canvas.style.position = "absolute";
      canvas.style.top = "0";
      canvas.style.left = "0";
      container.appendChild(canvas);

      const program = new Program(gl, {
        vertex,
        fragment,
        uniforms: {
          uResolution: { value: new Float32Array([1, 1]) },
          uDpr: { value: 1 },
          uDriftA: { value: new Float32Array([0, 0]) },
          uDriftB: { value: new Float32Array([0, 0]) },
          uScale: { value: scale },
          uDepth: { value: depth },
          uRipple: { value: ripple },
          uRefraction: { value: refraction },
          uBrightness: { value: brightness },
          uPointer: { value: new Float32Array([0, 0]) },
          uPointerInfluence: { value: pointerInfluence },
          uInk: { value: new Float32Array(hexToRgb01(inkColor)) },
          uGlow: { value: new Float32Array(hexToRgb01(glowColor)) },
          uBg: { value: new Float32Array(hexToRgb01(backgroundColor)) },
        },
      });
      const mesh = new Mesh(gl, { geometry: new Triangle(gl), program });
      const u = program.uniforms as Record<string, { value: number | Float32Array }>;

      const driftA = new Float32Array([0, 0]);
      const driftB = new Float32Array([0, 0]);
      const DIR_A = [0.62, 0.21];
      const DIR_B = [-0.29, 0.47];

      const sync = () => {
        const l = live.current;
        (u.uDriftA.value as Float32Array).set(driftA);
        (u.uDriftB.value as Float32Array).set(driftB);
        u.uScale.value = l.scale;
        u.uDepth.value = l.depth;
        u.uRipple.value = l.ripple;
        u.uRefraction.value = l.refraction;
        u.uBrightness.value = l.brightness;
        u.uPointerInfluence.value = l.pointerInfluence;
        (u.uPointer.value as Float32Array)[0] = pointer.current.x;
        (u.uPointer.value as Float32Array)[1] = pointer.current.y;
        (u.uInk.value as Float32Array).set(hexToRgb01(l.inkColor));
        (u.uGlow.value as Float32Array).set(hexToRgb01(l.glowColor));
        (u.uBg.value as Float32Array).set(hexToRgb01(l.backgroundColor));
      };

      drawRef.current = (dt) => {
        const v = live.current.speed * dt;
        driftA[0] = (driftA[0] + DIR_A[0] * v) % PERIOD;
        driftA[1] = (driftA[1] + DIR_A[1] * v) % PERIOD;
        driftB[0] = (driftB[0] + DIR_B[0] * v) % PERIOD;
        driftB[1] = (driftB[1] + DIR_B[1] * v) % PERIOD;

        const p = pointer.current;
        const k = Math.min(1, dt * 6);
        p.x += (p.tx - p.x) * k;
        p.y += (p.ty - p.y) * k;
        sync();
        renderer.render({ scene: mesh });
      };

      measureRef.current = ({ width, height, dpr }) => {
        renderer.dpr = dpr;
        renderer.setSize(Math.max(1, Math.floor(width)), Math.max(1, Math.floor(height)));
        const res = u.uResolution.value as Float32Array;
        res[0] = gl.drawingBufferWidth;
        res[1] = gl.drawingBufferHeight;
        u.uDpr.value = dpr;
        sync();
        renderer.render({ scene: mesh });
      };

      loop.resize();
      loop.start();

      return () => {
        drawRef.current = null;
        measureRef.current = null;
        if (container.contains(canvas)) container.removeChild(canvas);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fallback]);

    useEffect(() => {
      loop.paint();
    }, [
      scale, speed, depth, ripple, refraction, brightness,
      pointerInfluence, inkColor, glowColor, backgroundColor, loop,
    ]);

    const track = (e: React.PointerEvent<HTMLDivElement>) => {
      const r = e.currentTarget.getBoundingClientRect();
      if (r.width === 0 || r.height === 0) return;
      pointer.current.tx = ((e.clientX - r.left) / r.width) * 2 - 1;
      pointer.current.ty = ((e.clientY - r.top) / r.height) * 2 - 1;
      loop.start();
    };

    const release = () => {
      pointer.current.tx = 0;
      pointer.current.ty = 0;
      loop.start();
    };

    if (fallback) {
      const wash = (x: number, y: number, color: string, size: number) =>
        `radial-gradient(${size}% ${size}% at ${x}% ${y}%, ${color} 0%, transparent 62%)`;
      return (
        <div
          className={className ?? "relative h-full w-full overflow-hidden"}
          style={{
            backgroundColor,
            backgroundImage: [
              wash(28, 32, glowColor, 60),
              wash(72, 58, inkColor, 80),
              wash(48, 88, inkColor, 70),
            ].join(", "),
            opacity: 0.9,
          }}
        />
      );
    }

    return (
      <div
        ref={containerRef}
        className={className ?? "relative h-full w-full overflow-hidden"}
        onPointerMove={track}
        onPointerLeave={release}
        onPointerCancel={release}
      />
    );
  },
);

Caustics.displayName = "Caustics";

export default Caustics;
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `scale` | `number` | `4` | Noise cells across the frame. Low values give a few slow, room-sized sheets of light; high values pack the frame with a fine mesh that starts to read as texture rather than as water. Range 1–14. |
| `speed` | `number` | `0.35` | How fast the field flows. At 0 the pattern holds still and stays a legible backdrop; the loop keeps running, so the pointer still pushes it. Range 0–2 ×. |
| `depth` | `number` | `3` | Octaves contributing to the network. Each one costs a full warped noise lookup, so this is the performance knob. Contribution falls at the same rate frequency climbs, so adding an octave adds detail without brightening the frame. Range 1–5. |
| `ripple` | `number` | `3.2` | Exponent on the folded ridge. This is what separates caustics from clouds: raising it thins the filaments and concentrates the light into them without softening an edge, which no brightness threshold can do. Range 1–8. |
| `refraction` | `number` | `0.85` | How far the field is displaced through a copy of itself before folding. At 0 the network is a fixed pattern sliding past; the branching and reconnecting people read as water is entirely this. Range 0–3. |
| `brightness` | `number` | `1.35` | Gain on the filaments. Above 1 the ramp starts reaching its second stop, so the cores take the glow colour and the network gains a hot centre rather than simply getting paler. Range 0.2–2.5 ×. |
| `pointerInfluence` | `number` | `1` | How far the pointer pushes the field. Smoothed toward the cursor rather than tracking it exactly, so a jumped pointer never snaps the whole network sideways. Range 0–3 ×. |
| `inkColor` | `string (hex)` | `"#a855f7"` | Body of a filament — the colour the network reads as. |
| `glowColor` | `string (hex)` | `"#e9d5ff"` | Core of a filament, reached only where the light concentrates past full. Two stops rather than one: a single ramp toward one bright colour flattens the network into a wire diagram. |
| `backgroundColor` | `string (hex)` | `"#08050e"` | The water itself. Its own material rather than a themed surface — a full-bleed background that flips to white under a light theme is not a background, it is a flash. |

## Usage

```tsx
import Caustics from "@/components/registry/caustics/caustics";

<Caustics
  scale={4}
  speed={0.35}
  depth={3}
  ripple={3.2}
  refraction={0.85}
  brightness={1.35}
  pointerInfluence={1}
  inkColor="#a855f7"
  glowColor="#e9d5ff"
  backgroundColor="#08050e"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
