1"use client";
2
3import { useRef, useEffect, useMemo, useState, type CSSProperties } from "react";
4import * as THREE from "three";
5
6interface AnimationConfig {
7 animate: boolean;
8 speed: number;
9}
10
11interface SingleColorConfig {
12 mode: "single";
13 color: string;
14}
15
16interface MultiColorConfig {
17 mode: "multi";
18 color1: string;
19 color2: string;
20}
21
22interface RandomColorConfig {
23 mode: "random";
24}
25
26type RaysColorConfig = SingleColorConfig | MultiColorConfig | RandomColorConfig;
27
28interface RaysProps {
29 intensity?: number;
30 rays?: number;
31 reach?: number;
32 position?: number;
33 radius?: string;
34 backgroundColor?: string;
35 animation?: AnimationConfig;
36 raysColor?: RaysColorConfig;
37 style?: CSSProperties;
38 className?: string;
39}
40
41const RAY_Y_POSITION_1 = -0.4;
42const RAY_Y_POSITION_2 = -0.5;
43
44export default function Rays({
45 intensity = 13,
46 rays = 32,
47 reach = 16,
48 position = 50,
49 radius = "0px",
50 backgroundColor = "#000",
51 animation = { animate: true, speed: 10 },
52 raysColor = { mode: "single", color: "#639AFF" },
53 style,
54 className,
55}: RaysProps) {
56 const containerRef = useRef<HTMLDivElement>(null);
57 const meshRef = useRef<THREE.Mesh | null>(null);
58 const frameIdRef = useRef<number | undefined>(undefined);
59 const animationRef = useRef<AnimationConfig>(animation);
60
61 const [isMounted, setIsMounted] = useState(false);
62
63 useEffect(() => {
64 setIsMounted(true);
65 return () => setIsMounted(false);
66 }, []);
67
68 useEffect(() => {
69 animationRef.current = animation;
70 }, [animation]);
71
72 const [randomColor1RGB, randomColor2RGB] = useMemo(() => {
73 if (raysColor.mode === "random") {
74 const h = Math.random() * 360;
75 const s = 60 + Math.random() * 40;
76 return [hslToRgb(h, s, 50), hslToRgb(h, s, 65)];
77 }
78 return [
79 [1, 1, 1],
80 [1, 1, 1],
81 ] as [[number, number, number], [number, number, number]];
82 }, [raysColor.mode]);
83
84 const [color1RGB, color2RGB] = useMemo((): [
85 [number, number, number],
86 [number, number, number],
87 ] => {
88 if (raysColor.mode === "random") {
89 return [randomColor1RGB, randomColor2RGB] as [
90 [number, number, number],
91 [number, number, number],
92 ];
93 }
94
95 let color1 = "#fff";
96 let color2 = "#fff";
97
98 if (raysColor.mode === "single") {
99 color1 = raysColor.color;
100 color2 = raysColor.color;
101 } else if (raysColor.mode === "multi") {
102 color1 = raysColor.color1;
103 color2 = raysColor.color2;
104 }
105
106 return [colorToRGB(color1), colorToRGB(color2)];
107 }, [raysColor, randomColor1RGB, randomColor2RGB]);
108
109 useEffect(() => {
110 const container = containerRef.current;
111 if (!container || !isMounted) return;
112
113 const scene = new THREE.Scene();
114 const camera = new THREE.PerspectiveCamera(
115 75,
116 container.clientWidth / container.clientHeight,
117 0.1,
118 1000
119 );
120 camera.position.z = 5;
121
122 const renderer = new THREE.WebGLRenderer({
123 preserveDrawingBuffer: true,
124 premultipliedAlpha: true,
125 alpha: true,
126 antialias: true,
127 precision: "highp",
128 powerPreference: "high-performance",
129 });
130
131 renderer.setSize(container.clientWidth, container.clientHeight);
132 renderer.setPixelRatio(1);
133 container.appendChild(renderer.domElement);
134
135 const geometry = new THREE.PlaneGeometry(1024, 1024);
136 const material = new THREE.ShaderMaterial({
137 fragmentShader: FRAGMENT_SHADER,
138 vertexShader: VERTEX_SHADER,
139 uniforms: {
140 u_colors: {
141 value: [
142 new THREE.Vector4(color1RGB[0], color1RGB[1], color1RGB[2], 1),
143 new THREE.Vector4(color2RGB[0], color2RGB[1], color2RGB[2], 1),
144 ],
145 },
146 u_intensity: { value: mapRange(intensity, 0, 100, 0, 0.5) },
147 u_rays: { value: mapRange(rays, 0, 100, 0, 0.3) },
148 u_reach: { value: mapRange(reach, 0, 100, 0, 0.5) },
149 u_time: { value: Math.random() * 10000 },
150 u_mouse: { value: [0, 0] },
151 u_resolution: {
152 value: [container.clientWidth, container.clientHeight],
153 },
154 u_rayPos1: {
155 value: [
156 (position / 100) * container.clientWidth,
157 RAY_Y_POSITION_1 * container.clientHeight,
158 ],
159 },
160 u_rayPos2: {
161 value: [
162 (position / 100 + 0.02) * container.clientWidth,
163 RAY_Y_POSITION_2 * container.clientHeight,
164 ],
165 },
166 },
167 wireframe: false,
168 dithering: false,
169 side: THREE.DoubleSide,
170 });
171
172 const mesh = new THREE.Mesh(geometry, material);
173 scene.add(mesh);
174
175 meshRef.current = mesh;
176
177 let lastTime = 0;
178 const animate = (time: number) => {
179 const anim = animationRef.current;
180 if (!anim.animate) {
181 lastTime = time;
182 }
183
184 const delta = time - lastTime;
185 lastTime = time;
186
187 if (mesh.material instanceof THREE.ShaderMaterial) {
188 if (anim.animate) {
189 mesh.material.uniforms.u_time.value +=
190 (delta * anim.speed) / 1000 / 10;
191 }
192 }
193
194 renderer.render(scene, camera);
195 frameIdRef.current = requestAnimationFrame(animate);
196 };
197
198 frameIdRef.current = requestAnimationFrame(animate);
199
200 return () => {
201 if (frameIdRef.current !== undefined) {
202 cancelAnimationFrame(frameIdRef.current);
203 }
204 renderer.dispose();
205 geometry.dispose();
206 material.dispose();
207 if (container.contains(renderer.domElement)) {
208 container.removeChild(renderer.domElement);
209 }
210 };
211 }, [isMounted]);
212
213 useEffect(() => {
214 if (meshRef.current?.material instanceof THREE.ShaderMaterial) {
215 const material = meshRef.current.material;
216 const container = containerRef.current;
217 if (!container) return;
218
219 material.uniforms.u_colors.value = [
220 new THREE.Vector4(color1RGB[0], color1RGB[1], color1RGB[2], 1),
221 new THREE.Vector4(color2RGB[0], color2RGB[1], color2RGB[2], 1),
222 ];
223 material.uniforms.u_intensity.value = mapRange(intensity, 0, 100, 0, 0.5);
224 material.uniforms.u_rays.value = mapRange(rays, 0, 100, 0, 0.3);
225 material.uniforms.u_reach.value = mapRange(reach, 0, 100, 0, 0.5);
226 material.uniforms.u_rayPos1.value = [
227 (position / 100) * container.clientWidth,
228 RAY_Y_POSITION_1 * container.clientHeight,
229 ];
230 material.uniforms.u_rayPos2.value = [
231 (position / 100 + 0.02) * container.clientWidth,
232 RAY_Y_POSITION_2 * container.clientHeight,
233 ];
234 }
235 }, [intensity, rays, reach, position, color1RGB, color2RGB]);
236
237 return (
238 <div
239 ref={containerRef}
240 className={className}
241 style={{
242 position: "absolute",
243 inset: 0,
244 zIndex: -1,
245 borderRadius: radius,
246 overflow: "hidden",
247 backgroundColor,
248 ...style,
249 }}
250 />
251 );
252}
253
254function colorToRGB(hex: string): [number, number, number] {
255 let r = 1,
256 g = 1,
257 b = 1;
258
259 if (hex.startsWith("rgba(")) {
260 const parts = hex.slice(5, -1).split(",");
261 r = parseInt(parts[0]) / 255;
262 g = parseInt(parts[1]) / 255;
263 b = parseInt(parts[2]) / 255;
264 } else if (hex.startsWith("rgb(")) {
265 const parts = hex.slice(4, -1).split(",");
266 r = parseInt(parts[0]) / 255;
267 g = parseInt(parts[1]) / 255;
268 b = parseInt(parts[2]) / 255;
269 } else if (hex.startsWith("#")) {
270 const c = hex.slice(1);
271 if (c.length === 3) {
272 r = parseInt(c[0] + c[0], 16) / 255;
273 g = parseInt(c[1] + c[1], 16) / 255;
274 b = parseInt(c[2] + c[2], 16) / 255;
275 } else if (c.length >= 6) {
276 r = parseInt(c.slice(0, 2), 16) / 255;
277 g = parseInt(c.slice(2, 4), 16) / 255;
278 b = parseInt(c.slice(4, 6), 16) / 255;
279 }
280 }
281
282 return [r, g, b];
283}
284
285function hslToRgb(h: number, s: number, l: number): [number, number, number] {
286 s /= 100;
287 l /= 100;
288 const c = (1 - Math.abs(2 * l - 1)) * s;
289 const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
290 const m = l - c / 2;
291 let r = 0,
292 g = 0,
293 b = 0;
294
295 if (h >= 0 && h < 60) {
296 r = c;
297 g = x;
298 b = 0;
299 } else if (h >= 60 && h < 120) {
300 r = x;
301 g = c;
302 b = 0;
303 } else if (h >= 120 && h < 180) {
304 r = 0;
305 g = c;
306 b = x;
307 } else if (h >= 180 && h < 240) {
308 r = 0;
309 g = x;
310 b = c;
311 } else if (h >= 240 && h < 300) {
312 r = x;
313 g = 0;
314 b = c;
315 } else if (h >= 300 && h < 360) {
316 r = c;
317 g = 0;
318 b = x;
319 }
320
321 return [r + m, g + m, b + m];
322}
323
324function mapRange(
325 value: number,
326 fromLow: number,
327 fromHigh: number,
328 toLow: number,
329 toHigh: number
330): number {
331 const percentage = (value - fromLow) / (fromHigh - fromLow);
332 return toLow + percentage * (toHigh - toLow);
333}
334
335const VERTEX_SHADER = `
336void main() {
337 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
338}
339`;
340
341const FRAGMENT_SHADER = `
342uniform vec2 u_resolution;
343uniform vec2 u_mouse;
344uniform float u_time;
345uniform vec4 u_colors[2];
346uniform float u_intensity;
347uniform float u_rays;
348uniform float u_reach;
349uniform vec2 u_rayPos1;
350uniform vec2 u_rayPos2;
351
352float rayStrength(vec2 raySource, vec2 rayRefDirection, vec2 coord, float seedA, float seedB, float speed) {
353 vec2 sourceToCoord = coord - raySource;
354 float cosAngle = dot(normalize(sourceToCoord), rayRefDirection);
355 float diagonal = length(u_resolution);
356
357 return clamp(
358 (.45 + 0.15 * sin(cosAngle * seedA + u_time * speed)) +
359 (0.3 + 0.2 * cos(-cosAngle * seedB + u_time * speed)),
360 u_reach, 1.0) *
361 clamp((diagonal - length(sourceToCoord)) / diagonal, u_reach, 1.0);
362}
363
364void main() {
365 vec2 uv = gl_FragCoord.xy / u_resolution.xy;
366 uv.y = 1.0 - uv.y;
367 vec2 coord = vec2(gl_FragCoord.x, u_resolution.y - gl_FragCoord.y);
368 float speed = u_rays * 10.0;
369
370 vec2 rayPos1 = u_rayPos1;
371 vec2 rayRefDir1 = normalize(vec2(1.0, -0.116));
372 float raySeedA1 = 36.2214 * speed;
373 float raySeedB1 = 21.11349 * speed;
374 float raySpeed1 = 1.5 * speed;
375
376 vec2 rayPos2 = u_rayPos2;
377 vec2 rayRefDir2 = normalize(vec2(1.0, 0.241));
378 float raySeedA2 = 22.39910 * speed;
379 float raySeedB2 = 18.0234 * speed;
380 float raySpeed2 = 1.1 * speed;
381
382 float strength1 = rayStrength(rayPos1, rayRefDir1, coord, raySeedA1, raySeedB1, raySpeed1);
383 float strength2 = rayStrength(rayPos2, rayRefDir2, coord, raySeedA2, raySeedB2, raySpeed2);
384
385 float brightness = 1.0 * u_reach - (coord.y / u_resolution.y);
386 float attenuation = clamp(brightness + (0.5 + u_intensity), 0.0, 1.0);
387
388 float alpha1 = strength1 * attenuation * u_colors[0].a;
389 float alpha2 = strength2 * attenuation * u_colors[1].a;
390
391 vec3 premultColor1 = u_colors[0].rgb * alpha1;
392 vec3 premultColor2 = u_colors[1].rgb * alpha2;
393
394 vec3 blendedColor = premultColor1 + premultColor2;
395 float blendedAlpha = alpha1 + alpha2 * (1.0 - alpha1);
396
397 vec3 finalRGB = blendedColor / max(blendedAlpha, 0.0001);
398
399 gl_FragColor = vec4(finalRGB * blendedAlpha, blendedAlpha);
400}
401`;
402