Gearworks
A living machine behind your content. Three depths of machined gears in dark graphite and steel on pure black (spoked wheels, discs with lightening holes, lathe-turned plates), every corner rounded, with soft quarter-round bevels, polished highlights and a brushed sheen. Every gear is placed tooth to tooth with its neighbour and turns at the true ratio of their tooth counts, so the whole wall is one working mechanism; far layers recede into black and near ones cast soft shadows on those behind. Every motion runs on soft springs, so the machine glides, gently overshoots and settles, never jolts. Your cursor is a work lamp that glides after it and rakes light across the metal while the layers drift in parallax, flicking it nudges the machine, a click spins it up as the lamp swells, and scrolling the page cranks the whole train (scroll up and it runs backwards). It idles slowly so it is never still, and spins up from rest on load.
Tweak
LIVELIVEColour
Machine
Motion
Interactive
Lamp follows the cursor, flicks and clicks spin the machine, scroll cranks it
Usage
Follows your tweaks.
import { Gearworks } from "@/components/inreact/gearworks";
export function Hero() {
return (
<Gearworks
className="h-screen w-full"
>
{/* optional: your hero content, drawn above the machine */}
</Gearworks>
);
}Install with the CLI
npx shadcn@latest add https://inreact.vercel.app/r/gearworks.jsonOr copy the source
Install the dependencies, then save this as components/inreact/gearworks.tsx.
npm install gsap"use client";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useEffect, useRef, type ReactNode } from "react";
gsap.registerPlugin(ScrollTrigger);
/**
* Gearworks: a living machine of real, meshing gears behind your content.
*
* Three depths of machined gears in dark graphite and steel: spoked wheels,
* discs with lightening holes and lathe-turned plates, every corner rounded,
* with soft quarter-round bevels, polished highlights and a brushed sheen. Every gear
* is placed tooth to tooth with its neighbour and turns at the true ratio of
* their tooth counts, in opposite directions, so the whole wall is one working
* mechanism. Far layers recede into black; near layers cast soft shadows on
* the ones behind. Every motion runs on soft springs, so it glides, gently
* overshoots and settles, never jolts.
*
* It reacts: your cursor is a work lamp that rakes light across the metal and
* the layers shift in parallax. Flick the cursor and the machine takes the
* torque, a click kicks it with a flash of light, and scrolling the page
* cranks the whole train (scroll up and it runs backwards). It idles slowly so
* it is never still, and on load it spins up from rest.
*
* <Gearworks className="h-screen w-full">
* <YourHero />
* </Gearworks>
*
* WebGL2: gears are generated once per size as a meshing tree, then drawn as
* instanced quads (one draw per layer) with a distance-field gear in each, plus
* a bloom at 1/4 and 1/16 size. GSAP drives every motion. Pauses off-screen;
* reduced motion shows a still frame; a CSS gradient without WebGL2.
*/
export interface GearworksProps {
/** The three metal tints (graphite, dark steel, light steel by default). */
colors?: [string, string, string];
/** Colour of the work lamp. */
light?: string;
/** Background colour. */
background?: string;
/** Gear size multiplier. */
scale?: number;
/** Idle speed of the machine. */
speed?: number;
/** Calms the centre so a headline on top stays readable, 0 to 1. */
focus?: number;
/** Strength of the bloom on metal highlights. */
glow?: number;
/** Lamp, torque, click kick, scroll crank. */
interactive?: boolean;
/** Scroll container if the page does not scroll the window. */
scroller?: Element | null;
/** Foreground content, drawn above the machine. */
children?: ReactNode;
className?: string;
}
const GEAR_VS = `#version 300 es
layout(location = 0) in vec2 aQ;
layout(location = 1) in vec2 iC;
layout(location = 2) in vec4 iG; // pitch radius, teeth, module, style
layout(location = 3) in vec4 iK; // ratio, phase, layer, tint
uniform vec2 uRes;
uniform vec2 uOff[3];
uniform float uShadow;
out vec2 vL, vS;
flat out vec4 vG, vK;
void main() {
int L = int(iK.z);
float pad = iG.x + iG.z * 1.6 + (uShadow > 0.5 ? iG.x * 0.3 : 0.0);
vec2 c = iC + uOff[L] + (uShadow > 0.5 ? vec2(0.05, 0.09) * iG.x : vec2(0.0));
vL = aQ * pad;
vS = c + vL;
vG = iG;
vK = iK;
gl_Position = vec4(vS.x / uRes.x * 2.0 - 1.0, 1.0 - vS.y / uRes.y * 2.0, 0.0, 1.0);
}`;
const GEAR_FS = `#version 300 es
precision highp float;
in vec2 vL, vS;
flat in vec4 vG, vK;
uniform vec2 uRes, uLight;
uniform float uDrive[3];
uniform vec3 uTint[3], uLamp, uBg;
uniform float uDpr, uLightZ, uLightI, uShadow, uFocus, uIntro, uTime;
out vec4 o;
const float TAU = 6.2831853;
float h21(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
// smooth max: rounds every inside corner, so nothing reads as a hard cut
float smax(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (a - b) / k, 0.0, 1.0); return mix(b, a, h) + k * h * (1.0 - h); }
// the gear's signed distance in px; sampled several times for a smooth, exact normal
float gearD(vec2 q, float R, float n, float m, float style, float ang) {
float r = length(q);
float a = atan(q.y, q.x) - ang;
float f = abs(fract(a * n / TAU + 0.5) - 0.5);
float tooth = 1.0 - smoothstep(0.1, 0.34, f);
tooth = tooth * tooth * (3.0 - 2.0 * tooth);
float d = r - (R - 1.15 * m + 2.1 * m * tooth);
float rh = max(0.2 * R, 2.4 * m);
float ri = R - 2.7 * m;
float k = m * 0.9;
if (ri - rh > 2.5 * m) {
if (style < 0.34) {
float ns = 4.0 + mod(n, 4.0);
float sd = r * abs(fract(a * ns / TAU + 0.5) - 0.5) * TAU / ns;
float sw = max(0.07 * R, 0.8 * m);
d = smax(d, -smax(smax(rh - r, r - ri, k), sw - sd, k), k * 0.6);
} else if (style < 0.67) {
float nh = 5.0 + mod(n, 3.0);
float rc = (rh + ri) * 0.5;
float seg = TAU / nh;
float a2 = (fract(a / seg + 0.5) - 0.5) * seg;
vec2 hp = vec2(cos(a2), sin(a2)) * r - vec2(rc, 0.0);
float hr = min((ri - rh) * 0.38, rc * sin(seg * 0.5) * 0.72);
d = smax(d, hr - length(hp), k * 0.5);
}
}
return smax(d, max(0.9 * m, 0.07 * R) - r, k * 0.5);
}
void main() {
float R = vG.x, n = vG.y, m = vG.z, style = vG.w;
int L = int(vK.z);
float depth = L == 0 ? 0.34 : L == 1 ? 0.62 : 1.0;
float show = smoothstep(float(L) * 0.2, float(L) * 0.2 + 0.6, uIntro);
vec2 q = vL;
float r = length(q);
if (uShadow > 0.5) {
// a wide, soft shadow cast on the layer behind
float a = (1.0 - smoothstep(R * 0.35, R + m * 2.6, r)) * 0.5 * show;
o = vec4(0.0, 0.0, 0.0, a);
return;
}
float ang = vK.x * uDrive[L] + vK.y;
float d = gearD(q, R, n, m, style, ang);
float rh = max(0.2 * R, 2.4 * m);
float aa = 0.75 / uDpr;
float cov = clamp(0.5 - d / aa, 0.0, 1.0);
if (cov <= 0.0) discard;
// a wide, rounded bevel (a quarter-round profile) instead of a sharp chamfer
float bw = m * 1.5;
float e = clamp(-d / bw, 0.0, 1.0);
float slope = sqrt(max(1.0 - e * e, 0.0)) * (1.0 - e * 0.15);
// differences on the distance field itself: a smooth normal with no pixel stair-steps
// (only inside the bevel band: on the flat face the normal points straight up, so it costs nothing)
const float EPS = 0.7;
vec2 gr = vec2(0.0);
if (e < 1.0) {
gr = vec2(gearD(q + vec2(EPS, 0.0), R, n, m, style, ang) - d, gearD(q + vec2(0.0, EPS), R, n, m, style, ang) - d);
gr = gr / max(length(gr), 1e-4);
}
vec3 nrm = normalize(vec3(gr * slope * 1.1, 1.0));
// a gently domed hub and a soft groove around it
float boss = smoothstep(rh + m * 0.6, rh - m * 0.2, r);
float groove = exp(-pow((r - rh - m * 0.35) / (m * 0.35), 2.0));
nrm = normalize(nrm + vec3(q / max(rh, 1.0) * 0.35 * boss, 0.0));
vec3 Lv = normalize(vec3(uLight - vS, uLightZ));
vec3 H = normalize(Lv + vec3(0.0, 0.0, 1.0));
float lam = max(dot(nrm, Lv), 0.0);
float ld = length(uLight - vS) / max(uRes.x, uRes.y);
float att = 1.0 / (1.0 + ld * ld * 11.0);
// polished metal: a broad soft highlight, a crisp one riding the bevels, a brushed radial sheen
float soft = pow(max(dot(nrm, H), 0.0), 18.0);
float crisp = pow(max(dot(nrm, H), 0.0), 90.0) * (1.0 - e);
vec2 rad = r > 1.0 ? q / r : vec2(1.0, 0.0);
float aniso = pow(abs(dot(rad, normalize(Lv.xy + 1e-4))), 10.0) * smoothstep(0.3, 1.0, e);
// a studio reflection: faces tilted up catch a faint softbox, everything else falls to black
float env = 0.02 + 0.05 * smoothstep(-0.3, 0.8, -nrm.y);
float id = h21(vK.xy + vG.xy);
float rings = 0.95 + 0.05 * sin(r * 0.9 + id * 40.0) * (style >= 0.67 ? 1.6 : 0.6);
vec3 tint = uTint[int(vK.w)];
vec3 c = tint * (env + 0.42 * lam * att) * rings;
c += uLamp * (soft * 0.28 + aniso * 0.22) * mix(tint, vec3(1.0), 0.6) * att * uLightI;
c += uLamp * crisp * 0.9 * att * uLightI;
c *= 1.0 + boss * 0.1 - groove * 0.5;
// depth: far layers recede into black
vec3 haze = uBg + vec3(0.006);
c = mix(haze, c * depth, mix(0.5, 1.0, depth));
vec2 cc = (vS - uRes * 0.5) / (uRes * 0.5);
float calm = 1.0 - uFocus * 0.8 * exp(-dot(cc * vec2(1.0, 1.3), cc * vec2(1.0, 1.3)) / 0.3);
c = mix(haze, c, calm);
float al = cov * show;
o = vec4(c * al, al);
}`;
const QUAD = `#version 300 es
in vec2 aQ; out vec2 vUv;
void main(){ vUv = aQ * 0.5 + 0.5; gl_Position = vec4(aQ, 0.0, 1.0); }`;
const BLUR = `#version 300 es
precision mediump float;
uniform sampler2D uTex; uniform vec2 uStep; in vec2 vUv; out vec4 o;
void main() {
vec4 c = texture(uTex, vUv) * 0.2270;
c += (texture(uTex, vUv + uStep * 1.3846) + texture(uTex, vUv - uStep * 1.3846)) * 0.3162;
c += (texture(uTex, vUv + uStep * 3.2308) + texture(uTex, vUv - uStep * 3.2308)) * 0.0703;
o = c;
}`;
const BRIGHT = `#version 300 es
precision mediump float;
uniform sampler2D uTex; in vec2 vUv; out vec4 o;
void main() {
vec3 c = texture(uTex, vUv).rgb;
float l = max(c.r, max(c.g, c.b));
o = vec4(c * smoothstep(0.6, 1.1, l), 1.0);
}`;
const COMPOSITE = `#version 300 es
precision mediump float;
uniform sampler2D uScene, uBloom, uWide; uniform float uGlow, uTime; in vec2 vUv; out vec4 o;
float h(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
void main() {
vec3 sc = texture(uScene, vUv).rgb;
vec3 bl = texture(uBloom, vUv).rgb * 0.6 + texture(uWide, vUv).rgb * 0.4;
vec3 x = sc + bl * uGlow;
vec3 col = x / (1.0 + max(x - 0.8, 0.0) * 1.2);
col += (h(gl_FragCoord.xy + fract(uTime * 7.0) * 91.0) - 0.5) / 255.0;
o = vec4(min(col, vec3(1.0)), 1.0);
}`;
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function rgb(hex: string): [number, number, number] {
let h = hex.replace("#", "");
if (h.length === 3) h = h.replace(/./g, (c) => c + c);
const n = parseInt(h, 16) || 0;
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
type Gear = { x: number; y: number; R: number; n: number; m: number; style: number; layer: number; tint: number; k: number; c: number };
/**
* Grows a tree of meshing gears over the area. Each child sits at exactly the
* sum of pitch radii from its parent and is phased so its gaps meet the
* parent's teeth; its angle is k * drive + c.
*/
function growLayer(layer: number, m: number, w: number, h: number, rnd: () => number, max: number): Gear[] {
const gears: Gear[] = [];
const pad = 0.12;
const inside = (x: number, y: number, R: number) => x > -w * pad - R * 0.4 && x < w * (1 + pad) + R * 0.4 && y > -h * pad - R * 0.4 && y < h * (1 + pad) + R * 0.4;
const fits = (x: number, y: number, R: number, parent: number) =>
inside(x, y, R) && gears.every((g, i) => i === parent || Math.hypot(g.x - x, g.y - y) > g.R + R + 2.8 * m);
const pickTint = () => {
const r = rnd();
if (layer === 0) return r < 0.6 ? 1 : r < 0.9 ? 0 : 2;
return r < 0.45 ? 0 : r < 0.75 ? 1 : 2;
};
const pickStyle = () => [0.1, 0.5, 0.85][Math.floor(rnd() * 3)];
const pickTeeth = () => Math.round(12 + Math.pow(rnd(), 1.4) * 34);
for (let tries = 0; tries < 70 && gears.length < max; tries++) {
const n = pickTeeth();
const R = (m * n) / 2;
const x = -w * pad + rnd() * w * (1 + 2 * pad), y = -h * pad + rnd() * h * (1 + 2 * pad);
if (!fits(x, y, R, -1)) continue;
const queue = [gears.length];
gears.push({ x, y, R, n, m, style: pickStyle(), layer, tint: pickTint(), k: (rnd() < 0.5 ? -1 : 1) * (0.7 + rnd() * 0.6), c: rnd() * Math.PI * 2 });
while (queue.length && gears.length < max) {
const pi = queue.shift()!;
const P = gears[pi];
for (let t = 0; t < 9 && gears.length < max; t++) {
const n2 = pickTeeth();
const R2 = (m * n2) / 2;
const th = rnd() * Math.PI * 2;
const x2 = P.x + Math.cos(th) * (P.R + R2), y2 = P.y + Math.sin(th) * (P.R + R2);
if (!fits(x2, y2, R2, pi)) continue;
const ratio = P.n / n2;
queue.push(gears.length);
gears.push({
x: x2, y: y2, R: R2, n: n2, m, style: pickStyle(), layer, tint: pickTint(),
k: -ratio * P.k,
c: -ratio * (P.c - th) + th + Math.PI + Math.PI / n2,
});
}
}
}
return gears;
}
const DEFAULT_COLORS: [string, string, string] = ["#6a6f77", "#3c3f45", "#9a9fa8"];
export function Gearworks({
colors = DEFAULT_COLORS,
light = "#f3f5f9",
background = "#000000",
scale = 1,
speed = 1,
focus = 0.45,
glow = 0.35,
interactive = true,
scroller,
children,
className,
}: GearworksProps) {
const hostRef = useRef<HTMLDivElement>(null);
const [c1, c2, c3] = colors;
const props = useRef({ c1, c2, c3, light, background, speed, focus, glow, interactive });
const redraw = useRef<(() => void) | null>(null);
useEffect(() => {
props.current = { c1, c2, c3, light, background, speed, focus, glow, interactive };
redraw.current?.();
}, [c1, c2, c3, light, background, speed, focus, glow, interactive]);
const scaleRef = useRef(scale);
const setScale = useRef<(() => void) | null>(null);
useEffect(() => {
scaleRef.current = scale;
setScale.current?.();
}, [scale]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const still = isReducedMotion();
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:pan-y;";
host.prepend(canvas);
const gl = canvas.getContext("webgl2", { alpha: false, antialias: false, powerPreference: "high-performance" });
if (!gl) {
const p = props.current;
host.style.background = `radial-gradient(70% 60% at 20% 15%, ${p.c2}22, transparent 60%), radial-gradient(70% 60% at 85% 90%, ${p.c3}1c, transparent 60%), ${p.background}`;
canvas.remove();
return;
}
const build = (vs: string, fs: string) => {
const pr = gl.createProgram()!;
for (const [type, src] of [
[gl.VERTEX_SHADER, vs],
[gl.FRAGMENT_SHADER, fs],
] as const) {
const sh = gl.createShader(type)!;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(sh));
gl.attachShader(pr, sh);
}
gl.bindAttribLocation(pr, 0, "aQ");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) console.error(gl.getProgramInfoLog(pr));
return pr;
};
const gearProg = build(GEAR_VS, GEAR_FS);
const blurProg = build(QUAD, BLUR);
const brightProg = build(QUAD, BRIGHT);
const compProg = build(QUAD, COMPOSITE);
const uni = (pr: WebGLProgram, names: string[]) =>
Object.fromEntries(names.map((n) => [n, gl.getUniformLocation(pr, n)])) as Record<string, WebGLUniformLocation | null>;
const UG = uni(gearProg, [
"uRes", "uOff", "uShadow", "uLight", "uDrive", "uTint", "uLamp", "uBg", "uDpr", "uLightZ", "uLightI", "uFocus", "uIntro", "uTime",
]);
const UB = uni(blurProg, ["uTex", "uStep"]);
const UR = uni(brightProg, ["uTex"]);
const UC = uni(compProg, ["uScene", "uBloom", "uWide", "uGlow", "uTime"]);
// fullscreen triangle for the post passes
const fsVao = gl.createVertexArray();
gl.bindVertexArray(fsVao);
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 drawQuad = () => {
gl.bindVertexArray(fsVao);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
// gear quads: one unit quad, instanced
const gearVao = gl.createVertexArray()!;
gl.bindVertexArray(gearVao);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const instBuf = gl.createBuffer()!;
const STRIDE = 10 * 4;
for (const loc of [1, 2, 3]) {
gl.enableVertexAttribArray(loc);
gl.vertexAttribDivisor(loc, 1);
}
gl.bindVertexArray(null);
const layerRange: { start: number; count: number }[] = [
{ start: 0, count: 0 },
{ start: 0, count: 0 },
{ start: 0, count: 0 },
];
const pointAt = (start: number) => {
gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
const o = start * STRIDE;
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, STRIDE, o);
gl.vertexAttribPointer(2, 4, gl.FLOAT, false, STRIDE, o + 8);
gl.vertexAttribPointer(3, 4, gl.FLOAT, false, STRIDE, o + 24);
};
let w = 1, h = 1, dpr = 1;
const layout = () => {
let seed = 1234567;
const rnd = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;
const s = Math.max(0.55, Math.min(1, Math.min(w, h * 1.3) / 1100)) * Math.max(0.4, scaleRef.current);
const all = [
...growLayer(0, 5.5 * s, w, h, rnd, 70),
...growLayer(1, 8 * s, w, h, rnd, 45),
...growLayer(2, 11 * s, w, h, rnd, 30),
];
const data = new Float32Array(all.length * 10);
all.forEach((g, i) => data.set([g.x, g.y, g.R, g.n, g.m, g.style, g.k, g.c, g.layer, g.tint], i * 10));
let start = 0;
for (let L = 0; L < 3; L++) {
const count = all.filter((g) => g.layer === L).length;
layerRange[L] = { start, count };
start += count;
}
gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
};
type Target = { fb: WebGLFramebuffer; tex: WebGLTexture; w: number; h: number };
const target = (tw: number, th: number): Target => {
const tex = gl.createTexture()!;
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, gl.RGBA, tw, th, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { fb, tex, w: tw, h: th };
};
let T: { scene: Target; a: Target; b: Target; c: Target; d: Target } | null = null;
const freeTargets = () => {
if (!T) return;
for (const t of Object.values(T)) {
gl.deleteFramebuffer(t.fb);
gl.deleteTexture(t.tex);
}
T = null;
};
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 1.5);
const nw = Math.max(1, host.clientWidth), nh = Math.max(1, host.clientHeight);
const changed = nw !== w || nh !== h;
w = nw;
h = nh;
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const sw = canvas.width, sh = canvas.height;
freeTargets();
T = {
scene: target(sw, sh),
a: target(Math.max(1, sw >> 2), Math.max(1, sh >> 2)),
b: target(Math.max(1, sw >> 2), Math.max(1, sh >> 2)),
c: target(Math.max(1, sw >> 4), Math.max(1, sh >> 4)),
d: target(Math.max(1, sw >> 4), Math.max(1, sh >> 4)),
};
if (changed) layout();
};
resize();
const s = { intro: still ? 1 : 0, mx: -9999, my: -9999, hover: 0, px: 0, py: 0, scroll: 0, flare: 0, fx: 0, fy: 0 };
// the drive is a soft spring chasing a target speed: no jolts, a gentle overshoot, then it settles
let drive = 0, omega = 0, omegaV = 0, goal = 0;
const t0 = performance.now();
const clock = () => (still ? 10 : (performance.now() - t0) / 1000);
const offs = new Float32Array(6);
const drives = new Float32Array(3);
const blurPass = (src: Target, dst: Target, dx: number, dy: number) => {
gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fb);
gl.viewport(0, 0, dst.w, dst.h);
gl.useProgram(blurProg);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, src.tex);
gl.uniform1i(UB.uTex, 0);
gl.uniform2f(UB.uStep, dx / src.w, dy / src.h);
drawQuad();
};
const draw = () => {
if (!T) return;
const p = props.current;
const X = T;
const now = clock();
// the lamp drifts slowly when no cursor; hovering brings it to the cursor; a click flares it
const idleX = w * (0.3 + 0.4 * (0.5 + 0.5 * Math.sin(now * 0.17))), idleY = h * (0.15 + 0.2 * Math.sin(now * 0.11));
let lx = idleX + (s.mx - idleX) * s.hover, ly = idleY + (s.my - idleY) * s.hover;
lx += (s.fx - lx) * s.flare;
ly += (s.fy - ly) * s.flare;
for (let L = 0; L < 3; L++) {
const dep = [0.35, 0.65, 1][L];
offs[L * 2] = s.px * dep * 22;
offs[L * 2 + 1] = s.py * dep * 16 + s.scroll * dep;
// each layer is its own train, geared down further back
drives[L] = drive * [0.55, 0.8, 1][L];
}
gl.bindFramebuffer(gl.FRAMEBUFFER, X.scene.fb);
gl.viewport(0, 0, X.scene.w, X.scene.h);
const bg = rgb(p.background);
gl.clearColor(bg[0], bg[1], bg[2], 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.useProgram(gearProg);
gl.uniform2f(UG.uRes, w, h);
gl.uniform2fv(UG.uOff, offs);
gl.uniform2f(UG.uLight, lx, ly);
gl.uniform1fv(UG.uDrive, drives);
gl.uniform3fv(UG.uTint, new Float32Array([...rgb(p.c1), ...rgb(p.c2), ...rgb(p.c3)]));
gl.uniform3fv(UG.uLamp, rgb(p.light));
gl.uniform3fv(UG.uBg, bg);
gl.uniform1f(UG.uDpr, dpr);
gl.uniform1f(UG.uLightZ, 260 + 160 * (1 - s.hover));
gl.uniform1f(UG.uLightI, 1 + s.flare * 0.5);
gl.uniform1f(UG.uFocus, Math.max(0, Math.min(1, p.focus)));
gl.uniform1f(UG.uIntro, s.intro);
gl.uniform1f(UG.uTime, now);
gl.bindVertexArray(gearVao);
for (let L = 0; L < 3; L++) {
const { start, count } = layerRange[L];
if (!count) continue;
pointAt(start);
if (L > 0) {
gl.uniform1f(UG.uShadow, 1);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, count);
}
gl.uniform1f(UG.uShadow, 0);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, count);
}
gl.bindVertexArray(null);
gl.disable(gl.BLEND);
gl.bindFramebuffer(gl.FRAMEBUFFER, X.a.fb);
gl.viewport(0, 0, X.a.w, X.a.h);
gl.useProgram(brightProg);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, X.scene.tex);
gl.uniform1i(UR.uTex, 0);
drawQuad();
blurPass(X.a, X.b, 1, 0);
blurPass(X.b, X.a, 0, 1);
blurPass(X.a, X.c, 1, 0);
blurPass(X.c, X.d, 0, 1);
blurPass(X.d, X.c, 1.8, 0);
blurPass(X.c, X.d, 0, 1.8);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(compProg);
[X.scene.tex, X.a.tex, X.d.tex].forEach((tex, i) => {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, tex);
});
gl.uniform1i(UC.uScene, 0);
gl.uniform1i(UC.uBloom, 1);
gl.uniform1i(UC.uWide, 2);
gl.uniform1f(UC.uGlow, p.glow);
gl.uniform1f(UC.uTime, now);
drawQuad();
gl.activeTexture(gl.TEXTURE0);
};
setScale.current = () => {
layout();
draw();
};
const ro = new ResizeObserver(() => {
resize();
draw();
});
ro.observe(host);
if (still) {
drive = 1.3;
draw();
redraw.current = draw;
return () => {
redraw.current = null;
setScale.current = null;
ro.disconnect();
freeTargets();
canvas.remove();
gl.getExtension("WEBGL_lose_context")?.loseContext();
};
}
// ---- on load: layers fade in back to front while the machine spins up ----
const intro = gsap.to(s, { intro: 1, duration: 2.6, ease: "expo.out", delay: 0.1 });
goal = 1.6;
// ---- cursor: the work lamp, parallax, and torque from quick flicks ----
const mxTo = gsap.quickTo(s, "mx", { duration: 0.9, ease: "power3" });
const myTo = gsap.quickTo(s, "my", { duration: 0.9, ease: "power3" });
const pxTo = gsap.quickTo(s, "px", { duration: 1.8, ease: "power3" });
const pyTo = gsap.quickTo(s, "py", { duration: 1.8, ease: "power3" });
const hoverTo = gsap.quickTo(s, "hover", { duration: 1.1, ease: "sine.inOut" });
let first = true;
let last = { x: 0, t: 0 };
const local = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top, nx: (e.clientX - r.left) / r.width - 0.5, ny: (e.clientY - r.top) / r.height - 0.5 };
};
const move = (e: PointerEvent) => {
if (!props.current.interactive) return;
const p = local(e);
const t = performance.now();
if (first) {
gsap.set(s, { mx: p.x, my: p.y });
first = false;
} else {
const vx = (p.x - last.x) / Math.max(4, t - last.t);
goal += Math.max(-0.25, Math.min(0.25, vx * 0.08));
}
last = { x: p.x, t };
mxTo(p.x);
myTo(p.y);
pxTo(-p.nx * 2);
pyTo(-p.ny * 2);
hoverTo(1);
};
const leave = () => {
first = true;
hoverTo(0);
pxTo(0);
pyTo(0);
};
// ---- click: a kick to the train and a flare of the lamp ----
const down = (e: PointerEvent) => {
if (!props.current.interactive) return;
const p = local(e);
goal += (p.nx >= 0 ? 1 : -1) * 2.2;
gsap.set(s, { fx: p.x, fy: p.y });
gsap.killTweensOf(s, "flare");
gsap.timeline().to(s, { flare: 1, duration: 0.35, ease: "sine.out" }).to(s, { flare: 0, duration: 1.4, ease: "sine.inOut" });
};
host.addEventListener("pointermove", move);
host.addEventListener("pointerdown", down);
host.addEventListener("pointerleave", leave);
// ---- scroll: the page is the crank ----
const scrollTo = gsap.quickTo(s, "scroll", { duration: 1, ease: "power3" });
let lastProgress = -1;
const st = ScrollTrigger.create({
trigger: host,
scroller: scroller ?? undefined,
start: "top bottom",
end: "bottom top",
onUpdate: (self) => {
scrollTo((self.progress - 0.5) * -140);
if (lastProgress >= 0 && props.current.interactive) goal += (self.progress - lastProgress) * 40;
lastProgress = self.progress;
},
});
// ---- loop: the drive has inertia and settles back to its idle speed ----
let visible = true;
let prev = performance.now();
const loop = () => {
const t = performance.now();
const dt = Math.min(0.05, (t - prev) / 1000);
prev = t;
if (!visible) return;
const idle = 0.22 * props.current.speed;
goal = Math.max(-5, Math.min(5, goal));
goal += (idle - goal) * (1 - Math.exp(-dt * 0.7));
// underdamped spring: the speed glides toward the target with a soft, gluey overshoot
omegaV += ((goal - omega) * 9 - omegaV * 4.2) * dt;
omega += omegaV * dt;
drive += omega * dt;
draw();
};
const io = new IntersectionObserver(([en]) => {
visible = en.isIntersecting;
prev = performance.now();
});
io.observe(host);
gsap.ticker.add(loop);
redraw.current = null;
return () => {
gsap.ticker.remove(loop);
intro.kill();
st.kill();
io.disconnect();
ro.disconnect();
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerdown", down);
host.removeEventListener("pointerleave", leave);
gsap.killTweensOf(s);
setScale.current = null;
freeTargets();
canvas.remove();
gl.getExtension("WEBGL_lose_context")?.loseContext();
};
}, [scroller]);
return (
<div ref={hostRef} className={["isolate overflow-hidden", className].filter(Boolean).join(" ")} style={{ background }}>
{children && <div className="relative z-10 h-full">{children}</div>}
</div>
);
}
export default Gearworks;
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
11 propscolors[string, string, string]The three metal tints (graphite, dark steel, light steel).default ["#6a6f77", "#3c3f45", "#9a9fa8"]default ["#6a6f77", "#3c3f45", "#9a9fa8"]lightstringColour of the work lamp.default "#f3f5f9"default "#f3f5f9"backgroundstringBackground colour.default "#000000"default "#000000"scalenumberGear size multiplier.default 1default 1speednumberIdle speed of the machine.default 1default 1focusnumberCalms the centre so a headline on top stays readable, 0 to 1.default 0.45default 0.45glownumberStrength of the bloom on metal highlights.default 0.35default 0.35interactivebooleanLamp, torque, click kick and scroll crank.default truedefault truescrollerElement | nullScroll container, if the page does not scroll the window.childrenReactNodeForeground content, drawn above the machine.classNamestringSize it, e.g. h-screen w-full.