Loading…
← All components

Background · Grid

Subtle Cyber Grid

A thin perspective grid with light pulses running along its lines; the cursor lights nearby crossings and fires new pulses.

<SubtleCyberGrid />Live

Customize

Background#050608
Primary#1f2735
Accent#5cf2ff

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add subtle-cyber-grid
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber && npm install -D @types/three
02

Add the component

One self-contained file: create components/SubtleCyberGrid.tsx and paste it in.

components/SubtleCyberGrid.tsx
1"use client";
2
3import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
4import * as THREE from "three";
5import { Canvas, useFrame, useThree } from "@react-three/fiber";
6
7/**
8 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
9 * their own tailored scenes).
10 *
11 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
12 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
13 *
14 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
15 *
16 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
17 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
18 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
19 */
20
21/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
22export type TiltAxis = "both" | "x-only" | "y-only" | "none";
23
24/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
25interface CursorProps {
26 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */
27 cursorRadius?: number;
28 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
29 cursorForce?: number;
30 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
31 magneticStrength?: number;
32 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
33 cursorDamping?: number;
34}
35
36/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
37interface TiltProps {
38 /** Largest lean towards the pointer, in degrees. Default 15. */
39 maxTiltAngle?: number;
40 /** Axes that follow the pointer. Default "both". */
41 tiltAxis?: TiltAxis;
42 /** Lean away from the pointer instead of towards it. Default false. */
43 invertTilt?: boolean;
44 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
45 parallaxOffset?: number;
46}
47
48/** 3. Text and 3D typography, for components that draw a label. */
49interface Text3DProps {
50 /** The label drawn by the component. */
51 text?: string;
52 /** Scale of the lettering. Default 1. */
53 fontSize?: number;
54 /** Extrusion depth of 3D letters. Default 0.2. */
55 textDepth?: number;
56 /** Bevelled, light-catching edges on 3D letters. Default true. */
57 bevelEnabled?: boolean;
58 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
59 fontUrl?: string;
60}
61
62/** 4. Rendering, materials and glow. */
63interface MaterialProps {
64 /** Main color of the object. Default "#6366f1". */
65 primaryColor?: string;
66 /** Color of the glow. Default "#00f0ff". */
67 emissiveColor?: string;
68 /** Strength of the glow, 0 (none) to 3. Default 1. */
69 emissiveIntensity?: number;
70 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
71 roughness?: number;
72 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
73 metalness?: number;
74 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
75 transmission?: number;
76 /** Technical wireframe rendering. Default false. */
77 wireframe?: boolean;
78}
79
80/** 5. Particles, idle motion and shader animation. */
81interface MotionProps {
82 /** Number of instanced elements. Default depends on the component. */
83 particleCount?: number;
84 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
85 autoRotateSpeed?: number;
86 /** Pulses or ripples per second. Default 1. */
87 pulseRate?: number;
88 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
89 displacementScale?: number;
90}
91
92/** 6. Environment and camera. */
93interface EnvironmentProps {
94 /** Camera field of view, in degrees. Default depends on the component. */
95 cameraFov?: number;
96 /** Color of the depth fog. Default "#0a0a0a". */
97 fogColor?: string;
98 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
99 fogDensity?: number;
100}
101
102/** 7. Performance and accessibility. */
103interface PerformanceProps {
104 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
105 lowPowerMode?: boolean;
106 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
107 respectReducedMotion?: boolean;
108 /** Stop the render loop while the component is scrolled out of view. Default true. */
109 pauseWhenOffscreen?: boolean;
110}
111
112/** Every group at once. Components extend only the groups they apply (see the top of this file). */
113interface Base3DComponentProps
114 extends CursorProps,
115 TiltProps,
116 Text3DProps,
117 MaterialProps,
118 MotionProps,
119 EnvironmentProps,
120 PerformanceProps {}
121
122type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
123
124/** The values a prop takes when it is left out. A component may override one, and then documents it. */
125const DEFAULT_3D_PROPS: Defaults = {
126 cursorRadius: 220,
127 cursorForce: 1,
128 magneticStrength: 0,
129 cursorDamping: 0.1,
130 maxTiltAngle: 15,
131 tiltAxis: "both",
132 invertTilt: false,
133 parallaxOffset: 1,
134 fontSize: 1,
135 textDepth: 0.2,
136 bevelEnabled: true,
137 primaryColor: "#6366f1",
138 emissiveColor: "#00f0ff",
139 emissiveIntensity: 1,
140 roughness: 0.3,
141 metalness: 0.5,
142 transmission: 0,
143 wireframe: false,
144 autoRotateSpeed: 0,
145 pulseRate: 1,
146 displacementScale: 1,
147 fogColor: "#0a0a0a",
148 fogDensity: 0,
149 lowPowerMode: false,
150 respectReducedMotion: true,
151 pauseWhenOffscreen: true,
152};
153
154/**
155 * The shared behaviour behind the props of ./types: pointer inertia, tilt, magnetic pull, idle spin,
156 * the OS "reduce motion" setting and the off-screen pause. Inlined into each component's bundle.
157 */
158
159/** True while the OS asks for reduced motion; follows the setting live. */
160function usePrefersReducedMotion(): boolean {
161 const [reduced, setReduced] = useState(false);
162 useEffect(() => {
163 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
164 const sync = () => setReduced(query.matches);
165 sync();
166 query.addEventListener("change", sync);
167 return () => query.removeEventListener("change", sync);
168 }, []);
169 return reduced;
170}
171
172/**
173 * The <Canvas> frameloop for `pauseWhenOffscreen`: "never" while the element is out of view. Put the ref
174 * on the element that wraps the canvas (outside it: this hook runs in the component, not in the scene).
175 */
176function useOffscreenFrameloop(ref: RefObject<HTMLElement | null>, pauseWhenOffscreen: boolean = DEFAULT_3D_PROPS.pauseWhenOffscreen): "always" | "never" {
177 // In view at first: some WebGL backends show an opaque canvas if it is paused before its first frame
178 const [inView, setInView] = useState(true);
179 useEffect(() => {
180 const el = ref.current;
181 if (!el || !pauseWhenOffscreen) return undefined;
182 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
183 observer.observe(el);
184 return () => observer.disconnect();
185 }, [ref, pauseWhenOffscreen]);
186 return !pauseWhenOffscreen || inView ? "always" : "never";
187}
188
189/**
190 * Shared GLSL noise functions, injected into the background shaders as strings.
191 *
192 * Both are the classic webgl-noise implementations by Ian McEwan and Stefan
193 * Gustavson (Ashima Arts), MIT License — https://github.com/ashima/webgl-noise
194 */
195
196/** 3D simplex noise: `float snoise(vec3 v)`, returns roughly -1..1. */
197const SIMPLEX_3D = /* glsl */ `
198vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
199vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
200vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }
201vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
202
203float snoise(vec3 v) {
204 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);
205 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
206
207 vec3 i = floor(v + dot(v, C.yyy));
208 vec3 x0 = v - i + dot(i, C.xxx);
209
210 vec3 g = step(x0.yzx, x0.xyz);
211 vec3 l = 1.0 - g;
212 vec3 i1 = min(g.xyz, l.zxy);
213 vec3 i2 = max(g.xyz, l.zxy);
214
215 vec3 x1 = x0 - i1 + C.xxx;
216 vec3 x2 = x0 - i2 + C.yyy;
217 vec3 x3 = x0 - D.yyy;
218
219 i = mod289(i);
220 vec4 p = permute(permute(permute(
221 i.z + vec4(0.0, i1.z, i2.z, 1.0))
222 + i.y + vec4(0.0, i1.y, i2.y, 1.0))
223 + i.x + vec4(0.0, i1.x, i2.x, 1.0));
224
225 float n_ = 0.142857142857;
226 vec3 ns = n_ * D.wyz - D.xzx;
227
228 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
229 vec4 x_ = floor(j * ns.z);
230 vec4 y_ = floor(j - 7.0 * x_);
231
232 vec4 x = x_ * ns.x + ns.yyyy;
233 vec4 y = y_ * ns.x + ns.yyyy;
234 vec4 h = 1.0 - abs(x) - abs(y);
235
236 vec4 b0 = vec4(x.xy, y.xy);
237 vec4 b1 = vec4(x.zw, y.zw);
238 vec4 s0 = floor(b0) * 2.0 + 1.0;
239 vec4 s1 = floor(b1) * 2.0 + 1.0;
240 vec4 sh = -step(h, vec4(0.0));
241
242 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
243 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
244
245 vec3 p0 = vec3(a0.xy, h.x);
246 vec3 p1 = vec3(a0.zw, h.y);
247 vec3 p2 = vec3(a1.xy, h.z);
248 vec3 p3 = vec3(a1.zw, h.w);
249
250 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
251 p0 *= norm.x;
252 p1 *= norm.y;
253 p2 *= norm.z;
254 p3 *= norm.w;
255
256 vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
257 m = m * m;
258 return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
259}
260`;
261
262// GLSL shared by the procedural backgrounds. Every fragment shader starts with PRELUDE, then defines
263// main(). Coordinates: `vUv` is 0..1 across the canvas (y up); aspectCoord() gives a centered space where
264// the canvas is 1 unit tall and `uAspect` units wide, so circles stay round on any screen.
265
266const FULLSCREEN_VERTEX = /* glsl */ `
267varying vec2 vUv;
268void main() {
269 vUv = uv;
270 gl_Position = vec4(position.xy, 0.0, 1.0);
271}
272`;
273
274const UNIFORMS = /* glsl */ `
275uniform float uTime; // seconds, already multiplied by \`speed\`
276uniform vec2 uResolution; // drawing buffer size, px
277uniform float uAspect; // width / height
278uniform vec2 uMouse; // smoothed pointer, 0..1
279uniform vec2 uMouseVelocity; // smoothed pointer velocity, canvas units per second
280uniform float uInteract; // 0..1 presence of the pointer (0 when \`interactive\` is false)
281uniform float uPress; // 0..1 while a button is held
282uniform float uScale; // pattern size multiplier
283uniform vec3 uColorBg;
284uniform vec3 uColorPrimary;
285uniform vec3 uColorAccent;
286uniform sampler2D uTrail; // cursor simulation (see TrailSimulation), when the background has one
287uniform vec2 uTrailTexel; // 1 / its resolution
288varying vec2 vUv;
289`;
290
291const HELPERS = /* glsl */ `
292const float PI = 3.14159265;
293
294vec2 aspectCoord(vec2 uv) { return (uv - 0.5) * vec2(uAspect, 1.0); }
295vec2 mouseCoord() { return aspectCoord(uMouse); }
296vec2 mouseVelocity() { return uMouseVelocity * vec2(uAspect, 1.0); }
297
298mat2 rot2(float a) {
299 float c = cos(a);
300 float s = sin(a);
301 return mat2(c, s, -s, c);
302}
303
304// Hashes without sine (Dave Hoskins, MIT): stable on every GPU
305float hash12(vec2 p) {
306 vec3 p3 = fract(vec3(p.xyx) * 0.1031);
307 p3 += dot(p3, p3.yzx + 33.33);
308 return fract((p3.x + p3.y) * p3.z);
309}
310vec2 hash22(vec2 p) {
311 vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
312 p3 += dot(p3, p3.yzx + 33.33);
313 return fract((p3.xx + p3.yz) * p3.zy);
314}
315
316// Fractional Brownian motion over simplex noise, up to 6 octaves
317float fbm(vec3 p, int octaves) {
318 float sum = 0.0;
319 float amp = 0.5;
320 for (int i = 0; i < 6; i++) {
321 if (i >= octaves) break;
322 sum += amp * snoise(p);
323 p = p * 2.02 + vec3(17.1, -3.7, 5.3);
324 amp *= 0.5;
325 }
326 return sum;
327}
328
329// Gradient of the ripple simulation's height at uv (central differences)
330vec2 trailGradient(vec2 uv) {
331 float l = texture2D(uTrail, uv - vec2(uTrailTexel.x, 0.0)).r;
332 float r = texture2D(uTrail, uv + vec2(uTrailTexel.x, 0.0)).r;
333 float d = texture2D(uTrail, uv - vec2(0.0, uTrailTexel.y)).r;
334 float u = texture2D(uTrail, uv + vec2(0.0, uTrailTexel.y)).r;
335 return vec2(r - l, u - d) * 0.5;
336}
337
338// Breaks the 8-bit banding of slow gradients; never negative (the sRGB conversion would turn it black)
339vec3 dither(vec3 color) {
340 return max(color + (hash12(gl_FragCoord.xy) - 0.5) / 255.0, 0.0);
341}
342`;
343
344const PRELUDE = UNIFORMS + SIMPLEX_3D + HELPERS;
345
346const SIM_UNIFORMS = /* glsl */ `
347uniform sampler2D uPrev;
348uniform vec2 uTexel;
349uniform float uAspect;
350uniform vec2 uMouse;
351uniform vec2 uMouseVelocity;
352uniform float uInteract;
353uniform float uDt;
354varying vec2 vUv;
355`;
356
357/** Ripple: a damped 2D wave equation; the moving cursor drops into it like a finger in water. */
358const RIPPLE_FRAGMENT = /* glsl */ `
359${SIM_UNIFORMS}
360void main() {
361 vec2 uv = vUv;
362 vec4 here = texture2D(uPrev, uv);
363 float sum = texture2D(uPrev, uv + vec2(uTexel.x, 0.0)).r + texture2D(uPrev, uv - vec2(uTexel.x, 0.0)).r
364 + texture2D(uPrev, uv + vec2(0.0, uTexel.y)).r + texture2D(uPrev, uv - vec2(0.0, uTexel.y)).r;
365 float h = (sum * 0.5 - here.g) * 0.975;
366
367 vec2 d = (uv - uMouse) * vec2(uAspect, 1.0);
368 float speed = length(uMouseVelocity * vec2(uAspect, 1.0));
369 h += exp(-dot(d, d) / 0.0009) * min(speed, 1.2) * uInteract * 0.012;
370 gl_FragColor = vec4(clamp(h, -1.0, 1.0), here.r, 0.0, 1.0);
371}
372`;
373
374/**
375 * Props shared by the procedural backgrounds (FluidSmokeDrift, FerrofluidTopography, …). Every one of
376 * them is a single shader: no image, no video, no external asset. Changing a prop live never recompiles
377 * the shader: colors, speed and scale are uniforms.
378 */
379interface DeepBackgroundProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode" | "respectReducedMotion"> {
380 /** React to the pointer. false removes the listeners and lets every cursor force ease back to 0. Default true. */
381 interactive?: boolean;
382 /** Palette: [background, primary, accent]. The accent falls back to the component's own. */
383 colors?: [string, string, string?];
384 /** Animation speed multiplier; changing it live never makes the animation jump. Default 1. */
385 speed?: number;
386 /** Size of the patterns, grain or cells: 2 makes them twice as large. Default 1. */
387 scale?: number;
388 /** Extra classes for the container (absolutely positioned, filling its parent). */
389 className?: string;
390}
391
392type BackgroundPalette = readonly [string, string, string];
393
394const DEEP_BACKGROUND_DEFAULTS = {
395 interactive: true,
396 speed: 1,
397 scale: 1,
398} as const;
399
400/**
401 * Memory of the cursor, simulated on the GPU at low resolution and handed to the shader as `uTrail`.
402 * "ripple": a damped wave equation (r = height, g = previous height): circular waves spreading out.
403 */
404type TrailSimulation = "ripple";
405
406/** The cursor as the shaders see it. Read inside useFrame: pointer moves never re-render React. */
407interface PointerPhysics {
408 /** Smoothed position in the canvas, 0..1 (y up). */
409 position: THREE.Vector2;
410 /** Smoothed velocity, in canvas units (0..1) per second. */
411 velocity: THREE.Vector2;
412 /** 0..1: eases to 1 while the pointer is over the canvas (and `interactive`), back to 0 otherwise. */
413 strength: number;
414 /** 0..1: eases to 1 while a button or a finger is down. */
415 press: number;
416}
417
418interface RawPointer {
419 x: number;
420 y: number;
421 inside: boolean;
422 down: boolean;
423 seen: boolean;
424}
425
426const FOLLOW = 14; // damp rate of the position
427
428const VELOCITY_FOLLOW = 8;
429
430const STRENGTH_FOLLOW = 3.5; // forces fade in and out over ~half a second
431
432/**
433 * Pointer physics shared by the procedural backgrounds: smoothed position, smoothed velocity and an
434 * eased presence. The canvas has `pointer-events: none` (the page above it stays clickable), so the
435 * pointer is read from window listeners. With `interactive` false there is no listener at all and
436 * every force eases back to 0, leaving the autonomous animation alone.
437 */
438function usePointerPhysics(interactive: boolean): RefObject<PointerPhysics> {
439 const gl = useThree((state) => state.gl);
440 const raw = useRef<RawPointer>({ x: 0.5, y: 0.5, inside: false, down: false, seen: false });
441 const physics = useRef<PointerPhysics>({ position: new THREE.Vector2(0.5, 0.5), velocity: new THREE.Vector2(), strength: 0, press: 0 });
442 const previous = useRef(new THREE.Vector2(0.5, 0.5));
443
444 useEffect(() => {
445 const p = raw.current;
446 if (!interactive) {
447 p.inside = false;
448 p.down = false;
449 return undefined;
450 }
451 const el = gl.domElement;
452 const move = (event: PointerEvent) => {
453 const rect = el.getBoundingClientRect();
454 if (!rect.width || !rect.height) return;
455 p.x = (event.clientX - rect.left) / rect.width;
456 p.y = 1 - (event.clientY - rect.top) / rect.height;
457 p.inside = p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1;
458 if (!p.seen) {
459 // First contact: start from the pointer instead of sweeping in from the center
460 p.seen = true;
461 physics.current.position.set(p.x, p.y);
462 previous.current.set(p.x, p.y);
463 }
464 };
465 const down = (event: PointerEvent) => {
466 move(event);
467 p.down = true;
468 };
469 const up = () => {
470 p.down = false;
471 };
472 const leave = () => {
473 p.inside = false;
474 p.down = false;
475 };
476 window.addEventListener("pointermove", move, { passive: true });
477 window.addEventListener("pointerdown", down, { passive: true });
478 window.addEventListener("pointerup", up, { passive: true });
479 window.addEventListener("pointercancel", leave, { passive: true });
480 document.documentElement.addEventListener("pointerleave", leave);
481 window.addEventListener("blur", leave);
482 return () => {
483 window.removeEventListener("pointermove", move);
484 window.removeEventListener("pointerdown", down);
485 window.removeEventListener("pointerup", up);
486 window.removeEventListener("pointercancel", leave);
487 document.documentElement.removeEventListener("pointerleave", leave);
488 window.removeEventListener("blur", leave);
489 };
490 }, [gl, interactive]);
491
492 useFrame((_, delta) => {
493 const dt = Math.min(delta, 1 / 20);
494 const p = raw.current;
495 const s = physics.current;
496 const damp = THREE.MathUtils.damp;
497 s.position.set(damp(s.position.x, p.x, FOLLOW, dt), damp(s.position.y, p.y, FOLLOW, dt));
498 const vx = dt > 0 ? (s.position.x - previous.current.x) / dt : 0;
499 const vy = dt > 0 ? (s.position.y - previous.current.y) / dt : 0;
500 previous.current.copy(s.position);
501 const active = interactive && p.inside;
502 s.velocity.set(damp(s.velocity.x, active ? vx : 0, VELOCITY_FOLLOW, dt), damp(s.velocity.y, active ? vy : 0, VELOCITY_FOLLOW, dt));
503 s.strength = damp(s.strength, active ? 1 : 0, STRENGTH_FOLLOW, dt);
504 s.press = damp(s.press, active && p.down ? 1 : 0, STRENGTH_FOLLOW * 2, dt);
505 });
506
507 return physics;
508}
509
510interface BackgroundUniforms {
511 uTime: THREE.IUniform<number>;
512 uResolution: THREE.IUniform<THREE.Vector2>;
513 uAspect: THREE.IUniform<number>;
514 uMouse: THREE.IUniform<THREE.Vector2>;
515 uMouseVelocity: THREE.IUniform<THREE.Vector2>;
516 uInteract: THREE.IUniform<number>;
517 uPress: THREE.IUniform<number>;
518 uScale: THREE.IUniform<number>;
519 uColorBg: THREE.IUniform<THREE.Color>;
520 uColorPrimary: THREE.IUniform<THREE.Color>;
521 uColorAccent: THREE.IUniform<THREE.Color>;
522 uTrail: THREE.IUniform<THREE.Texture | null>;
523 uTrailTexel: THREE.IUniform<THREE.Vector2>;
524}
525
526interface SimUniforms {
527 uPrev: THREE.IUniform<THREE.Texture | null>;
528 uTexel: THREE.IUniform<THREE.Vector2>;
529 uAspect: THREE.IUniform<number>;
530 uMouse: THREE.IUniform<THREE.Vector2>;
531 uMouseVelocity: THREE.IUniform<THREE.Vector2>;
532 uInteract: THREE.IUniform<number>;
533 uDt: THREE.IUniform<number>;
534}
535
536const SIM_STEP = 1 / 60; // fixed step: waves travel at the same speed at 60, 120 or 144 fps
537
538const SIM_SIZE: Record<TrailSimulation, number> = { ripple: 288 }; // px on the long side
539
540/**
541 * Ping-pong render targets at low resolution, stepped before the frame is drawn. Writes its latest
542 * state into `target.uTrail`.
543 */
544function useTrailSimulation(kind: TrailSimulation | undefined, physics: RefObject<PointerPhysics>, target: BackgroundUniforms) {
545 const gl = useThree((state) => state.gl);
546 const width = useThree((state) => state.size.width);
547 const height = useThree((state) => state.size.height);
548 const aspect = width / Math.max(height, 1);
549
550 // Resolution follows the canvas shape, rounded so small resizes keep the current simulation
551 const long = kind ? SIM_SIZE[kind] : 0;
552 const simW = kind ? Math.max(16, Math.round((aspect >= 1 ? long : long * aspect) / 8) * 8) : 0;
553 const simH = kind ? Math.max(16, Math.round((aspect >= 1 ? long / aspect : long) / 8) * 8) : 0;
554
555 const sim = useMemo(() => {
556 if (!kind) return null;
557 const make = () =>
558 new THREE.WebGLRenderTarget(simW, simH, {
559 type: THREE.HalfFloatType,
560 format: THREE.RGBAFormat,
561 minFilter: THREE.LinearFilter,
562 magFilter: THREE.LinearFilter,
563 wrapS: THREE.ClampToEdgeWrapping,
564 wrapT: THREE.ClampToEdgeWrapping,
565 depthBuffer: false,
566 stencilBuffer: false,
567 });
568 const uniforms: SimUniforms = {
569 uPrev: { value: null },
570 uTexel: { value: new THREE.Vector2(1 / simW, 1 / simH) },
571 uAspect: { value: 1 },
572 uMouse: { value: new THREE.Vector2(0.5, 0.5) },
573 uMouseVelocity: { value: new THREE.Vector2() },
574 uInteract: { value: 0 },
575 uDt: { value: SIM_STEP },
576 };
577 const material = new THREE.ShaderMaterial({
578 uniforms: uniforms as unknown as Record<string, THREE.IUniform>,
579 vertexShader: FULLSCREEN_VERTEX,
580 fragmentShader: RIPPLE_FRAGMENT,
581 depthTest: false,
582 depthWrite: false,
583 });
584 const geometry = new THREE.PlaneGeometry(2, 2);
585 const quad = new THREE.Mesh(geometry, material);
586 quad.frustumCulled = false;
587 const scene = new THREE.Scene();
588 scene.add(quad);
589 return { targets: [make(), make()] as [THREE.WebGLRenderTarget, THREE.WebGLRenderTarget], uniforms, material, geometry, scene, camera: new THREE.Camera(), read: 0, carry: 0 };
590 }, [kind, simW, simH]);
591
592 useEffect(() => {
593 if (!sim) return undefined;
594 target.uTrailTexel.value.set(1 / simW, 1 / simH);
595 return () => {
596 sim.targets.forEach((t) => t.dispose());
597 sim.material.dispose();
598 sim.geometry.dispose();
599 if (sim.targets.some((t) => t.texture === target.uTrail.value)) target.uTrail.value = null;
600 };
601 }, [sim, simW, simH, target]);
602
603 useFrame((_, delta) => {
604 if (!sim) return;
605 const p = physics.current;
606 const u = sim.uniforms;
607 u.uAspect.value = aspect;
608 u.uMouse.value.copy(p.position);
609 u.uMouseVelocity.value.copy(p.velocity);
610 u.uInteract.value = p.strength;
611
612 // Fixed steps, at most 3 per frame (a background tab coming back must not fast-forward for seconds)
613 sim.carry = Math.min(sim.carry + delta, SIM_STEP * 3);
614 const previousTarget = gl.getRenderTarget();
615 while (sim.carry >= SIM_STEP) {
616 sim.carry -= SIM_STEP;
617 const read = sim.targets[sim.read];
618 const write = sim.targets[1 - sim.read];
619 u.uPrev.value = read.texture;
620 gl.setRenderTarget(write);
621 gl.render(sim.scene, sim.camera);
622 sim.read = 1 - sim.read;
623 }
624 gl.setRenderTarget(previousTarget);
625 target.uTrail.value = sim.targets[sim.read].texture;
626 });
627}
628
629interface ShaderPlaneProps {
630 fragmentShader: string;
631 palette: BackgroundPalette;
632 interactive: boolean;
633 speed: number;
634 scale: number;
635 still: boolean;
636 simulation?: TrailSimulation;
637}
638
639function ShaderPlane({ fragmentShader, palette, interactive, speed, scale, still, simulation }: ShaderPlaneProps) {
640 const physics = usePointerPhysics(interactive);
641 // Smoothed so a slider drag never makes the patterns jump (starts at the initial value)
642 const scaleTarget = useRef(Math.max(0.05, scale));
643
644 // Compiled once per shader; every prop below only updates uniforms
645 const { material, uniforms } = useMemo(() => {
646 const u: BackgroundUniforms = {
647 uTime: { value: 0 },
648 uResolution: { value: new THREE.Vector2(1, 1) },
649 uAspect: { value: 1 },
650 uMouse: { value: new THREE.Vector2(0.5, 0.5) },
651 uMouseVelocity: { value: new THREE.Vector2() },
652 uInteract: { value: 0 },
653 uPress: { value: 0 },
654 uScale: { value: scaleTarget.current },
655 uColorBg: { value: new THREE.Color() },
656 uColorPrimary: { value: new THREE.Color() },
657 uColorAccent: { value: new THREE.Color() },
658 uTrail: { value: null },
659 uTrailTexel: { value: new THREE.Vector2(1, 1) },
660 };
661 const m = new THREE.ShaderMaterial({
662 uniforms: u as unknown as Record<string, THREE.IUniform>,
663 vertexShader: FULLSCREEN_VERTEX,
664 fragmentShader: PRELUDE + fragmentShader + "\n",
665 depthTest: false,
666 depthWrite: false,
667 });
668 return { material: m, uniforms: u };
669 }, [fragmentShader]);
670 const geometry = useMemo(() => new THREE.PlaneGeometry(2, 2), []);
671
672 useEffect(() => () => material.dispose(), [material]);
673 useEffect(() => () => geometry.dispose(), [geometry]);
674
675 const [background, primary, accent] = palette;
676 useEffect(() => {
677 uniforms.uColorBg.value.set(background);
678 uniforms.uColorPrimary.value.set(primary);
679 uniforms.uColorAccent.value.set(accent);
680 }, [uniforms, background, primary, accent]);
681
682 useEffect(() => {
683 scaleTarget.current = Math.max(0.05, scale);
684 }, [scale]);
685
686 useTrailSimulation(simulation, physics, uniforms);
687
688 useFrame((state, delta) => {
689 const dt = Math.min(delta, 1 / 20);
690 const u = uniforms;
691 // Time integrates the speed: changing it live changes the pace, never the position in the animation
692 if (!still) u.uTime.value += dt * speed;
693 const { width, height } = state.size;
694 u.uResolution.value.set(width * state.viewport.dpr, height * state.viewport.dpr);
695 u.uAspect.value = width / Math.max(height, 1);
696 u.uScale.value = THREE.MathUtils.damp(u.uScale.value, scaleTarget.current, 6, dt);
697 const p = physics.current;
698 u.uMouse.value.copy(p.position);
699 u.uMouseVelocity.value.copy(p.velocity);
700 u.uInteract.value = p.strength;
701 u.uPress.value = p.press;
702 });
703
704 return <mesh geometry={geometry} material={material} frustumCulled={false} />;
705}
706
707interface ShaderBackgroundProps extends DeepBackgroundProps {
708 /** Body of the fragment shader: PRELUDE (uniforms, noise, helpers) is prepended. */
709 fragmentShader: string;
710 /** The component's own palette, used for any color left out of `colors`. */
711 defaultColors: BackgroundPalette;
712 simulation?: TrailSimulation;
713}
714
715/**
716 * One full-screen shader behind the page: fills its positioned parent, never catches clicks, pauses
717 * off-screen, freezes its clock under "reduce motion" (the cursor still reacts) and disposes every GPU
718 * resource on unmount.
719 */
720function ShaderBackground({
721 fragmentShader,
722 defaultColors,
723 simulation,
724 interactive = DEEP_BACKGROUND_DEFAULTS.interactive,
725 colors,
726 speed = DEEP_BACKGROUND_DEFAULTS.speed,
727 scale = DEEP_BACKGROUND_DEFAULTS.scale,
728 className = "",
729 pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen,
730 lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode,
731 respectReducedMotion = DEFAULT_3D_PROPS.respectReducedMotion,
732}: ShaderBackgroundProps) {
733 const container = useRef<HTMLDivElement>(null);
734 const frameloop = useOffscreenFrameloop(container, pauseWhenOffscreen);
735 const reduced = usePrefersReducedMotion();
736 const palette: BackgroundPalette = [colors?.[0] ?? defaultColors[0], colors?.[1] ?? defaultColors[1], colors?.[2] ?? defaultColors[2]];
737
738 return (
739 <div ref={container} className={`pointer-events-none absolute inset-0 overflow-hidden ${className}`} style={{ background: palette[0] }} aria-hidden="true">
740 <Canvas
741 dpr={lowPowerMode ? 1 : [1, 1.75]}
742 frameloop={frameloop}
743 gl={{ antialias: false, alpha: false, powerPreference: "high-performance" }}
744 style={{ pointerEvents: "none" }}
745 >
746 <ShaderPlane
747 fragmentShader={fragmentShader}
748 palette={palette}
749 interactive={interactive}
750 speed={speed}
751 scale={scale}
752 still={respectReducedMotion && reduced}
753 simulation={simulation}
754 />
755 </Canvas>
756 </div>
757 );
758}
759
760export type { DeepBackgroundProps };
761
762const COLORS: BackgroundPalette = ["#050608", "#1f2735", "#5cf2ff"];
763
764// A thin perspective grid on the floor, gliding towards the viewer, with light pulses running along
765// some of its lines (picked by hash). The pointer, projected onto the floor, lights the intersections
766// around it with a soft halo and fires pulses outwards along the two lines crossing under it.
767// Everything is computed without branches: fwidth() needs every pixel to take the same path.
768const FRAGMENT = /* glsl */ `
769const float HORIZON = 0.16;
770const float DENSITY = 8.0;
771
772vec2 floorCoord(vec2 p) {
773 float depth = 0.35 / max(HORIZON - p.y, 0.004);
774 return vec2(p.x * depth, depth) * DENSITY / uScale + vec2(0.0, uTime * 0.6);
775}
776
777void main() {
778 vec2 p = aspectCoord(vUv);
779 float onFloor = step(p.y, HORIZON - 0.002);
780 float depth = 0.35 / max(HORIZON - p.y, 0.004);
781 vec2 g = floorCoord(p);
782
783 vec2 fw = max(fwidth(g), vec2(1e-5));
784 vec2 lineDist = abs(fract(g - 0.5) - 0.5) / fw;
785 float onRow = 1.0 - min(lineDist.y, 1.0); // line of constant depth (horizontal on screen)
786 float onCol = 1.0 - min(lineDist.x, 1.0); // line running into the distance
787 float line = max(onRow, onCol);
788 float fade = exp(-depth * 0.35) * onFloor;
789 // Far lines melt into a haze instead of aliasing
790 float haze = smoothstep(1.4, 0.4, max(fw.x, fw.y));
791
792 vec2 nearest = floor(g + 0.5);
793 float rowHash = hash12(vec2(nearest.y, 3.1));
794 float colHash = hash12(vec2(nearest.x, 7.7));
795 float rowPulse = step(0.72, rowHash) * pow(fract(g.x * 0.08 - uTime * (0.25 + rowHash * 0.3) + rowHash * 10.0), 16.0);
796 float colPulse = step(0.7, colHash) * pow(fract(g.y * 0.06 + uTime * (0.2 + colHash * 0.3) + colHash * 10.0), 16.0);
797
798 // The pointer on the floor
799 vec2 m = mouseCoord();
800 float mouseOnFloor = step(m.y, HORIZON - 0.01) * uInteract;
801 vec2 mg = floorCoord(m);
802 vec2 mCell = floor(mg + 0.5);
803 vec2 toMouse = g - mg;
804 float halo = exp(-dot(toMouse, toMouse) / 3.0) * mouseOnFloor;
805 float crossing = onRow * onCol;
806 float sameRow = 1.0 - step(0.5, abs(nearest.y - mCell.y));
807 float sameCol = 1.0 - step(0.5, abs(nearest.x - mCell.x));
808 float along = abs(toMouse.x);
809 float alongCol = abs(toMouse.y);
810 float firedRow = sameRow * onRow * pow(fract(along * 0.2 - uTime * 1.4), 10.0) * exp(-along * 0.12);
811 float firedCol = sameCol * onCol * pow(fract(alongCol * 0.2 - uTime * 1.4), 10.0) * exp(-alongCol * 0.12);
812
813 vec3 color = uColorBg;
814 color += uColorAccent * 0.07 * exp(-abs(p.y - HORIZON) * 14.0);
815 color += uColorPrimary * line * haze * fade * 1.1;
816 color += uColorAccent * (onRow * rowPulse + onCol * colPulse) * haze * fade * 1.3;
817 color += uColorAccent * (firedRow + firedCol) * mouseOnFloor * haze * fade * 1.6;
818 color += uColorAccent * (halo * 0.06 + crossing * halo * 1.4) * fade;
819 color *= 1.0 - 0.25 * dot(p, p);
820 gl_FragColor = vec4(dither(color), 1.0);
821 #include <colorspace_fragment>
822}
823`;
824
825/** A subtle perspective grid with light pulses; the pointer lights nearby crossings and fires new pulses. */
826export default function SubtleCyberGrid(props: DeepBackgroundProps) {
827 return <ShaderBackground {...props} fragmentShader={FRAGMENT} defaultColors={COLORS} />;
828}
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import SubtleCyberGrid from "@/components/SubtleCyberGrid";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <SubtleCyberGrid
8 speed={1}
9 scale={1}
10 background="#050608"
11 primary="#1f2735"
12 accent="#5cf2ff"
13 interactive
14 />
15 </div>
16 );
17}
Next componentOrbital Horizon→