A 3d-globe component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useRef, useMemo, useState, useCallback, Suspense } from "react";
3import { Canvas, useFrame, useThree } from "@react-three/fiber";
4import { OrbitControls, Html, useTexture } from "@react-three/drei";
5import * as THREE from "three";
6import { cn } from "@/lib/utils";
7
8// ============================================================================
9// Types
10// ============================================================================
11
12export interface GlobeMarker {
13 lat: number;
14 lng: number;
15 src: string;
16 label?: string;
17 size?: number;
18}
19
20export interface Globe3DConfig {
21 /** Globe radius */
22 radius?: number;
23 /** Globe base color (used as fallback or tint) */
24 globeColor?: string;
25 /** URL to the Earth texture map */
26 textureUrl?: string;
27 /** URL to the bump/elevation map for terrain */
28 bumpMapUrl?: string;
29 /** Whether to show atmosphere glow */
30 showAtmosphere?: boolean;
31 /** Atmosphere color */
32 atmosphereColor?: string;
33 /** Atmosphere intensity */
34 atmosphereIntensity?: number;
35 /** Atmosphere blur/softness (higher = more diffuse, default 3) */
36 atmosphereBlur?: number;
37 /** Terrain bump scale (0 = flat, higher = more pronounced) */
38 bumpScale?: number;
39 /** Auto rotate speed (0 = disabled) */
40 autoRotateSpeed?: number;
41 /** Enable zoom */
42 enableZoom?: boolean;
43 /** Enable pan */
44 enablePan?: boolean;
45 /** Min zoom distance */
46 minDistance?: number;
47 /** Max zoom distance */
48 maxDistance?: number;
49 /** Initial rotation */
50 initialRotation?: { x: number; y: number };
51 /** Marker default size */
52 markerSize?: number;
53 /** Show wireframe overlay */
54 showWireframe?: boolean;
55 /** Wireframe color */
56 wireframeColor?: string;
57 /** Ambient light intensity */
58 ambientIntensity?: number;
59 /** Point light intensity */
60 pointLightIntensity?: number;
61 /** Background color (null for transparent) */
62 backgroundColor?: string | null;
63}
64
65interface Globe3DProps {
66 /** Array of markers to display on the globe */
67 markers?: GlobeMarker[];
68 /** Globe configuration */
69 config?: Globe3DConfig;
70 /** Additional CSS classes */
71 className?: string;
72 /** Callback when a marker is clicked */
73 onMarkerClick?: (marker: GlobeMarker) => void;
74 /** Callback when a marker is hovered */
75 onMarkerHover?: (marker: GlobeMarker | null) => void;
76}
77
78// ============================================================================
79// Constants - Earth Texture URLs (NASA Blue Marble)
80// ============================================================================
81
82const DEFAULT_EARTH_TEXTURE =
83 "https://unpkg.com/three-globe@2.31.0/example/img/earth-blue-marble.jpg";
84const DEFAULT_BUMP_TEXTURE =
85 "https://unpkg.com/three-globe@2.31.0/example/img/earth-topology.png";
86
87// ============================================================================
88// Utility Functions
89// ============================================================================
90
91/**
92 * Convert latitude/longitude to 3D cartesian coordinates
93 */
94function latLngToVector3(
95 lat: number,
96 lng: number,
97 radius: number,
98): THREE.Vector3 {
99 const phi = (90 - lat) * (Math.PI / 180);
100 const theta = (lng + 180) * (Math.PI / 180);
101
102 const x = -(radius * Math.sin(phi) * Math.cos(theta));
103 const z = radius * Math.sin(phi) * Math.sin(theta);
104 const y = radius * Math.cos(phi);
105
106 return new THREE.Vector3(x, y, z);
107}
108
109// ============================================================================
110// Marker Component (static - rotation handled by parent group)
111// ============================================================================
112
113interface MarkerProps {
114 marker: GlobeMarker;
115 radius: number;
116 defaultSize: number;
117 onClick?: (marker: GlobeMarker) => void;
118 onHover?: (marker: GlobeMarker | null) => void;
119}
120
121function Marker({
122 marker,
123 radius,
124 defaultSize,
125 onClick,
126 onHover,
127}: MarkerProps) {
128 const [hovered, setHovered] = useState(false);
129 const [isVisible, setIsVisible] = useState(true);
130 const groupRef = useRef<THREE.Group>(null);
131 const imageGroupRef = useRef<THREE.Group>(null);
132 const { camera } = useThree();
133
134 // Surface position (where the line starts)
135 const surfacePosition = useMemo(() => {
136 return latLngToVector3(marker.lat, marker.lng, radius * 1.001);
137 }, [marker.lat, marker.lng, radius]);
138
139 // Top of the line (where the image is) - positioned further out to prevent going inside globe
140 const topPosition = useMemo(() => {
141 return latLngToVector3(marker.lat, marker.lng, radius * 1.18);
142 }, [marker.lat, marker.lng, radius]);
143
144 const lineHeight = topPosition.distanceTo(surfacePosition);
145
146 // Check if marker is facing the camera
147 useFrame(() => {
148 if (!imageGroupRef.current) return;
149
150 // Get the world position of the image (the positioned element)
151 const worldPos = new THREE.Vector3();
152 imageGroupRef.current.getWorldPosition(worldPos);
153
154 // Direction from globe center (0,0,0) to marker
155 const markerDirection = worldPos.clone().normalize();
156
157 // Direction from globe center to camera
158 const cameraDirection = camera.position.clone().normalize();
159
160 // Dot product: positive means facing camera, negative means behind
161 const dot = markerDirection.dot(cameraDirection);
162
163 // Show marker only if it's facing the camera (stricter threshold)
164 setIsVisible(dot > 0.1);
165 });
166
167 const handlePointerEnter = useCallback(() => {
168 setHovered(true);
169 onHover?.(marker);
170 }, [marker, onHover]);
171
172 const handlePointerLeave = useCallback(() => {
173 setHovered(false);
174 onHover?.(null);
175 }, [onHover]);
176
177 const handleClick = useCallback(() => {
178 onClick?.(marker);
179 }, [marker, onClick]);
180
181 // Calculate line center and orientation
182 const { lineCenter, lineQuaternion } = useMemo(() => {
183 const center = surfacePosition.clone().lerp(topPosition, 0.5);
184
185 // Calculate rotation to align cylinder with the direction from surface to top
186 const direction = topPosition.clone().sub(surfacePosition).normalize();
187 const quaternion = new THREE.Quaternion();
188 quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
189
190 return { lineCenter: center, lineQuaternion: quaternion };
191 }, [surfacePosition, topPosition]);
192
193 return (
194 <group ref={groupRef} visible={isVisible}>
195 {/* Pin line from surface to image - properly oriented */}
196 <mesh position={lineCenter} quaternion={lineQuaternion}>
197 <cylinderGeometry args={[0.003, 0.003, lineHeight, 8]} />
198 <meshBasicMaterial
199 color={hovered ? "#ffffff" : "#94a3b8"}
200 transparent
201 opacity={hovered ? 0.9 : 0.6}
202 />
203 </mesh>
204
205 {/* Pin point at the surface */}
206 <mesh position={surfacePosition} quaternion={lineQuaternion}>
207 <coneGeometry args={[0.015, 0.04, 8]} />
208 <meshBasicMaterial color={hovered ? "#f97316" : "#ef4444"} />
209 </mesh>
210
211 {/* Circular image at the top */}
212 <group ref={imageGroupRef} position={topPosition}>
213 <Html
214 transform
215 center
216 sprite
217 distanceFactor={10}
218 style={{
219 pointerEvents: isVisible ? "auto" : "none",
220 opacity: isVisible ? 1 : 0,
221 transition: "opacity 0.15s ease-out",
222 }}
223 >
224 <div
225 className={cn(
226 "cursor-pointer overflow-hidden rounded-full bg-neutral-900 shadow-lg transition-transform duration-200",
227 hovered && "scale-125 shadow-xl ring-1 ring-white/50",
228 )}
229 style={{
230 width: "8px",
231 height: "8px",
232 }}
233 onMouseEnter={handlePointerEnter}
234 onMouseLeave={handlePointerLeave}
235 onClick={handleClick}
236 >
237 <img
238 src={marker.src}
239 alt={marker.label || "Marker"}
240 className="h-full w-full object-cover"
241 draggable={false}
242 />
243 </div>
244 </Html>
245 </group>
246 </group>
247 );
248}
249
250// ============================================================================
251// Rotating Globe with Markers (all rotate together)
252// ============================================================================
253
254interface RotatingGlobeProps {
255 config: Required<Globe3DConfig>;
256 markers: GlobeMarker[];
257 onMarkerClick?: (marker: GlobeMarker) => void;
258 onMarkerHover?: (marker: GlobeMarker | null) => void;
259}
260
261function RotatingGlobe({
262 config,
263 markers,
264 onMarkerClick,
265 onMarkerHover,
266}: RotatingGlobeProps) {
267 const groupRef = useRef<THREE.Group>(null);
268
269 // Load Earth textures
270 const [earthTexture, bumpTexture] = useTexture([
271 config.textureUrl,
272 config.bumpMapUrl,
273 ]);
274
275 // Configure textures
276 useMemo(() => {
277 if (earthTexture) {
278 earthTexture.colorSpace = THREE.SRGBColorSpace;
279 earthTexture.anisotropy = 16;
280 }
281 if (bumpTexture) {
282 bumpTexture.anisotropy = 8;
283 }
284 }, [earthTexture, bumpTexture]);
285
286 // Create geometries
287 const geometry = useMemo(() => {
288 return new THREE.SphereGeometry(config.radius, 64, 64);
289 }, [config.radius]);
290
291 const wireframeGeometry = useMemo(() => {
292 return new THREE.SphereGeometry(config.radius * 1.002, 32, 16);
293 }, [config.radius]);
294
295 return (
296 <group ref={groupRef}>
297 {/* Main globe mesh with Earth texture */}
298 <mesh geometry={geometry}>
299 <meshStandardMaterial
300 map={earthTexture}
301 bumpMap={bumpTexture}
302 bumpScale={config.bumpScale * 0.05}
303 roughness={0.7}
304 metalness={0.0}
305 />
306 </mesh>
307
308 {/* Wireframe overlay */}
309 {config.showWireframe && (
310 <mesh geometry={wireframeGeometry}>
311 <meshBasicMaterial
312 color={config.wireframeColor}
313 wireframe
314 transparent
315 opacity={0.08}
316 />
317 </mesh>
318 )}
319
320 {/* Markers - now inside the rotating group */}
321 {markers.map((marker, index) => (
322 <Marker
323 key={`marker-${index}-${marker.lat}-${marker.lng}`}
324 marker={marker}
325 radius={config.radius}
326 defaultSize={config.markerSize}
327 onClick={onMarkerClick}
328 onHover={onMarkerHover}
329 />
330 ))}
331 </group>
332 );
333}
334
335// ============================================================================
336// Atmosphere Component (stays static - doesn't rotate)
337// ============================================================================
338
339interface AtmosphereProps {
340 radius: number;
341 color: string;
342 intensity: number;
343 blur: number;
344}
345
346function Atmosphere({ radius, color, intensity, blur }: AtmosphereProps) {
347 // blur controls the fresnel exponent: lower = more diffuse, higher = sharper edge
348 // We invert it so higher blur value = more diffuse (lower exponent)
349 const fresnelPower = Math.max(0.5, 5 - blur);
350
351 const atmosphereMaterial = useMemo(() => {
352 return new THREE.ShaderMaterial({
353 uniforms: {
354 atmosphereColor: { value: new THREE.Color(color) },
355 intensity: { value: intensity },
356 fresnelPower: { value: fresnelPower },
357 },
358 vertexShader: `
359 varying vec3 vNormal;
360 varying vec3 vPosition;
361 void main() {
362 vNormal = normalize(normalMatrix * normal);
363 vPosition = (modelViewMatrix * vec4(position, 1.0)).xyz;
364 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
365 }
366 `,
367 fragmentShader: `
368 uniform vec3 atmosphereColor;
369 uniform float intensity;
370 uniform float fresnelPower;
371 varying vec3 vNormal;
372 varying vec3 vPosition;
373 void main() {
374 float fresnel = pow(1.0 - abs(dot(vNormal, normalize(-vPosition))), fresnelPower);
375 gl_FragColor = vec4(atmosphereColor, fresnel * intensity);
376 }
377 `,
378 side: THREE.BackSide,
379 transparent: true,
380 depthWrite: false,
381 });
382 }, [color, intensity, fresnelPower]);
383
384 return (
385 <mesh scale={[1.12, 1.12, 1.12]}>
386 <sphereGeometry args={[radius, 64, 32]} />
387 <primitive object={atmosphereMaterial} attach="material" />
388 </mesh>
389 );
390}
391
392// ============================================================================
393// Scene Component
394// ============================================================================
395
396interface SceneProps {
397 markers: GlobeMarker[];
398 config: Required<Globe3DConfig>;
399 onMarkerClick?: (marker: GlobeMarker) => void;
400 onMarkerHover?: (marker: GlobeMarker | null) => void;
401}
402
403function Scene({ markers, config, onMarkerClick, onMarkerHover }: SceneProps) {
404 const { camera } = useThree();
405
406 // Set initial camera position (pulled back to accommodate markers)
407 React.useEffect(() => {
408 camera.position.set(0, 0, config.radius * 3.5);
409 camera.lookAt(0, 0, 0);
410 }, [camera, config.radius]);
411
412 return (
413 <>
414 {/* Lighting */}
415 <ambientLight intensity={config.ambientIntensity} />
416 <directionalLight
417 position={[config.radius * 5, config.radius * 2, config.radius * 5]}
418 intensity={config.pointLightIntensity}
419 color="#ffffff"
420 />
421 <directionalLight
422 position={[-config.radius * 3, config.radius, -config.radius * 2]}
423 intensity={config.pointLightIntensity * 0.3}
424 color="#88ccff"
425 />
426
427 {/* Rotating Globe with Markers */}
428 <RotatingGlobe
429 config={config}
430 markers={markers}
431 onMarkerClick={onMarkerClick}
432 onMarkerHover={onMarkerHover}
433 />
434
435 {/* Atmosphere (static) */}
436 {config.showAtmosphere && (
437 <Atmosphere
438 radius={config.radius}
439 color={config.atmosphereColor}
440 intensity={config.atmosphereIntensity}
441 blur={config.atmosphereBlur}
442 />
443 )}
444
445 {/* Controls */}
446 <OrbitControls
447 makeDefault
448 enablePan={config.enablePan}
449 enableZoom={config.enableZoom}
450 minDistance={config.minDistance}
451 maxDistance={config.maxDistance}
452 rotateSpeed={0.4}
453 autoRotate={config.autoRotateSpeed > 0}
454 autoRotateSpeed={config.autoRotateSpeed}
455 enableDamping
456 dampingFactor={0.1}
457 />
458 </>
459 );
460}
461
462// ============================================================================
463// Loading Fallback
464// ============================================================================
465
466function LoadingFallback() {
467 return (
468 <Html center>
469 <div className="flex shrink-0 flex-col items-center gap-3">
470 <span className="inline-block shrink-0 text-sm text-neutral-400">
471 Loading globe...
472 </span>
473 </div>
474 </Html>
475 );
476}
477
478// ============================================================================
479// Main Globe3D Component
480// ============================================================================
481
482const defaultConfig: Required<Globe3DConfig> = {
483 radius: 2,
484 globeColor: "#1a1a2e",
485 textureUrl: DEFAULT_EARTH_TEXTURE,
486 bumpMapUrl: DEFAULT_BUMP_TEXTURE,
487 showAtmosphere: false,
488 atmosphereColor: "#4da6ff",
489 atmosphereIntensity: 0.5,
490 atmosphereBlur: 2,
491 bumpScale: 1,
492 autoRotateSpeed: 0.3,
493 enableZoom: false,
494 enablePan: false,
495 minDistance: 5,
496 maxDistance: 15,
497 initialRotation: { x: 0, y: 0 },
498 markerSize: 0.06,
499 showWireframe: false,
500 wireframeColor: "#4a9eff",
501 ambientIntensity: 0.6,
502 pointLightIntensity: 1.5,
503 backgroundColor: null,
504};
505
506export function Globe3D({
507 markers = [],
508 config = {},
509 className,
510 onMarkerClick,
511 onMarkerHover,
512}: Globe3DProps) {
513 const mergedConfig = useMemo(
514 () => ({ ...defaultConfig, ...config }),
515 [config],
516 );
517
518 return (
519 <div className={cn("relative h-[500px] w-full", className)}>
520 <Canvas
521 gl={{
522 antialias: true,
523 alpha: true,
524 powerPreference: "high-performance",
525 }}
526 dpr={[1, 2]}
527 camera={{
528 fov: 45,
529 near: 0.1,
530 far: 1000,
531 position: [0, 0, mergedConfig.radius * 3.5],
532 }}
533 style={{
534 background: mergedConfig.backgroundColor || "transparent",
535 }}
536 >
537 <Suspense fallback={<LoadingFallback />}>
538 <Scene
539 markers={markers}
540 config={mergedConfig}
541 onMarkerClick={onMarkerClick}
542 onMarkerHover={onMarkerHover}
543 />
544 </Suspense>
545 </Canvas>
546 </div>
547 );
548}
549
550export default Globe3D;
551