Loading…
← All components

Background · Space

Orbital Horizon

A cinematic view from low orbit: a procedural planet in six biomes curving across the screen, a two-layer atmosphere on its limb, light trails racing along it and a star breaking over the horizon with its starburst and lens flare. The surface stays almost black by default; raise planetLight to light it.

<OrbitalHorizonBackground />Live

Customize

Biome
Star#fff4e0
Flare#8b5cf6
Atmosphere#a78bfa

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add orbital-horizon
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/OrbitalHorizonBackground.tsx and paste it in.

components/OrbitalHorizonBackground.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/** The cursor as the shaders see it. Read inside useFrame: pointer moves never re-render React. */
190interface PointerPhysics {
191 /** Smoothed position in the canvas, 0..1 (y up). */
192 position: THREE.Vector2;
193 /** Smoothed velocity, in canvas units (0..1) per second. */
194 velocity: THREE.Vector2;
195 /** 0..1: eases to 1 while the pointer is over the canvas (and `interactive`), back to 0 otherwise. */
196 strength: number;
197 /** 0..1: eases to 1 while a button or a finger is down. */
198 press: number;
199}
200
201interface RawPointer {
202 x: number;
203 y: number;
204 inside: boolean;
205 down: boolean;
206 seen: boolean;
207}
208
209const FOLLOW = 14; // damp rate of the position
210
211const VELOCITY_FOLLOW = 8;
212
213const STRENGTH_FOLLOW = 3.5; // forces fade in and out over ~half a second
214
215/**
216 * Pointer physics shared by the procedural backgrounds: smoothed position, smoothed velocity and an
217 * eased presence. The canvas has `pointer-events: none` (the page above it stays clickable), so the
218 * pointer is read from window listeners. With `interactive` false there is no listener at all and
219 * every force eases back to 0, leaving the autonomous animation alone.
220 */
221function usePointerPhysics(interactive: boolean): RefObject<PointerPhysics> {
222 const gl = useThree((state) => state.gl);
223 const raw = useRef<RawPointer>({ x: 0.5, y: 0.5, inside: false, down: false, seen: false });
224 const physics = useRef<PointerPhysics>({ position: new THREE.Vector2(0.5, 0.5), velocity: new THREE.Vector2(), strength: 0, press: 0 });
225 const previous = useRef(new THREE.Vector2(0.5, 0.5));
226
227 useEffect(() => {
228 const p = raw.current;
229 if (!interactive) {
230 p.inside = false;
231 p.down = false;
232 return undefined;
233 }
234 const el = gl.domElement;
235 const move = (event: PointerEvent) => {
236 const rect = el.getBoundingClientRect();
237 if (!rect.width || !rect.height) return;
238 p.x = (event.clientX - rect.left) / rect.width;
239 p.y = 1 - (event.clientY - rect.top) / rect.height;
240 p.inside = p.x >= 0 && p.x <= 1 && p.y >= 0 && p.y <= 1;
241 if (!p.seen) {
242 // First contact: start from the pointer instead of sweeping in from the center
243 p.seen = true;
244 physics.current.position.set(p.x, p.y);
245 previous.current.set(p.x, p.y);
246 }
247 };
248 const down = (event: PointerEvent) => {
249 move(event);
250 p.down = true;
251 };
252 const up = () => {
253 p.down = false;
254 };
255 const leave = () => {
256 p.inside = false;
257 p.down = false;
258 };
259 window.addEventListener("pointermove", move, { passive: true });
260 window.addEventListener("pointerdown", down, { passive: true });
261 window.addEventListener("pointerup", up, { passive: true });
262 window.addEventListener("pointercancel", leave, { passive: true });
263 document.documentElement.addEventListener("pointerleave", leave);
264 window.addEventListener("blur", leave);
265 return () => {
266 window.removeEventListener("pointermove", move);
267 window.removeEventListener("pointerdown", down);
268 window.removeEventListener("pointerup", up);
269 window.removeEventListener("pointercancel", leave);
270 document.documentElement.removeEventListener("pointerleave", leave);
271 window.removeEventListener("blur", leave);
272 };
273 }, [gl, interactive]);
274
275 useFrame((_, delta) => {
276 const dt = Math.min(delta, 1 / 20);
277 const p = raw.current;
278 const s = physics.current;
279 const damp = THREE.MathUtils.damp;
280 s.position.set(damp(s.position.x, p.x, FOLLOW, dt), damp(s.position.y, p.y, FOLLOW, dt));
281 const vx = dt > 0 ? (s.position.x - previous.current.x) / dt : 0;
282 const vy = dt > 0 ? (s.position.y - previous.current.y) / dt : 0;
283 previous.current.copy(s.position);
284 const active = interactive && p.inside;
285 s.velocity.set(damp(s.velocity.x, active ? vx : 0, VELOCITY_FOLLOW, dt), damp(s.velocity.y, active ? vy : 0, VELOCITY_FOLLOW, dt));
286 s.strength = damp(s.strength, active ? 1 : 0, STRENGTH_FOLLOW, dt);
287 s.press = damp(s.press, active && p.down ? 1 : 0, STRENGTH_FOLLOW * 2, dt);
288 });
289
290 return physics;
291}
292
293/**
294 * Shared GLSL noise functions, injected into the background shaders as strings.
295 *
296 * Both are the classic webgl-noise implementations by Ian McEwan and Stefan
297 * Gustavson (Ashima Arts), MIT License — https://github.com/ashima/webgl-noise
298 */
299
300/** 3D simplex noise: `float snoise(vec3 v)`, returns roughly -1..1. */
301const SIMPLEX_3D = /* glsl */ `
302vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
303vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
304vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }
305vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
306
307float snoise(vec3 v) {
308 const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);
309 const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
310
311 vec3 i = floor(v + dot(v, C.yyy));
312 vec3 x0 = v - i + dot(i, C.xxx);
313
314 vec3 g = step(x0.yzx, x0.xyz);
315 vec3 l = 1.0 - g;
316 vec3 i1 = min(g.xyz, l.zxy);
317 vec3 i2 = max(g.xyz, l.zxy);
318
319 vec3 x1 = x0 - i1 + C.xxx;
320 vec3 x2 = x0 - i2 + C.yyy;
321 vec3 x3 = x0 - D.yyy;
322
323 i = mod289(i);
324 vec4 p = permute(permute(permute(
325 i.z + vec4(0.0, i1.z, i2.z, 1.0))
326 + i.y + vec4(0.0, i1.y, i2.y, 1.0))
327 + i.x + vec4(0.0, i1.x, i2.x, 1.0));
328
329 float n_ = 0.142857142857;
330 vec3 ns = n_ * D.wyz - D.xzx;
331
332 vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
333 vec4 x_ = floor(j * ns.z);
334 vec4 y_ = floor(j - 7.0 * x_);
335
336 vec4 x = x_ * ns.x + ns.yyyy;
337 vec4 y = y_ * ns.x + ns.yyyy;
338 vec4 h = 1.0 - abs(x) - abs(y);
339
340 vec4 b0 = vec4(x.xy, y.xy);
341 vec4 b1 = vec4(x.zw, y.zw);
342 vec4 s0 = floor(b0) * 2.0 + 1.0;
343 vec4 s1 = floor(b1) * 2.0 + 1.0;
344 vec4 sh = -step(h, vec4(0.0));
345
346 vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
347 vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
348
349 vec3 p0 = vec3(a0.xy, h.x);
350 vec3 p1 = vec3(a0.zw, h.y);
351 vec3 p2 = vec3(a1.xy, h.z);
352 vec3 p3 = vec3(a1.zw, h.w);
353
354 vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
355 p0 *= norm.x;
356 p1 *= norm.y;
357 p2 *= norm.z;
358 p3 *= norm.w;
359
360 vec4 m = max(0.5 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);
361 m = m * m;
362 return 105.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));
363}
364`;
365
366// OrbitalHorizon in one full-screen fragment shader, ray traced: the camera sits in low orbit above a
367// planet of radius 1 centred at the origin. Every layer is computed per pixel, without any texture:
368// deep space, the planet surface (one function per biome, picked by a uniform so switching
369// biome never recompiles), the atmosphere limb, the orbital trails, then the star and its lens flare.
370// Colors are accumulated in linear HDR and tone mapped (ACES) at the end.
371
372const ORBITAL_VERTEX = /* glsl */ `
373varying vec2 vUv;
374void main() {
375 vUv = uv;
376 gl_Position = vec4(position.xy, 0.0, 1.0);
377}
378`;
379
380const HEADER = /* glsl */ `
381uniform float uTime; // seconds, already multiplied by \`speed\`
382uniform float uAspect; // width / height
383uniform vec2 uResolution; // drawing buffer, px
384uniform float uBiome; // index in BIOMES2 (PlanetBiome)
385uniform vec3 uStarColor;
386uniform vec3 uFlareColor;
387uniform vec3 uAtmoColor;
388uniform float uFlareIntensity; // 0..2
389uniform float uTrails; // 0..1, eased
390uniform float uScale; // planet zoom, eased
391uniform float uDayLift; // art-directed daylight: lifts the light so the near side is lit (per biome)
392uniform float uAxial; // tilt of the planet's axis: which latitudes face the camera (per biome)
393uniform float uPlanetLight; // how much starlight the surface reflects (0 = black, emissions stay)
394uniform vec2 uTilt; // camera yaw / pitch offsets, radians (pointer parallax + drift)
395uniform vec2 uPointer; // pointer in screen space (height 1, centred)
396uniform float uInteract; // 0..1 presence of the pointer
397varying vec2 vUv;
398
399const float PI = 3.14159265;
400const float FOV_TAN = 0.4; // tan(half vertical field of view)
401`;
402
403const HELPERS = /* glsl */ `
404// Hashes without sine (Dave Hoskins, MIT)
405float hash12(vec2 p) {
406 vec3 p3 = fract(vec3(p.xyx) * 0.1031);
407 p3 += dot(p3, p3.yzx + 33.33);
408 return fract((p3.x + p3.y) * p3.z);
409}
410vec2 hash22(vec2 p) {
411 vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
412 p3 += dot(p3, p3.yzx + 33.33);
413 return fract((p3.xx + p3.yz) * p3.zy);
414}
415vec3 hash33(vec3 p3) {
416 p3 = fract(p3 * vec3(0.1031, 0.1030, 0.0973));
417 p3 += dot(p3, p3.yxz + 33.33);
418 return fract((p3.xxy + p3.yxx) * p3.zyx);
419}
420
421float fbm(vec3 p, int octaves) {
422 float sum = 0.0;
423 float amp = 0.5;
424 for (int i = 0; i < 6; i++) {
425 if (i >= octaves) break;
426 sum += amp * snoise(p);
427 p = p * 2.03 + vec3(17.1, -3.7, 5.3);
428 amp *= 0.5;
429 }
430 return sum;
431}
432
433// Domain warp offset, shared by the rocky biomes
434vec3 warp(vec3 p) {
435 return vec3(fbm(p, 3), fbm(p + vec3(5.2, 1.3, 2.8), 3), 0.0);
436}
437
438mat3 rotX(float a) {
439 float c = cos(a);
440 float s = sin(a);
441 return mat3(1.0, 0.0, 0.0, 0.0, c, s, 0.0, -s, c);
442}
443mat3 rotY(float a) {
444 float c = cos(a);
445 float s = sin(a);
446 return mat3(c, 0.0, -s, 0.0, 1.0, 0.0, s, 0.0, c);
447}
448
449float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
450
451vec3 aces(vec3 x) {
452 return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
453}
454`;
455
456const BIOMES2 = /* glsl */ `
457struct Surface {
458 vec3 albedo;
459 vec3 glow; // emission at any hour (lava, circuits)
460 vec3 lights; // emission seen on the night side only (cities)
461 float spec; // specular mask (oceans, ice)
462 float gloss; // specular exponent
463 float sparkle; // tiny crystal glints
464 float cloud; // cloud coverage 0..1
465 vec3 cloudTint;
466};
467
468Surface emptySurface() {
469 Surface s;
470 s.albedo = vec3(0.0);
471 s.glow = vec3(0.0);
472 s.lights = vec3(0.0);
473 s.spec = 0.0;
474 s.gloss = 32.0;
475 s.sparkle = 0.0;
476 s.cloud = 0.0;
477 s.cloudTint = vec3(1.0);
478 return s;
479}
480
481// fp: size of a pixel on the surface (planet radii): fine details fade out before they alias
482
483Surface terranNight(vec3 S, vec3 Sc, float fp) {
484 Surface s = emptySurface();
485 vec3 q = warp(S * 1.6);
486 float h = fbm(S * 1.9 + q * 1.2, 5);
487 float land = smoothstep(0.0, 0.05, h);
488 float relief = fbm(S * 14.0, 3);
489 s.albedo = mix(vec3(0.004, 0.012, 0.03), vec3(0.045, 0.048, 0.034) * (0.8 + relief * 0.6), land);
490 // Cities: clusters along the coasts and the plains, made of fine points of light
491 float coast = 1.0 - smoothstep(0.0, 0.2, h);
492 float region = smoothstep(0.12, 0.55, fbm(S * 5.0 + 3.0, 3) + coast * 0.3);
493 float fine = smoothstep(0.012, 0.003, fp);
494 float sparks = pow(max(snoise(S * 160.0), 0.0), 3.0) * fine + pow(max(snoise(S * 52.0), 0.0), 4.0) * 0.7;
495 s.lights = vec3(1.0, 0.6, 0.24) * land * region * sparks * 2.6;
496 s.spec = 1.0 - land;
497 s.gloss = 220.0;
498 s.cloud = smoothstep(0.1, 0.65, fbm(Sc * 3.0 + q * 0.6, 4)) * 0.5;
499 s.cloudTint = vec3(0.78, 0.82, 0.9);
500 return s;
501}
502
503Surface terranDay(vec3 S, vec3 Sc, float fp) {
504 Surface s = emptySurface();
505 vec3 q = warp(S * 1.6);
506 float h = fbm(S * 1.9 + q * 1.2, 5);
507 float land = smoothstep(0.0, 0.03, h);
508 float deep = smoothstep(0.0, -0.25, h);
509 vec3 ocean = mix(vec3(0.02, 0.11, 0.2), vec3(0.004, 0.028, 0.09), deep);
510 float moisture = fbm(S * 3.0 + 11.0, 3);
511 vec3 ground = mix(vec3(0.06, 0.1, 0.03), vec3(0.34, 0.25, 0.13), smoothstep(-0.12, 0.22, moisture));
512 ground = mix(ground, vec3(0.24, 0.22, 0.21), smoothstep(0.16, 0.42, h));
513 ground *= 0.7 + (fbm(S * 22.0, 3) * 0.5 + 0.5) * 0.6;
514 float polar = abs(S.y) + fbm(S * 6.0, 3) * 0.08;
515 float ice = smoothstep(0.8, 0.86, polar);
516 s.albedo = mix(mix(ocean, ground, land), vec3(0.85, 0.9, 0.95), ice);
517 s.spec = (1.0 - land) * (1.0 - ice);
518 s.gloss = 160.0;
519 s.cloud = smoothstep(0.05, 0.45, fbm(Sc * 2.6 + q, 5)) * 0.7;
520 s.cloudTint = vec3(0.95);
521 return s;
522}
523
524Surface volcanic(vec3 S, vec3 Sc, float fp) {
525 Surface s = emptySurface();
526 vec3 q = warp(S * 1.8);
527 float h = fbm(S * 2.2 + q * 1.6, 5);
528 // Fractal fissures: ridges of noise, thinner and brighter at their crest
529 float ridge = 1.0 - abs(snoise(S * 5.0 + q * 2.0));
530 float veins = pow(ridge, 14.0);
531 float cracks = pow(1.0 - abs(snoise(S * 17.0 + q * 3.0)), 22.0) * smoothstep(0.02, 0.005, fp);
532 float pools = smoothstep(0.32, 0.55, h);
533 float heat = veins + cracks * 0.6 + pools * 0.35;
534 float pulse = 0.72 + 0.28 * sin(uTime * 1.3 + h * 18.0 + q.x * 6.0);
535 s.albedo = vec3(0.024, 0.02, 0.022) * (0.6 + (fbm(S * 20.0, 3) * 0.5 + 0.5) * 0.9);
536 s.glow = mix(vec3(1.0, 0.16, 0.02), vec3(1.0, 0.68, 0.24), clamp(veins * 1.6 - 0.25, 0.0, 1.0)) * heat * pulse * 3.2;
537 s.spec = 0.35;
538 s.gloss = 90.0;
539 s.cloud = smoothstep(0.25, 0.7, fbm(Sc * 3.5, 4)) * 0.38;
540 s.cloudTint = vec3(0.22, 0.2, 0.2);
541 return s;
542}
543
544Surface cyberGrid(vec3 S, float fp) {
545 Surface s = emptySurface();
546 float h = fbm(S * 2.4, 4);
547 s.albedo = vec3(0.016, 0.018, 0.03) * (1.0 + h);
548 float lon = atan(S.z, S.x) / PI;
549 float lat = asin(clamp(S.y, -1.0, 1.0)) / (PI * 0.5);
550 vec2 g = vec2(lon * 48.0, lat * 24.0);
551 // Line width kept around one pixel, energy kept constant when the lines get thinner than that
552 float w = max(fp * 48.0 / PI * 1.4, 0.015);
553 vec2 ld = abs(fract(g - 0.5) - 0.5);
554 float lines = max(1.0 - smoothstep(0.0, w, ld.x), 1.0 - smoothstep(0.0, w, ld.y)) * min(1.0, 0.05 / w);
555 float district = 0.25 + 0.75 * smoothstep(-0.15, 0.12, h);
556 vec2 lineId = floor(g + 0.5);
557 float rowSeed = hash12(vec2(lineId.y, 4.0));
558 float colSeed = hash12(vec2(lineId.x, 9.0));
559 float onRow = (1.0 - smoothstep(0.0, w, ld.y)) * step(0.62, rowSeed);
560 float onCol = (1.0 - smoothstep(0.0, w, ld.x)) * step(0.66, colSeed);
561 float rowPulse = pow(fract(g.x * 0.06 - uTime * (0.3 + rowSeed * 0.5) + rowSeed * 7.0), 18.0);
562 float colPulse = pow(fract(g.y * 0.08 + uTime * (0.25 + colSeed * 0.4) + colSeed * 5.0), 18.0);
563 float data = (onRow * rowPulse + onCol * colPulse) * district;
564 float node = (1.0 - smoothstep(0.0, w * 2.5, length(ld))) * step(0.7, hash12(lineId)) * district;
565 // Magnetic poles: an aurora ring and a glowing cap
566 float aurora = exp(-pow((abs(S.y) - 0.8) / 0.022, 2.0)) * (0.6 + 0.4 * sin(lon * PI * 6.0 + uTime * 2.0));
567 float cap = smoothstep(0.9, 1.0, abs(S.y));
568 vec3 pole = mix(uAtmoColor, uFlareColor, 0.5);
569 s.glow = uAtmoColor * (lines * 0.9 * district + data * 4.0) + uFlareColor * node * 1.6 + pole * (aurora * 2.0 + cap * 0.8);
570 s.spec = 0.2;
571 s.gloss = 60.0;
572 return s;
573}
574
575// Distance to the nearest of a cloud of random points (3D Voronoi, F1)
576vec2 cells(vec3 p) {
577 vec3 i = floor(p);
578 vec3 f = fract(p);
579 float best = 8.0;
580 float id = 0.0;
581 for (int z = -1; z <= 1; z++)
582 for (int y = -1; y <= 1; y++)
583 for (int x = -1; x <= 1; x++) {
584 vec3 o = vec3(float(x), float(y), float(z));
585 vec3 r = o + hash33(i + o) - f;
586 float d = dot(r, r);
587 if (d < best) {
588 best = d;
589 id = hash12((i + o).xy + (i + o).z * 7.31);
590 }
591 }
592 return vec2(sqrt(best), id);
593}
594
595Surface iceWorld(vec3 S, vec3 Sc, float fp) {
596 Surface s = emptySurface();
597 vec3 q = warp(S * 1.7);
598 float h = fbm(S * 2.0 + q, 5);
599 vec3 albedo = mix(vec3(0.5, 0.64, 0.78), vec3(0.88, 0.93, 0.97), smoothstep(-0.3, 0.3, h));
600 float crack = pow(1.0 - abs(snoise(S * 7.0 + q * 1.5)), 26.0);
601 float hairline = pow(1.0 - abs(snoise(S * 23.0 + q * 2.0)), 30.0) * smoothstep(0.015, 0.004, fp);
602 albedo = mix(albedo, vec3(0.03, 0.14, 0.28), clamp(crack + hairline * 0.7, 0.0, 1.0));
603 // Glacial craters: a dark bowl and a bright rim
604 vec2 c = cells(S * 5.0);
605 float crater = step(0.55, c.y);
606 float bowl = smoothstep(0.3, 0.08, c.x) * crater;
607 float rim = exp(-pow((c.x - 0.32) / 0.05, 2.0)) * crater;
608 albedo *= 1.0 - bowl * 0.35;
609 albedo += vec3(0.08, 0.1, 0.12) * rim;
610 s.albedo = albedo;
611 s.spec = 0.7;
612 s.gloss = 260.0;
613 vec3 cell = floor(S * 650.0);
614 s.sparkle = step(0.994, hash12(cell.xy + cell.z * 3.7)) * smoothstep(0.004, 0.001, fp) * (0.5 + 0.5 * sin(uTime * 3.0 + cell.x));
615 s.cloud = smoothstep(0.3, 0.72, fbm(Sc * 3.0, 4)) * 0.25;
616 s.cloudTint = vec3(0.86, 0.9, 1.0);
617 return s;
618}
619
620Surface gasGiant(vec3 S, float fp) {
621 Surface s = emptySurface();
622 // Differential rotation: every latitude drifts at its own pace
623 vec3 P = rotY(sin(S.y * 9.0) * uTime * 0.03) * S;
624 // An anticyclone: the bands are twisted around its centre
625 vec3 storm = normalize(vec3(0.62, -0.22, 0.75));
626 vec3 v = P - storm;
627 float d = length(v * vec3(1.0, 2.4, 1.0));
628 float a = (5.0 + uTime * 0.4) * exp(-d * 9.0);
629 v = v * cos(a) + cross(storm, v) * sin(a) + storm * dot(storm, v) * (1.0 - cos(a));
630 P = storm + v;
631 float turb = fbm(P * vec3(3.0, 11.0, 3.0) + vec3(0.0, 0.0, uTime * 0.01), 5);
632 float band = sin(P.y * 22.0 + turb * 4.0);
633 float band2 = sin(P.y * 47.0 + turb * 5.0);
634 vec3 col = mix(vec3(0.36, 0.2, 0.11), vec3(0.9, 0.79, 0.6), smoothstep(-0.6, 0.6, band));
635 col = mix(col, vec3(0.45, 0.2, 0.09), smoothstep(0.3, 1.0, band2) * 0.7);
636 col = mix(col, vec3(0.92, 0.9, 0.84), smoothstep(0.85, 1.0, sin(P.y * 9.0 + turb)) * 0.4);
637 col = mix(col, vec3(0.72, 0.3, 0.15), smoothstep(0.3, 0.05, d) * 0.8);
638 s.albedo = col * 0.8;
639 s.spec = 0.05;
640 s.gloss = 20.0;
641 return s;
642}
643
644Surface biomeSurface(vec3 S, vec3 Sc, float fp) {
645 if (uBiome < 0.5) return terranNight(S, Sc, fp);
646 if (uBiome < 1.5) return terranDay(S, Sc, fp);
647 if (uBiome < 2.5) return volcanic(S, Sc, fp);
648 if (uBiome < 3.5) return cyberGrid(S, fp);
649 if (uBiome < 4.5) return iceWorld(S, Sc, fp);
650 return gasGiant(S, fp);
651}
652`;
653
654const LAYERS = /* glsl */ `
655vec3 shadePlanet(vec3 N, vec3 V, vec3 L, vec3 sunDir, float fp) {
656 float spin = uTime * 0.012;
657 vec3 axial = rotX(uAxial) * N;
658 vec3 S = rotY(spin) * axial;
659 vec3 Sc = rotY(spin * 1.4 + 0.7) * axial;
660 Surface s = biomeSurface(S, Sc, fp);
661
662 float ndl = dot(N, L);
663 float day = smoothstep(-0.1, 0.3, ndl);
664 float night = 1.0 - smoothstep(-0.18, 0.06, ndl);
665 float twilight = exp(-ndl * ndl / 0.012);
666 vec3 light = (uStarColor * (max(ndl, 0.0) * 1.35 + day * 0.06) + uFlareColor * twilight * 0.45) * uPlanetLight;
667 vec3 col = s.albedo * light;
668
669 // Reflection of the star on oceans and ice
670 vec3 H = normalize(L + V);
671 float nh = max(dot(N, H), 0.0);
672 col += uStarColor * s.spec * day * (pow(nh, s.gloss) * 3.0 + pow(nh, s.gloss * 0.08) * 0.06) * uPlanetLight;
673 col += uStarColor * s.sparkle * day * 2.5 * uPlanetLight;
674
675 vec3 cloud = s.cloudTint * light * 0.85;
676 col = mix(col, cloud, s.cloud);
677 col += s.glow * (1.0 - s.cloud * 0.7);
678 col += s.lights * night * (1.0 - s.cloud * 0.85);
679
680 // Air seen through: a haze thickening towards the limb, warm on the sunward side
681 float mu = clamp(dot(N, V), 0.0, 1.0);
682 float rim = pow(1.0 - mu, 3.0);
683 float toward = pow(max(dot(-V, sunDir), 0.0), 16.0);
684 float lightK = min(uPlanetLight, 1.0);
685 col = mix(col, uAtmoColor * (0.4 * day * uPlanetLight + 0.012), rim * (0.2 + 0.55 * day * lightK));
686 col += uFlareColor * rim * toward * (0.25 + day * lightK) * 0.4;
687 return col;
688}
689
690// One satellite trail: a great circle at altitude radius - 1, with streaks running along it
691vec3 trail(vec3 ro, vec3 rd, float tMax, vec3 axis, float radius, float speed, float phase, float pixelAngle) {
692 float b = dot(ro, rd);
693 float c = dot(ro, ro) - radius * radius;
694 float disc = b * b - c;
695 if (disc <= 0.0) return vec3(0.0);
696 float sq = sqrt(disc);
697 vec3 u = normalize(cross(axis, vec3(0.0, 0.0, 1.0)));
698 vec3 v = cross(axis, u);
699 float total = 0.0;
700 for (int k = 0; k < 2; k++) {
701 float t = k == 0 ? -b - sq : -b + sq;
702 if (t <= 0.0 || t >= tMax) continue;
703 vec3 n = (ro + rd * t) / radius;
704 float off = dot(n, axis) * radius / (pixelAngle * t * 1.9); // px from the circle
705 float line = exp(-off * off);
706 float along = atan(dot(n, v), dot(n, u)) / (2.0 * PI);
707 float head = fract(along * 8.0 - uTime * speed + phase);
708 float streak = pow(head, 2.5) * smoothstep(1.0, 0.97, head);
709 float grazing = inversesqrt(max(abs(dot(n, rd)), 0.12));
710 total += line * (streak + 0.1) * grazing;
711 }
712 return mix(uFlareColor, vec3(1.0, 0.8, 0.45), 0.45) * total;
713}
714
715// Axis of a great circle crossing the limb at azimuth az, at angle beta to it
716vec3 trailAxis(float az, float beta, float dist) {
717 float y = 1.0 / dist;
718 float s = sqrt(1.0 - y * y);
719 vec3 B = vec3(sin(az) * s, y, -cos(az) * s);
720 vec3 along = vec3(cos(az), 0.0, sin(az));
721 vec3 north = normalize(vec3(0.0, 1.0, 0.0) - B * B.y);
722 return normalize(cross(B, along * cos(beta) + north * sin(beta)));
723}
724
725float ghost(vec2 p, vec2 at, float radius, float ring) {
726 float d = length(p - at);
727 float disc = smoothstep(radius, radius * 0.65, d) * (0.4 + 0.6 * d / radius);
728 float edge = exp(-pow((d - radius) / (radius * 0.07), 2.0));
729 return mix(disc, edge, ring);
730}
731`;
732
733const MAIN = /* glsl */ `
734void main() {
735 vec2 p = (vUv - 0.5) * vec2(uAspect, 1.0);
736 float pixelAngle = 2.0 * FOV_TAN / uResolution.y;
737
738 // Camera: low orbit; narrow screens back off so the curve still spans the width
739 float wide = smoothstep(0.55, 1.35, uAspect);
740 float alt = 0.3 / uScale * mix(1.9, 1.0, wide);
741 float dist = 1.0 + alt;
742 vec3 ro = vec3(0.0, dist, 0.0);
743 float dip = acos(1.0 / dist);
744 float horizonY = mix(-0.04, -0.17, wide);
745 float pitch = -dip - atan(horizonY * 2.0 * FOV_TAN) + uTilt.y;
746 float yaw = uTilt.x;
747 float roll = -0.1 + uTilt.x * 0.4;
748 vec3 f = vec3(sin(yaw) * cos(pitch), sin(pitch), -cos(yaw) * cos(pitch));
749 vec3 r = normalize(cross(f, vec3(0.0, 1.0, 0.0)));
750 vec3 u = cross(r, f);
751 vec3 right = r * cos(roll) + u * sin(roll);
752 vec3 up = cross(right, f);
753 vec3 rd = normalize(f + (p.x * right + p.y * up) * 2.0 * FOV_TAN);
754
755 // The star, just above the horizon
756 float az = 0.17 * clamp(uAspect, 0.6, 1.8);
757 float el = -dip + 0.014;
758 vec3 sunDir = normalize(vec3(sin(az) * cos(el), sin(el), -cos(az) * cos(el)));
759 vec3 L = normalize(sunDir + vec3(0.0, uDayLift, 0.0));
760
761 // Planet
762 float b = dot(ro, rd);
763 float closest = b < 0.0 ? sqrt(max(dist * dist - b * b, 0.0)) : dist;
764 float hRay = closest - 1.0;
765 float tLimb = sqrt(dist * dist - 1.0);
766 float edge = pixelAngle * tLimb;
767 float planetMask = b < 0.0 ? 1.0 - smoothstep(-edge, edge, hRay) : 0.0;
768 float tHit = -b - sqrt(max(b * b - dist * dist + 1.0, 0.0));
769 vec3 V = -rd;
770
771 vec3 col = vec3(0.0);
772 if (planetMask < 1.0) {
773 // Deep space: almost black, a faint nebula
774 vec3 sky = vec3(0.0006, 0.0006, 0.0011);
775 float neb = smoothstep(0.05, 0.75, fbm(rd * 2.4 + vec3(0.0, 0.0, uTime * 0.002), 3) + 0.2);
776 sky += mix(uAtmoColor, uFlareColor, smoothstep(-0.3, 0.3, rd.x)) * neb * 0.006;
777 col = sky;
778 }
779 if (planetMask > 0.0) {
780 vec3 N = normalize(ro + rd * tHit);
781 float fp = pixelAngle * tHit / max(dot(N, V), 0.12);
782 col = mix(col, shadePlanet(N, V, L, sunDir, fp), planetMask);
783 }
784
785 // Atmosphere limb: a thin cold layer (atmosphereColor) under a wide warm diffusion (flareColor)
786 vec3 Q = ro + rd * max(-b, 0.0);
787 float lit = smoothstep(-0.45, 0.2, dot(normalize(Q), sunDir));
788 float h = max(hRay, 0.0);
789 float inner = exp(-h / 0.008);
790 float outer = exp(-h / 0.022);
791 float cosS = max(dot(rd, sunDir), 0.0);
792 float mie = pow(cosS, 40.0) * 0.35 + pow(cosS, 400.0) * 2.0;
793 float depthIn = exp(min(hRay, 0.0) / 0.006);
794 vec3 atmo = uAtmoColor * inner * (0.05 + 1.5 * lit) + uFlareColor * (outer * (0.03 + 0.25 * lit) + (inner + outer) * mie * 0.9);
795 atmo *= depthIn;
796 col += atmo;
797
798 // Orbital trails
799 if (uTrails > 0.001) {
800 float tMax = planetMask > 0.5 ? tHit : 1e6;
801 vec3 trails = trail(ro, rd, tMax, trailAxis(-0.25, 0.22, dist), 1.012, 0.32, 0.0, pixelAngle)
802 + trail(ro, rd, tMax, trailAxis(0.15, -0.16, dist), 1.022, 0.45, 0.37, pixelAngle)
803 + trail(ro, rd, tMax, trailAxis(0.45, 0.32, dist), 1.034, 0.26, 0.71, pixelAngle);
804 col += trails * uTrails * (0.45 + lit) * 2.2;
805 }
806
807 // Star and lens flare
808 vec3 sd = vec3(dot(sunDir, right), dot(sunDir, up), dot(sunDir, f));
809 float front = step(0.0, sd.z);
810 vec2 sp = sd.xy / max(sd.z, 1e-3) / (2.0 * FOV_TAN);
811 float bs = dot(ro, sunDir);
812 float above = (sqrt(max(dist * dist - bs * bs, 0.0)) - 1.0) / tLimb; // radians above the limb
813 float vis = smoothstep(-0.004, 0.01, above) * front;
814 float glowVis = smoothstep(-0.03, 0.01, above) * front;
815 vec2 dp = p - sp;
816 float d = length(dp) * 2.0 * FOV_TAN;
817 float ang = atan(dp.y, dp.x);
818 float breathe = 0.92 + 0.08 * sin(uTime * 0.6);
819
820 vec3 flare = uStarColor * smoothstep(0.0062, 0.0044, d) * (1.0 - planetMask) * 16.0 * front;
821 flare += uStarColor * (exp(-d / 0.01) * 2.2 + exp(-d / 0.04) * 0.3) * glowVis;
822 flare += uFlareColor * exp(-d / 0.1) * 0.07 * glowVis;
823 float spikes = pow(0.5 + 0.5 * cos(ang * 6.0 + 0.4), 500.0) + 0.5 * pow(0.5 + 0.5 * cos(ang * 6.0 + 0.4 + PI / 6.0), 800.0);
824 float fineRays = pow(max(snoise(vec3(cos(ang) * 9.0, sin(ang) * 9.0, uTime * 0.04)), 0.0), 4.0);
825 float rays = spikes * exp(-d / 0.045) * 1.4 + fineRays * exp(-d / 0.028) * 0.6;
826 flare += mix(uStarColor, uFlareColor, 0.35) * rays * vis * breathe;
827 // Anamorphic streak, horizontal on screen
828 flare += uFlareColor * exp(-abs(dp.y) / 0.0025) * exp(-abs(dp.x) / 0.45) * 0.6 * vis;
829 // A faint chromatic halo ring
830 vec3 halo = vec3(exp(-pow((d - 0.188) / 0.01, 2.0)), exp(-pow((d - 0.183) / 0.01, 2.0)), exp(-pow((d - 0.178) / 0.01, 2.0)));
831 flare += halo * mix(uFlareColor, uAtmoColor, 0.5) * 0.03 * vis;
832 // Ghosts: lens reflections lined up through the pivot (the centre, pulled towards the pointer)
833 vec2 pivot = uPointer * 0.35 * uInteract;
834 vec2 axisV = sp - pivot;
835 vec3 ghosts = uFlareColor * ghost(p, pivot + axisV * -0.35, 0.026, 0.0) * 0.04
836 + uAtmoColor * ghost(p, pivot + axisV * -0.65, 0.05, 0.0) * 0.025
837 + mix(uFlareColor, uStarColor, 0.5) * ghost(p, pivot + axisV * -1.05, 0.11, 0.0) * 0.014
838 + uAtmoColor * ghost(p, pivot + axisV * 0.45, 0.035, 0.0) * 0.03
839 + mix(uAtmoColor, uFlareColor, 0.5) * ghost(p, pivot + axisV * -1.6, 0.22, 1.0) * 0.018;
840 flare += ghosts * vis;
841 col += flare * uFlareIntensity;
842
843 // Tone mapping, vignette, dither
844 col = aces(col * 1.05);
845 col *= 1.0 - 0.28 * dot(p * 0.85, p * 0.85);
846 col = max(col + (hash12(gl_FragCoord.xy) - 0.5) / 255.0, 0.0);
847 gl_FragColor = vec4(col, 1.0);
848 #include <colorspace_fragment>
849}
850`;
851
852const ORBITAL_FRAGMENT = HEADER + SIMPLEX_3D + HELPERS + BIOMES2 + LAYERS + MAIN;
853
854export type PlanetBiome =
855 /** Dark oceans, thin clouds and golden city lights on the night side. */
856 | "terran-night"
857 /** Deep blue oceans, detailed continents, ice caps and clouds. */
858 | "terran-day"
859 /** Black basalt crust split by glowing magma fissures. */
860 | "volcanic"
861 /** A dark planet wired with glowing circuits and magnetic poles. */
862 | "cyber-grid"
863 /** Fractured ice sheets, glacial craters and crystal glints. */
864 | "ice-world"
865 /** Turbulent atmospheric bands and a swirling anticyclone. */
866 | "gas-giant";
867
868export interface OrbitalHorizonProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode" | "respectReducedMotion"> {
869 /** The planet's procedural surface. Switching it live never recompiles the shader. Default "gas-giant". */
870 biome?: PlanetBiome;
871 /** Color of the star on the horizon and of its light. Default "#fff4e0". */
872 starColor?: string;
873 /** Color of the glare, the rays and the outer atmospheric diffusion. Default "#8b5cf6". */
874 flareColor?: string;
875 /** Color of the thin inner layer of the atmosphere. Default "#a78bfa". */
876 atmosphereColor?: string;
877 /** Strength of the star's glare, 0 to 2. Default 2. */
878 flareIntensity?: number;
879 /** Light trails racing along the upper atmosphere. Default false. */
880 orbitalTrails?: boolean;
881 /** Subtle camera parallax following the pointer; the flare ghosts follow it too. Default true. */
882 interactive?: boolean;
883 /** Pace of the planet's and clouds' rotation. Default 0.15: a slow, almost still drift. */
884 speed?: number;
885 /**
886 * How much starlight the planet's surface reflects: 0 is black, 1 is a fully lit day side. Its own
887 * lights (cities, lava, circuits) and the atmosphere keep their strength. Default 0.03: almost black.
888 */
889 planetLight?: number;
890 /** Zoom on the planet's curve: above 1 the planet is closer and larger. Default 1. */
891 scale?: number;
892 /** Extra classes for the container (absolutely positioned, filling its parent). */
893 className?: string;
894}
895
896/**
897 * Per biome: its index in the shader, how far the light is lifted so the near side is lit (the star
898 * itself stays on the horizon), and the axial tilt choosing which latitudes face the camera.
899 */
900const BIOMES: Record<PlanetBiome, { index: number; dayLift: number; axial: number }> = {
901 "terran-night": { index: 0, dayLift: 0.12, axial: -1.2 },
902 "terran-day": { index: 1, dayLift: 1.1, axial: -1.2 },
903 volcanic: { index: 2, dayLift: 0.3, axial: -1.1 },
904 "cyber-grid": { index: 3, dayLift: 0.2, axial: -0.55 },
905 "ice-world": { index: 4, dayLift: 0.9, axial: -0.9 },
906 "gas-giant": { index: 5, dayLift: 0.8, axial: -1.35 },
907};
908
909export const ORBITAL_HORIZON_DEFAULTS = {
910 biome: "gas-giant",
911 starColor: "#fff4e0",
912 flareColor: "#8b5cf6",
913 atmosphereColor: "#a78bfa",
914 flareIntensity: 2,
915 orbitalTrails: false,
916 interactive: true,
917 speed: 0.15,
918 planetLight: 0.03,
919 scale: 1,
920} as const;
921
922/** Every uniform of the shader (see orbital/shaders.ts). */
923interface OrbitalUniforms {
924 uTime: THREE.IUniform<number>;
925 uAspect: THREE.IUniform<number>;
926 uResolution: THREE.IUniform<THREE.Vector2>;
927 uBiome: THREE.IUniform<number>;
928 uStarColor: THREE.IUniform<THREE.Color>;
929 uFlareColor: THREE.IUniform<THREE.Color>;
930 uAtmoColor: THREE.IUniform<THREE.Color>;
931 uFlareIntensity: THREE.IUniform<number>;
932 uTrails: THREE.IUniform<number>;
933 uScale: THREE.IUniform<number>;
934 uDayLift: THREE.IUniform<number>;
935 uAxial: THREE.IUniform<number>;
936 uPlanetLight: THREE.IUniform<number>;
937 uTilt: THREE.IUniform<THREE.Vector2>;
938 uPointer: THREE.IUniform<THREE.Vector2>;
939 uInteract: THREE.IUniform<number>;
940}
941
942// Pointer parallax: how far the camera turns at the edge of the screen (radians)
943const TILT_YAW = 0.035;
944const TILT_PITCH = 0.02;
945/** The shader runs per pixel: past this many pixels the ratio drops (never below 1, never above 2). */
946const PIXEL_BUDGET = 2_600_000;
947
948interface HorizonPlaneProps {
949 biome: PlanetBiome;
950 starColor: string;
951 flareColor: string;
952 atmosphereColor: string;
953 flareIntensity: number;
954 orbitalTrails: boolean;
955 interactive: boolean;
956 speed: number;
957 planetLight: number;
958 scale: number;
959 still: boolean;
960}
961
962function HorizonPlane({ biome, starColor, flareColor, atmosphereColor, flareIntensity, orbitalTrails, interactive, speed, planetLight, scale, still }: HorizonPlaneProps) {
963 const physics = usePointerPhysics(interactive);
964 const preset = BIOMES[biome] ?? BIOMES[ORBITAL_HORIZON_DEFAULTS.biome];
965 // Targets the uniforms ease towards: a slider drag or a biome switch never makes the scene jump
966 const targets = useRef({ scale, flareIntensity, planetLight, trails: orbitalTrails ? 1 : 0, dayLift: preset.dayLift, axial: preset.axial });
967 useEffect(() => {
968 targets.current = { scale: Math.max(0.3, scale), flareIntensity: THREE.MathUtils.clamp(flareIntensity, 0, 2), planetLight: Math.max(0, planetLight), trails: orbitalTrails ? 1 : 0, dayLift: preset.dayLift, axial: preset.axial };
969 }, [scale, flareIntensity, planetLight, orbitalTrails, preset.dayLift, preset.axial]);
970
971 const { material, uniforms } = useMemo(() => {
972 const t = targets.current;
973 const u: OrbitalUniforms = {
974 uTime: { value: 0 },
975 uAspect: { value: 1 },
976 uResolution: { value: new THREE.Vector2(1, 1) },
977 uBiome: { value: 0 },
978 uStarColor: { value: new THREE.Color() },
979 uFlareColor: { value: new THREE.Color() },
980 uAtmoColor: { value: new THREE.Color() },
981 uFlareIntensity: { value: t.flareIntensity },
982 uTrails: { value: t.trails },
983 uScale: { value: t.scale },
984 uDayLift: { value: t.dayLift },
985 uAxial: { value: t.axial },
986 uPlanetLight: { value: t.planetLight },
987 uTilt: { value: new THREE.Vector2() },
988 uPointer: { value: new THREE.Vector2() },
989 uInteract: { value: 0 },
990 };
991 const m = new THREE.ShaderMaterial({
992 uniforms: u as unknown as Record<string, THREE.IUniform>,
993 vertexShader: ORBITAL_VERTEX,
994 fragmentShader: ORBITAL_FRAGMENT,
995 depthTest: false,
996 depthWrite: false,
997 });
998 return { material: m, uniforms: u };
999 }, []);
1000 const geometry = useMemo(() => new THREE.PlaneGeometry(2, 2), []);
1001 useEffect(() => () => material.dispose(), [material]);
1002 useEffect(() => () => geometry.dispose(), [geometry]);
1003
1004 useEffect(() => {
1005 uniforms.uBiome.value = preset.index;
1006 }, [uniforms, preset.index]);
1007 useEffect(() => {
1008 uniforms.uStarColor.value.set(starColor);
1009 uniforms.uFlareColor.value.set(flareColor);
1010 uniforms.uAtmoColor.value.set(atmosphereColor);
1011 }, [uniforms, starColor, flareColor, atmosphereColor]);
1012
1013 const clock = useRef(0);
1014 useFrame((state, delta) => {
1015 const dt = Math.min(delta, 1 / 20);
1016 const u = uniforms;
1017 const t = targets.current;
1018 const damp = THREE.MathUtils.damp;
1019 // Time integrates the speed: changing it live changes the pace, never the position
1020 if (!still) {
1021 u.uTime.value += dt * speed;
1022 clock.current += dt;
1023 }
1024 const { width, height } = state.size;
1025 const aspect = width / Math.max(height, 1);
1026 u.uAspect.value = aspect;
1027 u.uResolution.value.set(width * state.viewport.dpr, height * state.viewport.dpr);
1028 u.uScale.value = damp(u.uScale.value, t.scale, 4, dt);
1029 u.uFlareIntensity.value = damp(u.uFlareIntensity.value, t.flareIntensity, 6, dt);
1030 u.uTrails.value = damp(u.uTrails.value, t.trails, 3, dt);
1031 u.uDayLift.value = damp(u.uDayLift.value, t.dayLift, 2.5, dt);
1032 u.uAxial.value = damp(u.uAxial.value, t.axial, 2.5, dt);
1033 u.uPlanetLight.value = damp(u.uPlanetLight.value, t.planetLight, 4, dt);
1034
1035 // Camera: a slow autonomous orbital drift, plus the pointer's parallax when interactive
1036 const p = physics.current;
1037 const px = (p.position.x - 0.5) * 2;
1038 const py = (p.position.y - 0.5) * 2;
1039 const c = clock.current;
1040 const yaw = Math.sin(c * 0.05) * 0.012 + px * TILT_YAW * p.strength;
1041 const pitch = Math.sin(c * 0.037) * 0.005 + py * TILT_PITCH * p.strength;
1042 u.uTilt.value.set(damp(u.uTilt.value.x, yaw, 2.5, dt), damp(u.uTilt.value.y, pitch, 2.5, dt));
1043 u.uPointer.value.set((p.position.x - 0.5) * aspect, p.position.y - 0.5);
1044 u.uInteract.value = p.strength;
1045 });
1046
1047 return <mesh geometry={geometry} material={material} frustumCulled={false} />;
1048}
1049
1050/**
1051 * A cinematic view from low orbit: a procedural planet (six biomes) curving across the bottom of the
1052 * screen, a two-layer atmosphere on its limb, light trails racing along it, and a star breaking over
1053 * the horizon with its starburst, anamorphic streak and lens ghosts. One shader, no asset: every prop
1054 * is a uniform and changes live. Fills its positioned parent, never catches clicks, pauses off-screen,
1055 * freezes its clock under "reduce motion" and disposes everything on unmount.
1056 */
1057export default function OrbitalHorizonBackground({
1058 biome = ORBITAL_HORIZON_DEFAULTS.biome,
1059 starColor = ORBITAL_HORIZON_DEFAULTS.starColor,
1060 flareColor = ORBITAL_HORIZON_DEFAULTS.flareColor,
1061 atmosphereColor = ORBITAL_HORIZON_DEFAULTS.atmosphereColor,
1062 flareIntensity = ORBITAL_HORIZON_DEFAULTS.flareIntensity,
1063 orbitalTrails = ORBITAL_HORIZON_DEFAULTS.orbitalTrails,
1064 interactive = ORBITAL_HORIZON_DEFAULTS.interactive,
1065 speed = ORBITAL_HORIZON_DEFAULTS.speed,
1066 planetLight = ORBITAL_HORIZON_DEFAULTS.planetLight,
1067 scale = ORBITAL_HORIZON_DEFAULTS.scale,
1068 className = "",
1069 pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen,
1070 lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode,
1071 respectReducedMotion = DEFAULT_3D_PROPS.respectReducedMotion,
1072}: OrbitalHorizonProps) {
1073 const container = useRef<HTMLDivElement>(null);
1074 const frameloop = useOffscreenFrameloop(container, pauseWhenOffscreen);
1075 const reduced = usePrefersReducedMotion();
1076
1077 // Pixel ratio capped at 2, lowered on very large canvases so the per-pixel ray tracing stays at 60 fps
1078 const [maxDpr, setMaxDpr] = useState(1.5);
1079 useEffect(() => {
1080 const el = container.current;
1081 if (!el) return undefined;
1082 const update = () => {
1083 const area = Math.max(1, el.clientWidth * el.clientHeight);
1084 setMaxDpr(Math.round(Math.min(2, Math.max(1, Math.sqrt(PIXEL_BUDGET / area))) * 4) / 4);
1085 };
1086 update();
1087 const observer = new ResizeObserver(update);
1088 observer.observe(el);
1089 return () => observer.disconnect();
1090 }, []);
1091
1092 return (
1093 <div ref={container} className={`pointer-events-none absolute inset-0 overflow-hidden ${className}`} style={{ background: "#020204" }} aria-hidden="true">
1094 <Canvas dpr={lowPowerMode ? 1 : [1, maxDpr]} frameloop={frameloop} gl={{ antialias: false, alpha: false, powerPreference: "high-performance" }} style={{ pointerEvents: "none" }}>
1095 <HorizonPlane
1096 biome={biome}
1097 starColor={starColor}
1098 flareColor={flareColor}
1099 atmosphereColor={atmosphereColor}
1100 flareIntensity={flareIntensity}
1101 orbitalTrails={orbitalTrails}
1102 interactive={interactive}
1103 speed={speed}
1104 planetLight={planetLight}
1105 scale={scale}
1106 still={respectReducedMotion && reduced}
1107 />
1108 </Canvas>
1109 </div>
1110 );
1111}
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import OrbitalHorizonBackground from "@/components/OrbitalHorizonBackground";
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 <OrbitalHorizonBackground
8 biome="gas-giant"
9 flareIntensity={2}
10 planetLight={0.03}
11 speed={0.15}
12 scale={1}
13 starColor="#fff4e0"
14 flareColor="#8b5cf6"
15 atmosphereColor="#a78bfa"
16 orbitalTrails={false}
17 interactive
18 />
19 </div>
20 );
21}
Next componentLiquid Chrome→