A orb component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import { useEffect, useMemo, useRef } from "react"
4import { useTexture } from "@react-three/drei"
5import { Canvas, useFrame, useThree } from "@react-three/fiber"
6import * as THREE from "three"
7
8export type AgentState = null | "thinking" | "listening" | "talking"
9
10type OrbProps = {
11 colors?: [string, string]
12 colorsRef?: React.RefObject<[string, string]>
13 resizeDebounce?: number
14 seed?: number
15 agentState?: AgentState
16 volumeMode?: "auto" | "manual"
17 manualInput?: number
18 manualOutput?: number
19 inputVolumeRef?: React.RefObject<number>
20 outputVolumeRef?: React.RefObject<number>
21 getInputVolume?: () => number
22 getOutputVolume?: () => number
23 className?: string
24}
25
26export function Orb({
27 colors = ["#CADCFC", "#A0B9D1"],
28 colorsRef,
29 resizeDebounce = 100,
30 seed,
31 agentState = null,
32 volumeMode = "auto",
33 manualInput,
34 manualOutput,
35 inputVolumeRef,
36 outputVolumeRef,
37 getInputVolume,
38 getOutputVolume,
39 className,
40}: OrbProps) {
41 return (
42 <div className={className ?? "relative h-full w-full"}>
43 <Canvas
44 resize={{ debounce: resizeDebounce }}
45 gl={{
46 alpha: true,
47 antialias: true,
48 premultipliedAlpha: true,
49 }}
50 >
51 <Scene
52 colors={colors}
53 colorsRef={colorsRef}
54 seed={seed}
55 agentState={agentState}
56 volumeMode={volumeMode}
57 manualInput={manualInput}
58 manualOutput={manualOutput}
59 inputVolumeRef={inputVolumeRef}
60 outputVolumeRef={outputVolumeRef}
61 getInputVolume={getInputVolume}
62 getOutputVolume={getOutputVolume}
63 />
64 </Canvas>
65 </div>
66 )
67}
68
69function Scene({
70 colors,
71 colorsRef,
72 seed,
73 agentState,
74 volumeMode,
75 manualInput,
76 manualOutput,
77 inputVolumeRef,
78 outputVolumeRef,
79 getInputVolume,
80 getOutputVolume,
81}: {
82 colors: [string, string]
83 colorsRef?: React.RefObject<[string, string]>
84 seed?: number
85 agentState: AgentState
86 volumeMode: "auto" | "manual"
87 manualInput?: number
88 manualOutput?: number
89 inputVolumeRef?: React.RefObject<number>
90 outputVolumeRef?: React.RefObject<number>
91 getInputVolume?: () => number
92 getOutputVolume?: () => number
93}) {
94 const { gl } = useThree()
95 const circleRef =
96 useRef<THREE.Mesh<THREE.CircleGeometry, THREE.ShaderMaterial>>(null)
97 const initialColorsRef = useRef<[string, string]>(colors)
98 const targetColor1Ref = useRef(new THREE.Color(colors[0]))
99 const targetColor2Ref = useRef(new THREE.Color(colors[1]))
100 const animSpeedRef = useRef(0.1)
101 const perlinNoiseTexture = useTexture(
102 "https://storage.googleapis.com/eleven-public-cdn/images/perlin-noise.png"
103 )
104
105 const agentRef = useRef<AgentState>(agentState)
106 const modeRef = useRef<"auto" | "manual">(volumeMode)
107 const manualInRef = useRef<number>(manualInput ?? 0)
108 const manualOutRef = useRef<number>(manualOutput ?? 0)
109 const curInRef = useRef(0)
110 const curOutRef = useRef(0)
111
112 useEffect(() => {
113 agentRef.current = agentState
114 }, [agentState])
115
116 useEffect(() => {
117 modeRef.current = volumeMode
118 }, [volumeMode])
119
120 useEffect(() => {
121 manualInRef.current = clamp01(
122 manualInput ?? inputVolumeRef?.current ?? getInputVolume?.() ?? 0
123 )
124 }, [manualInput, inputVolumeRef, getInputVolume])
125
126 useEffect(() => {
127 manualOutRef.current = clamp01(
128 manualOutput ?? outputVolumeRef?.current ?? getOutputVolume?.() ?? 0
129 )
130 }, [manualOutput, outputVolumeRef, getOutputVolume])
131
132 const random = useMemo(
133 () => splitmix32(seed ?? Math.floor(Math.random() * 2 ** 32)),
134 [seed]
135 )
136 const offsets = useMemo(
137 () =>
138 new Float32Array(Array.from({ length: 7 }, () => random() * Math.PI * 2)),
139 [random]
140 )
141
142 useEffect(() => {
143 targetColor1Ref.current = new THREE.Color(colors[0])
144 targetColor2Ref.current = new THREE.Color(colors[1])
145 }, [colors])
146
147 useEffect(() => {
148 const apply = () => {
149 if (!circleRef.current) return
150 const isDark = document.documentElement.classList.contains("dark")
151 circleRef.current.material.uniforms.uInverted.value = isDark ? 1 : 0
152 }
153
154 apply()
155
156 const observer = new MutationObserver(apply)
157 observer.observe(document.documentElement, {
158 attributes: true,
159 attributeFilter: ["class"],
160 })
161 return () => observer.disconnect()
162 }, [])
163
164 useFrame((_, delta: number) => {
165 const mat = circleRef.current?.material
166 if (!mat) return
167 const live = colorsRef?.current
168 if (live) {
169 if (live[0]) targetColor1Ref.current.set(live[0])
170 if (live[1]) targetColor2Ref.current.set(live[1])
171 }
172 const u = mat.uniforms
173 u.uTime.value += delta * 0.5
174
175 if (u.uOpacity.value < 1) {
176 u.uOpacity.value = Math.min(1, u.uOpacity.value + delta * 2)
177 }
178
179 let targetIn = 0
180 let targetOut = 0.3
181 if (modeRef.current === "manual") {
182 targetIn = clamp01(
183 manualInput ?? inputVolumeRef?.current ?? getInputVolume?.() ?? 0
184 )
185 targetOut = clamp01(
186 manualOutput ?? outputVolumeRef?.current ?? getOutputVolume?.() ?? 0
187 )
188 } else {
189 const t = u.uTime.value * 2
190 if (agentRef.current === null) {
191 targetIn = 0
192 targetOut = 0.3
193 } else if (agentRef.current === "listening") {
194 targetIn = clamp01(0.55 + Math.sin(t * 3.2) * 0.35)
195 targetOut = 0.45
196 } else if (agentRef.current === "talking") {
197 targetIn = clamp01(0.65 + Math.sin(t * 4.8) * 0.22)
198 targetOut = clamp01(0.75 + Math.sin(t * 3.6) * 0.22)
199 } else {
200 const base = 0.38 + 0.07 * Math.sin(t * 0.7)
201 const wander = 0.05 * Math.sin(t * 2.1) * Math.sin(t * 0.37 + 1.2)
202 targetIn = clamp01(base + wander)
203 targetOut = clamp01(0.48 + 0.12 * Math.sin(t * 1.05 + 0.6))
204 }
205 }
206
207 curInRef.current += (targetIn - curInRef.current) * 0.2
208 curOutRef.current += (targetOut - curOutRef.current) * 0.2
209
210 const targetSpeed = 0.1 + (1 - Math.pow(curOutRef.current - 1, 2)) * 0.9
211 animSpeedRef.current += (targetSpeed - animSpeedRef.current) * 0.12
212
213 u.uAnimation.value += delta * animSpeedRef.current
214 u.uInputVolume.value = curInRef.current
215 u.uOutputVolume.value = curOutRef.current
216 u.uColor1.value.lerp(targetColor1Ref.current, 0.08)
217 u.uColor2.value.lerp(targetColor2Ref.current, 0.08)
218 })
219
220 useEffect(() => {
221 const canvas = gl.domElement
222 const onContextLost = (event: Event) => {
223 event.preventDefault()
224 setTimeout(() => {
225 gl.forceContextRestore()
226 }, 1)
227 }
228 canvas.addEventListener("webglcontextlost", onContextLost, false)
229 return () =>
230 canvas.removeEventListener("webglcontextlost", onContextLost, false)
231 }, [gl])
232
233 const uniforms = useMemo(() => {
234 perlinNoiseTexture.wrapS = THREE.RepeatWrapping
235 perlinNoiseTexture.wrapT = THREE.RepeatWrapping
236 const isDark =
237 typeof document !== "undefined" &&
238 document.documentElement.classList.contains("dark")
239 return {
240 uColor1: new THREE.Uniform(new THREE.Color(initialColorsRef.current[0])),
241 uColor2: new THREE.Uniform(new THREE.Color(initialColorsRef.current[1])),
242 uOffsets: { value: offsets },
243 uPerlinTexture: new THREE.Uniform(perlinNoiseTexture),
244 uTime: new THREE.Uniform(0),
245 uAnimation: new THREE.Uniform(0.1),
246 uInverted: new THREE.Uniform(isDark ? 1 : 0),
247 uInputVolume: new THREE.Uniform(0),
248 uOutputVolume: new THREE.Uniform(0),
249 uOpacity: new THREE.Uniform(0),
250 }
251 }, [perlinNoiseTexture, offsets])
252
253 return (
254 <mesh ref={circleRef}>
255 <circleGeometry args={[3.5, 64]} />
256 <shaderMaterial
257 uniforms={uniforms}
258 fragmentShader={fragmentShader}
259 vertexShader={vertexShader}
260 transparent={true}
261 />
262 </mesh>
263 )
264}
265
266function splitmix32(a: number) {
267 return function () {
268 a |= 0
269 a = (a + 0x9e3779b9) | 0
270 let t = a ^ (a >>> 16)
271 t = Math.imul(t, 0x21f0aaad)
272 t = t ^ (t >>> 15)
273 t = Math.imul(t, 0x735a2d97)
274 return ((t = t ^ (t >>> 15)) >>> 0) / 4294967296
275 }
276}
277
278function clamp01(n: number) {
279 if (!Number.isFinite(n)) return 0
280 return Math.min(1, Math.max(0, n))
281}
282const vertexShader = /* glsl */ `
283uniform float uTime;
284uniform sampler2D uPerlinTexture;
285varying vec2 vUv;
286
287void main() {
288 vUv = uv;
289 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
290}
291`
292
293const fragmentShader = /* glsl */ `
294uniform float uTime;
295uniform float uAnimation;
296uniform float uInverted;
297uniform float uOffsets[7];
298uniform vec3 uColor1;
299uniform vec3 uColor2;
300uniform float uInputVolume;
301uniform float uOutputVolume;
302uniform float uOpacity;
303uniform sampler2D uPerlinTexture;
304varying vec2 vUv;
305
306const float PI = 3.14159265358979323846;
307
308// Draw a single oval with soft edges and calculate its gradient color
309bool drawOval(vec2 polarUv, vec2 polarCenter, float a, float b, bool reverseGradient, float softness, out vec4 color) {
310 vec2 p = polarUv - polarCenter;
311 float oval = (p.x * p.x) / (a * a) + (p.y * p.y) / (b * b);
312
313 float edge = smoothstep(1.0, 1.0 - softness, oval);
314
315 if (edge > 0.0) {
316 float gradient = reverseGradient ? (1.0 - (p.x / a + 1.0) / 2.0) : ((p.x / a + 1.0) / 2.0);
317 // Flatten gradient toward middle value for more uniform appearance
318 gradient = mix(0.5, gradient, 0.1);
319 color = vec4(vec3(gradient), 0.85 * edge);
320 return true;
321 }
322 return false;
323}
324
325// Map grayscale value to a 4-color ramp (color1, color2, color3, color4)
326vec3 colorRamp(float grayscale, vec3 color1, vec3 color2, vec3 color3, vec3 color4) {
327 if (grayscale < 0.33) {
328 return mix(color1, color2, grayscale * 3.0);
329 } else if (grayscale < 0.66) {
330 return mix(color2, color3, (grayscale - 0.33) * 3.0);
331 } else {
332 return mix(color3, color4, (grayscale - 0.66) * 3.0);
333 }
334}
335
336vec2 hash2(vec2 p) {
337 return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453);
338}
339
340// 2D noise for the ring
341float noise2D(vec2 p) {
342 vec2 i = floor(p);
343 vec2 f = fract(p);
344
345 vec2 u = f * f * (3.0 - 2.0 * f);
346 float n = mix(
347 mix(dot(hash2(i + vec2(0.0, 0.0)), f - vec2(0.0, 0.0)),
348 dot(hash2(i + vec2(1.0, 0.0)), f - vec2(1.0, 0.0)), u.x),
349 mix(dot(hash2(i + vec2(0.0, 1.0)), f - vec2(0.0, 1.0)),
350 dot(hash2(i + vec2(1.0, 1.0)), f - vec2(1.0, 1.0)), u.x),
351 u.y
352 );
353
354 return 0.5 + 0.5 * n;
355}
356
357float sharpRing(vec3 decomposed, float time) {
358 float ringStart = 1.0;
359 float ringWidth = 0.3;
360 float noiseScale = 5.0;
361
362 float noise = mix(
363 noise2D(vec2(decomposed.x, time) * noiseScale),
364 noise2D(vec2(decomposed.y, time) * noiseScale),
365 decomposed.z
366 );
367
368 noise = (noise - 0.5) * 2.5;
369
370 return ringStart + noise * ringWidth * 1.5;
371}
372
373float smoothRing(vec3 decomposed, float time) {
374 float ringStart = 0.9;
375 float ringWidth = 0.2;
376 float noiseScale = 6.0;
377
378 float noise = mix(
379 noise2D(vec2(decomposed.x, time) * noiseScale),
380 noise2D(vec2(decomposed.y, time) * noiseScale),
381 decomposed.z
382 );
383
384 noise = (noise - 0.5) * 5.0;
385
386 return ringStart + noise * ringWidth;
387}
388
389float flow(vec3 decomposed, float time) {
390 return mix(
391 texture(uPerlinTexture, vec2(time, decomposed.x / 2.0)).r,
392 texture(uPerlinTexture, vec2(time, decomposed.y / 2.0)).r,
393 decomposed.z
394 );
395}
396
397void main() {
398 // Normalize vUv to be centered around (0.0, 0.0)
399 vec2 uv = vUv * 2.0 - 1.0;
400
401 // Convert uv to polar coordinates
402 float radius = length(uv);
403 float theta = atan(uv.y, uv.x);
404 if (theta < 0.0) theta += 2.0 * PI; // Normalize theta to [0, 2*PI]
405
406 // Decomposed angle is used for sampling noise textures without seams:
407 // float noise = mix(sample(decomposed.x), sample(decomposed.y), decomposed.z);
408 vec3 decomposed = vec3(
409 // angle in the range [0, 1]
410 theta / (2.0 * PI),
411 // angle offset by 180 degrees in the range [1, 2]
412 mod(theta / (2.0 * PI) + 0.5, 1.0) + 1.0,
413 // mixing factor between two noises
414 abs(theta / PI - 1.0)
415 );
416
417 // Add noise to the angle for a flow-like distortion (reduced for flatter look)
418 float noise = flow(decomposed, radius * 0.03 - uAnimation * 0.2) - 0.5;
419 theta += noise * mix(0.08, 0.25, uOutputVolume);
420
421 // Initialize the base color to white
422 vec4 color = vec4(1.0, 1.0, 1.0, 1.0);
423
424 // Original parameters for the ovals in polar coordinates
425 float originalCenters[7] = float[7](0.0, 0.5 * PI, 1.0 * PI, 1.5 * PI, 2.0 * PI, 2.5 * PI, 3.0 * PI);
426
427 // Parameters for the animated centers in polar coordinates
428 float centers[7];
429 for (int i = 0; i < 7; i++) {
430 centers[i] = originalCenters[i] + 0.5 * sin(uTime / 20.0 + uOffsets[i]);
431 }
432
433 float a, b;
434 vec4 ovalColor;
435
436 // Check if the pixel is inside any of the ovals
437 for (int i = 0; i < 7; i++) {
438 float noise = texture(uPerlinTexture, vec2(mod(centers[i] + uTime * 0.05, 1.0), 0.5)).r;
439 a = 0.5 + noise * 0.3; // Increased for more coverage
440 b = noise * mix(3.5, 2.5, uInputVolume); // Increased height for fuller appearance
441 bool reverseGradient = (i % 2 == 1); // Reverse gradient for every second oval
442
443 // Calculate the distance in polar coordinates
444 float distTheta = min(
445 abs(theta - centers[i]),
446 min(
447 abs(theta + 2.0 * PI - centers[i]),
448 abs(theta - 2.0 * PI - centers[i])
449 )
450 );
451 float distRadius = radius;
452
453 float softness = 0.6; // Increased softness for flatter, less pronounced edges
454
455 // Check if the pixel is inside the oval in polar coordinates
456 if (drawOval(vec2(distTheta, distRadius), vec2(0.0, 0.0), a, b, reverseGradient, softness, ovalColor)) {
457 // Blend the oval color with the existing color
458 color.rgb = mix(color.rgb, ovalColor.rgb, ovalColor.a);
459 color.a = max(color.a, ovalColor.a); // Max alpha
460 }
461 }
462
463 // Calculate both noisy rings
464 float ringRadius1 = sharpRing(decomposed, uTime * 0.1);
465 float ringRadius2 = smoothRing(decomposed, uTime * 0.1);
466
467 // Adjust rings based on input volume (reduced for flatter appearance)
468 float inputRadius1 = radius + uInputVolume * 0.2;
469 float inputRadius2 = radius + uInputVolume * 0.15;
470 float opacity1 = mix(0.2, 0.6, uInputVolume);
471 float opacity2 = mix(0.15, 0.45, uInputVolume);
472
473 // Blend both rings
474 float ringAlpha1 = (inputRadius2 >= ringRadius1) ? opacity1 : 0.0;
475 float ringAlpha2 = smoothstep(ringRadius2 - 0.05, ringRadius2 + 0.05, inputRadius1) * opacity2;
476
477 float totalRingAlpha = max(ringAlpha1, ringAlpha2);
478
479 // Apply screen blend mode for combined rings
480 vec3 ringColor = vec3(1.0); // White ring color
481 color.rgb = 1.0 - (1.0 - color.rgb) * (1.0 - ringColor * totalRingAlpha);
482
483 // Define colours to ramp against greyscale (could increase the amount of colours in the ramp)
484 vec3 color1 = vec3(0.0, 0.0, 0.0); // Black
485 vec3 color2 = uColor1; // Darker Color
486 vec3 color3 = uColor2; // Lighter Color
487 vec3 color4 = vec3(1.0, 1.0, 1.0); // White
488
489 // Convert grayscale color to the color ramp
490 float luminance = mix(color.r, 1.0 - color.r, uInverted);
491 color.rgb = colorRamp(luminance, color1, color2, color3, color4); // Apply the color ramp
492
493 // Apply fade-in opacity
494 color.a *= uOpacity;
495
496 gl_FragColor = color;
497}
498`
499