Animations105 / 118
Tidal Orb
A hollow sphere of moving water turning slowly in the dark, with sparks floating inside it. It reaches for your cursor like a drop pulled by a finger and trails ripples wherever you move; spin it and the water sloshes behind the motion; click and it gathers itself, splashes, throws droplets and wobbles back into shape.
three.jsthree.jsVertex shaderVertex shaderWaterWaterParticlesParticlesSpringsSpringsGSAPGSAP
Move over the water, drag to spin itClick to make a splash
Tweak
LIVELIVEWater
Palette
1.0
Motion
1.0×
Sparks
Usage
Follows your tweaks.
usage.tsx
import { TidalOrb } from "@/components/inreact/tidal-orb";
export function Hero() {
return (
<section className="h-[640px] bg-black">
<TidalOrb palette="moon" turbulence={1} speed={1} />
</section>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/tidal-orb.jsonOr copy the source
Install the dependencies, then save this as components/inreact/tidal-orb.tsx.
terminal
npm install gsap threecomponents/inreact/tidal-orb.tsx
"use client";
import { gsap } from "gsap";
import { useEffect, useRef } from "react";
import * as THREE from "three";
/**
* Tidal Orb: a hollow sphere of moving water, turning slowly in the dark.
*
* - Its surface is never still: lobes, vertical folds and fine ripples drift
* across it, catching a studio of soft lights; sparks hang inside it.
* - It reaches for the cursor like a drop of water pulled by a finger, and
* moving over it trails ripples that spread round the sphere.
* - Drag to spin it: it coasts on, and the water sloshes behind the motion.
* - Click (or Enter / Space) to splash: it gathers itself, bursts back with a
* ripple, throws droplets and wobbles back into shape.
*
* <div className="h-[600px] bg-black"><TidalOrb palette="moon" /></div>
*/
export type TidalPalette = "moon" | "lagoon" | "rose";
export type TidalOrbProps = {
/** Colours of the water and its light. */
palette?: TidalPalette;
/** How restless the surface is, 0 (glassy) to 2. */
turbulence?: number;
/** Speed of the slow turn (0 = still, 1 = default). */
speed?: number;
/** Sparks inside the water and motes around it. */
sparkles?: boolean;
/** Canvas background. */
background?: string;
/** Called on each splash. */
onSplash?: () => void;
className?: string;
};
type Pal = { sky: number; key: number; rimA: number; rimB: number; glow: number; spark: number; spark2: number };
const PALETTES: Record<TidalPalette, Pal> = {
moon: { sky: 0x1a1c48, key: 0xf2eeff, rimA: 0xb7b2ff, rimB: 0xff9ec4, glow: 0x8d8cff, spark: 0x5d86ff, spark2: 0xff5a4a },
lagoon: { sky: 0x062b38, key: 0xeafffb, rimA: 0x7ff3e1, rimB: 0xffd38a, glow: 0x40d6c8, spark: 0x3fd2ff, spark2: 0xffc35a },
rose: { sky: 0x2e0f24, key: 0xfff0f2, rimA: 0xffb3cf, rimB: 0xffc58a, glow: 0xff7fae, spark: 0xff7ab8, spark2: 0xffd27a },
};
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const RIPPLES = 8;
// Ashima / Stefan Gustavson 3D simplex noise
const NOISE = /* glsl */ `
vec3 m289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 m289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}
vec4 perm(vec4 x){return m289(((x*34.0)+1.0)*x);}
vec4 tis(vec4 r){return 1.79284291400159-0.85373472095314*r;}
float snoise(vec3 v){
const vec2 C=vec2(1.0/6.0,1.0/3.0);const vec4 D=vec4(0.0,0.5,1.0,2.0);
vec3 i=floor(v+dot(v,C.yyy));vec3 x0=v-i+dot(i,C.xxx);
vec3 g=step(x0.yzx,x0.xyz);vec3 l=1.0-g;vec3 i1=min(g.xyz,l.zxy);vec3 i2=max(g.xyz,l.zxy);
vec3 x1=x0-i1+C.xxx;vec3 x2=x0-i2+C.yyy;vec3 x3=x0-D.yyy;
i=m289(i);
vec4 p=perm(perm(perm(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));
float n_=0.142857142857;vec3 ns=n_*D.wyz-D.xzx;
vec4 j=p-49.0*floor(p*ns.z*ns.z);vec4 x_=floor(j*ns.z);vec4 y_=floor(j-7.0*x_);
vec4 x=x_*ns.x+ns.yyyy;vec4 y=y_*ns.x+ns.yyyy;vec4 h=1.0-abs(x)-abs(y);
vec4 b0=vec4(x.xy,y.xy);vec4 b1=vec4(x.zw,y.zw);
vec4 s0=floor(b0)*2.0+1.0;vec4 s1=floor(b1)*2.0+1.0;vec4 sh=-step(h,vec4(0.0));
vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;
vec3 p0=vec3(a0.xy,h.x);vec3 p1=vec3(a0.zw,h.y);vec3 p2=vec3(a1.xy,h.z);vec3 p3=vec3(a1.zw,h.w);
vec4 norm=tis(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));
p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;
vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);m=m*m;
return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));
}`;
// the water's shape: a radial offset of the unit sphere
const SHAPE = /* glsl */ `
uniform float uT;
uniform float uTurb;
uniform float uSlosh;
uniform vec4 uPull;
uniform vec4 uRip[${RIPPLES}];
uniform float uRipA[${RIPPLES}];
float dispAt(vec3 p){
float phi = atan(p.z, p.x);
float d = 0.085 * snoise(p * 1.1 + vec3(0.0, uT * 0.06, 0.0));
// soft vertical folds, like a fruit or a gathered cloth of water
d += 0.045 * cos(5.0 * phi + 1.3 * snoise(p * 1.4 + 3.1 + uT * 0.05)) * (1.0 - p.y * p.y);
// a dimple at the crown
d -= 0.11 * exp(-pow((p.y - 1.0) / 0.24, 2.0));
// slosh: the whole body lags and surges after a spin
d += uSlosh * 0.1 * snoise(p * 2.0 + vec3(uT * 1.3, 0.0, 0.0));
// the restless skin: ripples stretched along the folds, and a finer chop
float rum = snoise(vec3(p.x * 4.6, p.y * 1.5, p.z * 4.6) + vec3(0.0, uT * 0.3, uT * 0.16));
rum += 0.35 * snoise(vec3(p.x * 9.0, p.y * 3.5, p.z * 9.0) + vec3(uT * 0.4));
d += 0.02 * uTurb * rum;
// reaching for the cursor
float hp = dot(p, uPull.xyz);
d += uPull.w * 0.1 * exp(-(1.0 - hp) / 0.045);
// ripples spreading round the sphere from where they started
for (int i = 0; i < ${RIPPLES}; i++) {
float age = uT - uRip[i].w;
if (age < 0.0 || age > 4.5) continue;
float ang = acos(clamp(dot(p, uRip[i].xyz), -1.0, 1.0));
float x = ang - age * 0.85;
d += uRipA[i] * exp(-age * 1.1) * sin(x * 24.0) * exp(-x * x / 0.07);
}
return d;
}
vec3 shapeAt(vec3 p){ return p * (1.0 + dispAt(p)); }`;
function starTexture() {
const S = 256;
const c = document.createElement("canvas");
c.width = c.height = S;
const x = c.getContext("2d")!;
x.translate(S / 2, S / 2);
const streak = (ang: number, len: number, w: number, a: number) => {
x.save();
x.rotate(ang);
const g = x.createLinearGradient(-len, 0, len, 0);
g.addColorStop(0, "rgba(255,255,255,0)");
g.addColorStop(0.5, `rgba(255,255,255,${a})`);
g.addColorStop(1, "rgba(255,255,255,0)");
x.fillStyle = g;
x.beginPath();
x.ellipse(0, 0, len, w, 0, 0, Math.PI * 2);
x.fill();
x.restore();
};
streak(-0.62, 124, 2.2, 0.9);
streak(-0.62 + Math.PI / 2, 46, 1.4, 0.45);
const core = x.createRadialGradient(0, 0, 0, 0, 0, 22);
core.addColorStop(0, "rgba(255,255,255,1)");
core.addColorStop(0.25, "rgba(255,255,255,0.55)");
core.addColorStop(1, "rgba(255,255,255,0)");
x.fillStyle = core;
x.fillRect(-22, -22, 44, 44);
return c;
}
export function TidalOrb({ palette = "moon", turbulence = 1, speed = 1, sparkles = true, background = "#000000", onSplash, className }: TidalOrbProps) {
const rootRef = useRef<HTMLDivElement>(null);
const live = useRef({ turbulence, speed, sparkles, onSplash });
live.current = { turbulence, speed, sparkles, onSplash };
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const still = reduced();
const pal = PALETTES[palette] ?? PALETTES.moon;
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;";
root.appendChild(canvas);
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, powerPreference: "high-performance" });
} catch {
canvas.remove();
return;
}
const dpr = Math.min(2, Math.max(1.5, window.devicePixelRatio || 1));
renderer.setPixelRatio(dpr);
renderer.setClearColor(new THREE.Color(background), 1);
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
// the studio the water reflects: a deep coloured sky, a big soft key up front-left,
// a ring of light behind (bright edges), warm accents, a few hard little lamps for glints
const KEY = new THREE.Vector3(0.62, -0.38, 0.69).normalize(); // the flare's light: low right, toward the viewer
const pmrem = new THREE.PMREMGenerator(renderer);
const studio = new THREE.Scene();
const envMat = new THREE.ShaderMaterial({
side: THREE.BackSide,
depthWrite: false,
uniforms: {
uSky: { value: new THREE.Color(pal.sky) },
uKey: { value: new THREE.Color(pal.key) },
uRimA: { value: new THREE.Color(pal.rimA) },
uRimB: { value: new THREE.Color(pal.rimB) },
uHot: { value: KEY.clone() },
},
vertexShader: "varying vec3 vD;\nvoid main(){ vD = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
fragmentShader: `
varying vec3 vD;
uniform vec3 uSky, uKey, uRimA, uRimB, uHot;
float box(vec3 d, vec3 c, float a, float b){ return smoothstep(a, b, dot(d, normalize(c))); }
void main(){
vec3 d = normalize(vD);
vec3 c = uSky * 0.25 * (0.2 + 0.8 * smoothstep(-1.0, 1.0, d.y));
float th = acos(clamp(-d.z, -1.0, 1.0));
c += uRimA * exp(-pow((th - 0.5) / 0.26, 2.0)) * 4.5;
// tall strip lights either side: long vertical streaks down the folds
float az = atan(d.x, d.z);
c += uKey * smoothstep(0.1, 0.0, abs(az + 0.85)) * smoothstep(0.85, 0.3, abs(d.y)) * 3.5;
c += uRimB * smoothstep(0.08, 0.0, abs(az - 1.05)) * smoothstep(0.8, 0.2, abs(d.y)) * 2.6;
c += uKey * box(d, vec3(-0.6, 0.55, 0.6), 0.86, 0.93) * 5.0;
c += uRimB * box(d, vec3(0.9, -0.15, -0.2), 0.8, 0.97) * 2.4;
c += uRimA * box(d, vec3(-0.85, -0.5, -0.1), 0.85, 0.97) * 1.6;
c += uKey * box(d, vec3(0.1, 0.95, 0.2), 0.9, 0.98) * 2.0;
c += vec3(1.0) * box(d, uHot, 0.985, 0.996) * 30.0;
// hard little lamps scattered round the room: the glints that make water sparkle
vec3 g = floor(d * 7.0);
float h = fract(sin(dot(g, vec3(12.9898, 78.233, 37.719))) * 43758.5453);
vec3 f = fract(d * 7.0) - 0.5;
c += uKey * step(0.84, h) * smoothstep(0.14, 0.0, length(f)) * 5.0;
gl_FragColor = vec4(c, 1.0);
}`,
});
const envSphere = new THREE.Mesh(new THREE.SphereGeometry(10, 96, 48), envMat);
studio.add(envSphere);
const env = pmrem.fromScene(studio, 0.01).texture;
envSphere.geometry.dispose();
envMat.dispose();
scene.environment = env;
// ---- the water ----
const uni = {
uT: { value: 0 },
uTurb: { value: live.current.turbulence },
uSlosh: { value: 0 },
uPull: { value: new THREE.Vector4(0, 0, 1, 0) },
uRip: { value: Array.from({ length: RIPPLES }, () => new THREE.Vector4(0, 1, 0, -99)) },
uRipA: { value: new Array(RIPPLES).fill(0) },
uGlow: { value: new THREE.Color(pal.glow) },
uFlash: { value: 0 },
};
const makeWater = (back: boolean) => {
const m = new THREE.MeshPhysicalMaterial({
color: 0x000000,
metalness: 0,
roughness: 0.05,
ior: 1.33,
specularIntensity: 1,
envMapIntensity: back ? 0.7 : 1.7,
iridescence: 0.3,
iridescenceIOR: 1.25,
transparent: true,
depthWrite: !back,
side: back ? THREE.BackSide : THREE.FrontSide,
});
m.onBeforeCompile = (sh) => {
Object.assign(sh.uniforms, uni);
sh.vertexShader = sh.vertexShader
.replace("#include <common>", `#include <common>\n${NOISE}\n${SHAPE}\n`)
.replace(
"#include <beginnormal_vertex>",
`vec3 sp = normalize(position);
vec3 tA = normalize(cross(sp, abs(sp.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0)));
vec3 tB = cross(sp, tA);
vec3 gP = shapeAt(sp);
vec3 pa = shapeAt(normalize(sp + tA * 0.006));
vec3 pb = shapeAt(normalize(sp + tB * 0.006));
vec3 objectNormal = normalize(cross(pa - gP, pb - gP));
if (dot(objectNormal, sp) < 0.0) objectNormal = -objectNormal;`,
)
.replace("#include <begin_vertex>", "vec3 transformed = gP;\nvWP = (modelMatrix * vec4(gP, 1.0)).xyz;")
.replace("void main() {", "varying vec3 vWP;\nvoid main() {");
sh.fragmentShader =
`uniform vec3 uGlow;\nuniform float uFlash;\nvarying vec3 vWP;\n` +
sh.fragmentShader.replace(
"#include <opaque_fragment>",
`{
// the water bends the light behind it: a soft glow gathered through the body,
// red, green and blue bent by their own index
vec3 nW = normalize(inverseTransformDirection(normal, viewMatrix));
vec3 vW = normalize(vWP - cameraPosition);
vec3 body = vec3(0.0);
vec3 iors = vec3(1.31, 1.335, 1.36);
for (int k = 0; k < 3; k++) {
vec3 r = refract(vW, nW, 1.0 / iors[k]);
body[k] = uGlow[k] * pow(max(0.0, dot(r, normalize(vW + vec3(0.25, -0.15, 0.0)))), 13.0);
}
outgoingLight += body * ${back ? "0.28" : "0.5"};
outgoingLight *= 1.0 + 0.35 * uFlash;
float lum = dot(outgoingLight, vec3(0.3, 0.55, 0.15));
// clear where it is dark, so the sparks inside show through
diffuseColor.a = clamp(${back ? "0.1 + lum * 0.8" : "0.16 + lum * 1.5"}, 0.0, 1.0);
}
#include <opaque_fragment>`,
);
};
return m;
};
const geo = new THREE.IcosahedronGeometry(1, 64);
const backMat = makeWater(true), frontMat = makeWater(false);
const backMesh = new THREE.Mesh(geo, backMat);
const frontMesh = new THREE.Mesh(geo, frontMat);
backMesh.renderOrder = 0;
frontMesh.renderOrder = 2;
// the sphere bends out of its bounds in the shader: never cull it
backMesh.frustumCulled = frontMesh.frustumCulled = false;
// rig: holder (squash) > spin (turn) > water + sparks
const holder = new THREE.Group();
const spin = new THREE.Group();
holder.add(spin);
spin.add(backMesh, frontMesh);
scene.add(holder);
// ---- sparks inside, motes and droplets outside ----
const ptMat = (count: number) =>
new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
uniforms: { uT: uni.uT, uPx: { value: 1 }, uOn: { value: 1 } },
vertexShader: `
attribute float aSize;
attribute float aPhase;
attribute vec3 aColor;
attribute float aAlpha;
uniform float uT;
uniform float uPx;
uniform float uOn;
varying vec3 vC;
varying float vA;
void main(){
vec4 mv = modelViewMatrix * vec4(position, 1.0);
float tw = 0.45 + 0.55 * sin(uT * (1.4 + fract(aPhase * 7.3) * 2.6) + aPhase * 6.2831);
gl_PointSize = aSize * uPx * (0.6 + 0.6 * tw) / -mv.z;
vC = aColor;
vA = aAlpha * uOn * (0.35 + 0.65 * tw);
gl_Position = projectionMatrix * mv;
}`,
fragmentShader: `
varying vec3 vC;
varying float vA;
void main(){
float r = length(gl_PointCoord - 0.5) * 2.0;
float a = smoothstep(1.0, 0.0, r);
gl_FragColor = vec4(vC * a * a * vA, 1.0);
}`,
}) as THREE.ShaderMaterial & { count?: number };
const makePoints = (n: number) => {
const g = new THREE.BufferGeometry();
g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(n * 3), 3));
g.setAttribute("aSize", new THREE.BufferAttribute(new Float32Array(n), 1));
g.setAttribute("aPhase", new THREE.BufferAttribute(new Float32Array(n), 1));
g.setAttribute("aColor", new THREE.BufferAttribute(new Float32Array(n * 3), 3));
g.setAttribute("aAlpha", new THREE.BufferAttribute(new Float32Array(n), 1));
return g;
};
const cSpark = new THREE.Color(pal.spark), cSpark2 = new THREE.Color(pal.spark2), cWhite = new THREE.Color(0xffffff);
const pick = () => (Math.random() < 0.08 ? cSpark2 : Math.random() < 0.3 ? cWhite : cSpark);
// inside: a slow galaxy of sparks that turns with the water
const NIN = 1400;
const inGeo = makePoints(NIN);
{
const p = inGeo.attributes.position.array as Float32Array;
const s = inGeo.attributes.aSize.array as Float32Array;
const ph = inGeo.attributes.aPhase.array as Float32Array;
const co = inGeo.attributes.aColor.array as Float32Array;
const al = inGeo.attributes.aAlpha.array as Float32Array;
for (let i = 0; i < NIN; i++) {
const v = new THREE.Vector3().randomDirection().multiplyScalar(Math.cbrt(Math.random()) * 0.82);
p.set([v.x, v.y, v.z], i * 3);
s[i] = 7 + Math.random() * Math.random() * 26;
ph[i] = Math.random();
const c = pick();
co.set([c.r, c.g, c.b], i * 3);
al[i] = 0.5 + Math.random() * 0.5;
}
}
const inMat = ptMat(NIN);
const inPts = new THREE.Points(inGeo, inMat);
inPts.renderOrder = 1;
spin.add(inPts);
// outside: idle motes drifting round it, and the droplets of a splash
const NOUT = 320;
const outGeo = makePoints(NOUT);
const outMat = ptMat(NOUT);
const outPts = new THREE.Points(outGeo, outMat);
outPts.renderOrder = 3;
outPts.frustumCulled = false;
scene.add(outPts);
const op = outGeo.attributes.position.array as Float32Array;
const oS = outGeo.attributes.aSize.array as Float32Array;
const oA = outGeo.attributes.aAlpha.array as Float32Array;
const oC = outGeo.attributes.aColor.array as Float32Array;
const oPh = outGeo.attributes.aPhase.array as Float32Array;
const vel = new Float32Array(NOUT * 3);
const life = new Float32Array(NOUT); // seconds left; motes live forever (-1)
const baseSize = new Float32Array(NOUT);
const NMOTE = 90;
for (let i = 0; i < NOUT; i++) {
oPh[i] = Math.random();
const c = pick();
oC.set([c.r, c.g, c.b], i * 3);
if (i < NMOTE) {
const v = new THREE.Vector3().randomDirection().multiplyScalar(1.25 + Math.random() * 0.9);
op.set([v.x, v.y, v.z], i * 3);
vel.set([(Math.random() - 0.5) * 0.04, 0.02 + Math.random() * 0.05, (Math.random() - 0.5) * 0.04], i * 3);
baseSize[i] = 3 + Math.random() * 7;
life[i] = -1;
} else {
baseSize[i] = 6 + Math.random() * 14;
life[i] = 0;
}
oS[i] = baseSize[i];
oA[i] = i < NMOTE ? 0.35 + Math.random() * 0.4 : 0;
}
let nextDrop = NMOTE;
// the flare: a thin star on the brightest glint
const starTex = new THREE.CanvasTexture(starTexture());
starTex.colorSpace = THREE.SRGBColorSpace;
const star = new THREE.Sprite(new THREE.SpriteMaterial({ map: starTex, transparent: true, depthWrite: false, depthTest: false, blending: THREE.AdditiveBlending, color: new THREE.Color(pal.key) }));
star.renderOrder = 4;
scene.add(star);
// ---- camera ----
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 100);
let W = 0, H = 0;
const resize = () => {
const w = root.clientWidth, h = root.clientHeight;
if (w < 2 || h < 2 || (w === W && h === H)) return;
W = w;
H = h;
renderer.setSize(W, H, false);
camera.aspect = W / H;
const span = 3.5;
const t = Math.tan(THREE.MathUtils.degToRad(15));
const d = Math.max(span / (2 * t), span / (2 * t * camera.aspect));
camera.position.set(0, 0.15, d);
camera.lookAt(0, 0, 0);
camera.updateProjectionMatrix();
inMat.uniforms.uPx.value = outMat.uniforms.uPx.value = H * dpr * 0.0016;
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(root);
// ---- motion ----
type Spring = { x: number; v: number; t: number; k: number; c: number };
const sp = (x: number, k: number, c: number): Spring => ({ x, v: 0, t: x, k, c });
const step = (s: Spring, dt: number) => {
const h = dt / 2;
for (let i = 0; i < 2; i++) {
s.v += (s.k * (s.t - s.x) - s.c * s.v) * h;
s.x += s.v * h;
}
};
const squash = sp(1, 150, 6.5); // gooey: it wobbles a few times before it settles
const slosh = sp(0, 26, 3.2);
const pullAmt = sp(0, 40, 8);
const flare = sp(0.35, 30, 9);
const pullDir = new THREE.Vector3(0, 0, 1);
const pullGoal = new THREE.Vector3(0, 0, 1);
const w = new THREE.Vector3(0, 0.35, 0);
const prevW = new THREE.Vector3();
const dragW = new THREE.Vector3();
const dq = new THREE.Quaternion();
const tmp = new THREE.Vector3();
let flash = 0;
let rip = 0;
let lastRip = -1;
const lastRipDir = new THREE.Vector3(0, 0, -1);
const calls: gsap.core.Tween[] = [];
let t = 0;
const addRipple = (dirObj: THREE.Vector3, amp: number) => {
uni.uRip.value[rip].set(dirObj.x, dirObj.y, dirObj.z, t);
uni.uRipA.value[rip] = amp;
rip = (rip + 1) % RIPPLES;
};
// pointer → a direction on the sphere, in the water's own frame (so ripples turn with it)
const ray = new THREE.Raycaster();
const sphere = new THREE.Sphere(new THREE.Vector3(), 1.04);
const ndc = new THREE.Vector2();
const hitW = new THREE.Vector3();
const inv = new THREE.Matrix4();
const hitDir = (cx: number, cy: number) => {
const r = root.getBoundingClientRect();
ndc.set(((cx - r.left) / r.width) * 2 - 1, -((cy - r.top) / r.height) * 2 + 1);
ray.setFromCamera(ndc, camera);
sphere.radius = 1.04 * holder.scale.x;
if (!ray.ray.intersectSphere(sphere, hitW)) return null;
inv.copy(spin.matrixWorld).invert();
return { obj: hitW.clone().applyMatrix4(inv).normalize(), world: hitW.clone().normalize() };
};
const splash = (dirObj: THREE.Vector3 | null, dirWorld: THREE.Vector3 | null) => {
live.current.onSplash?.();
const dO = dirObj ?? new THREE.Vector3(0, 0, 1).applyQuaternion(spin.quaternion.clone().invert());
const dW = dirWorld ?? new THREE.Vector3(0, 0, 1);
if (still) {
addRipple(dO, 0.03);
return;
}
// anticipation: it gathers itself in
squash.t = 0.86;
flare.t = 0.1;
calls.push(
gsap.delayedCall(0.12, () => {
// and bursts back out: a ripple runs round it, droplets fly, it wobbles
squash.t = 1;
squash.v += 2.2;
slosh.v += 2.5;
flare.t = 0.35;
flare.v += 9;
flash = 1;
addRipple(dO, 0.05);
for (let k = 0; k < 70; k++) {
const i = nextDrop;
nextDrop = nextDrop + 1 >= NOUT ? NMOTE : nextDrop + 1;
const o = tmp.copy(dW).multiplyScalar(1.02).add(new THREE.Vector3().randomDirection().multiplyScalar(0.12));
op.set([o.x, o.y, o.z], i * 3);
const v = new THREE.Vector3().randomDirection().multiplyScalar(0.9).add(dW.clone().multiplyScalar(1.4 + Math.random() * 1.4));
vel.set([v.x, v.y, v.z], i * 3);
life[i] = 0.8 + Math.random() * 0.9;
oA[i] = 1;
}
}),
);
};
let pointer = false;
let drag: { x: number; y: number; t: number; sx: number; sy: number; t0: number; id: number } | null = null;
let visible = true;
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting), { rootMargin: "80px" });
io.observe(root);
const tick = (_time: number, dms: number) => {
const dt = Math.min(0.05, Math.max(0.001, dms / 1000));
t += dt;
const L2 = live.current;
uni.uT.value = still ? 0 : t;
uni.uTurb.value = L2.turbulence;
// spin: a slow turn; a drag steers it; let go and it coasts back to the slow turn
prevW.copy(w);
if (drag) w.lerp(dragW, 1 - Math.exp(-dt * 20));
else w.lerp(tmp.set(0, still ? 0 : 0.32 * L2.speed, 0), 1 - Math.exp(-dt * 0.6));
dragW.multiplyScalar(Math.exp(-dt * 6));
const s0 = w.length();
if (s0 > 1e-5) {
dq.setFromAxisAngle(tmp.copy(w).divideScalar(s0), s0 * dt);
spin.quaternion.premultiply(dq).normalize();
}
// the water lags behind any change of spin and surges after it
if (!still) slosh.v += prevW.distanceTo(w) * 1.6;
// reach for the cursor (a direction in the water's frame, eased so it glides)
pullAmt.t = pointer && !drag && !still ? 1 : 0;
pullDir.lerp(pullGoal, 1 - Math.exp(-dt * 10)).normalize();
[squash, slosh, pullAmt, flare].forEach((s) => step(s, dt));
uni.uPull.value.set(pullDir.x, pullDir.y, pullDir.z, Math.max(0, pullAmt.x));
uni.uSlosh.value = slosh.x;
// squash and stretch, keeping its volume
const q = Math.max(0.7, squash.x);
holder.scale.set(1 / Math.sqrt(q), q, 1 / Math.sqrt(q));
holder.position.y = still ? 0 : Math.sin(t * 0.8) * 0.04;
flash *= Math.exp(-dt * 4);
uni.uFlash.value = flash;
// motes drift and wrap; droplets fly, slow in the air and fade
for (let i = 0; i < NOUT; i++) {
const j = i * 3;
if (life[i] === 0) continue;
if (life[i] > 0) {
life[i] = Math.max(0.0001, life[i] - dt);
const drag2 = Math.exp(-dt * 2.4);
vel[j] *= drag2;
vel[j + 1] = vel[j + 1] * drag2 - dt * 0.35;
vel[j + 2] *= drag2;
oA[i] = Math.min(1, life[i] * 1.6);
oS[i] = baseSize[i] * (0.6 + 0.4 * Math.min(1, life[i]));
if (life[i] <= 0.0001) {
life[i] = 0;
oA[i] = 0;
}
}
op[j] += vel[j] * dt;
op[j + 1] += vel[j + 1] * dt;
op[j + 2] += vel[j + 2] * dt;
if (life[i] < 0 && op[j + 1] > 2.0) op[j + 1] = -2.0; // motes rise and wrap
}
outGeo.attributes.position.needsUpdate = true;
outGeo.attributes.aAlpha.needsUpdate = true;
outGeo.attributes.aSize.needsUpdate = true;
inMat.uniforms.uOn.value = outMat.uniforms.uOn.value = L2.sparkles ? 1 : 0;
// the flare sits where the hot lamp glints back at the camera
const view = tmp.copy(camera.position).normalize();
const nrm = view.add(KEY).normalize();
star.position.copy(nrm).multiplyScalar(1.03 * holder.scale.x);
star.position.y += holder.position.y;
const fs = Math.max(0, flare.x) * (still ? 0.6 : 0.85 + 0.15 * Math.sin(t * 2.3));
star.scale.setScalar(1.5 * Math.max(0.05, fs));
star.material.opacity = Math.min(1, fs * 2.2);
if (visible && W) renderer.render(scene, camera);
};
gsap.ticker.add(tick);
// ---- input ----
const onMove = (e: PointerEvent) => {
const hit = hitDir(e.clientX, e.clientY);
pointer = Boolean(hit);
if (hit) {
pullGoal.copy(hit.obj);
// trail ripples as the cursor moves over the water
if (!still && !drag && t - lastRip > 0.09 && hit.obj.angleTo(lastRipDir) > 0.16) {
addRipple(hit.obj, 0.012);
lastRip = t;
lastRipDir.copy(hit.obj);
}
}
if (!drag) return;
const now = performance.now();
const ddt = Math.max(8, now - drag.t) / 1000;
const dx = (e.clientX - drag.x) / root.clientWidth, dy = (e.clientY - drag.y) / root.clientHeight;
dragW.set((dy / ddt) * 5, (dx / ddt) * 5, 0).clampLength(0, 10);
drag.x = e.clientX;
drag.y = e.clientY;
drag.t = now;
};
const onDown = (e: PointerEvent) => {
if (e.button !== 0) return;
const now = performance.now();
drag = { x: e.clientX, y: e.clientY, t: now, sx: e.clientX, sy: e.clientY, t0: now, id: e.pointerId };
dragW.copy(w);
try {
root.setPointerCapture(e.pointerId);
} catch {
/* synthetic pointers can't be captured */
}
};
const onUp = (e: PointerEvent) => {
if (!drag) return;
const moved = Math.hypot(e.clientX - drag.sx, e.clientY - drag.sy);
const quick = performance.now() - drag.t0 < 450;
try {
root.releasePointerCapture(drag.id);
} catch {
/* not captured */
}
drag = null;
if (moved < 7 && quick) {
const hit = hitDir(e.clientX, e.clientY);
splash(hit?.obj ?? null, hit?.world ?? null);
}
};
const onLeave = () => {
if (!drag) pointer = false;
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
splash(null, null);
} else if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
e.preventDefault();
w.y += e.key === "ArrowLeft" ? -1.8 : 1.8;
}
};
root.addEventListener("pointermove", onMove);
root.addEventListener("pointerdown", onDown);
root.addEventListener("pointerup", onUp);
root.addEventListener("pointercancel", onUp);
root.addEventListener("pointerleave", onLeave);
root.addEventListener("keydown", onKey);
return () => {
gsap.ticker.remove(tick);
calls.forEach((c) => c.kill());
io.disconnect();
ro.disconnect();
root.removeEventListener("pointermove", onMove);
root.removeEventListener("pointerdown", onDown);
root.removeEventListener("pointerup", onUp);
root.removeEventListener("pointercancel", onUp);
root.removeEventListener("pointerleave", onLeave);
root.removeEventListener("keydown", onKey);
[geo, inGeo, outGeo].forEach((g) => g.dispose());
[backMat, frontMat, inMat, outMat, star.material].forEach((m) => m.dispose());
starTex.dispose();
env.dispose();
pmrem.dispose();
renderer.dispose();
canvas.remove();
};
}, [palette, background]);
return (
<div
ref={rootRef}
tabIndex={0}
role="button"
aria-label="Orb of water. Drag to spin it, press to splash it."
className={["relative h-full min-h-[280px] w-full cursor-grab touch-none overflow-hidden outline-none select-none active:cursor-grabbing", className].filter(Boolean).join(" ")}
style={{ background }}
/>
);
}
export default TidalOrb;
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
7 propspalette"moon" | "lagoon" | "rose"Colours of the water and its light.default "moon"default "moon"turbulencenumberHow restless the surface is, 0 (glassy) to 2.default 1default 1speednumberSpeed of the slow turn (0 = still).default 1default 1sparklesbooleanSparks inside and motes around it.default truedefault truebackgroundstringCanvas background.default "#000000"default "#000000"onSplash() => voidCalled on each splash.classNamestringExtra classes (it fills its parent).