Loading…
← All components

Background · Procedural

Procedural Terrain

An endless wireframe landscape streaming towards the camera and fading into fog.

<ProceduralTerrainBackground />Live

Customize

Lines#a5b4fc
Surface#0b1020
Fog#05060a

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add procedural-terrain
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/ProceduralTerrainBackground.tsx and paste it in.

components/ProceduralTerrainBackground.tsx
1"use client";
2
3import { memo, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
4import * as THREE from "three";
5import { Canvas, useFrame, type CanvasProps } 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/** Fills the positioned parent; never intercepts clicks meant for the page content above it. */
155const FILL_STYLE: CSSProperties = {
156 position: "absolute",
157 top: 0,
158 left: 0,
159 width: "100%",
160 height: "100%",
161 pointerEvents: "none",
162};
163
164interface BackgroundCanvasProps extends Omit<CanvasProps, "children" | "style" | "frameloop" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
165 children: ReactNode;
166}
167
168/**
169 * Ready-to-use <Canvas> shared by every background.
170 * - Pauses the render loop while the canvas is scrolled out of view.
171 * - Renders a single still frame when the user prefers reduced motion.
172 * - Caps the pixel ratio; R3F disposes the renderer and releases the WebGL
173 * context (forceContextLoss) when the Canvas unmounts.
174 */
175function BackgroundCanvas({ children, dpr = [1, 1.75], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: BackgroundCanvasProps) {
176 const containerRef = useRef<HTMLDivElement>(null);
177 // Starts "in view" so the first frame is always drawn before the loop can be paused
178 const [inView, setInView] = useState(true);
179 const [reducedMotion, setReducedMotion] = useState(false);
180
181 useEffect(() => {
182 const el = containerRef.current;
183 if (!el) return undefined;
184 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
185 observer.observe(el);
186
187 const query = window.matchMedia("(prefers-reduced-motion: reduce)");
188 const sync = () => setReducedMotion(query.matches);
189 sync();
190 query.addEventListener("change", sync);
191
192 return () => {
193 observer.disconnect();
194 query.removeEventListener("change", sync);
195 };
196 }, []);
197
198 return (
199 <div ref={containerRef} style={FILL_STYLE} aria-hidden="true">
200 <Canvas
201 dpr={lowPowerMode ? 1 : dpr}
202 frameloop={!inView && pauseWhenOffscreen ? "never" : reducedMotion ? "demand" : "always"}
203 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
204 style={{ pointerEvents: "none" }}
205 {...canvasProps}
206 >
207 {children}
208 </Canvas>
209 </div>
210 );
211}
212
213/** Classic 2D Perlin noise: `float cnoise(vec2 P)`, returns roughly -1..1. */
214const PERLIN_2D = /* glsl */ `
215vec4 pMod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
216vec4 pPermute(vec4 x) { return pMod289(((x * 34.0) + 10.0) * x); }
217vec4 pTaylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
218vec2 pFade(vec2 t) { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
219
220float cnoise(vec2 P) {
221 vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0);
222 vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0);
223 Pi = pMod289(Pi);
224 vec4 ix = Pi.xzxz;
225 vec4 iy = Pi.yyww;
226 vec4 fx = Pf.xzxz;
227 vec4 fy = Pf.yyww;
228
229 vec4 i = pPermute(pPermute(ix) + iy);
230
231 vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0;
232 vec4 gy = abs(gx) - 0.5;
233 vec4 tx = floor(gx + 0.5);
234 gx = gx - tx;
235
236 vec2 g00 = vec2(gx.x, gy.x);
237 vec2 g10 = vec2(gx.y, gy.y);
238 vec2 g01 = vec2(gx.z, gy.z);
239 vec2 g11 = vec2(gx.w, gy.w);
240
241 vec4 norm = pTaylorInvSqrt(vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11)));
242 g00 *= norm.x;
243 g01 *= norm.y;
244 g10 *= norm.z;
245 g11 *= norm.w;
246
247 float n00 = dot(g00, vec2(fx.x, fy.x));
248 float n10 = dot(g10, vec2(fx.y, fy.y));
249 float n01 = dot(g01, vec2(fx.z, fy.z));
250 float n11 = dot(g11, vec2(fx.w, fy.w));
251
252 vec2 fadeXY = pFade(Pf.xy);
253 vec2 nX = mix(vec2(n00, n01), vec2(n10, n11), fadeXY.x);
254 return 2.3 * mix(nX.x, nX.y, fadeXY.y);
255}
256`;
257
258export interface TerrainProps extends Pick<MaterialProps, "primaryColor" | "wireframe">, Pick<MotionProps, "displacementScale">, Pick<EnvironmentProps, "fogColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
259 /** Draws the grid lines over the surface. Default true. */
260 wireframe?: boolean;
261 wireframeColor?: string;
262 primaryColor?: string;
263 /** @deprecated Use `primaryColor`. */
264 surfaceColor?: string;
265 /** Fog and sky color: the terrain fades into it in the distance. */
266 fogColor?: string;
267 /** Height of the relief, in world units. Default 2.2. */
268 displacementScale?: number;
269 /** @deprecated Use `displacementScale`. */
270 elevationScale?: number;
271 /** Flight speed multiplier. Default 1. */
272 speed?: number;
273 /** Subdivisions across the width (the depth gets 1.5×). Default 128. */
274 gridSegments?: number;
275}
276
277const SIZE_X = 40;
278const SIZE_Z = 60;
279
280const vertexShader = /* glsl */ `
281#include <common>
282#include <fog_pars_vertex>
283
284uniform float uTravel;
285uniform float uElevation;
286
287varying float vHeight;
288varying vec3 vNormalW;
289
290${PERLIN_2D}
291
292float fbm(vec2 p) {
293 float h = 0.0;
294 float amplitude = 1.0;
295 float frequency = 1.0;
296 for (int i = 0; i < 4; i++) {
297 h += cnoise(p * frequency) * amplitude;
298 frequency *= 2.07;
299 amplitude *= 0.5;
300 }
301 return h;
302}
303
304// The noise is sampled at z - travel: the mesh stays put while the relief streams towards the camera
305float heightAt(vec2 xz) {
306 float h = fbm(vec2(xz.x, xz.y - uTravel) * 0.09);
307 // Flatter valley in the middle, so the flight path stays clear
308 float valley = smoothstep(1.5, 9.0, abs(xz.x));
309 return h * uElevation * mix(0.25, 1.0, valley);
310}
311
312void main() {
313 vec3 pos = position;
314 float h = heightAt(pos.xz);
315 pos.y = h;
316
317 // Normal from finite differences of the height field
318 const float e = 0.15;
319 float hx = heightAt(pos.xz + vec2(e, 0.0));
320 float hz = heightAt(pos.xz + vec2(0.0, e));
321 vNormalW = normalize(vec3(h - hx, e, h - hz));
322 vHeight = h / max(uElevation, 0.0001);
323
324 vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
325 gl_Position = projectionMatrix * mvPosition;
326 #include <fog_vertex>
327}
328`;
329
330const fragmentShader = /* glsl */ `
331#include <common>
332#include <fog_pars_fragment>
333
334uniform vec3 uColor;
335uniform float uShade;
336uniform float uOpacity;
337
338varying float vHeight;
339varying vec3 vNormalW;
340
341void main() {
342 vec3 lightDirection = normalize(vec3(-0.4, 0.8, -0.5));
343 float diffuse = clamp(dot(normalize(vNormalW), lightDirection), 0.0, 1.0);
344 vec3 shaded = uColor * (0.35 + 0.9 * diffuse) + vec3(0.05) * smoothstep(0.2, 1.0, vHeight);
345 // uShade = 1 → lit surface, 0 → flat wireframe color
346 gl_FragColor = vec4(mix(uColor, shaded, uShade), uOpacity);
347 #include <colorspace_fragment>
348 #include <fog_fragment>
349}
350`;
351
352function createTerrainMaterial(shade: number, opacity: number, wireframe: boolean) {
353 return new THREE.ShaderMaterial({
354 uniforms: THREE.UniformsUtils.merge([
355 THREE.UniformsLib.fog,
356 {
357 uTravel: { value: 0 },
358 uElevation: { value: 2 },
359 uColor: { value: new THREE.Color() },
360 uShade: { value: shade },
361 uOpacity: { value: opacity },
362 },
363 ]),
364 vertexShader,
365 fragmentShader,
366 fog: true,
367 wireframe,
368 transparent: opacity < 1,
369 depthWrite: opacity >= 1,
370 // Pushes the surface back slightly so the grid lines drawn on top never z-fight with it
371 polygonOffset: !wireframe,
372 polygonOffsetFactor: 1,
373 polygonOffsetUnits: 1,
374 });
375}
376
377type TerrainSceneProps = Required<Omit<TerrainProps, "primaryColor" | "displacementScale" | "pauseWhenOffscreen" | "lowPowerMode" | "fogColor">>;
378
379const TerrainScene = memo(function TerrainScene({
380 wireframe,
381 wireframeColor,
382 surfaceColor,
383 elevationScale,
384 speed,
385 gridSegments,
386}: TerrainSceneProps) {
387 const travel = useRef(0);
388
389 const geometry = useMemo(() => {
390 const g = new THREE.PlaneGeometry(SIZE_X, SIZE_Z, gridSegments, Math.round(gridSegments * 1.5));
391 g.rotateX(-Math.PI / 2);
392 // From just in front of the camera (z = 6) to deep in the fog (z = -54)
393 g.translate(0, 0, -SIZE_Z / 2 + 6);
394 return g;
395 }, [gridSegments]);
396
397 const surfaceMaterial = useMemo(() => createTerrainMaterial(1, 1, false), []);
398 const wireMaterial = useMemo(() => createTerrainMaterial(0, 0.6, true), []);
399
400 useEffect(() => {
401 surfaceMaterial.uniforms.uElevation.value = elevationScale;
402 wireMaterial.uniforms.uElevation.value = elevationScale;
403 (surfaceMaterial.uniforms.uColor.value as THREE.Color).set(surfaceColor);
404 (wireMaterial.uniforms.uColor.value as THREE.Color).set(wireframeColor);
405 }, [surfaceMaterial, wireMaterial, elevationScale, surfaceColor, wireframeColor]);
406
407 useEffect(() => () => geometry.dispose(), [geometry]);
408 useEffect(
409 () => () => {
410 surfaceMaterial.dispose();
411 wireMaterial.dispose();
412 },
413 [surfaceMaterial, wireMaterial]
414 );
415
416 useFrame((state, delta) => {
417 travel.current += delta * speed * 4;
418 surfaceMaterial.uniforms.uTravel.value = travel.current;
419 wireMaterial.uniforms.uTravel.value = travel.current;
420
421 // Slow lateral sway, always looking down the valley
422 const t = state.clock.elapsedTime;
423 state.camera.position.x = Math.sin(t * 0.2) * 0.6;
424 state.camera.lookAt(Math.sin(t * 0.2 + 0.6) * 0.4, 0.8, -12);
425 });
426
427 return (
428 <>
429 <mesh geometry={geometry} material={surfaceMaterial} />
430 {wireframe ? <mesh geometry={geometry} material={wireMaterial} /> : null}
431 </>
432 );
433});
434
435function ProceduralTerrainBackground({
436 wireframe = true,
437 wireframeColor = "#a5b4fc",
438 primaryColor,
439 surfaceColor = primaryColor ?? "#0b1020",
440 fogColor = "#05060a",
441 displacementScale,
442 elevationScale = displacementScale ?? 2.2,
443 speed = 1,
444 gridSegments = 128,
445 pauseWhenOffscreen,
446 lowPowerMode,
447}: TerrainProps) {
448 return (
449 <BackgroundCanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 2.4, 7], fov: 55, near: 0.1, far: 80 }}>
450 <color attach="background" args={[fogColor]} />
451 <fog attach="fog" args={[fogColor, 6, 42]} />
452 <TerrainScene
453 wireframe={wireframe}
454 wireframeColor={wireframeColor}
455 surfaceColor={surfaceColor}
456 elevationScale={elevationScale}
457 speed={speed}
458 gridSegments={gridSegments}
459 />
460 </BackgroundCanvas>
461 );
462}
463
464export default memo(ProceduralTerrainBackground);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import ProceduralTerrainBackground from "@/components/ProceduralTerrainBackground";
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 <ProceduralTerrainBackground
8 displacementScale={2.2}
9 speed={1}
10 gridSegments={128}
11 wireframeColor="#a5b4fc"
12 primaryColor="#0b1020"
13 fogColor="#05060a"
14 />
15 </div>
16 );
17}
Next componentOrganic Fluid→