Backgrounds02 / 118
Shallows
An underwater hero background. The water is a real fluid simulation your cursor pushes around, caustic light dances across the floor, a giant word is refracted by the moving water, and the soft shadows of a flock of birds glide over it, scattering from your cursor.
WebGL2 fluid simWebGL2 fluid simZero dependenciesZero dependencies60fps60fpsLive tweaksLive tweaksReduced-motion safeReduced-motion safe
Drift
Stir the waterClick for a burstChase the birds
Tweak
LIVELIVEContent
Colour
#08336b
#020816
#8cdbff
#c7bda3
Water
1.00
1.00
1.00
1.00
Flock
6
1.00
Usage
Follows your tweaks.
usage.tsx
import { Shallows } from "@/components/inreact/shallows";
export function Hero() {
return (
<Shallows
text="Drift"
className="h-[80vh] w-full"
>
{/* optional: your hero content, drawn above the water */}
</Shallows>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/shallows.jsonTS + CSS
npx shadcn@latest add https://inreact.vercel.app/r/shallows-css.jsonOr copy the source
No dependencies. Save this as components/inreact/shallows.tsx.
components/inreact/shallows.tsx
"use client";
import { useEffect, useRef, type ReactNode } from "react";
/**
* Shallows: an underwater hero background.
*
* - The water is a real-time GPU fluid (stable fluids: advection, vorticity
* confinement, Jacobi pressure solve). Your cursor pushes it around and a
* click sends a burst through it.
* - Caustic light dances across the floor, brighter where the water is stirred,
* with sun shafts from the surface.
* - A giant word lies on the floor and is refracted by the moving water.
* - A flock of birds flies overhead in formation; you only see their soft
* shadows, and they scatter away from your cursor.
*
* Usage:
*
* <Shallows text="Drift" className="h-[80vh] w-full">
* <YourHeroContent />
* </Shallows>
*
* The word uses the component's font (set font-family on it or a parent).
* Needs WebGL2 with float render targets; otherwise it shows a still gradient
* with the word in plain text. Pauses off-screen, honours
* prefers-reduced-motion. Colours and sliders update live.
*/
export interface ShallowsProps {
/** The word on the sea floor. Also exposed to screen readers. */
text?: string;
/** Shallow water colour, near the surface (top). */
water?: string;
/** Deep water colour (bottom and edges). */
deep?: string;
/** Colour of the caustic light and sun shafts. */
light?: string;
/** Colour of the word on the floor. */
textColor?: string;
/** Brightness of the caustics. */
caustics?: number;
/** How strongly the moving water bends the floor. */
refraction?: number;
/** How much the water swirls after you stir it. */
swirl?: number;
/** Animation speed multiplier. */
speed?: number;
/** Birds per flock (0 to 8). */
birds?: number;
/** Size multiplier for the bird shadows. */
birdSize?: number;
className?: string;
/** Foreground content, drawn above the water. */
children?: ReactNode;
}
const MAX_BIRDS = 8;
const VERT = `#version 300 es
precision highp float;
in vec2 aPos;
uniform vec2 uTexel;
out vec2 vUv, vL, vR, vT, vB;
void main(){
vUv = aPos * 0.5 + 0.5;
vL = vUv - vec2(uTexel.x, 0.0);
vR = vUv + vec2(uTexel.x, 0.0);
vT = vUv + vec2(0.0, uTexel.y);
vB = vUv - vec2(0.0, uTexel.y);
gl_Position = vec4(aPos, 0.0, 1.0);
}`;
const HEAD = `#version 300 es
precision highp float;
precision highp sampler2D;
in vec2 vUv, vL, vR, vT, vB;
out vec4 o;
`;
const FRAG = {
splat: `${HEAD}
uniform sampler2D uTarget; uniform float uAspect; uniform vec3 uColor; uniform vec2 uPoint; uniform float uRadius;
void main(){
vec2 p = vUv - uPoint; p.x *= uAspect;
vec3 s = exp(-dot(p, p) / uRadius) * uColor;
o = vec4(texture(uTarget, vUv).xyz + s, 1.0);
}`,
advect: `${HEAD}
uniform sampler2D uVelocity; uniform sampler2D uSource; uniform vec2 uSimTexel; uniform float uDt; uniform float uDissipation;
void main(){
vec2 coord = vUv - uDt * texture(uVelocity, vUv).xy * uSimTexel;
o = texture(uSource, coord) / (1.0 + uDissipation * uDt);
o.a = 1.0;
}`,
divergence: `${HEAD}
uniform sampler2D uVelocity;
void main(){
float L = texture(uVelocity, vL).x, R = texture(uVelocity, vR).x;
float T = texture(uVelocity, vT).y, B = texture(uVelocity, vB).y;
vec2 C = texture(uVelocity, vUv).xy;
if (vL.x < 0.0) L = -C.x;
if (vR.x > 1.0) R = -C.x;
if (vT.y > 1.0) T = -C.y;
if (vB.y < 0.0) B = -C.y;
o = vec4(0.5 * (R - L + T - B), 0.0, 0.0, 1.0);
}`,
curl: `${HEAD}
uniform sampler2D uVelocity;
void main(){
float L = texture(uVelocity, vL).y, R = texture(uVelocity, vR).y;
float T = texture(uVelocity, vT).x, B = texture(uVelocity, vB).x;
o = vec4(0.5 * (R - L - T + B), 0.0, 0.0, 1.0);
}`,
vorticity: `${HEAD}
uniform sampler2D uVelocity; uniform sampler2D uCurl; uniform float uCurlStrength; uniform float uDt;
void main(){
float L = texture(uCurl, vL).x, R = texture(uCurl, vR).x;
float T = texture(uCurl, vT).x, B = texture(uCurl, vB).x;
float C = texture(uCurl, vUv).x;
vec2 f = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L));
f /= length(f) + 1e-4;
f *= uCurlStrength * C;
f.y *= -1.0;
vec2 v = texture(uVelocity, vUv).xy + f * uDt;
o = vec4(clamp(v, -1000.0, 1000.0), 0.0, 1.0);
}`,
pressure: `${HEAD}
uniform sampler2D uPressure; uniform sampler2D uDivergence;
void main(){
float L = texture(uPressure, vL).x, R = texture(uPressure, vR).x;
float T = texture(uPressure, vT).x, B = texture(uPressure, vB).x;
float d = texture(uDivergence, vUv).x;
o = vec4((L + R + B + T - d) * 0.25, 0.0, 0.0, 1.0);
}`,
gradient: `${HEAD}
uniform sampler2D uPressure; uniform sampler2D uVelocity;
void main(){
float L = texture(uPressure, vL).x, R = texture(uPressure, vR).x;
float T = texture(uPressure, vT).x, B = texture(uPressure, vB).x;
vec2 v = texture(uVelocity, vUv).xy - vec2(R - L, T - B);
o = vec4(v, 0.0, 1.0);
}`,
scale: `${HEAD}
uniform sampler2D uTexture; uniform float uValue;
void main(){ o = uValue * texture(uTexture, vUv); }`,
display: `${HEAD}
uniform sampler2D uDye; uniform sampler2D uVelocity; uniform sampler2D uText;
uniform float uTime; uniform float uAspect;
uniform vec3 uDeep; uniform vec3 uShallow; uniform vec3 uLight; uniform vec3 uSand;
uniform float uCaustics; uniform float uRefract;
uniform vec4 uBirdA[${MAX_BIRDS}]; // x, y (uv), heading, flap phase
uniform vec4 uBirdB[${MAX_BIRDS}]; // size, alpha, -, -
uniform int uBirdCount;
float caustics(vec2 p, float t){
// Warped wave interference: bright, curvy filaments where the
// product of two wave fields crosses zero, like light through ripples.
vec2 q = p * 3.3;
float c = 0.0;
for (int i = 0; i < 3; i++){
float fi = float(i);
q += vec2(sin(q.y * 1.6 + t * 0.55 + fi * 1.3), cos(q.x * 1.4 - t * 0.5 + fi * 2.1)) * 0.55;
float wave = sin(q.x * 1.15 + q.y * 0.65 + t * 0.35) * cos(q.y * 1.25 - q.x * 0.45 - t * 0.25);
c += 0.045 / (abs(wave) + 0.04);
}
c /= 3.0;
return clamp(pow(c, 2.0) * 0.95, 0.0, 1.8);
}
// soft top-down silhouette of a bird; local space: +x is the flight direction
float bird(vec2 q, float flap){
float span = 1.0 * (0.72 + 0.28 * cos(flap));
float ax = abs(q.y);
float sweep = -ax * 0.45 + 0.08 * sin(flap) * ax;
float chord = 0.26 * (1.0 - smoothstep(0.0, span, ax));
float wing = abs(q.x - sweep) - chord;
wing = max(wing, ax - span);
float body = length(q * vec2(0.55, 2.4)) - 0.16;
float tail = length((q - vec2(-0.38, 0.0)) * vec2(1.4, 2.0)) - 0.12;
return min(min(wing, body), tail);
}
void main(){
float t = uTime;
vec2 vel = texture(uVelocity, vUv).xy;
float stir = texture(uDye, vUv).r;
vec2 p = vec2(vUv.x * uAspect, vUv.y);
// the surface refracts everything on the floor
vec2 refr = (vel * 0.00022 + vec2(stir * 0.006) * vec2(sin(t * 3.0 + p.y * 20.0), cos(t * 2.6 + p.x * 20.0)) + vec2(sin(p.y * 9.0 + t * 1.3), cos(p.x * 8.0 - t * 1.1)) * 0.004) * uRefract;
vec2 fp = p + refr;
vec2 fuv = vUv + vec2(refr.x / uAspect, refr.y);
// water body: deep at the bottom, lighter toward the surface
vec3 col = mix(uDeep, uShallow, smoothstep(-0.1, 1.1, vUv.y));
// the word on the floor
float text = texture(uText, vec2(fuv.x, 1.0 - fuv.y)).r;
col = mix(col, uSand * (0.55 + 0.45 * vUv.y), text * 0.9);
// bird shadows, cast from high above: soft and wobbling with the water
float shadow = 0.0;
for (int i = 0; i < ${MAX_BIRDS}; i++){
if (i >= uBirdCount) break;
vec4 A = uBirdA[i];
vec4 B = uBirdB[i];
vec2 d = fp - vec2(A.x * uAspect, A.y);
float c = cos(-A.z), s = sin(-A.z);
vec2 q = vec2(d.x * c - d.y * s, d.x * s + d.y * c) / B.x;
float sd = bird(q, A.w);
shadow = max(shadow, (1.0 - smoothstep(-0.12, 0.3, sd)) * B.y);
}
col *= 1.0 - shadow * 0.7;
// caustic light dances on the floor, brighter where the water is stirred
float c = caustics(fp, t) * (1.0 + stir * 2.5) * uCaustics;
vec3 light = uLight * c * (1.0 - shadow * 0.9);
col += light * (0.28 + 0.4 * vUv.y) + light * text * 0.35;
// sun shafts from the surface
float rays = pow(max(0.0, sin(p.x * 5.0 - p.y * 1.8 + sin(t * 0.25) * 1.5)), 10.0)
+ 0.6 * pow(max(0.0, sin(p.x * 8.3 - p.y * 2.6 - t * 0.18)), 14.0);
col += uLight * vec3(0.82, 0.84, 1.0) * rays * smoothstep(0.2, 1.0, vUv.y) * 0.16;
// stirred water: a soft shimmer, never coloured ink
col += uLight * vec3(0.91, 0.95, 1.0) * smoothstep(0.4, 1.6, stir) * 0.1;
// depth fog toward the edges
vec2 v = vUv - vec2(0.5, 0.62);
col = mix(col, uDeep, smoothstep(0.35, 1.0, length(v * vec2(1.0, 1.3))) * 0.65);
o = vec4(col, 1.0);
}`,
} as const;
type Prog = { prog: WebGLProgram; u: Record<string, WebGLUniformLocation | null> };
type FBO = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number };
type DFBO = { read: FBO; write: FBO; swap: () => void };
interface Bird {
ox: number; // formation offset (aspect space, local to heading)
oy: number;
sx: number; // scatter offset from the cursor
sy: number;
vx: number;
vy: number;
phase: number;
flap: number;
size: number;
}
function hexToRgb(hex: string): [number, number, number] {
const h = hex.replace("#", "");
const n = parseInt(h.length === 3 ? h.replace(/./g, "$&$&") : h, 16);
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function Shallows({
text = "Drift",
water = "#08336b",
deep = "#020816",
light = "#8cdbff",
textColor = "#c7bda3",
caustics = 1,
refraction = 1,
swirl = 1,
speed = 1,
birds = 6,
birdSize = 1,
className,
children,
}: ShallowsProps) {
const hostRef = useRef<HTMLDivElement>(null);
const wordRef = useRef<HTMLSpanElement>(null);
const live = useRef({ text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize });
const hooks = useRef<{ relayout: () => void; reflock: () => void; redraw: () => void } | null>(null);
useEffect(() => {
const prev = live.current;
live.current = { text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize };
if (prev.text !== text) hooks.current?.relayout();
if (prev.birds !== birds) hooks.current?.reflock();
hooks.current?.redraw();
}, [text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
// stay where the user put it (absolute, fixed...), otherwise anchor the layers
if (getComputedStyle(host).position === "static") host.style.position = "relative";
// a fresh canvas per mount: a context lost on unmount never comes back
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%";
canvas.setAttribute("aria-hidden", "true");
host.prepend(canvas);
const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, depth: false, stencil: false });
const canFloat = gl && (gl.getExtension("EXT_color_buffer_float") || gl.getExtension("EXT_color_buffer_half_float"));
if (!gl || !canFloat) {
// no fluid sim here: a still underwater gradient and the word as plain text
const L = live.current;
canvas.remove();
host.style.background = `radial-gradient(80% 70% at 50% 15%, ${L.water}, ${L.deep} 85%)`;
const word = wordRef.current;
if (word) {
Object.assign(word.style, {
inset: "0",
width: "auto",
height: "auto",
clip: "auto",
display: "grid",
placeItems: "center",
fontSize: "min(22vw, 40vh)",
fontWeight: "800",
lineHeight: "1",
color: L.textColor,
});
}
return;
}
/* ---------- GL helpers ---------- */
const shader = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.warn(gl.getShaderInfoLog(s));
return s;
};
const vs = shader(gl.VERTEX_SHADER, VERT);
const program = (src: string): Prog => {
const prog = gl.createProgram()!;
gl.attachShader(prog, vs);
gl.attachShader(prog, shader(gl.FRAGMENT_SHADER, src));
gl.bindAttribLocation(prog, 0, "aPos");
gl.linkProgram(prog);
const u: Prog["u"] = {};
const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;
for (let i = 0; i < n; i++) {
const name = gl.getActiveUniform(prog, i)!.name;
u[name] = gl.getUniformLocation(prog, name);
}
return { prog, u };
};
const P = Object.fromEntries(Object.entries(FRAG).map(([k, src]) => [k, program(src)])) as Record<
keyof typeof FRAG,
Prog
>;
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const fbo = (w: number, h: number, internal: number, format: number): FBO => {
const tex = gl.createTexture()!;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, internal, w, h, 0, format, gl.HALF_FLOAT, null);
const fb = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.viewport(0, 0, w, h);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return { tex, fbo: fb, w, h };
};
const dfbo = (w: number, h: number, internal: number, format: number): DFBO => {
const d = { read: fbo(w, h, internal, format), write: fbo(w, h, internal, format), swap: () => {} };
d.swap = () => {
const t = d.read;
d.read = d.write;
d.write = t;
};
return d;
};
const free = (t: FBO) => {
gl.deleteTexture(t.tex);
gl.deleteFramebuffer(t.fbo);
};
// RGBA16F is renderable everywhere EXT_color_buffer_* exists; use it for all.
const F = gl.RGBA16F;
const FMT = gl.RGBA;
let bound = 0;
const bind = (t: FBO) => {
gl.activeTexture(gl.TEXTURE0 + bound);
gl.bindTexture(gl.TEXTURE_2D, t.tex);
return bound++;
};
const run = (p: Prog, target: FBO | null, texel: [number, number], set: () => void) => {
gl.useProgram(p.prog);
bound = 0;
gl.uniform2f(p.u.uTexel, texel[0], texel[1]);
set();
if (target) {
gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo);
gl.viewport(0, 0, target.w, target.h);
} else {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
/* ---------- sizing & targets ---------- */
let w = 1;
let h = 1;
let velocity!: DFBO;
let dye!: DFBO;
let pressure!: DFBO;
let divergence!: FBO;
let curl!: FBO;
let sim: [number, number] = [1, 1];
const textTex = gl.createTexture()!;
const textCanvas = document.createElement("canvas");
const drawText = () => {
const family = getComputedStyle(host).fontFamily || "Arial";
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
textCanvas.width = Math.round(w * dpr);
textCanvas.height = Math.round(h * dpr);
const c = textCanvas.getContext("2d")!;
c.setTransform(dpr, 0, 0, dpr, 0, 0);
c.fillStyle = "#000";
c.fillRect(0, 0, w, h);
const word = live.current.text;
if (word.trim()) {
let size = h * 0.62;
c.font = `800 ${size}px ${family}`;
const fit = (w * 0.86) / c.measureText(word).width;
if (fit < 1) size *= fit;
c.font = `800 ${size}px ${family}`;
c.textAlign = "center";
c.textBaseline = "middle";
c.fillStyle = "#fff";
c.fillText(word, w / 2, h * 0.44);
}
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textCanvas);
};
let sized = false;
const resize = () => {
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const aspect = w / h;
const simH = 128;
const simW = Math.round(simH * aspect);
const dyeH = Math.min(720, Math.round(h * dpr));
const dyeW = Math.round(dyeH * aspect);
sim = [simW, simH];
if (sized) {
[velocity, pressure, dye].forEach((d) => (free(d.read), free(d.write)));
free(divergence);
free(curl);
}
sized = true;
velocity = dfbo(simW, simH, F, FMT);
pressure = dfbo(simW, simH, F, FMT);
divergence = fbo(simW, simH, F, FMT);
curl = fbo(simW, simH, F, FMT);
dye = dfbo(dyeW, dyeH, F, FMT);
drawText();
};
resize();
let lastW = w;
let lastH = h;
const ro = new ResizeObserver(() => {
if (Math.abs(host.clientWidth - lastW) > 2 || Math.abs(host.clientHeight - lastH) > 2) {
lastW = host.clientWidth;
lastH = host.clientHeight;
resize();
if (!raf) render(t);
}
});
ro.observe(host);
/* ---------- simulation ---------- */
const simTexel = (): [number, number] => [1 / sim[0], 1 / sim[1]];
const splat = (x: number, y: number, dx: number, dy: number, color: [number, number, number], radius = 0.0025) => {
run(P.splat, velocity.write, simTexel(), () => {
gl.uniform1i(P.splat.u.uTarget, bind(velocity.read));
gl.uniform1f(P.splat.u.uAspect, w / h);
gl.uniform2f(P.splat.u.uPoint, x, y);
gl.uniform3f(P.splat.u.uColor, dx, dy, 0);
gl.uniform1f(P.splat.u.uRadius, radius);
});
velocity.swap();
run(P.splat, dye.write, [1 / dye.read.w, 1 / dye.read.h], () => {
gl.uniform1i(P.splat.u.uTarget, bind(dye.read));
gl.uniform1f(P.splat.u.uAspect, w / h);
gl.uniform2f(P.splat.u.uPoint, x, y);
gl.uniform3f(P.splat.u.uColor, color[0], color[1], color[2]);
gl.uniform1f(P.splat.u.uRadius, radius);
});
dye.swap();
};
const step = (dt: number) => {
const st = simTexel();
run(P.curl, curl, st, () => gl.uniform1i(P.curl.u.uVelocity, bind(velocity.read)));
run(P.vorticity, velocity.write, st, () => {
gl.uniform1i(P.vorticity.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.vorticity.u.uCurl, bind(curl));
gl.uniform1f(P.vorticity.u.uCurlStrength, 28 * live.current.swirl);
gl.uniform1f(P.vorticity.u.uDt, dt);
});
velocity.swap();
run(P.divergence, divergence, st, () => gl.uniform1i(P.divergence.u.uVelocity, bind(velocity.read)));
run(P.scale, pressure.write, st, () => {
gl.uniform1i(P.scale.u.uTexture, bind(pressure.read));
gl.uniform1f(P.scale.u.uValue, 0.8);
});
pressure.swap();
for (let i = 0; i < 20; i++) {
run(P.pressure, pressure.write, st, () => {
gl.uniform1i(P.pressure.u.uPressure, bind(pressure.read));
gl.uniform1i(P.pressure.u.uDivergence, bind(divergence));
});
pressure.swap();
}
run(P.gradient, velocity.write, st, () => {
gl.uniform1i(P.gradient.u.uPressure, bind(pressure.read));
gl.uniform1i(P.gradient.u.uVelocity, bind(velocity.read));
});
velocity.swap();
run(P.advect, velocity.write, st, () => {
gl.uniform1i(P.advect.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.advect.u.uSource, bind(velocity.read));
gl.uniform2f(P.advect.u.uSimTexel, st[0], st[1]);
gl.uniform1f(P.advect.u.uDt, dt);
gl.uniform1f(P.advect.u.uDissipation, 0.15);
});
velocity.swap();
run(P.advect, dye.write, [1 / dye.read.w, 1 / dye.read.h], () => {
gl.uniform1i(P.advect.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.advect.u.uSource, bind(dye.read));
gl.uniform2f(P.advect.u.uSimTexel, st[0], st[1]);
gl.uniform1f(P.advect.u.uDt, dt);
gl.uniform1f(P.advect.u.uDissipation, 1.6);
});
dye.swap();
};
/* ---------- the flock overhead ---------- */
const flock = { birds: [] as Bird[], cx: -1, cy: 0.5, heading: 0, speed: 0.075, wait: 0 };
const birdA = new Float32Array(MAX_BIRDS * 4);
const birdB = new Float32Array(MAX_BIRDS * 4);
let first = true; // the first flock starts in view
const spawnFlock = () => {
const want = Math.max(0, Math.min(MAX_BIRDS, Math.round(live.current.birds)));
// a little variety: one bird more or fewer than asked
const n = want === 0 ? 0 : Math.max(1, Math.min(MAX_BIRDS, want - 1 + Math.floor(Math.random() * 3)));
const fromLeft = Math.random() < 0.5;
const tilt = (Math.random() - 0.5) * 0.7;
flock.heading = fromLeft ? tilt : Math.PI + tilt;
flock.cx = first ? (fromLeft ? 0.2 : 0.8) : fromLeft ? -0.3 : 1.3;
first = false;
flock.cy = 0.25 + Math.random() * 0.5 - Math.sin(tilt) * 0.3;
flock.birds = Array.from({ length: n }, (_, i) => {
const rank = Math.ceil(i / 2);
const side = i % 2 ? 1 : -1;
return {
ox: -rank * 0.075 + (Math.random() - 0.5) * 0.02,
oy: side * rank * 0.065 + (Math.random() - 0.5) * 0.02,
sx: 0,
sy: 0,
vx: 0,
vy: 0,
phase: Math.random() * 6.28,
flap: 7 + Math.random() * 3,
size: 0.06 + Math.random() * 0.025,
};
});
if (!n) flock.wait = 2;
};
const updateFlock = (dt: number, time: number) => {
const aspect = w / h;
const scale = live.current.birdSize;
if (!flock.birds.length) {
flock.wait -= dt;
if (flock.wait <= 0) spawnFlock();
return 0;
}
flock.heading += Math.sin(time * 0.35) * 0.06 * dt;
const hx = Math.cos(flock.heading);
const hy = Math.sin(flock.heading);
flock.cx += (hx * flock.speed * dt) / aspect;
flock.cy += hy * flock.speed * dt;
let count = 0;
for (const b of flock.birds) {
// formation position, rotated into the heading
const ox = b.ox * scale;
const oy = b.oy * scale;
const fx = flock.cx * aspect + ox * hx - oy * hy + Math.sin(time * 0.9 + b.phase) * 0.008;
const fy = flock.cy + ox * hy + oy * hx + Math.cos(time * 1.1 + b.phase) * 0.008;
// scatter away from the cursor
if (ptr.hover && !reduced) {
const dx = fx + b.sx - ptr.x * aspect;
const dy = fy + b.sy - ptr.y;
const d = Math.hypot(dx, dy);
if (d < 0.22) {
const f = (1 - d / 0.22) * 2.4;
b.vx += (dx / (d + 1e-3)) * f * dt;
b.vy += (dy / (d + 1e-3)) * f * dt;
b.flap = 14;
}
}
b.vx = (b.vx - b.sx * 1.2 * dt) * 0.96;
b.vy = (b.vy - b.sy * 1.2 * dt) * 0.96;
b.sx += b.vx * dt;
b.sy += b.vy * dt;
b.flap += (8 - b.flap) * dt * 0.8;
// occasional glide
const gliding = Math.sin(time * 0.5 + b.phase * 3) > 0.55;
b.phase += dt * (gliding ? 0.6 : b.flap);
const x = fx + b.sx;
const y = fy + b.sy;
const edge = Math.min(x / aspect + 0.15, 1.15 - x / aspect, y + 0.15, 1.15 - y);
const k = count * 4;
birdA[k] = x / aspect;
birdA[k + 1] = y;
birdA[k + 2] = flock.heading;
birdA[k + 3] = b.phase;
birdB[k] = b.size * scale;
birdB[k + 1] = Math.max(0, Math.min(1, edge * 6)) * 0.9;
count++;
}
if (flock.cx < -0.6 || flock.cx > 1.6 || flock.cy < -0.6 || flock.cy > 1.6) {
flock.birds = [];
flock.wait = 1.5 + Math.random() * 3;
}
return count;
};
let birdCount = 0;
const render = (time: number) => {
const L = live.current;
run(P.display, null, simTexel(), () => {
const u = P.display.u;
gl.uniform1i(u.uDye, bind(dye.read));
gl.uniform1i(u.uVelocity, bind(velocity.read));
gl.activeTexture(gl.TEXTURE0 + bound);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.uniform1i(u.uText, bound++);
gl.uniform1f(u.uTime, time);
gl.uniform1f(u.uAspect, w / h);
gl.uniform3fv(u.uDeep, hexToRgb(L.deep));
gl.uniform3fv(u.uShallow, hexToRgb(L.water));
gl.uniform3fv(u.uLight, hexToRgb(L.light));
gl.uniform3fv(u.uSand, hexToRgb(L.textColor));
gl.uniform1f(u.uCaustics, L.caustics);
gl.uniform1f(u.uRefract, L.refraction);
gl.uniform4fv(u["uBirdA[0]"], birdA);
gl.uniform4fv(u["uBirdB[0]"], birdB);
gl.uniform1i(u.uBirdCount, birdCount);
});
};
/* ---------- input ---------- */
const reduced = isReducedMotion();
const ptr = { x: 0, y: 0, px: 0, py: 0, moved: false, hover: false };
const toUv = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
return [(e.clientX - r.left) / r.width, 1 - (e.clientY - r.top) / r.height];
};
const enter = (e: PointerEvent) => {
[ptr.px, ptr.py] = toUv(e);
ptr.x = ptr.px;
ptr.y = ptr.py;
ptr.hover = true;
};
const move = (e: PointerEvent) => {
if (!ptr.hover) enter(e);
[ptr.x, ptr.y] = toUv(e);
ptr.moved = true;
};
const leave = () => (ptr.hover = false);
const burst = (e: PointerEvent) => {
const [x, y] = toUv(e);
for (let i = 0; i < 10; i++) {
const a = (i / 10) * Math.PI * 2;
splat(x, y, Math.cos(a) * 700, Math.sin(a) * 700, [0.5, 0.5, 0.5], 0.0016);
}
};
host.addEventListener("pointerenter", enter);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
host.addEventListener("pointerdown", burst);
// A few currents so the water is already moving.
for (let i = 0; i < 6; i++) {
splat(0.15 + i * 0.14, 0.3 + (i % 2) * 0.4, (Math.random() - 0.5) * 250, (Math.random() - 0.5) * 250, [0.1, 0.1, 0.1], 0.004);
}
/* ---------- loop ---------- */
let raf = 0;
let visible = false;
let last = 0;
let t = 0;
const ghost = { x: 0.5, y: 0.5 };
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = (last ? Math.min(0.033, (now - last) / 1000) : 1 / 60) * live.current.speed;
last = now;
t += dt;
if (ptr.hover && ptr.moved) {
const dx = (ptr.x - ptr.px) * 6000;
const dy = (ptr.y - ptr.py) * 6000;
if (Math.abs(dx) + Math.abs(dy) > 0.5) {
const k = Math.min(0.4, (Math.abs(dx) + Math.abs(dy)) * 0.004);
splat(ptr.x, ptr.y, dx * 0.7, dy * 0.7, [k, k, k], 0.003);
}
ptr.px = ptr.x;
ptr.py = ptr.y;
ptr.moved = false;
} else if (!ptr.hover) {
// a slow current keeps the water alive
const nx = 0.5 + Math.sin(t * 0.35) * 0.35;
const ny = 0.5 + Math.sin(t * 0.5 + 1) * 0.3;
splat(nx, ny, (nx - ghost.x) * 2500, (ny - ghost.y) * 2500, [0.03, 0.03, 0.03], 0.004);
ghost.x = nx;
ghost.y = ny;
}
birdCount = updateFlock(dt, t);
step(dt);
render(t);
};
const sync = () => {
const go = visible && !document.hidden && !reduced;
if (go && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!go && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
document.fonts?.ready.then(() => {
drawText();
if (!raf) render(t);
});
const still = () => {
spawnFlock();
flock.cx = 0.5;
birdCount = updateFlock(0, 0);
};
if (reduced) {
still();
step(1 / 60);
render(0);
}
hooks.current = {
relayout: drawText,
reflock: () => {
if (reduced) {
first = true;
still();
} else {
flock.birds = [];
flock.wait = 0;
first = true;
}
},
redraw: () => {
if (!raf) render(t);
},
};
return () => {
hooks.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointerenter", enter);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
host.removeEventListener("pointerdown", burst);
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, []);
return (
<div ref={hostRef} className={["isolate overflow-hidden bg-black", className].filter(Boolean).join(" ")}>
{/* the word is painted into the water; this copy is for screen readers */}
<span
ref={wordRef}
style={{
position: "absolute",
width: 1,
height: 1,
overflow: "hidden",
clip: "rect(0 0 0 0)",
whiteSpace: "nowrap",
}}
>
{text}
</span>
{children !== undefined && <div style={{ position: "relative", zIndex: 1, height: "100%" }}>{children}</div>}
</div>
);
}
›Plain CSS variant (no Tailwind)
components/inreact/shallows.tsx
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import "./shallows.css";
/**
* Shallows: an underwater hero background.
*
* - The water is a real-time GPU fluid (stable fluids: advection, vorticity
* confinement, Jacobi pressure solve). Your cursor pushes it around and a
* click sends a burst through it.
* - Caustic light dances across the floor, brighter where the water is stirred,
* with sun shafts from the surface.
* - A giant word lies on the floor and is refracted by the moving water.
* - A flock of birds flies overhead in formation; you only see their soft
* shadows, and they scatter away from your cursor.
*
* Usage:
*
* <Shallows text="Drift" className="h-[80vh] w-full">
* <YourHeroContent />
* </Shallows>
*
* The word uses the component's font (set font-family on it or a parent).
* Needs WebGL2 with float render targets; otherwise it shows a still gradient
* with the word in plain text. Pauses off-screen, honours
* prefers-reduced-motion. Colours and sliders update live.
*/
export interface ShallowsProps {
/** The word on the sea floor. Also exposed to screen readers. */
text?: string;
/** Shallow water colour, near the surface (top). */
water?: string;
/** Deep water colour (bottom and edges). */
deep?: string;
/** Colour of the caustic light and sun shafts. */
light?: string;
/** Colour of the word on the floor. */
textColor?: string;
/** Brightness of the caustics. */
caustics?: number;
/** How strongly the moving water bends the floor. */
refraction?: number;
/** How much the water swirls after you stir it. */
swirl?: number;
/** Animation speed multiplier. */
speed?: number;
/** Birds per flock (0 to 8). */
birds?: number;
/** Size multiplier for the bird shadows. */
birdSize?: number;
className?: string;
/** Foreground content, drawn above the water. */
children?: ReactNode;
}
const MAX_BIRDS = 8;
const VERT = `#version 300 es
precision highp float;
in vec2 aPos;
uniform vec2 uTexel;
out vec2 vUv, vL, vR, vT, vB;
void main(){
vUv = aPos * 0.5 + 0.5;
vL = vUv - vec2(uTexel.x, 0.0);
vR = vUv + vec2(uTexel.x, 0.0);
vT = vUv + vec2(0.0, uTexel.y);
vB = vUv - vec2(0.0, uTexel.y);
gl_Position = vec4(aPos, 0.0, 1.0);
}`;
const HEAD = `#version 300 es
precision highp float;
precision highp sampler2D;
in vec2 vUv, vL, vR, vT, vB;
out vec4 o;
`;
const FRAG = {
splat: `${HEAD}
uniform sampler2D uTarget; uniform float uAspect; uniform vec3 uColor; uniform vec2 uPoint; uniform float uRadius;
void main(){
vec2 p = vUv - uPoint; p.x *= uAspect;
vec3 s = exp(-dot(p, p) / uRadius) * uColor;
o = vec4(texture(uTarget, vUv).xyz + s, 1.0);
}`,
advect: `${HEAD}
uniform sampler2D uVelocity; uniform sampler2D uSource; uniform vec2 uSimTexel; uniform float uDt; uniform float uDissipation;
void main(){
vec2 coord = vUv - uDt * texture(uVelocity, vUv).xy * uSimTexel;
o = texture(uSource, coord) / (1.0 + uDissipation * uDt);
o.a = 1.0;
}`,
divergence: `${HEAD}
uniform sampler2D uVelocity;
void main(){
float L = texture(uVelocity, vL).x, R = texture(uVelocity, vR).x;
float T = texture(uVelocity, vT).y, B = texture(uVelocity, vB).y;
vec2 C = texture(uVelocity, vUv).xy;
if (vL.x < 0.0) L = -C.x;
if (vR.x > 1.0) R = -C.x;
if (vT.y > 1.0) T = -C.y;
if (vB.y < 0.0) B = -C.y;
o = vec4(0.5 * (R - L + T - B), 0.0, 0.0, 1.0);
}`,
curl: `${HEAD}
uniform sampler2D uVelocity;
void main(){
float L = texture(uVelocity, vL).y, R = texture(uVelocity, vR).y;
float T = texture(uVelocity, vT).x, B = texture(uVelocity, vB).x;
o = vec4(0.5 * (R - L - T + B), 0.0, 0.0, 1.0);
}`,
vorticity: `${HEAD}
uniform sampler2D uVelocity; uniform sampler2D uCurl; uniform float uCurlStrength; uniform float uDt;
void main(){
float L = texture(uCurl, vL).x, R = texture(uCurl, vR).x;
float T = texture(uCurl, vT).x, B = texture(uCurl, vB).x;
float C = texture(uCurl, vUv).x;
vec2 f = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L));
f /= length(f) + 1e-4;
f *= uCurlStrength * C;
f.y *= -1.0;
vec2 v = texture(uVelocity, vUv).xy + f * uDt;
o = vec4(clamp(v, -1000.0, 1000.0), 0.0, 1.0);
}`,
pressure: `${HEAD}
uniform sampler2D uPressure; uniform sampler2D uDivergence;
void main(){
float L = texture(uPressure, vL).x, R = texture(uPressure, vR).x;
float T = texture(uPressure, vT).x, B = texture(uPressure, vB).x;
float d = texture(uDivergence, vUv).x;
o = vec4((L + R + B + T - d) * 0.25, 0.0, 0.0, 1.0);
}`,
gradient: `${HEAD}
uniform sampler2D uPressure; uniform sampler2D uVelocity;
void main(){
float L = texture(uPressure, vL).x, R = texture(uPressure, vR).x;
float T = texture(uPressure, vT).x, B = texture(uPressure, vB).x;
vec2 v = texture(uVelocity, vUv).xy - vec2(R - L, T - B);
o = vec4(v, 0.0, 1.0);
}`,
scale: `${HEAD}
uniform sampler2D uTexture; uniform float uValue;
void main(){ o = uValue * texture(uTexture, vUv); }`,
display: `${HEAD}
uniform sampler2D uDye; uniform sampler2D uVelocity; uniform sampler2D uText;
uniform float uTime; uniform float uAspect;
uniform vec3 uDeep; uniform vec3 uShallow; uniform vec3 uLight; uniform vec3 uSand;
uniform float uCaustics; uniform float uRefract;
uniform vec4 uBirdA[${MAX_BIRDS}]; // x, y (uv), heading, flap phase
uniform vec4 uBirdB[${MAX_BIRDS}]; // size, alpha, -, -
uniform int uBirdCount;
float caustics(vec2 p, float t){
// Warped wave interference: bright, curvy filaments where the
// product of two wave fields crosses zero, like light through ripples.
vec2 q = p * 3.3;
float c = 0.0;
for (int i = 0; i < 3; i++){
float fi = float(i);
q += vec2(sin(q.y * 1.6 + t * 0.55 + fi * 1.3), cos(q.x * 1.4 - t * 0.5 + fi * 2.1)) * 0.55;
float wave = sin(q.x * 1.15 + q.y * 0.65 + t * 0.35) * cos(q.y * 1.25 - q.x * 0.45 - t * 0.25);
c += 0.045 / (abs(wave) + 0.04);
}
c /= 3.0;
return clamp(pow(c, 2.0) * 0.95, 0.0, 1.8);
}
// soft top-down silhouette of a bird; local space: +x is the flight direction
float bird(vec2 q, float flap){
float span = 1.0 * (0.72 + 0.28 * cos(flap));
float ax = abs(q.y);
float sweep = -ax * 0.45 + 0.08 * sin(flap) * ax;
float chord = 0.26 * (1.0 - smoothstep(0.0, span, ax));
float wing = abs(q.x - sweep) - chord;
wing = max(wing, ax - span);
float body = length(q * vec2(0.55, 2.4)) - 0.16;
float tail = length((q - vec2(-0.38, 0.0)) * vec2(1.4, 2.0)) - 0.12;
return min(min(wing, body), tail);
}
void main(){
float t = uTime;
vec2 vel = texture(uVelocity, vUv).xy;
float stir = texture(uDye, vUv).r;
vec2 p = vec2(vUv.x * uAspect, vUv.y);
// the surface refracts everything on the floor
vec2 refr = (vel * 0.00022 + vec2(stir * 0.006) * vec2(sin(t * 3.0 + p.y * 20.0), cos(t * 2.6 + p.x * 20.0)) + vec2(sin(p.y * 9.0 + t * 1.3), cos(p.x * 8.0 - t * 1.1)) * 0.004) * uRefract;
vec2 fp = p + refr;
vec2 fuv = vUv + vec2(refr.x / uAspect, refr.y);
// water body: deep at the bottom, lighter toward the surface
vec3 col = mix(uDeep, uShallow, smoothstep(-0.1, 1.1, vUv.y));
// the word on the floor
float text = texture(uText, vec2(fuv.x, 1.0 - fuv.y)).r;
col = mix(col, uSand * (0.55 + 0.45 * vUv.y), text * 0.9);
// bird shadows, cast from high above: soft and wobbling with the water
float shadow = 0.0;
for (int i = 0; i < ${MAX_BIRDS}; i++){
if (i >= uBirdCount) break;
vec4 A = uBirdA[i];
vec4 B = uBirdB[i];
vec2 d = fp - vec2(A.x * uAspect, A.y);
float c = cos(-A.z), s = sin(-A.z);
vec2 q = vec2(d.x * c - d.y * s, d.x * s + d.y * c) / B.x;
float sd = bird(q, A.w);
shadow = max(shadow, (1.0 - smoothstep(-0.12, 0.3, sd)) * B.y);
}
col *= 1.0 - shadow * 0.7;
// caustic light dances on the floor, brighter where the water is stirred
float c = caustics(fp, t) * (1.0 + stir * 2.5) * uCaustics;
vec3 light = uLight * c * (1.0 - shadow * 0.9);
col += light * (0.28 + 0.4 * vUv.y) + light * text * 0.35;
// sun shafts from the surface
float rays = pow(max(0.0, sin(p.x * 5.0 - p.y * 1.8 + sin(t * 0.25) * 1.5)), 10.0)
+ 0.6 * pow(max(0.0, sin(p.x * 8.3 - p.y * 2.6 - t * 0.18)), 14.0);
col += uLight * vec3(0.82, 0.84, 1.0) * rays * smoothstep(0.2, 1.0, vUv.y) * 0.16;
// stirred water: a soft shimmer, never coloured ink
col += uLight * vec3(0.91, 0.95, 1.0) * smoothstep(0.4, 1.6, stir) * 0.1;
// depth fog toward the edges
vec2 v = vUv - vec2(0.5, 0.62);
col = mix(col, uDeep, smoothstep(0.35, 1.0, length(v * vec2(1.0, 1.3))) * 0.65);
o = vec4(col, 1.0);
}`,
} as const;
type Prog = { prog: WebGLProgram; u: Record<string, WebGLUniformLocation | null> };
type FBO = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number };
type DFBO = { read: FBO; write: FBO; swap: () => void };
interface Bird {
ox: number; // formation offset (aspect space, local to heading)
oy: number;
sx: number; // scatter offset from the cursor
sy: number;
vx: number;
vy: number;
phase: number;
flap: number;
size: number;
}
function hexToRgb(hex: string): [number, number, number] {
const h = hex.replace("#", "");
const n = parseInt(h.length === 3 ? h.replace(/./g, "$&$&") : h, 16);
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function Shallows({
text = "Drift",
water = "#08336b",
deep = "#020816",
light = "#8cdbff",
textColor = "#c7bda3",
caustics = 1,
refraction = 1,
swirl = 1,
speed = 1,
birds = 6,
birdSize = 1,
className,
children,
}: ShallowsProps) {
const hostRef = useRef<HTMLDivElement>(null);
const wordRef = useRef<HTMLSpanElement>(null);
const live = useRef({ text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize });
const hooks = useRef<{ relayout: () => void; reflock: () => void; redraw: () => void } | null>(null);
useEffect(() => {
const prev = live.current;
live.current = { text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize };
if (prev.text !== text) hooks.current?.relayout();
if (prev.birds !== birds) hooks.current?.reflock();
hooks.current?.redraw();
}, [text, water, deep, light, textColor, caustics, refraction, swirl, speed, birds, birdSize]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
// stay where the user put it (absolute, fixed...), otherwise anchor the layers
if (getComputedStyle(host).position === "static") host.style.position = "relative";
// a fresh canvas per mount: a context lost on unmount never comes back
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;display:block;width:100%;height:100%";
canvas.setAttribute("aria-hidden", "true");
host.prepend(canvas);
const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, depth: false, stencil: false });
const canFloat = gl && (gl.getExtension("EXT_color_buffer_float") || gl.getExtension("EXT_color_buffer_half_float"));
if (!gl || !canFloat) {
// no fluid sim here: a still underwater gradient and the word as plain text
const L = live.current;
canvas.remove();
host.style.background = `radial-gradient(80% 70% at 50% 15%, ${L.water}, ${L.deep} 85%)`;
const word = wordRef.current;
if (word) {
Object.assign(word.style, {
inset: "0",
width: "auto",
height: "auto",
clip: "auto",
display: "grid",
placeItems: "center",
fontSize: "min(22vw, 40vh)",
fontWeight: "800",
lineHeight: "1",
color: L.textColor,
});
}
return;
}
/* ---------- GL helpers ---------- */
const shader = (type: number, src: string) => {
const s = gl.createShader(type)!;
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.warn(gl.getShaderInfoLog(s));
return s;
};
const vs = shader(gl.VERTEX_SHADER, VERT);
const program = (src: string): Prog => {
const prog = gl.createProgram()!;
gl.attachShader(prog, vs);
gl.attachShader(prog, shader(gl.FRAGMENT_SHADER, src));
gl.bindAttribLocation(prog, 0, "aPos");
gl.linkProgram(prog);
const u: Prog["u"] = {};
const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;
for (let i = 0; i < n; i++) {
const name = gl.getActiveUniform(prog, i)!.name;
u[name] = gl.getUniformLocation(prog, name);
}
return { prog, u };
};
const P = Object.fromEntries(Object.entries(FRAG).map(([k, src]) => [k, program(src)])) as Record<
keyof typeof FRAG,
Prog
>;
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const fbo = (w: number, h: number, internal: number, format: number): FBO => {
const tex = gl.createTexture()!;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, internal, w, h, 0, format, gl.HALF_FLOAT, null);
const fb = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.viewport(0, 0, w, h);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
return { tex, fbo: fb, w, h };
};
const dfbo = (w: number, h: number, internal: number, format: number): DFBO => {
const d = { read: fbo(w, h, internal, format), write: fbo(w, h, internal, format), swap: () => {} };
d.swap = () => {
const t = d.read;
d.read = d.write;
d.write = t;
};
return d;
};
const free = (t: FBO) => {
gl.deleteTexture(t.tex);
gl.deleteFramebuffer(t.fbo);
};
// RGBA16F is renderable everywhere EXT_color_buffer_* exists; use it for all.
const F = gl.RGBA16F;
const FMT = gl.RGBA;
let bound = 0;
const bind = (t: FBO) => {
gl.activeTexture(gl.TEXTURE0 + bound);
gl.bindTexture(gl.TEXTURE_2D, t.tex);
return bound++;
};
const run = (p: Prog, target: FBO | null, texel: [number, number], set: () => void) => {
gl.useProgram(p.prog);
bound = 0;
gl.uniform2f(p.u.uTexel, texel[0], texel[1]);
set();
if (target) {
gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo);
gl.viewport(0, 0, target.w, target.h);
} else {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
/* ---------- sizing & targets ---------- */
let w = 1;
let h = 1;
let velocity!: DFBO;
let dye!: DFBO;
let pressure!: DFBO;
let divergence!: FBO;
let curl!: FBO;
let sim: [number, number] = [1, 1];
const textTex = gl.createTexture()!;
const textCanvas = document.createElement("canvas");
const drawText = () => {
const family = getComputedStyle(host).fontFamily || "Arial";
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
textCanvas.width = Math.round(w * dpr);
textCanvas.height = Math.round(h * dpr);
const c = textCanvas.getContext("2d")!;
c.setTransform(dpr, 0, 0, dpr, 0, 0);
c.fillStyle = "#000";
c.fillRect(0, 0, w, h);
const word = live.current.text;
if (word.trim()) {
let size = h * 0.62;
c.font = `800 ${size}px ${family}`;
const fit = (w * 0.86) / c.measureText(word).width;
if (fit < 1) size *= fit;
c.font = `800 ${size}px ${family}`;
c.textAlign = "center";
c.textBaseline = "middle";
c.fillStyle = "#fff";
c.fillText(word, w / 2, h * 0.44);
}
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textCanvas);
};
let sized = false;
const resize = () => {
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const aspect = w / h;
const simH = 128;
const simW = Math.round(simH * aspect);
const dyeH = Math.min(720, Math.round(h * dpr));
const dyeW = Math.round(dyeH * aspect);
sim = [simW, simH];
if (sized) {
[velocity, pressure, dye].forEach((d) => (free(d.read), free(d.write)));
free(divergence);
free(curl);
}
sized = true;
velocity = dfbo(simW, simH, F, FMT);
pressure = dfbo(simW, simH, F, FMT);
divergence = fbo(simW, simH, F, FMT);
curl = fbo(simW, simH, F, FMT);
dye = dfbo(dyeW, dyeH, F, FMT);
drawText();
};
resize();
let lastW = w;
let lastH = h;
const ro = new ResizeObserver(() => {
if (Math.abs(host.clientWidth - lastW) > 2 || Math.abs(host.clientHeight - lastH) > 2) {
lastW = host.clientWidth;
lastH = host.clientHeight;
resize();
if (!raf) render(t);
}
});
ro.observe(host);
/* ---------- simulation ---------- */
const simTexel = (): [number, number] => [1 / sim[0], 1 / sim[1]];
const splat = (x: number, y: number, dx: number, dy: number, color: [number, number, number], radius = 0.0025) => {
run(P.splat, velocity.write, simTexel(), () => {
gl.uniform1i(P.splat.u.uTarget, bind(velocity.read));
gl.uniform1f(P.splat.u.uAspect, w / h);
gl.uniform2f(P.splat.u.uPoint, x, y);
gl.uniform3f(P.splat.u.uColor, dx, dy, 0);
gl.uniform1f(P.splat.u.uRadius, radius);
});
velocity.swap();
run(P.splat, dye.write, [1 / dye.read.w, 1 / dye.read.h], () => {
gl.uniform1i(P.splat.u.uTarget, bind(dye.read));
gl.uniform1f(P.splat.u.uAspect, w / h);
gl.uniform2f(P.splat.u.uPoint, x, y);
gl.uniform3f(P.splat.u.uColor, color[0], color[1], color[2]);
gl.uniform1f(P.splat.u.uRadius, radius);
});
dye.swap();
};
const step = (dt: number) => {
const st = simTexel();
run(P.curl, curl, st, () => gl.uniform1i(P.curl.u.uVelocity, bind(velocity.read)));
run(P.vorticity, velocity.write, st, () => {
gl.uniform1i(P.vorticity.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.vorticity.u.uCurl, bind(curl));
gl.uniform1f(P.vorticity.u.uCurlStrength, 28 * live.current.swirl);
gl.uniform1f(P.vorticity.u.uDt, dt);
});
velocity.swap();
run(P.divergence, divergence, st, () => gl.uniform1i(P.divergence.u.uVelocity, bind(velocity.read)));
run(P.scale, pressure.write, st, () => {
gl.uniform1i(P.scale.u.uTexture, bind(pressure.read));
gl.uniform1f(P.scale.u.uValue, 0.8);
});
pressure.swap();
for (let i = 0; i < 20; i++) {
run(P.pressure, pressure.write, st, () => {
gl.uniform1i(P.pressure.u.uPressure, bind(pressure.read));
gl.uniform1i(P.pressure.u.uDivergence, bind(divergence));
});
pressure.swap();
}
run(P.gradient, velocity.write, st, () => {
gl.uniform1i(P.gradient.u.uPressure, bind(pressure.read));
gl.uniform1i(P.gradient.u.uVelocity, bind(velocity.read));
});
velocity.swap();
run(P.advect, velocity.write, st, () => {
gl.uniform1i(P.advect.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.advect.u.uSource, bind(velocity.read));
gl.uniform2f(P.advect.u.uSimTexel, st[0], st[1]);
gl.uniform1f(P.advect.u.uDt, dt);
gl.uniform1f(P.advect.u.uDissipation, 0.15);
});
velocity.swap();
run(P.advect, dye.write, [1 / dye.read.w, 1 / dye.read.h], () => {
gl.uniform1i(P.advect.u.uVelocity, bind(velocity.read));
gl.uniform1i(P.advect.u.uSource, bind(dye.read));
gl.uniform2f(P.advect.u.uSimTexel, st[0], st[1]);
gl.uniform1f(P.advect.u.uDt, dt);
gl.uniform1f(P.advect.u.uDissipation, 1.6);
});
dye.swap();
};
/* ---------- the flock overhead ---------- */
const flock = { birds: [] as Bird[], cx: -1, cy: 0.5, heading: 0, speed: 0.075, wait: 0 };
const birdA = new Float32Array(MAX_BIRDS * 4);
const birdB = new Float32Array(MAX_BIRDS * 4);
let first = true; // the first flock starts in view
const spawnFlock = () => {
const want = Math.max(0, Math.min(MAX_BIRDS, Math.round(live.current.birds)));
// a little variety: one bird more or fewer than asked
const n = want === 0 ? 0 : Math.max(1, Math.min(MAX_BIRDS, want - 1 + Math.floor(Math.random() * 3)));
const fromLeft = Math.random() < 0.5;
const tilt = (Math.random() - 0.5) * 0.7;
flock.heading = fromLeft ? tilt : Math.PI + tilt;
flock.cx = first ? (fromLeft ? 0.2 : 0.8) : fromLeft ? -0.3 : 1.3;
first = false;
flock.cy = 0.25 + Math.random() * 0.5 - Math.sin(tilt) * 0.3;
flock.birds = Array.from({ length: n }, (_, i) => {
const rank = Math.ceil(i / 2);
const side = i % 2 ? 1 : -1;
return {
ox: -rank * 0.075 + (Math.random() - 0.5) * 0.02,
oy: side * rank * 0.065 + (Math.random() - 0.5) * 0.02,
sx: 0,
sy: 0,
vx: 0,
vy: 0,
phase: Math.random() * 6.28,
flap: 7 + Math.random() * 3,
size: 0.06 + Math.random() * 0.025,
};
});
if (!n) flock.wait = 2;
};
const updateFlock = (dt: number, time: number) => {
const aspect = w / h;
const scale = live.current.birdSize;
if (!flock.birds.length) {
flock.wait -= dt;
if (flock.wait <= 0) spawnFlock();
return 0;
}
flock.heading += Math.sin(time * 0.35) * 0.06 * dt;
const hx = Math.cos(flock.heading);
const hy = Math.sin(flock.heading);
flock.cx += (hx * flock.speed * dt) / aspect;
flock.cy += hy * flock.speed * dt;
let count = 0;
for (const b of flock.birds) {
// formation position, rotated into the heading
const ox = b.ox * scale;
const oy = b.oy * scale;
const fx = flock.cx * aspect + ox * hx - oy * hy + Math.sin(time * 0.9 + b.phase) * 0.008;
const fy = flock.cy + ox * hy + oy * hx + Math.cos(time * 1.1 + b.phase) * 0.008;
// scatter away from the cursor
if (ptr.hover && !reduced) {
const dx = fx + b.sx - ptr.x * aspect;
const dy = fy + b.sy - ptr.y;
const d = Math.hypot(dx, dy);
if (d < 0.22) {
const f = (1 - d / 0.22) * 2.4;
b.vx += (dx / (d + 1e-3)) * f * dt;
b.vy += (dy / (d + 1e-3)) * f * dt;
b.flap = 14;
}
}
b.vx = (b.vx - b.sx * 1.2 * dt) * 0.96;
b.vy = (b.vy - b.sy * 1.2 * dt) * 0.96;
b.sx += b.vx * dt;
b.sy += b.vy * dt;
b.flap += (8 - b.flap) * dt * 0.8;
// occasional glide
const gliding = Math.sin(time * 0.5 + b.phase * 3) > 0.55;
b.phase += dt * (gliding ? 0.6 : b.flap);
const x = fx + b.sx;
const y = fy + b.sy;
const edge = Math.min(x / aspect + 0.15, 1.15 - x / aspect, y + 0.15, 1.15 - y);
const k = count * 4;
birdA[k] = x / aspect;
birdA[k + 1] = y;
birdA[k + 2] = flock.heading;
birdA[k + 3] = b.phase;
birdB[k] = b.size * scale;
birdB[k + 1] = Math.max(0, Math.min(1, edge * 6)) * 0.9;
count++;
}
if (flock.cx < -0.6 || flock.cx > 1.6 || flock.cy < -0.6 || flock.cy > 1.6) {
flock.birds = [];
flock.wait = 1.5 + Math.random() * 3;
}
return count;
};
let birdCount = 0;
const render = (time: number) => {
const L = live.current;
run(P.display, null, simTexel(), () => {
const u = P.display.u;
gl.uniform1i(u.uDye, bind(dye.read));
gl.uniform1i(u.uVelocity, bind(velocity.read));
gl.activeTexture(gl.TEXTURE0 + bound);
gl.bindTexture(gl.TEXTURE_2D, textTex);
gl.uniform1i(u.uText, bound++);
gl.uniform1f(u.uTime, time);
gl.uniform1f(u.uAspect, w / h);
gl.uniform3fv(u.uDeep, hexToRgb(L.deep));
gl.uniform3fv(u.uShallow, hexToRgb(L.water));
gl.uniform3fv(u.uLight, hexToRgb(L.light));
gl.uniform3fv(u.uSand, hexToRgb(L.textColor));
gl.uniform1f(u.uCaustics, L.caustics);
gl.uniform1f(u.uRefract, L.refraction);
gl.uniform4fv(u["uBirdA[0]"], birdA);
gl.uniform4fv(u["uBirdB[0]"], birdB);
gl.uniform1i(u.uBirdCount, birdCount);
});
};
/* ---------- input ---------- */
const reduced = isReducedMotion();
const ptr = { x: 0, y: 0, px: 0, py: 0, moved: false, hover: false };
const toUv = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
return [(e.clientX - r.left) / r.width, 1 - (e.clientY - r.top) / r.height];
};
const enter = (e: PointerEvent) => {
[ptr.px, ptr.py] = toUv(e);
ptr.x = ptr.px;
ptr.y = ptr.py;
ptr.hover = true;
};
const move = (e: PointerEvent) => {
if (!ptr.hover) enter(e);
[ptr.x, ptr.y] = toUv(e);
ptr.moved = true;
};
const leave = () => (ptr.hover = false);
const burst = (e: PointerEvent) => {
const [x, y] = toUv(e);
for (let i = 0; i < 10; i++) {
const a = (i / 10) * Math.PI * 2;
splat(x, y, Math.cos(a) * 700, Math.sin(a) * 700, [0.5, 0.5, 0.5], 0.0016);
}
};
host.addEventListener("pointerenter", enter);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
host.addEventListener("pointerdown", burst);
// A few currents so the water is already moving.
for (let i = 0; i < 6; i++) {
splat(0.15 + i * 0.14, 0.3 + (i % 2) * 0.4, (Math.random() - 0.5) * 250, (Math.random() - 0.5) * 250, [0.1, 0.1, 0.1], 0.004);
}
/* ---------- loop ---------- */
let raf = 0;
let visible = false;
let last = 0;
let t = 0;
const ghost = { x: 0.5, y: 0.5 };
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = (last ? Math.min(0.033, (now - last) / 1000) : 1 / 60) * live.current.speed;
last = now;
t += dt;
if (ptr.hover && ptr.moved) {
const dx = (ptr.x - ptr.px) * 6000;
const dy = (ptr.y - ptr.py) * 6000;
if (Math.abs(dx) + Math.abs(dy) > 0.5) {
const k = Math.min(0.4, (Math.abs(dx) + Math.abs(dy)) * 0.004);
splat(ptr.x, ptr.y, dx * 0.7, dy * 0.7, [k, k, k], 0.003);
}
ptr.px = ptr.x;
ptr.py = ptr.y;
ptr.moved = false;
} else if (!ptr.hover) {
// a slow current keeps the water alive
const nx = 0.5 + Math.sin(t * 0.35) * 0.35;
const ny = 0.5 + Math.sin(t * 0.5 + 1) * 0.3;
splat(nx, ny, (nx - ghost.x) * 2500, (ny - ghost.y) * 2500, [0.03, 0.03, 0.03], 0.004);
ghost.x = nx;
ghost.y = ny;
}
birdCount = updateFlock(dt, t);
step(dt);
render(t);
};
const sync = () => {
const go = visible && !document.hidden && !reduced;
if (go && !raf) {
last = 0;
raf = requestAnimationFrame(frame);
} else if (!go && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
document.fonts?.ready.then(() => {
drawText();
if (!raf) render(t);
});
const still = () => {
spawnFlock();
flock.cx = 0.5;
birdCount = updateFlock(0, 0);
};
if (reduced) {
still();
step(1 / 60);
render(0);
}
hooks.current = {
relayout: drawText,
reflock: () => {
if (reduced) {
first = true;
still();
} else {
flock.birds = [];
flock.wait = 0;
first = true;
}
},
redraw: () => {
if (!raf) render(t);
},
};
return () => {
hooks.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointerenter", enter);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
host.removeEventListener("pointerdown", burst);
gl.getExtension("WEBGL_lose_context")?.loseContext();
canvas.remove();
};
}, []);
return (
<div ref={hostRef} className={["shallows", className].filter(Boolean).join(" ")}>
{/* the word is painted into the water; this copy is for screen readers */}
<span
ref={wordRef}
style={{
position: "absolute",
width: 1,
height: 1,
overflow: "hidden",
clip: "rect(0 0 0 0)",
whiteSpace: "nowrap",
}}
>
{text}
</span>
{children !== undefined && <div style={{ position: "relative", zIndex: 1, height: "100%" }}>{children}</div>}
</div>
);
}
components/inreact/shallows.css
.shallows {
isolation: isolate;
overflow: hidden;
background: #000;
}
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
13 propstextstringThe word on the sea floor. Uses the component's font; also exposed to screen readers.default "Drift"default "Drift"waterstringShallow water colour, near the surface.default "#08336b"default "#08336b"deepstringDeep water colour, at the bottom and edges.default "#020816"default "#020816"lightstringColour of the caustic light and sun shafts.default "#8cdbff"default "#8cdbff"textColorstringColour of the word.default "#c7bda3"default "#c7bda3"causticsnumberBrightness of the caustics.default 1default 1refractionnumberHow strongly the moving water bends the floor.default 1default 1swirlnumberHow much the water swirls after you stir it.default 1default 1speednumberAnimation speed multiplier.default 1default 1birdsnumberBirds per flock, 0 to 8.default 6default 6birdSizenumberSize multiplier for the bird shadows.default 1default 1childrenReactNodeForeground content, drawn above the water.classNamestringSize it, e.g. h-[80vh] w-full.