# Integrate `IntroAnimation` from Motion Garden

You are helping me add the **IntroAnimation** 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:** IntroAnimation
- **Category:** Micro-interactions
- **Summary:** A wind front sweeps the wordmark right to left. The instant it reaches a glyph the text hands off to a baseline-aligned field of GPU grain — same pixels, same colour, no seam — which peels crown-first and drifts away as smoke through a curl field. The backdrop opens behind it to reveal the page. Mount it over your app and unmount on onDone.
- **Reference:** https://motion-garden.netlify.app/components/intro-animation
- **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

3 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/intro-animation/intro-animation.tsx`

```tsx
"use client";

import { memo, useEffect, useMemo, useRef } from "react";

import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";
import {
  createDustGL,
  GRAIN_IN,
  hexToRgb01,
  sampleWord,
  type DustGL,
  type DustParams,
} from "./dust-gl";

export interface IntroAnimationProps {
  text?: string;
  sweepDuration?: number;
  grainDensity?: number;
  windSpeed?: number;
  buoyancy?: number;
  turbulence?: number;
  grainSize?: number;
  splitIndex?: number;
  reveal?: "split" | "fade" | "none";
  autoplay?: boolean;
  replayDelay?: number;
  inkColor?: string;
  accentColor?: string;
  backgroundColor?: string;
  onDone?: () => void;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const SPLIT_DURATION = 0.9;
const FADE_DURATION = 0.85;
const PLUME_HOLD = 1.17;
const TAIL = 0.95;
const REVEAL_RATIO = 0.937;
const FRONT_LEAD = 40;
const FRONT_TAIL = 30;
const REDUCED_HOLD_MS = 900;
const FILL_CQW = 120;

const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);

const easeInOut = (p: number) =>
  p < 0.5 ? 2 * p * p : 1 - ((-2 * p + 2) * (-2 * p + 2)) / 2;

interface WordMetrics {
  frontStart: number;
  wordLeft: number;
  rights: number[];
}

const IntroAnimation = memo(
  ({
    text = "MOTIONGARDEN",
    sweepDuration = 1.9,
    grainDensity = 2500,
    windSpeed = 1,
    buoyancy = 1,
    turbulence = 1,
    grainSize = 1,
    splitIndex = 6,
    reveal = "split",
    autoplay = true,
    replayDelay = 1.2,
    inkColor = "#e9e7ef",
    accentColor = "#a855f7",
    backgroundColor = "#08050e",
    onDone,
    paused = false,
    reducedMotion = false,
    className,
  }: IntroAnimationProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const topRef = useRef<HTMLDivElement>(null);
    const bottomRef = useRef<HTMLDivElement>(null);
    const charRefs = useRef<(HTMLSpanElement | 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 chars = useMemo(() => [...text], [text]);

    const live = useRef({ sweepDuration, reveal, autoplay, replayDelay });
    live.current = { sweepDuration, reveal, autoplay, replayDelay };

    const restartRef = useRef<(() => void) | null>(null);

    const params = useRef<DustParams>({
      wind: windSpeed,
      buoyancy,
      turbulence,
      grainSize,
      ink: hexToRgb01(inkColor),
      accent: hexToRgb01(accentColor),
    });
    params.current = {
      wind: windSpeed,
      buoyancy,
      turbulence,
      grainSize,
      ink: hexToRgb01(inkColor),
      accent: hexToRgb01(accentColor),
    };

    const onDoneRef = useRef(onDone);
    onDoneRef.current = onDone;

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

    useEffect(() => {
      const container = containerRef.current;
      if (!container) return;

      charRefs.current.length = chars.length;

      if (reducedMotion) {
        for (const span of charRefs.current) {
          if (span) span.style.visibility = "visible";
        }
        const timer = setTimeout(() => onDoneRef.current?.(), REDUCED_HOLD_MS);
        return () => clearTimeout(timer);
      }

      let cancelled = false;
      let dust: DustGL | null = null;
      let word: WordMetrics | null = null;
      let time = 0;
      let done = false;
      let fontsReady = false;
      let glFailed = false;

      const measureWord = (): WordMetrics | null => {
        const origin = container.getBoundingClientRect();
        const rights: number[] = [];
        let left = Number.POSITIVE_INFINITY;
        let right = Number.NEGATIVE_INFINITY;
        for (const span of charRefs.current) {
          if (!span) {
            rights.push(Number.NEGATIVE_INFINITY);
            continue;
          }
          const box = span.getBoundingClientRect();
          rights.push(box.right - origin.left);
          if (box.width <= 0) continue;
          left = Math.min(left, box.left - origin.left);
          right = Math.max(right, box.right - origin.left);
        }
        if (!Number.isFinite(left) || !Number.isFinite(right)) return null;
        return { frontStart: right + FRONT_LEAD, wordLeft: left, rights };
      };

      const resetCycle = () => {
        time = 0;
        done = false;
        for (const span of charRefs.current) {
          if (span) span.style.visibility = "visible";
        }
        if (topRef.current) {
          topRef.current.style.transform = "translateY(0%)";
          topRef.current.style.opacity = "1";
        }
        if (bottomRef.current) {
          bottomRef.current.style.transform = "translateY(0%)";
          bottomRef.current.style.opacity = "1";
        }
        if (dust) dust.canvas.style.opacity = "1";
      };
      restartRef.current = resetCycle;

      const ensure = (): boolean => {
        if (!fontsReady) return false;
        const rect = container.getBoundingClientRect();
        if (rect.width < 1 || rect.height < 1) return false;
        const next = measureWord();
        if (!next) return false;
        word = next;
        if (dust || glFailed) return true;

        try {
          const grains = sampleWord(
            charRefs.current,
            rect,
            grainDensity,
            splitIndex,
          );
          if (grains.count === 0) return true;
          dust = createDustGL(container, grains, {
            width: rect.width,
            height: rect.height,
            dpr: Math.min(2, window.devicePixelRatio || 1),
            frontStart: word.frontStart,
            frontSpeed:
              (word.frontStart - (word.wordLeft - FRONT_TAIL)) /
              Math.max(0.1, live.current.sweepDuration),
            params: params.current,
          });
          glRef.current = dust.gl;
          dust.render(0);
        } catch {
          glFailed = true;
          dust = null;
        }
        return true;
      };

      measureRef.current = (metrics) => {
        const existing = dust !== null;
        if (!ensure()) return;
        dust?.setSize(metrics.width, metrics.height, metrics.dpr);
        if (existing) {
          const box = container.getBoundingClientRect();
          dust?.setGrains(
            sampleWord(charRefs.current, box, grainDensity, splitIndex),
          );
        }
      };

      drawRef.current = (dt) => {
          if (!word && !ensure()) return false;
          if (!word) return false;
          const {
            sweepDuration: sweep,
            reveal: mode,
            autoplay: loops,
            replayDelay: replay,
          } = live.current;

          time += dt;
          const t = time;

          const sweepSeconds = Math.max(0.1, sweep);
          const frontSpeedNow =
            (word.frontStart - (word.wordLeft - FRONT_TAIL)) / sweepSeconds;
          dust?.setFront(word.frontStart, frontSpeedNow);
          dust?.setParams(params.current);

          const revealAt = sweepSeconds * REVEAL_RATIO;
          const canvasFadeAt = revealAt + PLUME_HOLD;
          const finishAt = canvasFadeAt + TAIL;

          const grainPx = frontSpeedNow * GRAIN_IN;
          const front = word.frontStart - frontSpeedNow * t;
          for (let i = 0; i < charRefs.current.length; i++) {
            const span = charRefs.current[i];
            if (!span) continue;
            if (
              front < word.rights[i] - grainPx &&
              span.style.visibility !== "hidden"
            ) {
              span.style.visibility = "hidden";
            }
          }

          if (mode !== "none") {
            const opened = easeInOut(clamp01((t - revealAt) / SPLIT_DURATION));
            const top = topRef.current;
            const bottom = bottomRef.current;
            if (top && bottom) {
              const shift = mode === "split" ? 100 * opened : 0;
              const held = mode === "split" ? "1" : String(1 - opened);
              top.style.transform = `translateY(${-shift}%)`;
              bottom.style.transform = `translateY(${shift}%)`;
              top.style.opacity = held;
              bottom.style.opacity = held;
            }
          }

          const fade = clamp01((t - canvasFadeAt) / FADE_DURATION);
          if (dust) dust.canvas.style.opacity = String(1 - fade * fade);

          dust?.render(t);

          if (t >= finishAt) {
            if (!done) {
              done = true;
              onDoneRef.current?.();
            }
            if (!loops || replay <= 0) return false;
            if (t >= finishAt + replay) resetCycle();
          }
      };

      void (async () => {
        try {
          await document.fonts.ready;
        } catch {
        }
        if (cancelled) return;
        fontsReady = true;
        ensure();
        loop.resize();
        loop.start();
      })();

      return () => {
        cancelled = true;
        drawRef.current = null;
        measureRef.current = null;
        restartRef.current = null;
        glRef.current = null;
        dust?.dispose();
        dust = null;
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [chars, grainDensity, splitIndex, reducedMotion, loop]);

    useEffect(() => {
      if (!autoplay) return;
      restartRef.current?.();
      loop.start();
    }, [autoplay, loop]);

    useEffect(() => {
      loop.paint();
    }, [
      windSpeed,
      buoyancy,
      turbulence,
      grainSize,
      inkColor,
      accentColor,
      reveal,
      loop,
    ]);

    const replay = () => {
      restartRef.current?.();
      loop.start();
    };

    const backdrop = reveal === "none" ? null : (
      <>
        <div
          ref={topRef}
          aria-hidden
          className="absolute inset-x-0 top-0"
          style={{ height: "calc(50% + 1px)", background: backgroundColor }}
        />
        <div
          ref={bottomRef}
          aria-hidden
          className="absolute inset-x-0 bottom-0 h-1/2"
          style={{ background: backgroundColor }}
        />
      </>
    );

    return (
      <div
        ref={containerRef}
        role="img"
        aria-label={text}
        className={[
          "@container relative size-full overflow-hidden",
          className ?? "",
        ].join(" ")}
      >
        {backdrop}
        <div
          aria-hidden
          className="absolute inset-0 flex items-center justify-center"
        >
          <span
            className="font-sans font-bold whitespace-pre tracking-[0.02em]"
            style={{
              fontSize: `clamp(0.75rem, ${(FILL_CQW / Math.max(1, chars.length)).toFixed(2)}cqw, 7rem)`,
            }}
          >
            {chars.map((ch, i) => (
              <span
                key={i}
                ref={(el) => {
                  charRefs.current[i] = el;
                }}
                style={{ color: i < splitIndex ? inkColor : accentColor }}
              >
                {ch}
              </span>
            ))}
          </span>
        </div>
        {!autoplay && !reducedMotion ? (
          <button
            type="button"
            onClick={replay}
            className="absolute right-4 bottom-4 z-10 cursor-pointer rounded-full border px-4 py-1.5 text-[10px] tracking-[0.2em] uppercase opacity-70 transition-opacity hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-2"
            style={{
              color: inkColor,
              borderColor: `${inkColor}33`,
              outlineColor: accentColor,
            }}
          >
            Replay
          </button>
        ) : null}
      </div>
    );
  },
);

IntroAnimation.displayName = "IntroAnimation";

export default IntroAnimation;
```

### 2. `components/registry/intro-animation/dust-gl.ts` — supporting file, required

```tsx
import { Geometry, Mesh, Program, Renderer } from "ogl";

export interface GrainData {
  count: number;
  home: Float32Array;
  tint: Float32Array;
  rand: Float32Array;
  rand2: Float32Array;
  edge: Float32Array;
}

export interface DustParams {
  wind: number;
  buoyancy: number;
  turbulence: number;
  grainSize: number;
  ink: [number, number, number];
  accent: [number, number, number];
}

export interface DustGL {
  readonly gl: WebGLRenderingContext | WebGL2RenderingContext;
  readonly canvas: HTMLCanvasElement;
  setSize(w: number, h: number, dpr: number): void;
  setGrains(grains: GrainData): void;
  setFront(frontStart: number, frontSpeed: number): void;
  setParams(params: DustParams): void;
  render(t: number): void;
  dispose(): void;
}

export const GRAIN_IN = 0.1;

const PEEL_FLOOR = 0.12;

const VERTEX =  `
attribute vec2 aHome;
attribute float aTint;
attribute vec4 aRand;
attribute vec4 aRand2;
attribute vec2 aEdge;

uniform float uTime;
uniform float uFrontStart;
uniform float uFrontSpeed;
uniform vec2 uResolution;
uniform float uDpr;
uniform float uWind;
uniform float uBuoy;
uniform float uTurb;
uniform float uGrainSize;
uniform vec3 uInk;
uniform vec3 uAccent;

const float GRAIN_IN = ${GRAIN_IN.toFixed(3)};
const float PEEL_FLOOR = ${PEEL_FLOOR.toFixed(3)};

varying vec3 vColor;
varying float vAlpha;
varying float vSoft;

// Cheap per-grain hash off the home position — granulation order needs its own
// randomness and every aRand channel is already spoken for.
float hash12(vec2 p) {
  return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453);
}

// Stream function, domain-warped (sin inside sin) so the field never reads as
// the periodic sine sum it actually is. The domain scrolls downstream with the
// wind: eddies travel along with the plume rather than standing still in screen
// space, which is the actual signature of smoke.
float psiQ(vec2 q, float t) {
  float s  =        sin(q.x       + 1.7 * sin(q.y * 0.9 + t * 0.35));
  s       += 0.55 * sin(q.y * 2.1 - 1.3 * sin(q.x * 1.7 - t * 0.50));
  s       += 0.26 * sin((q.x + q.y) * 3.9 + t * 0.95);
  return s;
}

// Curl of psi — divergence-free, so the cloud swirls instead of pumping (a
// plain gradient field has sources and sinks: grains pile up and thin out in
// fixed spots, which reads as jitter). Differenced in normalized q space so the
// result is O(1) and the caller's amplitude stays in readable pixels.
vec2 curl(vec2 p, float t) {
  const float e = 0.06;
  vec2 q = p * 0.0055 - vec2(t * 0.62, 0.0);
  float dy = psiQ(q + vec2(0.0, e), t) - psiQ(q - vec2(0.0, e), t);
  float dx = psiQ(q + vec2(e, 0.0), t) - psiQ(q - vec2(e, 0.0), t);
  return vec2(dy, -dx) / (2.0 * e);
}

void main() {
  // A char starts granulating when the front touches its right edge, but its
  // grains do not all arrive at once — each waits out its own slice of the
  // GRAIN_IN window, so the letter crackles into dust instead of switching
  // over in one frame. The DOM glyph is still solid underneath for the whole
  // window, hiding the ramp entirely. No mask, no wipe line.
  float granT = (uFrontStart - aEdge.x) / uFrontSpeed;
  float visibleT = granT + GRAIN_IN * hash12(aHome);
  // A grain leaves once the front passes its own x (plus positive jitter so
  // dust lifts off the still-held face) — right-to-left, ragged, per-grain.
  float key = aHome.x + aRand2.z * 40.0;
  float releaseT = max((uFrontStart - key) / uFrontSpeed, visibleT);
  // Back-loaded peel: grains hold at home after release so the silhouette
  // stays anchored — but the window is tight (~2 chars of front travel), so
  // a char is mostly gone before the front reaches its second neighbor. The
  // crown of a glyph goes first (aEdge.y = 0 at the top): wind takes the
  // exposed top of a letter before it gets under the base. The floor is the
  // handoff guarantee — see PEEL_FLOOR.
  float peel = PEEL_FLOOR
    + 0.30 * pow(aRand.x, 0.7) * mix(0.55, 1.0, clamp(aEdge.y, 0.0, 1.0));
  float life = mix(1.0, 1.9, aRand2.x);
  float tf = clamp(uTime - releaseT - peel, 0.0, life);
  float lifeFrac = tf / life;

  // Drag-limited surge: v(t) = vterm * (1 - exp(-t/tau)) integrated — gentle
  // lift-off into a fast wash. sqrt bias favors screamers.
  float tau = 0.22;
  // Rank kept separate from the tuned speed: the motion-blur ghost below keys
  // off how fast this grain is *relative to its peers*, which is a property of
  // the grain. Fold uWind into it and turning the wind down would un-ghost the
  // whole field instead of just slowing it.
  float vrank = mix(150.0, 460.0, sqrt(aRand.y));
  float vterm = vrank * uWind;
  float base = vterm * (tf - tau * (1.0 - exp(-tf / tau)));

  // Buoyancy, accelerating — dust lifts as it loosens. Screen y is down.
  float rise = (mix(26.0, 88.0, aRand.w) * tf + 16.0) * tf * uBuoy;
  // Wind shear: the higher a grain climbs the faster the wind carries it, so
  // the plume rakes up-and-right in a curve instead of shooting flat.
  float dx = base * (1.0 + rise * 0.0016);
  // Fan spread: quadratic center-bias — soft tails peel off above and below.
  float fan = aRand.z * 2.0 - 1.0;
  float dy = fan * abs(fan) * 90.0 * tf - rise;

  vec2 ballistic = aHome + vec2(dx, dy);
  // Amplitude grows super-linearly with flight time: the diffusion-like spread
  // that frays the plume into wisps, without integrating any state.
  float turbAmp = mix(0.7, 1.5, aRand2.w) * 78.0 * pow(tf, 1.3) * uTurb;
  // The held face breathes before it lets go — a heat-haze shimmer that reads
  // as the letter loosening rather than waiting. Squared ramp from zero at the
  // grain's own arrival, so it is still sub-pixel while the DOM glyph is up.
  float held = clamp((uTime - visibleT) / 0.35, 0.0, 1.0);
  // Sampled at the travelling position, never at aHome — a grain has to enter
  // new eddies as it flies or the whole cloud just shimmers in place.
  vec2 pos = ballistic + curl(ballistic, uTime) * (turbAmp + 2.5 * held * held);

  // Arrival is a brief per-grain fade rather than a step — with the hash
  // stagger above, the char stipples in. Then opaque through most of the
  // travel and a long tail. Fast grains slightly ghosted — motion blur.
  float lifeK = 1.0 - lifeFrac;
  float alpha = clamp((uTime - visibleT) / 0.05, 0.0, 1.0) * pow(lifeK, 1.7);
  alpha *= mix(1.0, 0.62, (vrank / 460.0) * step(0.001, tf));
  vAlpha = alpha;
  vColor = mix(uInk, uAccent, aTint);
  // Drives the sprite profile: solid ink at rest, haze in flight.
  vSoft = pow(lifeFrac, 0.6);

  // Base size covers the sampling stride so the swap reads near-solid; the
  // 2.7x growth is dispersal — alpha falls faster than area grows, so total
  // ink still drops while each grain thins into haze.
  gl_PointSize =
    mix(2.6, 3.6, aRand2.y) * mix(1.0, 2.7, pow(lifeFrac, 0.75)) * uDpr * uGrainSize;
  gl_Position = vec4(
    pos.x / uResolution.x * 2.0 - 1.0,
    1.0 - pos.y / uResolution.y * 2.0,
    0.0,
    1.0
  );
  // Cull invisible points entirely — zero fragment cost.
  if (vAlpha < 0.004) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
}
`;

const FRAGMENT =  `
precision mediump float;

varying vec3 vColor;
varying float vAlpha;
varying float vSoft;

void main() {
  vec2 d = gl_PointCoord - 0.5;
  float r = length(d);
  // At rest the sprite is a plateau disc with a soft rim. This is what makes
  // the granulated glyph match solid ink: a gaussian's coverage collapses to
  // roughly half the sprite, so a field of them reads visibly lighter and
  // greyer than the DOM text it replaces — the letter appears to dim as it
  // cracks. In flight it morphs to a gaussian, where the soft falloff is
  // exactly what turns overlapping grains into haze instead of sand.
  float disc = 1.0 - smoothstep(0.34, 0.5, r);
  float haze = max(exp(-r * r * 11.0) - 0.064, 0.0) * 1.068;
  float m = mix(disc, haze, vSoft);
  float a = vAlpha * m;
  gl_FragColor = vec4(vColor * a, a); // premultiplied
}
`;

function supportsWebGL(): boolean {
  try {
    const c = document.createElement("canvas");
    return !!(
      c.getContext("webgl2") ||
      c.getContext("webgl") ||
      c.getContext("experimental-webgl")
    );
  } catch {
    return false;
  }
}

export function hexToRgb01(hex: string): [number, number, number] {
  let h = hex.trim().replace("#", "");
  if (h.length === 3) {
    h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
  }
  if (h.length !== 6 || !/^[0-9a-f]{6}$/i.test(h)) return [1, 1, 1];
  return [
    parseInt(h.slice(0, 2), 16) / 255,
    parseInt(h.slice(2, 4), 16) / 255,
    parseInt(h.slice(4, 6), 16) / 255,
  ];
}

export function sampleWord(
  spans: (HTMLElement | null)[],
  origin: { left: number; top: number },
  budgetPerChar: number,
  splitIndex: number,
): GrainData {
  const home: number[] = [];
  const tint: number[] = [];
  const rand: number[] = [];
  const rand2: number[] = [];
  const edge: number[] = [];

  for (let index = 0; index < spans.length; index++) {
    const span = spans[index];
    if (!span) continue;
    const box = span.getBoundingClientRect();
    const text = span.textContent;
    if (!text || box.width < 1 || box.height < 1) continue;

    const rect = {
      left: box.left - origin.left,
      top: box.top - origin.top,
      right: box.right - origin.left,
      width: box.width,
      height: box.height,
    };

    const cs = getComputedStyle(span);
    const fontSize = parseFloat(cs.fontSize);

    const w = Math.ceil(rect.width) + 8;
    const h = Math.ceil(rect.height) + 8;
    const off = document.createElement("canvas");
    off.width = w;
    off.height = h;
    const ctx = off.getContext("2d", { willReadFrequently: true });
    if (!ctx) continue;

    ctx.font = `${cs.fontStyle} ${cs.fontWeight} ${fontSize}px ${cs.fontFamily}`;
    ctx.textAlign = "center";
    ctx.fillStyle = "#ffffff";

    const originY = rect.top + rect.height / 2 - h / 2;
    const metrics = ctx.measureText(text);
    const fba = metrics.fontBoundingBoxAscent;
    const fbd = metrics.fontBoundingBoxDescent;
    if (Number.isFinite(fba) && Number.isFinite(fbd) && fba + fbd > 0) {
      const halfLeading = (rect.height - (fba + fbd)) / 2;
      const baselineY = rect.top + halfLeading + fba;
      ctx.textBaseline = "alphabetic";
      ctx.fillText(text, w / 2, baselineY - originY);
    } else {
      ctx.textBaseline = "middle";
      ctx.fillText(text, w / 2, h / 2);
    }

    const inkArea = rect.width * fontSize * 0.45;
    const gap = Math.max(2, Math.ceil(Math.sqrt(inkArea / budgetPerChar)));

    const data = ctx.getImageData(0, 0, w, h).data;
    const originX = rect.left + rect.width / 2 - w / 2;
    const tintValue = index < splitIndex ? 0 : 1;

    for (let py = 0; py < h; py += gap) {
      for (let px = 0; px < w; px += gap) {
        if (data[(py * w + px) * 4 + 3] > 128) {
          const y = originY + py + (Math.random() - 0.5) * gap;
          home.push(originX + px + (Math.random() - 0.5) * gap, y);
          tint.push(tintValue);
          rand.push(Math.random(), Math.random(), Math.random(), Math.random());
          rand2.push(Math.random(), Math.random(), Math.random(), Math.random());
          edge.push(rect.right, (y - rect.top) / rect.height);
        }
      }
    }
  }

  return {
    count: home.length / 2,
    home: new Float32Array(home),
    tint: new Float32Array(tint),
    rand: new Float32Array(rand),
    rand2: new Float32Array(rand2),
    edge: new Float32Array(edge),
  };
}

export function createDustGL(
  container: HTMLElement,
  grains: GrainData,
  opts: {
    width: number;
    height: number;
    dpr: number;
    frontStart: number;
    frontSpeed: number;
    params: DustParams;
  },
): DustGL {
  if (!supportsWebGL()) throw new Error("WebGL unavailable");
  if (!(opts.frontSpeed > 0)) throw new Error("frontSpeed must be > 0");

  const renderer = new Renderer({
    width: opts.width,
    height: opts.height,
    dpr: opts.dpr,
    alpha: true,
    premultipliedAlpha: true,
    depth: false,
    antialias: false,
    powerPreference: "high-performance",
  });
  const gl = renderer.gl;
  if (gl.isContextLost()) throw new Error("context lost at init");
  gl.clearColor(0, 0, 0, 0);

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

  const buildGeometry = (g: GrainData) =>
    new Geometry(gl, {
      aHome: { size: 2, data: g.home },
      aTint: { size: 1, data: g.tint },
      aRand: { size: 4, data: g.rand },
      aRand2: { size: 4, data: g.rand2 },
      aEdge: { size: 2, data: g.edge },
    });

  const uniforms = {
    uTime: { value: 0 },
    uFrontStart: { value: opts.frontStart },
    uFrontSpeed: { value: opts.frontSpeed },
    uResolution: { value: new Float32Array([opts.width, opts.height]) },
    uDpr: { value: opts.dpr },
    uWind: { value: opts.params.wind },
    uBuoy: { value: opts.params.buoyancy },
    uTurb: { value: opts.params.turbulence },
    uGrainSize: { value: opts.params.grainSize },
    uInk: { value: new Float32Array(opts.params.ink) },
    uAccent: { value: new Float32Array(opts.params.accent) },
  };

  const program = new Program(gl, {
    vertex: VERTEX,
    fragment: FRAGMENT,
    uniforms,
    transparent: true,
    depthTest: false,
    depthWrite: false,
  });
  if (!gl.getProgramParameter(program.program, gl.LINK_STATUS)) {
    throw new Error("dust shader failed to link");
  }

  let geometry = buildGeometry(grains);
  let mesh = new Mesh(gl, { geometry, program, mode: gl.POINTS });
  let disposed = false;

  return {
    gl,
    canvas,
    setSize(w, h, dpr) {
      if (disposed) return;
      renderer.dpr = dpr;
      renderer.setSize(w, h);
      uniforms.uResolution.value[0] = w;
      uniforms.uResolution.value[1] = h;
      uniforms.uDpr.value = dpr;
    },
    setGrains(next) {
      if (disposed || next.count === 0) return;
      const previous = geometry;
      geometry = buildGeometry(next);
      mesh = new Mesh(gl, { geometry, program, mode: gl.POINTS });
      previous.remove();
    },
    setFront(frontStart, frontSpeed) {
      if (disposed || !(frontSpeed > 0)) return;
      uniforms.uFrontStart.value = frontStart;
      uniforms.uFrontSpeed.value = frontSpeed;
    },
    setParams(params) {
      if (disposed) return;
      uniforms.uWind.value = params.wind;
      uniforms.uBuoy.value = params.buoyancy;
      uniforms.uTurb.value = params.turbulence;
      uniforms.uGrainSize.value = params.grainSize;
      uniforms.uInk.value.set(params.ink);
      uniforms.uAccent.value.set(params.accent);
    },
    render(t) {
      if (disposed) return;
      uniforms.uTime.value = t;
      renderer.render({ scene: mesh });
    },
    dispose() {
      if (disposed) return;
      disposed = true;
      geometry.remove();
      canvas.remove();
      gl.getExtension("WEBGL_lose_context")?.loseContext();
    },
  };
}
```

### 3. `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 |
| --- | --- | --- | --- |
| `sweepDuration` | `number` | `1.9` | Time the wind front takes to cross the wordmark. Everything downstream is derived from it — the reveal fires at 93.7% of the sweep, so shortening it tightens the whole sequence rather than leaving the plume stranded after a fast wipe. Range 0.6–5 s. |
| `grainDensity` | `number` | `2500` | Grains sampled per glyph. The sampling stride adapts to font size, so this is a count and not a spacing — a glyph holds roughly this many points whether it renders at 28px or 112px. The performance knob: every grain is one point in a single draw call, and changing it re-rasterizes the word. Range 400–6000. |
| `windSpeed` | `number` | `1` | How hard the wind carries released grains downstream. Each grain keeps its own speed rank, so the motion-blur ghosting on the fastest ones survives turning the wind down — the plume slows without flattening into a uniform sheet. Range 0–3 ×. |
| `buoyancy` | `number` | `1` | How fast the plume climbs. Lift also feeds the wind shear, so raising it does not just push the dust up — it rakes the risen grains further ahead and bends the plume into a curve instead of a diagonal. Range 0–3 ×. |
| `turbulence` | `number` | `1` | Amplitude of the divergence-free curl field the grains are advected through. The field is sampled at each grain's travelling position, so grains meet new eddies as they fly — that is the difference between smoke and shimmer. At zero the dust is pure ballistics. Range 0–3 ×. |
| `grainSize` | `number` | `1` | Size of an individual grain. The base covers the sampling stride so the held letter reads as solid ink; push it far below 1 and the handoff starts to show the lattice underneath. Range 0.4–2.5 ×. |
| `splitIndex` | `number` | `6` | How many characters carry the ink colour before the accent takes over. The tint travels with each grain, so the dust keeps the colour of the letter it came from all the way out. Range 0–16. |
| `reveal` | `"split" | "fade" | "none"` | `"split"` | How the backdrop leaves. Split slides two halves apart from the centre line; fade dissolves it in place; none draws no backdrop at all, so the wordmark erodes over whatever is already behind it. |
| `autoplay` | `boolean` | `true` | Replay the sequence on a loop. Off is the real thing: the intro plays once, calls onDone, and returns false to the loop host so it stops costing frames for good. |
| `replayDelay` | `number` | `1.2` | Pause between the plume clearing and the wordmark reassembling. Long enough to read as a fresh entrance rather than a stutter. Range 0–6 s. Ignored while `autoplay` is `false`. |
| `inkColor` | `string (hex)` | `"#e9e7ef"` | Colour of the leading characters and the dust that comes off them. |
| `accentColor` | `string (hex)` | `"#a855f7"` | Amethyst on the characters from the split onward. A uniform, not baked into the grain buffer, so dragging it never re-rasterizes the word. |
| `backgroundColor` | `string (hex)` | `"#08050e"` | The field the wordmark sits on and the thing the reveal opens. Its own material rather than a themed surface — an intro that flashes white in a light theme defeats the point of covering the page. |

## Usage

```tsx
import IntroAnimation from "@/components/registry/intro-animation/intro-animation";

<IntroAnimation
  sweepDuration={1.9}
  grainDensity={2500}
  windSpeed={1}
  buoyancy={1}
  turbulence={1}
  grainSize={1}
  splitIndex={6}
  reveal="split"
  autoplay={true}
  replayDelay={1.2}
  inkColor="#e9e7ef"
  accentColor="#a855f7"
  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.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- 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.
