Branchwell

PulseCanvas / website · pulsecanvas.ai / hero-scenes.js

Raw 25.9 KB on 0170e6db89f8ad397e79a6aca0a88e5ed0b67bb1
1import {
2 WebGLRenderer, WebGLRenderTarget, HalfFloatType, Scene, PerspectiveCamera, Vector2, Vector3,
3 BufferGeometry, Float32BufferAttribute, InstancedBufferGeometry,
4 InstancedBufferAttribute, ShaderMaterial, Points, Mesh, TorusGeometry,
5 PlaneGeometry, BoxGeometry, AdditiveBlending, DoubleSide, ACESFilmicToneMapping,
6} from 'three';
7import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
8import { Pass, FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
9import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
10import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
11
12const TAU = Math.PI * 2;
13const SCENE_NAMES = ['silk', 'helix', 'hyperlane'];
14const SCENE_LENGTH = 5;
15const TRANSITION = 1.1;
16const ORBIT_SPEED = TAU / 3.2;
17const BEAT = 60 / 128;
18const FOV = 46;
19const CAMERA_Z = 17;
20const TIME_OFFSET = 4;
21const MAX_PIXELS = 1.9e6;
22
23// Shared by every shader: the focal point travels a circle that each scene builds around.
24const COMMON = /* glsl */ `
25 uniform float uTime, uBeat, uScale, uPointScale, uOrbitSpeed;
26 uniform vec3 uOrbitCenter;
27 uniform vec2 uOrbitRadius;
28 vec3 focusAt(float t) {
29 float a = t * uOrbitSpeed;
30 return uOrbitCenter + vec3(cos(a) * uOrbitRadius.x, sin(a) * uOrbitRadius.y, 0.0);
31 }
32 mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, s, -s, c); }
33`;
34
35const VALUE_NOISE = /* glsl */ `
36 float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
37 float vnoise(vec2 p) {
38 vec2 i = floor(p), f = fract(p);
39 vec2 u = f * f * (3.0 - 2.0 * f);
40 return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), u.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x), u.y);
41 }
42`;
43
44const PALETTE = /* glsl */ `
45 vec3 neon(float s) {
46 if (s < 0.42) return vec3(0.3, 0.9, 1.35);
47 if (s < 0.72) return vec3(0.62, 0.42, 1.45);
48 if (s < 0.9) return vec3(1.35, 0.32, 0.9);
49 return vec3(1.45, 0.72, 0.45);
50 }
51`;
52
53const FLAT_FRAGMENT = /* glsl */ `
54 varying vec3 vColor;
55 varying float vAlpha;
56 void main() { gl_FragColor = vec4(vColor, vAlpha); }
57`;
58
59function seeded(seed) {
60 let state = seed;
61 return () => { state = (state * 16807) % 2147483647; return state / 2147483647; };
62}
63
64function additive(options) {
65 return new ShaderMaterial({ transparent: true, depthWrite: false, blending: AdditiveBlending, ...options });
66}
67
68function unbounded(object) {
69 object.frustumCulled = false;
70 return object;
71}
72
73// Copies a template's vertices into a geometry drawn once per instance attribute row.
74function instanced(template, name, data, size) {
75 const geometry = new InstancedBufferGeometry();
76 geometry.index = template.index;
77 geometry.setAttribute('position', template.getAttribute('position'));
78 geometry.setAttribute(name, new InstancedBufferAttribute(data, size));
79 geometry.instanceCount = data.length / size;
80 return geometry;
81}
82
83// A camera-facing light: hot core, soft bloom and a wide haze.
84function glow(uniforms, { center, size, color, depthTest = true }) {
85 return unbounded(new Mesh(new PlaneGeometry(1, 1), additive({
86 depthTest,
87 uniforms: { ...uniforms, uSize: { value: size }, uColor: { value: new Vector3(...color) } },
88 vertexShader: /* glsl */ `
89 ${COMMON}
90 ${LANE}
91 uniform float uSize;
92 varying vec2 vUv;
93 void main() {
94 vec4 mv = viewMatrix * vec4(${center}, 1.0);
95 mv.xy += position.xy * uSize * uScale;
96 gl_Position = projectionMatrix * mv;
97 vUv = position.xy * 2.0;
98 }
99 `,
100 fragmentShader: /* glsl */ `
101 ${COMMON}
102 uniform vec3 uColor;
103 varying vec2 vUv;
104 void main() {
105 float r2 = dot(vUv, vUv);
106 float light = exp(-r2 * 26.0) * 1.3 + exp(-r2 * 6.0) * 0.28 + exp(-r2 * 2.0) * 0.05;
107 light *= 1.0 - smoothstep(0.75, 1.0, r2);
108 gl_FragColor = vec4(uColor * light, 1.0);
109 }
110 `,
111 })));
112}
113
114// GPU-animated particles. Each vertex body positions one particle with place().
115function cloud(count, uniforms, vertexBody, declarations = '') {
116 const random = seeded(count * 31 + 7);
117 const data = new Float32Array(count * 4);
118 const direction = new Float32Array(count * 3);
119 for (let i = 0; i < count; i++) {
120 data.set([random(), random(), random(), random()], i * 4);
121 const z = random() * 2 - 1;
122 const angle = random() * TAU;
123 const radius = Math.sqrt(1 - z * z);
124 direction.set([Math.cos(angle) * radius, Math.sin(angle) * radius, z], i * 3);
125 }
126 const geometry = new BufferGeometry();
127 geometry.setAttribute('position', new Float32BufferAttribute(new Float32Array(count * 3), 3));
128 geometry.setAttribute('aData', new Float32BufferAttribute(data, 4));
129 geometry.setAttribute('aDir', new Float32BufferAttribute(direction, 3));
130 return unbounded(new Points(geometry, additive({
131 uniforms,
132 vertexShader: /* glsl */ `
133 ${COMMON}
134 ${PALETTE}
135 ${declarations}
136 attribute vec4 aData;
137 attribute vec3 aDir;
138 varying vec3 vColor;
139 varying float vAlpha;
140 void place(vec3 p, float size) {
141 vec4 mv = viewMatrix * vec4(p, 1.0);
142 gl_Position = projectionMatrix * mv;
143 float pixels = size * uPointScale / max(-mv.z, 0.2);
144 gl_PointSize = clamp(pixels, 1.5, 48.0);
145 vAlpha *= smoothstep(0.4, 3.0, -mv.z) * clamp(pixels / 1.5, 0.0, 1.0);
146 }
147 void main() { ${vertexBody} }
148 `,
149 fragmentShader: /* glsl */ `
150 varying vec3 vColor;
151 varying float vAlpha;
152 void main() {
153 vec2 c = gl_PointCoord - 0.5;
154 float r2 = dot(c, c) * 4.0;
155 if (r2 > 1.0) discard;
156 gl_FragColor = vec4(vColor, exp(-r2 * 3.5) * vAlpha);
157 }
158 `,
159 })));
160}
161
162function world(build) {
163 return (uniforms) => {
164 const scene = new Scene();
165 const camera = new PerspectiveCamera(FOV, 1, 0.1, 200);
166 return { scene, camera, update: build(scene, camera, uniforms) };
167 };
168}
169
170// Hyperlane: a warp corridor of light streaks and octagonal gates bends toward the orbiting focal point.
171const LANE = /* glsl */ `
172 float laneSpan(float z0, float speed) { return mod(z0 + uTime * speed, 98.0) - 82.0; }
173 vec3 laneCenter(float z) {
174 float d = max(${CAMERA_Z.toFixed(1)} - z, 0.0);
175 return focusAt(uTime - d * 0.005) * (d / ${CAMERA_Z.toFixed(1)});
176 }
177 float laneFade(float z) {
178 float d = ${CAMERA_Z.toFixed(1)} - z;
179 return smoothstep(3.0, 18.0, d) * smoothstep(99.0, 80.0, d) * exp(-d * 0.018);
180 }
181`;
182
183// The vanishing point: the far end of the corridor every tunnel bends toward.
184const FAR_CENTER = `(laneCenter(-71.0) + vec3(0.0, 0.0, -71.0))`;
185
186const hyperlane = world((scene, camera, uniforms) => {
187 const random = seeded(4049);
188 const lanes = [];
189 for (let i = 0; i < 1700; i++) {
190 const inner = random() < 0.12;
191 lanes.push(random() * TAU, inner ? 0.6 + random() * 1.1 : 2.4 + Math.pow(random(), 0.7) * 6.5, random() * 98, random());
192 }
193 scene.add(unbounded(new Mesh(instanced(new BoxGeometry(1, 1, 1), 'aLane', new Float32Array(lanes), 4), additive({
194 uniforms,
195 vertexShader: /* glsl */ `
196 ${COMMON}
197 ${PALETTE}
198 ${LANE}
199 attribute vec4 aLane;
200 varying vec3 vColor;
201 varying float vAlpha;
202 void main() {
203 float seed = aLane.w;
204 float head = laneSpan(aLane.z, 46.0 * (0.75 + seed * 0.5));
205 float z = head + (position.z - 0.5) * (1.6 + seed * 5.5);
206 float ang = aLane.x + uTime * 0.85 + z * 0.035;
207 float r = aLane.y * (1.0 + 0.16 * sin(z * 0.14 + uTime * 5.0 + aLane.x * 3.0));
208 vec3 p = laneCenter(z) + vec3(cos(ang) * r, sin(ang) * r, z);
209 p.xy += position.xy * (0.03 + seed * 0.03);
210 gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
211 float tip = position.z + 0.5;
212 vColor = neon(fract(seed * 5.31)) * (0.08 + tip * tip * 1.1) * (0.95 + uBeat * 0.1);
213 vAlpha = laneFade(z);
214 }
215 `,
216 fragmentShader: FLAT_FRAGMENT,
217 }))));
218
219 const gates = [];
220 for (let i = 0; i < 16; i++) gates.push((i / 16) * 98, random());
221 scene.add(unbounded(new Mesh(instanced(new TorusGeometry(1, 0.022, 4, 8), 'aGate', new Float32Array(gates), 2), additive({
222 uniforms,
223 vertexShader: /* glsl */ `
224 ${COMMON}
225 ${LANE}
226 attribute vec2 aGate;
227 varying vec3 vColor;
228 varying float vAlpha;
229 void main() {
230 float z = laneSpan(aGate.x, 26.0);
231 float spin = uTime * (aGate.y > 0.5 ? 1.7 : -1.3) + aGate.y * 6.2831;
232 float radius = 3.1 + 0.7 * sin(uTime * 3.0 + aGate.y * 10.0);
233 vec3 lp = position;
234 lp.xy = rot2(spin) * lp.xy;
235 vec3 p = laneCenter(z) + vec3(lp.xy * radius, z + lp.z * radius);
236 gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
237 float pick = fract(aGate.y * 3.7);
238 vColor = (pick < 0.4 ? vec3(1.6, 0.78, 0.5) : pick < 0.75 ? vec3(0.8, 0.6, 1.7) : vec3(0.4, 1.2, 1.6)) * 0.55;
239 vAlpha = laneFade(z) * smoothstep(10.0, 30.0, ${CAMERA_Z.toFixed(1)} - z);
240 }
241 `,
242 fragmentShader: FLAT_FRAGMENT,
243 }))));
244
245 scene.add(cloud(3600, uniforms, /* glsl */ `
246 float z = laneSpan(aData.z * 98.0, 34.0 * (0.7 + aData.w * 0.6));
247 float ang = aData.x * 6.2831 - uTime * 0.6 + z * 0.02;
248 float r = 0.8 + aData.y * 10.0;
249 vColor = neon(fract(aData.w * 7.7)) * 0.6;
250 vAlpha = laneFade(z) * (0.35 + 0.65 * aData.w);
251 place(laneCenter(z) + vec3(cos(ang) * r, sin(ang) * r, z), 0.04 + aData.w * 0.05);
252 `, LANE));
253
254 // A hot white-cyan star marks the vanishing point the corridor bends toward.
255 scene.add(glow(uniforms, { center: FAR_CENTER, size: 16, color: [0.7, 0.9, 1.4], depthTest: false }));
256 scene.add(glow(uniforms, { center: FAR_CENTER, size: 40, color: [0.35, 0.18, 0.6], depthTest: false }));
257
258 return (time) => {
259 camera.position.set(Math.sin(time * 1.1) * 0.5, Math.cos(time * 0.9) * 0.35, CAMERA_Z);
260 camera.rotation.set(0, 0, Math.sin(time * 0.7) * 0.2);
261 };
262});
263
264// Silk Vortex: a full-screen twisted tunnel of folded silk that spirals into the orbiting vanishing point.
265const silkVortex = world((scene, camera, uniforms) => {
266 const walls = unbounded(new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
267 depthTest: false,
268 depthWrite: false,
269 uniforms,
270 vertexShader: /* glsl */ `
271 ${COMMON}
272 ${LANE}
273 varying vec2 vUv;
274 varying vec2 vFocus;
275 varying float vAspect;
276 void main() {
277 vec4 clip = projectionMatrix * viewMatrix * vec4(laneCenter(-70.0) + vec3(0.0, 0.0, -70.0), 1.0);
278 vFocus = clip.xy / clip.w * 0.5 + 0.5;
279 vAspect = projectionMatrix[1][1] / projectionMatrix[0][0];
280 vUv = uv;
281 gl_Position = vec4(position.xy, 0.0, 1.0);
282 }
283 `,
284 fragmentShader: /* glsl */ `
285 ${COMMON}
286 varying vec2 vUv;
287 varying vec2 vFocus;
288 varying float vAspect;
289 void main() {
290 vec2 p = (vUv - vFocus) * vec2(vAspect, 1.0);
291 float r = max(length(p), 0.002);
292 float a = atan(p.y, p.x);
293 float z = 0.42 / r + uTime * 2.6;
294 float twist = a + z * 0.45 + uTime * 0.7;
295 float fold = 0.5 + 0.5 * sin(twist * 7.0 + sin(z * 1.3 + uTime) * 1.6);
296 float pleat = 0.5 + 0.5 * sin(twist * 13.0 - z * 1.1);
297 float layer = 0.5 + 0.5 * sin(twist * 3.0 - z * 0.9);
298 float rib = pow(0.5 + 0.5 * cos(z * 3.14159), 30.0);
299 vec3 peach = vec3(1.0, 0.42, 0.26);
300 vec3 lilac = vec3(0.42, 0.26, 1.0);
301 vec3 rose = vec3(0.9, 0.14, 0.5);
302 vec3 base = mix(peach, lilac, 0.5 + 0.5 * sin(z * 0.28));
303 base = mix(base, rose, layer * 0.6);
304 float depth = smoothstep(0.012, 0.25, r);
305 float shade = pow(fold, 2.5) * (0.55 + 0.45 * pleat);
306 vec3 color = base * (0.04 + shade * 0.55) * depth;
307 color += pow(fold, 30.0) * pow(pleat, 4.0) * vec3(1.1, 0.85, 1.0) * 0.8 * depth;
308 color += rib * mix(vec3(0.35, 0.75, 1.2), peach, layer) * 0.45 * depth;
309 color += exp(-r * r * 90.0) * vec3(1.0, 0.75, 1.2) * 0.8;
310 color *= 0.45 + 0.55 * smoothstep(1.5, 0.15, r);
311 gl_FragColor = vec4(color * (0.85 + uBeat * 0.15), 1.0);
312 }
313 `,
314 })));
315 walls.renderOrder = -1;
316 scene.add(walls);
317
318 scene.add(cloud(2600, uniforms, /* glsl */ `
319 float z = laneSpan(aData.z * 98.0, 30.0 * (0.7 + aData.w * 0.6));
320 float ang = aData.x * 6.2831 + uTime * 1.4 + z * 0.06;
321 float r = 1.2 + aData.y * 6.0;
322 vColor = mix(vec3(1.4, 0.8, 0.6), vec3(0.8, 0.6, 1.5), aData.w);
323 vAlpha = laneFade(z) * (0.3 + 0.7 * aData.w);
324 place(laneCenter(z) + vec3(cos(ang) * r, sin(ang) * r, z), 0.05 + aData.w * 0.05);
325 `, LANE));
326
327 return (time) => {
328 camera.position.set(Math.sin(time * 0.9) * 0.4, Math.cos(time * 0.7) * 0.3, CAMERA_Z);
329 camera.rotation.set(0, 0, Math.sin(time * 0.5) * 0.15);
330 };
331});
332
333// Helix Drive: a lit, six-lobed tube that twists around the camera while neon seams race toward it.
334const helixDrive = world((scene, camera, uniforms) => {
335 scene.add(unbounded(new Mesh(new PlaneGeometry(1, 1, 120, 420), new ShaderMaterial({
336 side: DoubleSide,
337 uniforms,
338 vertexShader: /* glsl */ `
339 ${COMMON}
340 ${LANE}
341 varying vec3 vPos;
342 varying float vAng;
343 varying float vZ;
344 float twistAt(float z) { return z * 0.075 + uTime * 1.3; }
345 void main() {
346 float ang = (position.x + 0.5) * 6.2831853;
347 float z = mix(-150.0, 15.0, position.y + 0.5);
348 float lobes = 1.0 + 0.24 * cos(6.0 * (ang - twistAt(z)));
349 float radius = 3.4 * lobes * (1.0 + 0.07 * sin(z * 0.22 + uTime * 3.0));
350 vPos = laneCenter(z) + vec3(cos(ang) * radius, sin(ang) * radius, z);
351 vAng = ang;
352 vZ = z;
353 gl_Position = projectionMatrix * viewMatrix * vec4(vPos, 1.0);
354 }
355 `,
356 fragmentShader: /* glsl */ `
357 ${COMMON}
358 varying vec3 vPos;
359 varying float vAng;
360 varying float vZ;
361 void main() {
362 vec3 n = normalize(cross(dFdx(vPos), dFdy(vPos)));
363 vec3 view = normalize(cameraPosition - vPos);
364 if (dot(n, view) < 0.0) n = -n;
365 float d = ${CAMERA_Z.toFixed(1)} - vZ;
366 float twist = vZ * 0.075 + uTime * 1.3;
367 float panel = (vAng - twist) * 12.0 / 6.2831853;
368 float edge = abs(fract(panel) - 0.5);
369 float seam = smoothstep(0.47, 0.5, edge);
370 float lobe = floor(panel);
371 float band = abs(fract((vZ + uTime * 36.0) / 4.5) - 0.5);
372 float ring = smoothstep(0.455, 0.5, band);
373 float ringTone = step(0.5, fract((vZ + uTime * 36.0) / 9.0));
374 float pulse = exp(-fract((vZ + uTime * 52.0) / 42.0) * 5.0);
375 float sweep = 0.35 + 0.65 * pow(0.5 + 0.5 * sin((vZ + uTime * 30.0) * 0.16), 4.0);
376 float bevel = 0.55 + 0.45 * sin(fract(panel) * 3.14159);
377 vec3 light = normalize(vec3(0.0, 0.0, ${CAMERA_Z.toFixed(1)}) - vPos);
378 float diffuse = max(dot(n, light), 0.0);
379 float spec = pow(max(dot(n, normalize(light + view)), 0.0), 36.0);
380 vec3 neon = 0.5 + 0.5 * cos(6.2831 * (lobe * 0.085 + vec3(0.02, 0.32, 0.62)));
381 neon = mix(neon, vec3(1.0, 0.55, 0.4), 0.35) * 1.5;
382 vec3 base = mix(vec3(0.16, 0.035, 0.14), vec3(0.04, 0.04, 0.17), 0.5 + 0.5 * sin(vZ * 0.09));
383 vec3 color = base * bevel * (0.2 + diffuse * 1.2) * sweep + spec * vec3(1.0, 0.7, 0.8) * 0.7 * sweep;
384 color += seam * neon * (0.45 + pulse * 1.6);
385 color += ring * mix(vec3(1.2, 0.55, 0.38), vec3(0.6, 0.45, 1.3), ringTone) * (0.35 + pulse * 0.8);
386 float fog = exp(-d * 0.02);
387 color = mix(vec3(0.03, 0.01, 0.06), color, fog) * smoothstep(160.0, 90.0, d);
388 gl_FragColor = vec4(color * (0.9 + uBeat * 0.1), 1.0);
389 }
390 `,
391 }))));
392
393 scene.add(cloud(2400, uniforms, /* glsl */ `
394 float z = laneSpan(aData.z * 98.0, 40.0 * (0.7 + aData.w * 0.6));
395 float ang = aData.x * 6.2831 - uTime * 1.1 + z * 0.075;
396 float r = 0.6 + aData.y * 3.0;
397 vColor = neon(fract(aData.w * 7.7)) * 0.8;
398 vAlpha = laneFade(z) * (0.35 + 0.65 * aData.w);
399 place(laneCenter(z) + vec3(cos(ang) * r, sin(ang) * r, z), 0.04 + aData.w * 0.05);
400 `, LANE));
401 scene.add(glow(uniforms, { center: '(laneCenter(-95.0) + vec3(0.0, 0.0, -95.0))', size: 24, color: [0.9, 0.55, 0.95], depthTest: false }));
402
403 return (time) => {
404 camera.position.set(Math.sin(time * 0.8) * 0.5, Math.cos(time * 0.65) * 0.4, CAMERA_Z);
405 camera.rotation.set(0, 0, -time * 0.35);
406 };
407});
408
409// Reveals the incoming scene through a noisy, glowing ring that expands from the focal point.
410class TransitionPass extends Pass {
411 constructor() {
412 super();
413 this.material = new ShaderMaterial({
414 depthTest: false,
415 depthWrite: false,
416 uniforms: {
417 tFrom: { value: null }, tTo: { value: null }, uProgress: { value: 1 },
418 uFocus: { value: new Vector2(0.5, 0.5) }, uAspect: { value: 1 }, uTime: { value: 0 },
419 },
420 vertexShader: /* glsl */ `
421 varying vec2 vUv;
422 void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }
423 `,
424 fragmentShader: /* glsl */ `
425 ${VALUE_NOISE}
426 uniform sampler2D tFrom, tTo;
427 uniform float uProgress, uAspect, uTime;
428 uniform vec2 uFocus;
429 varying vec2 vUv;
430 void main() {
431 if (uProgress >= 1.0) { gl_FragColor = texture2D(tTo, vUv); return; }
432 float p = uProgress;
433 vec2 dir = vUv - uFocus;
434 vec2 aspectDir = dir * vec2(uAspect, 1.0);
435 float dist = length(aspectDir);
436 vec2 around = aspectDir / max(dist, 1e-4);
437 float n = vnoise(around * 2.2 + vec2(uTime * 3.0, 9.0)) * 0.6 + vnoise(aspectDir * 5.0 + uTime * 2.0) * 0.4;
438 float radius = p * (max(uAspect, 1.0) * 1.25 + 0.45) - 0.2;
439 float edge = radius + (n - 0.5) * 0.4 - dist;
440 float reveal = smoothstep(-0.015, 0.05, edge);
441 float ring = exp(-edge * edge * 256.0) * sin(3.14159 * p);
442 vec2 fromUv = uFocus + dir * (1.0 - 0.25 * p * p);
443 vec2 toUv = uFocus + dir * (0.8 + 0.2 * p);
444 vec2 shift = normalize(dir + 1e-5) * ring * 0.012;
445 vec3 outgoing = texture2D(tFrom, fromUv).rgb * (1.0 - p * 0.7);
446 vec3 incoming = vec3(texture2D(tTo, toUv + shift).r, texture2D(tTo, toUv).g, texture2D(tTo, toUv - shift).b);
447 vec3 color = mix(outgoing, incoming, reveal);
448 color += ring * mix(vec3(1.2, 0.6, 0.42), vec3(0.5, 0.42, 1.25), n) * 0.65;
449 gl_FragColor = vec4(color, 1.0);
450 }
451 `,
452 });
453 this.quad = new FullScreenQuad(this.material);
454 }
455
456 render(renderer, writeBuffer) {
457 renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
458 this.quad.render(renderer);
459 }
460
461 dispose() {
462 this.material.dispose();
463 this.quad.dispose();
464 }
465}
466
467function smootherstep(x) {
468 const t = Math.min(Math.max(x, 0), 1);
469 return t * t * t * (t * (t * 6 - 15) + 10);
470}
471
472export function mountHeroScenes(container, { onError, onSceneChange }) {
473 const renderer = new WebGLRenderer({ antialias: false, powerPreference: 'high-performance' });
474 renderer.setClearColor('#0f0b12');
475 renderer.toneMapping = ACESFilmicToneMapping;
476 renderer.domElement.setAttribute('aria-hidden', 'true');
477 container.append(renderer.domElement);
478
479 const uniforms = {
480 uTime: { value: 0 }, uBeat: { value: 0 }, uScale: { value: 1 }, uPointScale: { value: 500 },
481 uOrbitSpeed: { value: ORBIT_SPEED }, uOrbitCenter: { value: new Vector3() }, uOrbitRadius: { value: new Vector2(2, 2) },
482 };
483 const layoutCenter = new Vector3();
484 const focusAt = (time, target) => {
485 const angle = time * ORBIT_SPEED;
486 const radius = uniforms.uOrbitRadius.value;
487 return target.copy(uniforms.uOrbitCenter.value).add({ x: Math.cos(angle) * radius.x, y: Math.sin(angle) * radius.y, z: 0 });
488 };
489 const worlds = [silkVortex, helixDrive, hyperlane].map((build) => build(uniforms));
490 const samples = Math.min(renderer.capabilities.maxSamples, 4);
491 const targets = [0, 1].map(() => new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples }));
492 const composer = new EffectComposer(renderer);
493 const transition = new TransitionPass();
494 const bloom = new UnrealBloomPass(new Vector2(1, 1), 0.6, 0.45, 0.82);
495 const output = new OutputPass();
496 composer.addPass(transition);
497 composer.addPass(bloom);
498 composer.addPass(output);
499
500 const pointer = new Vector2();
501 const pointerTarget = new Vector2();
502 const focus = new Vector3();
503 let running = false;
504 let disposed = false;
505 let elapsed = 0;
506 let previous = 0;
507 let lastFrame = 0;
508 let width = 1;
509 let height = 1;
510 let quality = 1;
511 let slowFrames = 0;
512 let sampledFrames = 0;
513 let lastScene = -1;
514
515 function renderWorld(world, target, time) {
516 world.update(time, focusAt);
517 renderer.setRenderTarget(target);
518 renderer.render(world.scene, world.camera);
519 }
520
521 function draw() {
522 const time = elapsed + TIME_OFFSET;
523 uniforms.uTime.value = time;
524 uniforms.uBeat.value = (0.5 + 0.5 * Math.cos(((time / BEAT) % 1) * TAU)) ** 2;
525 uniforms.uOrbitCenter.value.set(layoutCenter.x + pointer.x * 0.9, layoutCenter.y + pointer.y * 0.6, 0);
526
527 const index = Math.floor(elapsed / SCENE_LENGTH) % 3;
528 const age = elapsed % SCENE_LENGTH;
529 const progress = elapsed >= SCENE_LENGTH && age < TRANSITION ? smootherstep(age / TRANSITION) : 1;
530 const current = worlds[index];
531 renderWorld(current, targets[1], time);
532 if (progress < 1) renderWorld(worlds[(index + 2) % 3], targets[0], time);
533
534 focusAt(time, focus).project(current.camera);
535 const pass = transition.material.uniforms;
536 pass.tFrom.value = targets[0].texture;
537 pass.tTo.value = targets[1].texture;
538 pass.uProgress.value = progress;
539 pass.uFocus.value.set(focus.x * 0.5 + 0.5, focus.y * 0.5 + 0.5);
540 pass.uTime.value = time;
541 bloom.strength = 0.6 + (progress < 1 ? Math.sin(progress * Math.PI) * 0.15 : 0);
542 composer.render();
543
544 if (index !== lastScene) {
545 lastScene = index;
546 onSceneChange(SCENE_NAMES[index]);
547 }
548 }
549
550 // Tunnels fill the hero; the vanishing point orbits right of centre on landscape and above centre on portrait.
551 function layout() {
552 const aspect = width / height;
553 const halfHeight = Math.tan((FOV * Math.PI) / 360) * CAMERA_Z;
554 if (aspect >= 1) {
555 layoutCenter.set(halfHeight * aspect * 0.22, halfHeight * 0.04, 0);
556 uniforms.uOrbitRadius.value.set(halfHeight * 0.34, halfHeight * 0.34);
557 uniforms.uScale.value = 1;
558 } else {
559 layoutCenter.set(0, halfHeight * 0.28, 0);
560 uniforms.uOrbitRadius.value.set(halfHeight * aspect * 0.42, halfHeight * aspect * 0.42);
561 uniforms.uScale.value = 0.8;
562 }
563 }
564
565 function resize() {
566 if (disposed) return;
567 width = Math.max(container.clientWidth, 1);
568 height = Math.max(container.clientHeight, 1);
569 const pixelRatio = Math.min(window.devicePixelRatio || 1, 1.5, Math.sqrt(MAX_PIXELS / (width * height))) * quality;
570 renderer.setPixelRatio(pixelRatio);
571 renderer.setSize(width, height, false);
572 composer.setPixelRatio(pixelRatio);
573 composer.setSize(width, height);
574 targets.forEach((target) => target.setSize(Math.round(width * pixelRatio), Math.round(height * pixelRatio)));
575 worlds.forEach((world) => {
576 world.camera.aspect = width / height;
577 world.camera.updateProjectionMatrix();
578 });
579 uniforms.uPointScale.value = (height * pixelRatio) / (2 * Math.tan((FOV * Math.PI) / 360));
580 transition.material.uniforms.uAspect.value = width / height;
581 layout();
582 draw();
583 }
584
585 // Lower the drawing resolution on devices that cannot hold the frame rate.
586 function adapt(delta) {
587 sampledFrames += 1;
588 if (delta > 1 / 40) slowFrames += 1;
589 if (sampledFrames < 90) return;
590 if (slowFrames > 45 && quality > 0.55) {
591 quality = Math.max(quality * 0.82, 0.55);
592 resize();
593 }
594 sampledFrames = 0;
595 slowFrames = 0;
596 }
597
598 const observer = new ResizeObserver(resize);
599 function pointerMove(event) {
600 if (!running || event.pointerType === 'touch') return;
601 const bounds = container.getBoundingClientRect();
602 pointerTarget.set((event.clientX - bounds.left) / bounds.width - 0.5, 0.5 - (event.clientY - bounds.top) / bounds.height);
603 }
604 function contextLost(event) { event.preventDefault(); onError(); }
605 function dispose() {
606 if (disposed) return;
607 disposed = true;
608 renderer.setAnimationLoop(null);
609 observer.disconnect();
610 window.removeEventListener('pointermove', pointerMove);
611 renderer.domElement.removeEventListener('webglcontextlost', contextLost);
612 const geometries = new Set();
613 const materials = new Set();
614 worlds.forEach((entry) => entry.scene.traverse((object) => {
615 if (object.geometry) geometries.add(object.geometry);
616 if (object.material) materials.add(object.material);
617 }));
618 geometries.forEach((geometry) => geometry.dispose());
619 materials.forEach((material) => material.dispose());
620 targets.forEach((target) => target.dispose());
621 transition.dispose();
622 bloom.dispose();
623 output.dispose();
624 composer.dispose();
625 renderer.dispose();
626 renderer.forceContextLoss();
627 renderer.domElement.remove();
628 }
629
630 renderer.debug.onShaderError = () => { throw new Error('Hero scene shader failed to compile'); };
631 renderer.domElement.addEventListener('webglcontextlost', contextLost);
632 window.addEventListener('pointermove', pointerMove, { passive: true });
633 try {
634 // Compile every scene up front so later transitions never stall or fail mid-cycle.
635 worlds.forEach((entry) => renderer.compile(entry.scene, entry.camera));
636 resize();
637 } catch (error) {
638 dispose();
639 throw error;
640 }
641 observer.observe(container);
642
643 return {
644 setRunning(next) {
645 if (disposed || running === next) return;
646 running = next;
647 previous = 0;
648 lastFrame = 0;
649 renderer.setAnimationLoop(next ? (now) => {
650 // Skip only frames well inside the 60 fps budget, so 120 Hz displays settle on every other frame without judder.
651 if (lastFrame && now - lastFrame < 12) return;
652 const delta = previous ? Math.min((now - previous) / 1000, 0.1) : 0;
653 elapsed += delta;
654 previous = now;
655 lastFrame = now;
656 pointer.lerp(pointerTarget, 0.06);
657 try {
658 draw();
659 if (delta) adapt(delta);
660 } catch {
661 onError();
662 }
663 } : null);
664 },
665 // Renders one exact moment; used to produce the matching still images.
666 seek(seconds) {
667 if (disposed) return;
668 elapsed = seconds;
669 draw();
670 },
671 dispose,
672 };
673}