From ed8814a8b1ef87ef48f027e628e404307131ce98 Mon Sep 17 00:00:00 2001 From: xEsiah Date: Thu, 26 Feb 2026 17:17:28 +0100 Subject: [PATCH] Fade in on bgs & sticky nav --- src/{App.jsx => App.tsx} | 0 src/components/CardNav.css | 14 +- src/components/CardSwap.css | 28 - src/components/CardSwap.jsx | 208 --- src/components/CardSwap.tsx | 276 +++ src/components/FlowingMenu.css | 2 - src/components/FlowingMenu.jsx | 28 +- src/components/{Lanyard.jsx => Lanyard.tsx} | 0 src/components/{LogoLoop.jsx => LogoLoop.tsx} | 0 src/components/MagicBento.css | 139 -- src/components/MagicBento.jsx | 193 --- src/components/MagicBento.tsx | 275 +++ src/components/OrbitImages.tsx | 0 src/components/ServiceDetails.jsx | 60 - src/components/ServiceDetails.tsx | 77 + src/components/SplashCursor.jsx | 1070 ------------ ...roundWrapper.jsx => BackgroundWrapper.tsx} | 2 - .../backgrounds/{Galaxy.jsx => Galaxy.tsx} | 197 +-- src/components/backgrounds/LightPillar.css | 21 - .../{LightPillar.jsx => LightPillar.tsx} | 122 +- src/components/cursors/SplashCursor.jsx | 1257 -------------- src/components/cursors/SplashCursor.tsx | 1521 +++++++++++++++++ src/components/cursors/TargetCursor.css | 57 - .../{TargetCursor.jsx => TargetCursor.tsx} | 190 +- src/index.css | 3 +- src/main.jsx | 10 - src/main.tsx | 10 + src/pages/{Contact.jsx => Contact.tsx} | 0 src/pages/{Home.jsx => Home.tsx} | 1 - src/pages/{Projects.jsx => Projects.tsx} | 0 ...heLastStop.jsx => EchoesOfTheLastStop.tsx} | 0 .../{NeoTokyoRush.jsx => NeoTokyoRush.tsx} | 0 ...emon.jsx => ShadowPurgeRiteOfTheDemon.tsx} | 0 .../projects/{Zatyshok.jsx => Zatyshok.tsx} | 0 tsconfig.json | 2 +- vite-env.d.ts | 12 + 36 files changed, 2450 insertions(+), 3325 deletions(-) rename src/{App.jsx => App.tsx} (100%) delete mode 100644 src/components/CardSwap.css delete mode 100644 src/components/CardSwap.jsx create mode 100644 src/components/CardSwap.tsx rename src/components/{Lanyard.jsx => Lanyard.tsx} (100%) rename src/components/{LogoLoop.jsx => LogoLoop.tsx} (100%) delete mode 100644 src/components/MagicBento.css delete mode 100644 src/components/MagicBento.jsx create mode 100644 src/components/MagicBento.tsx create mode 100644 src/components/OrbitImages.tsx delete mode 100644 src/components/ServiceDetails.jsx create mode 100644 src/components/ServiceDetails.tsx delete mode 100644 src/components/SplashCursor.jsx rename src/components/backgrounds/{BackgroundWrapper.jsx => BackgroundWrapper.tsx} (96%) rename src/components/backgrounds/{Galaxy.jsx => Galaxy.tsx} (70%) delete mode 100644 src/components/backgrounds/LightPillar.css rename src/components/backgrounds/{LightPillar.jsx => LightPillar.tsx} (78%) delete mode 100644 src/components/cursors/SplashCursor.jsx create mode 100644 src/components/cursors/SplashCursor.tsx delete mode 100644 src/components/cursors/TargetCursor.css rename src/components/cursors/{TargetCursor.jsx => TargetCursor.tsx} (63%) delete mode 100644 src/main.jsx create mode 100644 src/main.tsx rename src/pages/{Contact.jsx => Contact.tsx} (100%) rename src/pages/{Home.jsx => Home.tsx} (96%) rename src/pages/{Projects.jsx => Projects.tsx} (100%) rename src/pages/projects/{EchoesOfTheLastStop.jsx => EchoesOfTheLastStop.tsx} (100%) rename src/pages/projects/{NeoTokyoRush.jsx => NeoTokyoRush.tsx} (100%) rename src/pages/projects/{ShadowPurgeRiteOfTheDemon.jsx => ShadowPurgeRiteOfTheDemon.tsx} (100%) rename src/pages/projects/{Zatyshok.jsx => Zatyshok.tsx} (100%) create mode 100644 vite-env.d.ts diff --git a/src/App.jsx b/src/App.tsx similarity index 100% rename from src/App.jsx rename to src/App.tsx diff --git a/src/components/CardNav.css b/src/components/CardNav.css index 959af52..8675998 100644 --- a/src/components/CardNav.css +++ b/src/components/CardNav.css @@ -1,12 +1,14 @@ .card-nav-container { - position: absolute; - top: 2em; - left: 50%; - transform: translateX(-50%); + position: sticky; + top: 1.5em; + margin-left: auto; + margin-right: auto; width: 90%; max-width: 800px; - z-index: 99; + z-index: 999; box-sizing: border-box; + margin-bottom: 2em; + display: block; } .card-nav { @@ -32,7 +34,7 @@ display: flex; align-items: center; justify-content: space-between; - padding: 0.5rem 0.8rem; /* Ajusté pour laisser de la place */ + padding: 0.5rem 0.8rem; z-index: 2; } diff --git a/src/components/CardSwap.css b/src/components/CardSwap.css deleted file mode 100644 index 728d1aa..0000000 --- a/src/components/CardSwap.css +++ /dev/null @@ -1,28 +0,0 @@ -.card-swap-container { - position: relative; - margin: 0 auto; - perspective: 1500px; - overflow: visible; - pointer-events: none; -} - -.card { - position: absolute; - top: 50%; - left: 50%; - transform-style: preserve-3d; - will-change: transform; - pointer-events: auto !important; -} - -/* Responsive : On réduit la taille des cartes de 800px sur mobile */ -@media (max-width: 1024px) { - .card-swap-container { - transform: scale(0.8); - } -} -@media (max-width: 768px) { - .card-swap-container { - transform: scale(0.5); - } -} diff --git a/src/components/CardSwap.jsx b/src/components/CardSwap.jsx deleted file mode 100644 index c9e9d4a..0000000 --- a/src/components/CardSwap.jsx +++ /dev/null @@ -1,208 +0,0 @@ -import React, { - Children, - cloneElement, - forwardRef, - isValidElement, - useEffect, - useMemo, - useRef, -} from "react"; -import gsap from "gsap"; -import "./CardSwap.css"; - -export const Card = forwardRef(({ customClass, ...rest }, ref) => ( -
-)); -Card.displayName = "Card"; - -const makeSlot = (i, distX, distY, total) => ({ - x: i * distX, - y: -i * distY, - z: -i * distX * 1.5, - zIndex: total - i, -}); -const placeNow = (el, slot, skew) => - gsap.set(el, { - x: slot.x, - y: slot.y, - z: slot.z, - xPercent: -50, - yPercent: -50, - skewY: skew, - transformOrigin: "center center", - zIndex: slot.zIndex, - force3D: true, - }); - -const CardSwap = ({ - width = 500, - height = 400, - cardDistance = 60, - verticalDistance = 70, - delay = 5000, - pauseOnHover = false, - onCardClick, - skewAmount = 6, - easing = "elastic", - children, -}) => { - const config = - easing === "elastic" - ? { - ease: "elastic.out(0.6,0.9)", - durDrop: 2, - durMove: 2, - durReturn: 2, - promoteOverlap: 0.9, - returnDelay: 0.05, - } - : { - ease: "power1.inOut", - durDrop: 0.8, - durMove: 0.8, - durReturn: 0.8, - promoteOverlap: 0.45, - returnDelay: 0.2, - }; - - const childArr = useMemo(() => Children.toArray(children), [children]); - const refs = useMemo( - () => childArr.map(() => React.createRef()), - // eslint-disable-next-line react-hooks/exhaustive-deps - [childArr.length], - ); - - const order = useRef(Array.from({ length: childArr.length }, (_, i) => i)); - - const tlRef = useRef(null); - const intervalRef = useRef(); - const container = useRef(null); - - useEffect(() => { - const total = refs.length; - refs.forEach((r, i) => - placeNow( - r.current, - makeSlot(i, cardDistance, verticalDistance, total), - skewAmount, - ), - ); - - const swap = () => { - if (order.current.length < 2) return; - - const [front, ...rest] = order.current; - const elFront = refs[front].current; - const tl = gsap.timeline(); - tlRef.current = tl; - - tl.to(elFront, { - y: "+=500", - duration: config.durDrop, - ease: config.ease, - }); - - tl.addLabel("promote", `-=${config.durDrop * config.promoteOverlap}`); - rest.forEach((idx, i) => { - const el = refs[idx].current; - const slot = makeSlot(i, cardDistance, verticalDistance, refs.length); - tl.set(el, { zIndex: slot.zIndex }, "promote"); - tl.to( - el, - { - x: slot.x, - y: slot.y, - z: slot.z, - duration: config.durMove, - ease: config.ease, - }, - `promote+=${i * 0.15}`, - ); - }); - - const backSlot = makeSlot( - refs.length - 1, - cardDistance, - verticalDistance, - refs.length, - ); - tl.addLabel("return", `promote+=${config.durMove * config.returnDelay}`); - tl.call( - () => { - gsap.set(elFront, { zIndex: backSlot.zIndex }); - }, - undefined, - "return", - ); - tl.to( - elFront, - { - x: backSlot.x, - y: backSlot.y, - z: backSlot.z, - duration: config.durReturn, - ease: config.ease, - }, - "return", - ); - - tl.call(() => { - order.current = [...rest, front]; - }); - }; - - swap(); - intervalRef.current = window.setInterval(swap, delay); - - if (pauseOnHover) { - const node = container.current; - const pause = () => { - tlRef.current?.pause(); - clearInterval(intervalRef.current); - }; - const resume = () => { - tlRef.current?.play(); - intervalRef.current = window.setInterval(swap, delay); - }; - node.addEventListener("mouseenter", pause); - node.addEventListener("mouseleave", resume); - return () => { - node.removeEventListener("mouseenter", pause); - node.removeEventListener("mouseleave", resume); - clearInterval(intervalRef.current); - }; - } - return () => clearInterval(intervalRef.current); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cardDistance, verticalDistance, delay, pauseOnHover, skewAmount, easing]); - - const rendered = childArr.map((child, i) => - isValidElement(child) - ? cloneElement(child, { - key: i, - ref: refs[i], - style: { width, height, ...(child.props.style ?? {}) }, - onClick: (e) => { - child.props.onClick?.(e); - onCardClick?.(i); - }, - }) - : child, - ); - - return ( -
- {rendered} -
- ); -}; - -export default CardSwap; diff --git a/src/components/CardSwap.tsx b/src/components/CardSwap.tsx new file mode 100644 index 0000000..833320d --- /dev/null +++ b/src/components/CardSwap.tsx @@ -0,0 +1,276 @@ +import React, { + Children, + cloneElement, + forwardRef, + isValidElement, + useEffect, + useMemo, + useRef, + useState, + ReactElement, + HTMLAttributes, +} from "react"; +import gsap from "gsap"; + +// --- Types --- +interface Slot { + x: number; + y: number; + z: number; + zIndex: number; +} + +interface CardProps extends HTMLAttributes { + customClass?: string; +} + +interface CardSwapProps { + width?: number | string; + height?: number | string; + cardDistance?: number; + verticalDistance?: number; + delay?: number; + pauseOnHover?: boolean; + onCardClick?: (index: number) => void; + skewAmount?: number; + easing?: "elastic" | "smooth"; + children: React.ReactNode; +} + +// --- Composant Card --- +export const Card = forwardRef( + ({ customClass, className, ...rest }, ref) => ( +
+ ), +); +Card.displayName = "Card"; + +// --- Helpers de positionnement --- +const makeSlot = ( + i: number, + distX: number, + distY: number, + total: number, +): Slot => ({ + x: i * distX, + y: -i * distY, + z: -i * distX * 1.5, + zIndex: total - i, +}); + +const placeNow = (el: HTMLDivElement | null, slot: Slot, skew: number) => { + if (!el) return; + gsap.set(el, { + x: slot.x, + y: slot.y, + z: slot.z, + xPercent: -50, + yPercent: -50, + skewY: skew, + transformOrigin: "center center", + zIndex: slot.zIndex, + force3D: true, + }); +}; + +// --- Composant Principal --- +const CardSwap: React.FC = ({ + width = 500, + height = 400, + cardDistance = 60, + verticalDistance = 70, + delay = 5000, + pauseOnHover = false, + onCardClick, + skewAmount = 6, + easing = "elastic", + children, +}) => { + const config = useMemo( + () => + easing === "elastic" + ? { + ease: "elastic.out(0.6,0.9)", + durDrop: 2, + durMove: 2, + durReturn: 2, + promoteOverlap: 0.9, + returnDelay: 0.05, + } + : { + ease: "power1.inOut", + durDrop: 0.8, + durMove: 0.8, + durReturn: 0.8, + promoteOverlap: 0.45, + returnDelay: 0.2, + }, + [easing], + ); + + const childArr = useMemo(() => Children.toArray(children), [children]); + + // Correction Erreur 2322 : Typage explicite des refs + const refs = useMemo( + () => childArr.map(() => React.createRef()), + [childArr.length], + ); + + const order = useRef( + Array.from({ length: childArr.length }, (_, i) => i), + ); + const tlRef = useRef(null); + const intervalRef = useRef(null); + const container = useRef(null); + + useEffect(() => { + const total = refs.length; + if (total === 0) return; + + // Positionnement initial + refs.forEach((r, i) => { + placeNow( + r.current, + makeSlot(i, cardDistance, verticalDistance, total), + skewAmount, + ); + }); + + const swap = () => { + if (order.current.length < 2) return; + + const [front, ...rest] = order.current; + const elFront = refs[front].current; + if (!elFront) return; + + const tl = gsap.timeline(); + tlRef.current = tl; + + // Animation de descente + tl.to(elFront, { + y: "+=500", + duration: config.durDrop, + ease: config.ease, + }); + + tl.addLabel("promote", `-=${config.durDrop * config.promoteOverlap}`); + + // Avancement des autres cartes + rest.forEach((idx, i) => { + const el = refs[idx].current; + if (!el) return; + const slot = makeSlot(i, cardDistance, verticalDistance, total); + + tl.set(el, { zIndex: slot.zIndex }, "promote"); + tl.to( + el, + { + x: slot.x, + y: slot.y, + z: slot.z, + duration: config.durMove, + ease: config.ease, + }, + `promote+=${i * 0.15}`, + ); + }); + + // Retour de la carte de devant vers le fond + const backSlot = makeSlot( + total - 1, + cardDistance, + verticalDistance, + total, + ); + tl.addLabel("return", `promote+=${config.durMove * config.returnDelay}`); + + tl.set(elFront, { zIndex: backSlot.zIndex }, "return"); + tl.to( + elFront, + { + x: backSlot.x, + y: backSlot.y, + z: backSlot.z, + duration: config.durReturn, + ease: config.ease, + }, + "return", + ); + + tl.call(() => { + order.current = [...rest, front]; + }); + }; + + intervalRef.current = window.setInterval(swap, delay); + + // Gestion du Hover + const node = container.current; + if (pauseOnHover && node) { + const pause = () => { + tlRef.current?.pause(); + if (intervalRef.current) clearInterval(intervalRef.current); + }; + const resume = () => { + tlRef.current?.play(); + intervalRef.current = window.setInterval(swap, delay); + }; + node.addEventListener("mouseenter", pause); + node.addEventListener("mouseleave", resume); + + return () => { + node.removeEventListener("mouseenter", pause); + node.removeEventListener("mouseleave", resume); + if (intervalRef.current) clearInterval(intervalRef.current); + }; + } + + return () => { + if (intervalRef.current) clearInterval(intervalRef.current); + }; + }, [ + cardDistance, + verticalDistance, + delay, + pauseOnHover, + skewAmount, + config, + refs, + ]); + + // Rendu des enfants avec injection des props + const rendered = childArr.map((child, i) => { + if (!isValidElement(child)) return child; + + const typedChild = child as ReactElement; + return cloneElement(typedChild, { + key: i, + ref: refs[i], + style: { + width, + height, + ...(typedChild.props.style ?? {}), + }, + onClick: (e: React.MouseEvent) => { + typedChild.props.onClick?.(e); + onCardClick?.(i); + }, + }); + }); + + return ( +
+ {rendered} +
+ ); +}; + +export default CardSwap; diff --git a/src/components/FlowingMenu.css b/src/components/FlowingMenu.css index 393eb67..8f6117a 100644 --- a/src/components/FlowingMenu.css +++ b/src/components/FlowingMenu.css @@ -85,14 +85,12 @@ .details-inner { padding: 4rem 4vw; display: grid; - grid-template-columns: 1fr 2fr; gap: 4rem; align-items: start; } @media (max-width: 768px) { .details-inner { - grid-template-columns: 1fr; gap: 2rem; } } diff --git a/src/components/FlowingMenu.jsx b/src/components/FlowingMenu.jsx index f4859b0..552c115 100644 --- a/src/components/FlowingMenu.jsx +++ b/src/components/FlowingMenu.jsx @@ -15,9 +15,24 @@ function FlowingMenu({ borderColor = "rgba(255,255,255,0.1)", }) { const [activeIdx, setActiveIdx] = useState(null); + const [isTransitioning, setIsTransitioning] = useState(false); const toggleItem = (idx) => { - setActiveIdx(activeIdx === idx ? null : idx); + if (isTransitioning) return; + if (activeIdx === idx) { + setActiveIdx(null); + return; + } + if (activeIdx !== null) { + setIsTransitioning(true); + setActiveIdx(null); + setTimeout(() => { + setActiveIdx(idx); + setIsTransitioning(false); + }, 500); + } else { + setActiveIdx(idx); + } }; return ( @@ -36,7 +51,6 @@ function FlowingMenu({ borderColor={borderColor} /> ))} -
{ if (isOpen && itemRef.current) { const isMobile = window.innerWidth < 768; + gsap.killTweensOf([contentRef.current, window, marqueeRef.current]); + gsap.to(contentRef.current, { height: "auto", opacity: 1, @@ -120,7 +136,7 @@ function MenuItem({ }); gsap.to(window, { duration: isMobile ? 0.8 : 1, - delay: 0.35, + delay: 0.1, scrollTo: { y: itemRef.current, offsetY: isMobile ? 0 : 60, @@ -134,6 +150,7 @@ function MenuItem({ ease: "power2.out", }); } else { + gsap.killTweensOf(contentRef.current); gsap.to(contentRef.current, { height: 0, opacity: 0, @@ -171,8 +188,6 @@ function MenuItem({ > {text}
- - {/* ZONE DÉTAILS */}
{Component && }
- - {/* MARQUEE */} - {/* Note : Le background est géré par le CSS pour le glassmorphism */}
{ - const el = document.createElement("div"); - el.className = "particle"; - el.style.cssText = `position: absolute; width: 3px; height: 3px; border-radius: 50%; background: rgba(${color}, 1); box-shadow: 0 0 6px rgba(${color}, 0.6); pointer-events: none; z-index: 10; left: ${x}px; top: ${y}px;`; - return el; -}; - -const ParticleCard = ({ children, className, glowColor, onClick, style }) => { - const cardRef = useRef(null); - const particlesRef = useRef([]); - const timeoutsRef = useRef([]); - - const clearParticles = useCallback(() => { - timeoutsRef.current.forEach(clearTimeout); - timeoutsRef.current = []; - particlesRef.current.forEach((p) => { - gsap.to(p, { - scale: 0, - opacity: 0, - duration: 0.3, - onComplete: () => p.parentNode?.removeChild(p), - }); - }); - particlesRef.current = []; - }, []); - - useEffect(() => { - const el = cardRef.current; - if (!el) return; - - const handleMove = (e) => { - const r = el.getBoundingClientRect(); - el.style.setProperty( - "--glow-x", - `${((e.clientX - r.left) / r.width) * 100}%`, - ); - el.style.setProperty( - "--glow-y", - `${((e.clientY - r.top) / r.height) * 100}%`, - ); - }; - - const handleEnter = () => { - el.style.setProperty("--glow-intensity", "1"); - for (let i = 0; i < 8; i++) { - const timeout = setTimeout(() => { - if (!el) return; - const p = createParticleElement( - Math.random() * el.offsetWidth, - Math.random() * el.offsetHeight, - glowColor, - ); - el.appendChild(p); - particlesRef.current.push(p); - gsap.fromTo( - p, - { scale: 0, opacity: 0 }, - { scale: 1, opacity: 1, duration: 0.3 }, - ); - gsap.to(p, { - x: "+=" + (Math.random() - 0.5) * 40, - y: "+=" + (Math.random() - 0.5) * 40, - duration: 1.5 + Math.random(), - repeat: -1, - yoyo: true, - ease: "sine.inOut", - }); - }, i * 100); - timeoutsRef.current.push(timeout); - } - }; - - const handleLeave = () => { - el.style.setProperty("--glow-intensity", "0"); - clearParticles(); - }; - - el.addEventListener("mousemove", handleMove); - el.addEventListener("mouseenter", handleEnter); - el.addEventListener("mouseleave", handleLeave); - return () => { - el.removeEventListener("mousemove", handleMove); - el.removeEventListener("mouseenter", handleEnter); - el.removeEventListener("mouseleave", handleLeave); - clearParticles(); - }; - }, [glowColor, clearParticles]); - - return ( -
- {children} -
- ); -}; - -export default function MagicBento({ - enableBorderGlow = true, - glowColor = DEFAULT_GLOW_COLOR, -}) { - const navigate = useNavigate(); - - const handleCardClick = (link) => { - if (link.startsWith("http")) window.open(link, "_blank"); - else navigate(link); - }; - - return ( -
-
- {cardData.map((card, i) => ( - handleCardClick(card.link)} - className={`magic-bento-card ${enableBorderGlow ? "magic-bento-card--border-glow" : ""}`} - glowColor={glowColor} - style={{ - backgroundImage: card.image ? `url(${card.image})` : "none", - backgroundColor: card.color || "#060010", - }} - > - {card.image &&
} -
-
{card.label}
-
-
-

{card.title}

-

- {card.description} -

-
- - ))} -
-
- ); -} diff --git a/src/components/MagicBento.tsx b/src/components/MagicBento.tsx new file mode 100644 index 0000000..afd61a7 --- /dev/null +++ b/src/components/MagicBento.tsx @@ -0,0 +1,275 @@ +"use client"; + +import React, { useRef, useEffect, useCallback } from "react"; +import { useNavigate } from "react-router-dom"; +import { gsap } from "gsap"; + +// --- Interfaces --- +export interface CardDataItem { + title: string; + image: string; + description: string; + label: string; + link: string; + color?: string; +} + +export interface MagicBentoProps { + enableStars?: boolean; + enableSpotlight?: boolean; + enableBorderGlow?: boolean; + enableTilt?: boolean; + enableMagnetism?: boolean; + clickEffect?: boolean; + spotlightRadius?: number; + particleCount?: number; + glowColor?: string; + disableAnimations?: boolean; +} + +const DEFAULT_GLOW_COLOR = "183, 28, 28"; + +const cardData: CardDataItem[] = [ + { + title: "Metz Campus", + image: "/images/MC.png", + description: "Web platform for students.", + label: "Web site", + link: "https://metzcampus.fr", + }, + { + title: "Neo Tokyo Rush", + image: "/images/NTR.png", + description: "Cyberpunk beat 'em All.", + label: "Gamedev", + link: "/projects/neo-tokyo-rush", + }, + { + title: "About Co Hai Se", + image: "/images/Cohaise.jpg", + description: "Crafting the Web of Your Ambitions.", + label: "Identity", + link: "/cohaise", + }, + { + title: "Contact", + image: "/images/Contact.jpg", + description: "Reach out to me.", + label: "Network", + link: "/contact", + }, + { + title: "Затишок", + image: "/images/Zatyshok.png", + description: "Moodboard developed with love.", + label: "Desktop App", + link: "/projects/zatyshok", + }, + { + title: "Shadow Purge", + image: "/images/SPRotD.png", + description: "Hack n'slash RPG.", + label: "Gamedev", + link: "/projects/shadow-purge", + }, +]; + +const createParticle = (x: number, y: number, color: string) => { + const el = document.createElement("div"); + el.className = "absolute w-1 h-1 rounded-full pointer-events-none z-50"; + el.style.backgroundColor = `rgb(${color})`; + el.style.boxShadow = `0 0 6px rgba(${color}, 0.8)`; + el.style.left = `${x}px`; + el.style.top = `${y}px`; + return el; +}; + +const ParticleCard: React.FC<{ + card: CardDataItem; + glowColor: string; + enableBorderGlow: boolean; + enableTilt: boolean; + enableMagnetism: boolean; + onClick: (link: string) => void; + className?: string; +}> = ({ + card, + glowColor, + enableBorderGlow, + enableTilt, + enableMagnetism, + onClick, + className, +}) => { + const cardRef = useRef(null); + const particlesRef = useRef([]); + + const clearParticles = useCallback(() => { + particlesRef.current.forEach((p) => { + gsap.to(p, { + opacity: 0, + scale: 0, + duration: 0.3, + onComplete: () => p.remove(), + }); + }); + particlesRef.current = []; + }, []); + + useEffect(() => { + const el = cardRef.current; + if (!el) return; + + const handleMouseMove = (e: MouseEvent) => { + const rect = el.getBoundingClientRect(); + const x = e.clientX - rect.left; + const y = e.clientY - rect.top; + + el.style.setProperty("--glow-x", `${(x / rect.width) * 100}%`); + el.style.setProperty("--glow-y", `${(y / rect.height) * 100}%`); + + if (enableTilt) { + const rotateX = ((y - rect.height / 2) / (rect.height / 2)) * -5; + const rotateY = ((x - rect.width / 2) / (rect.width / 2)) * 5; + gsap.to(el, { rotateX, rotateY, duration: 0.2 }); + } + + if (enableMagnetism) { + gsap.to(el, { + x: (x - rect.width / 2) * 0.1, + y: (y - rect.height / 2) * 0.1, + duration: 0.3, + }); + } + }; + + const handleMouseEnter = () => { + el.style.setProperty("--glow-intensity", "1"); + for (let i = 0; i < 6; i++) { + const p = createParticle( + Math.random() * el.offsetWidth, + Math.random() * el.offsetHeight, + glowColor, + ); + el.appendChild(p); + particlesRef.current.push(p); + gsap.fromTo( + p, + { scale: 0, opacity: 0 }, + { scale: 1, opacity: 1, duration: 0.3 }, + ); + gsap.to(p, { + x: "+=" + (Math.random() - 0.5) * 50, + y: "+=" + (Math.random() - 0.5) * 50, + duration: 1.5 + Math.random(), + repeat: -1, + yoyo: true, + ease: "sine.inOut", + }); + } + }; + + const handleMouseLeave = () => { + el.style.setProperty("--glow-intensity", "0"); + gsap.to(el, { rotateX: 0, rotateY: 0, x: 0, y: 0, duration: 0.5 }); + clearParticles(); + }; + + el.addEventListener("mousemove", handleMouseMove); + el.addEventListener("mouseenter", handleMouseEnter); + el.addEventListener("mouseleave", handleMouseLeave); + return () => { + el.removeEventListener("mousemove", handleMouseMove); + el.removeEventListener("mouseenter", handleMouseEnter); + el.removeEventListener("mouseleave", handleMouseLeave); + clearParticles(); + }; + }, [glowColor, enableTilt, enableMagnetism, clearParticles]); + + return ( +
onClick(card.link)} + className={`cursor-target group relative flex flex-col justify-between aspect-4/3 min-h-55 w-full p-6 rounded-[20px] border border-[#1a0505] bg-[#050000] bg-cover bg-center overflow-hidden transition-all duration-300 z-10 hover:-translate-y-1 hover:shadow-[0_0_30px_rgba(183,28,28,0.2)] ${className}`} + style={{ + backgroundImage: `url(${card.image})`, + transformStyle: "preserve-3d", + }} + > +
+ + {enableBorderGlow && ( +
+ )} + +
+ + {card.label} + +
+ +
+

{card.title}

+

+ {card.description} +

+
+
+ ); +}; + +export default function MagicBento({ + enableBorderGlow = true, + glowColor = DEFAULT_GLOW_COLOR, + enableTilt = true, + enableMagnetism = true, +}: MagicBentoProps) { + const navigate = useNavigate(); + + const handleCardClick = (link: string) => { + if (link.startsWith("http")) window.open(link, "_blank"); + else navigate(link); + }; + + const spanClasses = [ + "col-span-1", + "lg:col-span-1", + "lg:col-span-2 lg:row-span-2", + "lg:col-span-2 lg:row-span-2 lg:col-start-1 lg:row-start-2", + "col-span-1", + "lg:col-start-4 lg:row-start-3", + ]; + + return ( +
+
+ {cardData.map((card, i) => ( + + ))} +
+
+ ); +} diff --git a/src/components/OrbitImages.tsx b/src/components/OrbitImages.tsx new file mode 100644 index 0000000..e69de29 diff --git a/src/components/ServiceDetails.jsx b/src/components/ServiceDetails.jsx deleted file mode 100644 index b899d92..0000000 --- a/src/components/ServiceDetails.jsx +++ /dev/null @@ -1,60 +0,0 @@ -export const WebService = () => ( -
-

Modern & Fast Websites

-

- Building clean, responsive websites using Next.js and React. I focus on - speed, visibility, and converting visitors into clients. -

-
    -
  • Showcase Websites (Landing Pages)
  • -
  • SEO & Performance Optimization
  • -
  • CMS Integration (Content Management)
  • -
-
-); - -export const MobileService = () => ( -
-

iOS & Android Apps

-

- Turning your ideas into real mobile apps. Using React Native to create - smooth experiences that work perfectly on all phones. -

-
    -
  • Cross-Platform Apps
  • -
  • App Store Submission Help
  • -
  • User-Friendly Interfaces
  • -
-
-); - -export const DesignService = () => ( -
-

UI/UX Design

-

- Simple and effective designs. I create interfaces that look good and help - users find what they need effortlessly. -

-
    -
  • Wireframing & Prototyping
  • -
  • Mobile-First Design
  • -
  • Visual Identity Basics
  • -
-
-); - -export const SoftwareService = () => ( -
-

Custom Solutions

-

- Need something specific? I build custom tools and dashboards to help - automate your daily tasks and save you time. -

-
    -
  • Custom Web Tools
  • -
  • Desktop Web App
  • -
  • Dashboard Creation
  • -
  • API Connections
  • -
-
-); diff --git a/src/components/ServiceDetails.tsx b/src/components/ServiceDetails.tsx new file mode 100644 index 0000000..9c804ce --- /dev/null +++ b/src/components/ServiceDetails.tsx @@ -0,0 +1,77 @@ +import React from "react"; + +// Un sous-composant pour éviter de répéter le style des tags/li +const ServiceTag = ({ children }: { children: React.ReactNode }) => ( +
  • + {children} +
  • +); + +export const WebService = () => ( +
    +

    + Modern & Fast Websites +

    +

    + Building clean, responsive websites using Next.js and React. I focus on + speed, visibility, and converting visitors into clients. +

    +
      + Showcase Websites (Landing Pages) + SEO & Performance Optimization + CMS Integration (Content Management) +
    +
    +); + +export const MobileService = () => ( +
    +

    + iOS & Android Apps +

    +

    + Turning your ideas into real mobile apps. Using React Native to create + smooth experiences that work perfectly on all phones. +

    +
      + Cross-Platform Apps + App Store Submission Help + User-Friendly Interfaces +
    +
    +); + +export const DesignService = () => ( +
    +

    + UI/UX Design +

    +

    + Simple and effective designs. I create interfaces that look good and help + users find what they need effortlessly. +

    +
      + Wireframing & Prototyping + Mobile-First Design + Visual Identity Basics +
    +
    +); + +export const SoftwareService = () => ( +
    +

    + Custom Solutions +

    +

    + Need something specific? I build custom tools and dashboards to help + automate your daily tasks and save you time. +

    +
      + Custom Web Tools + Desktop Web App + Dashboard Creation + API Connections +
    +
    +); diff --git a/src/components/SplashCursor.jsx b/src/components/SplashCursor.jsx deleted file mode 100644 index 7bab5a4..0000000 --- a/src/components/SplashCursor.jsx +++ /dev/null @@ -1,1070 +0,0 @@ -'use client'; -import { useEffect, useRef } from 'react'; - -function SplashCursor({ - SIM_RESOLUTION = 128, - DYE_RESOLUTION = 1440, - CAPTURE_RESOLUTION = 512, - DENSITY_DISSIPATION = 3.5, - VELOCITY_DISSIPATION = 2, - PRESSURE = 0.1, - PRESSURE_ITERATIONS = 20, - CURL = 3, - SPLAT_RADIUS = 0.2, - SPLAT_FORCE = 6000, - SHADING = true, - COLOR_UPDATE_SPEED = 10, - BACK_COLOR = { r: 0.5, g: 0, b: 0 }, - TRANSPARENT = true -}) { - const canvasRef = useRef(null); - const animationFrameId = useRef(null); - - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - - // Track if the effect is still active for cleanup - let isActive = true; - - function pointerPrototype() { - this.id = -1; - this.texcoordX = 0; - this.texcoordY = 0; - this.prevTexcoordX = 0; - this.prevTexcoordY = 0; - this.deltaX = 0; - this.deltaY = 0; - this.down = false; - this.moved = false; - this.color = [0, 0, 0]; - } - - let config = { - SIM_RESOLUTION, - DYE_RESOLUTION, - CAPTURE_RESOLUTION, - DENSITY_DISSIPATION, - VELOCITY_DISSIPATION, - PRESSURE, - PRESSURE_ITERATIONS, - CURL, - SPLAT_RADIUS, - SPLAT_FORCE, - SHADING, - COLOR_UPDATE_SPEED, - PAUSED: false, - BACK_COLOR, - TRANSPARENT - }; - - let pointers = [new pointerPrototype()]; - - const { gl, ext } = getWebGLContext(canvas); - if (!ext.supportLinearFiltering) { - config.DYE_RESOLUTION = 256; - config.SHADING = false; - } - - function getWebGLContext(canvas) { - const params = { - alpha: true, - depth: false, - stencil: false, - antialias: false, - preserveDrawingBuffer: false - }; - let gl = canvas.getContext('webgl2', params); - const isWebGL2 = !!gl; - if (!isWebGL2) gl = canvas.getContext('webgl', params) || canvas.getContext('experimental-webgl', params); - - let halfFloat; - let supportLinearFiltering; - if (isWebGL2) { - gl.getExtension('EXT_color_buffer_float'); - supportLinearFiltering = gl.getExtension('OES_texture_float_linear'); - } else { - halfFloat = gl.getExtension('OES_texture_half_float'); - supportLinearFiltering = gl.getExtension('OES_texture_half_float_linear'); - } - gl.clearColor(0.0, 0.0, 0.0, 1.0); - - const halfFloatTexType = isWebGL2 ? gl.HALF_FLOAT : halfFloat && halfFloat.HALF_FLOAT_OES; - let formatRGBA; - let formatRG; - let formatR; - - if (isWebGL2) { - formatRGBA = getSupportedFormat(gl, gl.RGBA16F, gl.RGBA, halfFloatTexType); - formatRG = getSupportedFormat(gl, gl.RG16F, gl.RG, halfFloatTexType); - formatR = getSupportedFormat(gl, gl.R16F, gl.RED, halfFloatTexType); - } else { - formatRGBA = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - formatRG = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - formatR = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - } - - return { - gl, - ext: { - formatRGBA, - formatRG, - formatR, - halfFloatTexType, - supportLinearFiltering - } - }; - } - - function getSupportedFormat(gl, internalFormat, format, type) { - if (!supportRenderTextureFormat(gl, internalFormat, format, type)) { - switch (internalFormat) { - case gl.R16F: - return getSupportedFormat(gl, gl.RG16F, gl.RG, type); - case gl.RG16F: - return getSupportedFormat(gl, gl.RGBA16F, gl.RGBA, type); - default: - return null; - } - } - return { internalFormat, format }; - } - - function supportRenderTextureFormat(gl, internalFormat, format, type) { - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 4, 4, 0, format, type, null); - const fbo = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); - const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); - return status === gl.FRAMEBUFFER_COMPLETE; - } - - class Material { - constructor(vertexShader, fragmentShaderSource) { - this.vertexShader = vertexShader; - this.fragmentShaderSource = fragmentShaderSource; - this.programs = []; - this.activeProgram = null; - this.uniforms = []; - } - setKeywords(keywords) { - let hash = 0; - for (let i = 0; i < keywords.length; i++) hash += hashCode(keywords[i]); - let program = this.programs[hash]; - if (program == null) { - let fragmentShader = compileShader(gl.FRAGMENT_SHADER, this.fragmentShaderSource, keywords); - program = createProgram(this.vertexShader, fragmentShader); - this.programs[hash] = program; - } - if (program === this.activeProgram) return; - this.uniforms = getUniforms(program); - this.activeProgram = program; - } - bind() { - gl.useProgram(this.activeProgram); - } - } - - class Program { - constructor(vertexShader, fragmentShader) { - this.uniforms = {}; - this.program = createProgram(vertexShader, fragmentShader); - this.uniforms = getUniforms(this.program); - } - bind() { - gl.useProgram(this.program); - } - } - - function createProgram(vertexShader, fragmentShader) { - let program = gl.createProgram(); - gl.attachShader(program, vertexShader); - gl.attachShader(program, fragmentShader); - gl.linkProgram(program); - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) console.trace(gl.getProgramInfoLog(program)); - return program; - } - - function getUniforms(program) { - let uniforms = []; - let uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (let i = 0; i < uniformCount; i++) { - let uniformName = gl.getActiveUniform(program, i).name; - uniforms[uniformName] = gl.getUniformLocation(program, uniformName); - } - return uniforms; - } - - function compileShader(type, source, keywords) { - source = addKeywords(source, keywords); - const shader = gl.createShader(type); - gl.shaderSource(shader, source); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) console.trace(gl.getShaderInfoLog(shader)); - return shader; - } - - function addKeywords(source, keywords) { - if (!keywords) return source; - let keywordsString = ''; - keywords.forEach(keyword => { - keywordsString += '#define ' + keyword + '\n'; - }); - return keywordsString + source; - } - - const baseVertexShader = compileShader( - gl.VERTEX_SHADER, - ` - precision highp float; - attribute vec2 aPosition; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform vec2 texelSize; - - void main () { - vUv = aPosition * 0.5 + 0.5; - vL = vUv - vec2(texelSize.x, 0.0); - vR = vUv + vec2(texelSize.x, 0.0); - vT = vUv + vec2(0.0, texelSize.y); - vB = vUv - vec2(0.0, texelSize.y); - gl_Position = vec4(aPosition, 0.0, 1.0); - } - ` - ); - - const copyShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - uniform sampler2D uTexture; - - void main () { - gl_FragColor = texture2D(uTexture, vUv); - } - ` - ); - - const clearShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - uniform sampler2D uTexture; - uniform float value; - - void main () { - gl_FragColor = value * texture2D(uTexture, vUv); - } - ` - ); - - const displayShaderSource = ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform sampler2D uTexture; - uniform sampler2D uDithering; - uniform vec2 ditherScale; - uniform vec2 texelSize; - - vec3 linearToGamma (vec3 color) { - color = max(color, vec3(0)); - return max(1.055 * pow(color, vec3(0.416666667)) - 0.055, vec3(0)); - } - - void main () { - vec3 c = texture2D(uTexture, vUv).rgb; - #ifdef SHADING - vec3 lc = texture2D(uTexture, vL).rgb; - vec3 rc = texture2D(uTexture, vR).rgb; - vec3 tc = texture2D(uTexture, vT).rgb; - vec3 bc = texture2D(uTexture, vB).rgb; - - float dx = length(rc) - length(lc); - float dy = length(tc) - length(bc); - - vec3 n = normalize(vec3(dx, dy, length(texelSize))); - vec3 l = vec3(0.0, 0.0, 1.0); - - float diffuse = clamp(dot(n, l) + 0.7, 0.7, 1.0); - c *= diffuse; - #endif - - float a = max(c.r, max(c.g, c.b)); - gl_FragColor = vec4(c, a); - } - `; - - const splatShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D uTarget; - uniform float aspectRatio; - uniform vec3 color; - uniform vec2 point; - uniform float radius; - - void main () { - vec2 p = vUv - point.xy; - p.x *= aspectRatio; - vec3 splat = exp(-dot(p, p) / radius) * color; - vec3 base = texture2D(uTarget, vUv).xyz; - gl_FragColor = vec4(base + splat, 1.0); - } - ` - ); - - const advectionShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D uVelocity; - uniform sampler2D uSource; - uniform vec2 texelSize; - uniform vec2 dyeTexelSize; - uniform float dt; - uniform float dissipation; - - vec4 bilerp (sampler2D sam, vec2 uv, vec2 tsize) { - vec2 st = uv / tsize - 0.5; - vec2 iuv = floor(st); - vec2 fuv = fract(st); - - vec4 a = texture2D(sam, (iuv + vec2(0.5, 0.5)) * tsize); - vec4 b = texture2D(sam, (iuv + vec2(1.5, 0.5)) * tsize); - vec4 c = texture2D(sam, (iuv + vec2(0.5, 1.5)) * tsize); - vec4 d = texture2D(sam, (iuv + vec2(1.5, 1.5)) * tsize); - - return mix(mix(a, b, fuv.x), mix(c, d, fuv.x), fuv.y); - } - - void main () { - #ifdef MANUAL_FILTERING - vec2 coord = vUv - dt * bilerp(uVelocity, vUv, texelSize).xy * texelSize; - vec4 result = bilerp(uSource, coord, dyeTexelSize); - #else - vec2 coord = vUv - dt * texture2D(uVelocity, vUv).xy * texelSize; - vec4 result = texture2D(uSource, coord); - #endif - float decay = 1.0 + dissipation * dt; - gl_FragColor = result / decay; - } - `, - ext.supportLinearFiltering ? null : ['MANUAL_FILTERING'] - ); - - const divergenceShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uVelocity, vL).x; - float R = texture2D(uVelocity, vR).x; - float T = texture2D(uVelocity, vT).y; - float B = texture2D(uVelocity, vB).y; - - vec2 C = texture2D(uVelocity, vUv).xy; - if (vL.x < 0.0) { L = -C.x; } - if (vR.x > 1.0) { R = -C.x; } - if (vT.y > 1.0) { T = -C.y; } - if (vB.y < 0.0) { B = -C.y; } - - float div = 0.5 * (R - L + T - B); - gl_FragColor = vec4(div, 0.0, 0.0, 1.0); - } - ` - ); - - const curlShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uVelocity, vL).y; - float R = texture2D(uVelocity, vR).y; - float T = texture2D(uVelocity, vT).x; - float B = texture2D(uVelocity, vB).x; - float vorticity = R - L - T + B; - gl_FragColor = vec4(0.5 * vorticity, 0.0, 0.0, 1.0); - } - ` - ); - - const vorticityShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform sampler2D uVelocity; - uniform sampler2D uCurl; - uniform float curl; - uniform float dt; - - void main () { - float L = texture2D(uCurl, vL).x; - float R = texture2D(uCurl, vR).x; - float T = texture2D(uCurl, vT).x; - float B = texture2D(uCurl, vB).x; - float C = texture2D(uCurl, vUv).x; - - vec2 force = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L)); - force /= length(force) + 0.0001; - force *= curl * C; - force.y *= -1.0; - - vec2 velocity = texture2D(uVelocity, vUv).xy; - velocity += force * dt; - velocity = min(max(velocity, -1000.0), 1000.0); - gl_FragColor = vec4(velocity, 0.0, 1.0); - } - ` - ); - - const pressureShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uPressure; - uniform sampler2D uDivergence; - - void main () { - float L = texture2D(uPressure, vL).x; - float R = texture2D(uPressure, vR).x; - float T = texture2D(uPressure, vT).x; - float B = texture2D(uPressure, vB).x; - float C = texture2D(uPressure, vUv).x; - float divergence = texture2D(uDivergence, vUv).x; - float pressure = (L + R + B + T - divergence) * 0.25; - gl_FragColor = vec4(pressure, 0.0, 0.0, 1.0); - } - ` - ); - - const gradientSubtractShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uPressure; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uPressure, vL).x; - float R = texture2D(uPressure, vR).x; - float T = texture2D(uPressure, vT).x; - float B = texture2D(uPressure, vB).x; - vec2 velocity = texture2D(uVelocity, vUv).xy; - velocity.xy -= vec2(R - L, T - B); - gl_FragColor = vec4(velocity, 0.0, 1.0); - } - ` - ); - - const blit = (() => { - gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), gl.STATIC_DRAW); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 0, 2, 3]), gl.STATIC_DRAW); - gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); - gl.enableVertexAttribArray(0); - return (target, clear = false) => { - if (target == null) { - gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - } else { - gl.viewport(0, 0, target.width, target.height); - gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo); - } - if (clear) { - gl.clearColor(0.0, 0.0, 0.0, 1.0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); - }; - })(); - - let dye, velocity, divergence, curl, pressure; - - const copyProgram = new Program(baseVertexShader, copyShader); - const clearProgram = new Program(baseVertexShader, clearShader); - const splatProgram = new Program(baseVertexShader, splatShader); - const advectionProgram = new Program(baseVertexShader, advectionShader); - const divergenceProgram = new Program(baseVertexShader, divergenceShader); - const curlProgram = new Program(baseVertexShader, curlShader); - const vorticityProgram = new Program(baseVertexShader, vorticityShader); - const pressureProgram = new Program(baseVertexShader, pressureShader); - const gradienSubtractProgram = new Program(baseVertexShader, gradientSubtractShader); - const displayMaterial = new Material(baseVertexShader, displayShaderSource); - - function initFramebuffers() { - let simRes = getResolution(config.SIM_RESOLUTION); - let dyeRes = getResolution(config.DYE_RESOLUTION); - const texType = ext.halfFloatTexType; - const rgba = ext.formatRGBA; - const rg = ext.formatRG; - const r = ext.formatR; - const filtering = ext.supportLinearFiltering ? gl.LINEAR : gl.NEAREST; - gl.disable(gl.BLEND); - - if (!dye) - dye = createDoubleFBO(dyeRes.width, dyeRes.height, rgba.internalFormat, rgba.format, texType, filtering); - else - dye = resizeDoubleFBO(dye, dyeRes.width, dyeRes.height, rgba.internalFormat, rgba.format, texType, filtering); - - if (!velocity) - velocity = createDoubleFBO(simRes.width, simRes.height, rg.internalFormat, rg.format, texType, filtering); - else - velocity = resizeDoubleFBO( - velocity, - simRes.width, - simRes.height, - rg.internalFormat, - rg.format, - texType, - filtering - ); - - divergence = createFBO(simRes.width, simRes.height, r.internalFormat, r.format, texType, gl.NEAREST); - curl = createFBO(simRes.width, simRes.height, r.internalFormat, r.format, texType, gl.NEAREST); - pressure = createDoubleFBO(simRes.width, simRes.height, r.internalFormat, r.format, texType, gl.NEAREST); - } - - function createFBO(w, h, internalFormat, format, type, param) { - gl.activeTexture(gl.TEXTURE0); - let texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, param); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, param); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, w, h, 0, format, type, null); - - let fbo = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); - gl.viewport(0, 0, w, h); - gl.clear(gl.COLOR_BUFFER_BIT); - - let texelSizeX = 1.0 / w; - let texelSizeY = 1.0 / h; - return { - texture, - fbo, - width: w, - height: h, - texelSizeX, - texelSizeY, - attach(id) { - gl.activeTexture(gl.TEXTURE0 + id); - gl.bindTexture(gl.TEXTURE_2D, texture); - return id; - } - }; - } - - function createDoubleFBO(w, h, internalFormat, format, type, param) { - let fbo1 = createFBO(w, h, internalFormat, format, type, param); - let fbo2 = createFBO(w, h, internalFormat, format, type, param); - return { - width: w, - height: h, - texelSizeX: fbo1.texelSizeX, - texelSizeY: fbo1.texelSizeY, - get read() { - return fbo1; - }, - set read(value) { - fbo1 = value; - }, - get write() { - return fbo2; - }, - set write(value) { - fbo2 = value; - }, - swap() { - let temp = fbo1; - fbo1 = fbo2; - fbo2 = temp; - } - }; - } - - function resizeFBO(target, w, h, internalFormat, format, type, param) { - let newFBO = createFBO(w, h, internalFormat, format, type, param); - copyProgram.bind(); - gl.uniform1i(copyProgram.uniforms.uTexture, target.attach(0)); - blit(newFBO); - return newFBO; - } - - function resizeDoubleFBO(target, w, h, internalFormat, format, type, param) { - if (target.width === w && target.height === h) return target; - target.read = resizeFBO(target.read, w, h, internalFormat, format, type, param); - target.write = createFBO(w, h, internalFormat, format, type, param); - target.width = w; - target.height = h; - target.texelSizeX = 1.0 / w; - target.texelSizeY = 1.0 / h; - return target; - } - - function updateKeywords() { - let displayKeywords = []; - if (config.SHADING) displayKeywords.push('SHADING'); - displayMaterial.setKeywords(displayKeywords); - } - - updateKeywords(); - initFramebuffers(); - let lastUpdateTime = Date.now(); - let colorUpdateTimer = 0.0; - - function updateFrame() { - if (!isActive) return; - const dt = calcDeltaTime(); - if (resizeCanvas()) initFramebuffers(); - updateColors(dt); - applyInputs(); - step(dt); - render(null); - animationFrameId.current = requestAnimationFrame(updateFrame); - } - - function calcDeltaTime() { - let now = Date.now(); - let dt = (now - lastUpdateTime) / 1000; - dt = Math.min(dt, 0.016666); - lastUpdateTime = now; - return dt; - } - - function resizeCanvas() { - let width = scaleByPixelRatio(canvas.clientWidth); - let height = scaleByPixelRatio(canvas.clientHeight); - if (canvas.width !== width || canvas.height !== height) { - canvas.width = width; - canvas.height = height; - return true; - } - return false; - } - - function updateColors(dt) { - colorUpdateTimer += dt * config.COLOR_UPDATE_SPEED; - if (colorUpdateTimer >= 1) { - colorUpdateTimer = wrap(colorUpdateTimer, 0, 1); - pointers.forEach(p => { - p.color = generateColor(); - }); - } - } - - function applyInputs() { - pointers.forEach(p => { - if (p.moved) { - p.moved = false; - splatPointer(p); - } - }); - } - - function step(dt) { - gl.disable(gl.BLEND); - curlProgram.bind(); - gl.uniform2f(curlProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - gl.uniform1i(curlProgram.uniforms.uVelocity, velocity.read.attach(0)); - blit(curl); - - vorticityProgram.bind(); - gl.uniform2f(vorticityProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - gl.uniform1i(vorticityProgram.uniforms.uVelocity, velocity.read.attach(0)); - gl.uniform1i(vorticityProgram.uniforms.uCurl, curl.attach(1)); - gl.uniform1f(vorticityProgram.uniforms.curl, config.CURL); - gl.uniform1f(vorticityProgram.uniforms.dt, dt); - blit(velocity.write); - velocity.swap(); - - divergenceProgram.bind(); - gl.uniform2f(divergenceProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - gl.uniform1i(divergenceProgram.uniforms.uVelocity, velocity.read.attach(0)); - blit(divergence); - - clearProgram.bind(); - gl.uniform1i(clearProgram.uniforms.uTexture, pressure.read.attach(0)); - gl.uniform1f(clearProgram.uniforms.value, config.PRESSURE); - blit(pressure.write); - pressure.swap(); - - pressureProgram.bind(); - gl.uniform2f(pressureProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - gl.uniform1i(pressureProgram.uniforms.uDivergence, divergence.attach(0)); - for (let i = 0; i < config.PRESSURE_ITERATIONS; i++) { - gl.uniform1i(pressureProgram.uniforms.uPressure, pressure.read.attach(1)); - blit(pressure.write); - pressure.swap(); - } - - gradienSubtractProgram.bind(); - gl.uniform2f(gradienSubtractProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - gl.uniform1i(gradienSubtractProgram.uniforms.uPressure, pressure.read.attach(0)); - gl.uniform1i(gradienSubtractProgram.uniforms.uVelocity, velocity.read.attach(1)); - blit(velocity.write); - velocity.swap(); - - advectionProgram.bind(); - gl.uniform2f(advectionProgram.uniforms.texelSize, velocity.texelSizeX, velocity.texelSizeY); - if (!ext.supportLinearFiltering) - gl.uniform2f(advectionProgram.uniforms.dyeTexelSize, velocity.texelSizeX, velocity.texelSizeY); - let velocityId = velocity.read.attach(0); - gl.uniform1i(advectionProgram.uniforms.uVelocity, velocityId); - gl.uniform1i(advectionProgram.uniforms.uSource, velocityId); - gl.uniform1f(advectionProgram.uniforms.dt, dt); - gl.uniform1f(advectionProgram.uniforms.dissipation, config.VELOCITY_DISSIPATION); - blit(velocity.write); - velocity.swap(); - - if (!ext.supportLinearFiltering) - gl.uniform2f(advectionProgram.uniforms.dyeTexelSize, dye.texelSizeX, dye.texelSizeY); - gl.uniform1i(advectionProgram.uniforms.uVelocity, velocity.read.attach(0)); - gl.uniform1i(advectionProgram.uniforms.uSource, dye.read.attach(1)); - gl.uniform1f(advectionProgram.uniforms.dissipation, config.DENSITY_DISSIPATION); - blit(dye.write); - dye.swap(); - } - - function render(target) { - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - gl.enable(gl.BLEND); - drawDisplay(target); - } - - function drawDisplay(target) { - let width = target == null ? gl.drawingBufferWidth : target.width; - let height = target == null ? gl.drawingBufferHeight : target.height; - displayMaterial.bind(); - if (config.SHADING) gl.uniform2f(displayMaterial.uniforms.texelSize, 1.0 / width, 1.0 / height); - gl.uniform1i(displayMaterial.uniforms.uTexture, dye.read.attach(0)); - blit(target); - } - - function splatPointer(pointer) { - let dx = pointer.deltaX * config.SPLAT_FORCE; - let dy = pointer.deltaY * config.SPLAT_FORCE; - splat(pointer.texcoordX, pointer.texcoordY, dx, dy, pointer.color); - } - - function clickSplat(pointer) { - const color = generateColor(); - color.r *= 10.0; - color.g *= 10.0; - color.b *= 10.0; - let dx = 10 * (Math.random() - 0.5); - let dy = 30 * (Math.random() - 0.5); - splat(pointer.texcoordX, pointer.texcoordY, dx, dy, color); - } - - function splat(x, y, dx, dy, color) { - splatProgram.bind(); - gl.uniform1i(splatProgram.uniforms.uTarget, velocity.read.attach(0)); - gl.uniform1f(splatProgram.uniforms.aspectRatio, canvas.width / canvas.height); - gl.uniform2f(splatProgram.uniforms.point, x, y); - gl.uniform3f(splatProgram.uniforms.color, dx, dy, 0.0); - gl.uniform1f(splatProgram.uniforms.radius, correctRadius(config.SPLAT_RADIUS / 100.0)); - blit(velocity.write); - velocity.swap(); - - gl.uniform1i(splatProgram.uniforms.uTarget, dye.read.attach(0)); - gl.uniform3f(splatProgram.uniforms.color, color.r, color.g, color.b); - blit(dye.write); - dye.swap(); - } - - function correctRadius(radius) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio > 1) radius *= aspectRatio; - return radius; - } - - function updatePointerDownData(pointer, id, posX, posY) { - pointer.id = id; - pointer.down = true; - pointer.moved = false; - pointer.texcoordX = posX / canvas.width; - pointer.texcoordY = 1.0 - posY / canvas.height; - pointer.prevTexcoordX = pointer.texcoordX; - pointer.prevTexcoordY = pointer.texcoordY; - pointer.deltaX = 0; - pointer.deltaY = 0; - pointer.color = generateColor(); - } - - function updatePointerMoveData(pointer, posX, posY, color) { - pointer.prevTexcoordX = pointer.texcoordX; - pointer.prevTexcoordY = pointer.texcoordY; - pointer.texcoordX = posX / canvas.width; - pointer.texcoordY = 1.0 - posY / canvas.height; - pointer.deltaX = correctDeltaX(pointer.texcoordX - pointer.prevTexcoordX); - pointer.deltaY = correctDeltaY(pointer.texcoordY - pointer.prevTexcoordY); - pointer.moved = Math.abs(pointer.deltaX) > 0 || Math.abs(pointer.deltaY) > 0; - pointer.color = color; - } - - function updatePointerUpData(pointer) { - pointer.down = false; - } - - function correctDeltaX(delta) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio < 1) delta *= aspectRatio; - return delta; - } - - function correctDeltaY(delta) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio > 1) delta /= aspectRatio; - return delta; - } - - function generateColor() { - let c = HSVtoRGB(Math.random(), 1.0, 1.0); - c.r *= 0.15; - c.g *= 0.15; - c.b *= 0.15; - return c; - } - - function HSVtoRGB(h, s, v) { - let r, g, b, i, f, p, q, t; - i = Math.floor(h * 6); - f = h * 6 - i; - p = v * (1 - s); - q = v * (1 - f * s); - t = v * (1 - (1 - f) * s); - switch (i % 6) { - case 0: - r = v; - g = t; - b = p; - break; - case 1: - r = q; - g = v; - b = p; - break; - case 2: - r = p; - g = v; - b = t; - break; - case 3: - r = p; - g = q; - b = v; - break; - case 4: - r = t; - g = p; - b = v; - break; - case 5: - r = v; - g = p; - b = q; - break; - default: - break; - } - return { r, g, b }; - } - - function wrap(value, min, max) { - const range = max - min; - if (range === 0) return min; - return ((value - min) % range) + min; - } - - function getResolution(resolution) { - let aspectRatio = gl.drawingBufferWidth / gl.drawingBufferHeight; - if (aspectRatio < 1) aspectRatio = 1.0 / aspectRatio; - const min = Math.round(resolution); - const max = Math.round(resolution * aspectRatio); - if (gl.drawingBufferWidth > gl.drawingBufferHeight) return { width: max, height: min }; - else return { width: min, height: max }; - } - - function scaleByPixelRatio(input) { - const pixelRatio = window.devicePixelRatio || 1; - return Math.floor(input * pixelRatio); - } - - function hashCode(s) { - if (s.length === 0) return 0; - let hash = 0; - for (let i = 0; i < s.length; i++) { - hash = (hash << 5) - hash + s.charCodeAt(i); - hash |= 0; - } - return hash; - } - - // Named event handlers for proper cleanup - function handleMouseDown(e) { - let pointer = pointers[0]; - let posX = scaleByPixelRatio(e.clientX); - let posY = scaleByPixelRatio(e.clientY); - updatePointerDownData(pointer, -1, posX, posY); - clickSplat(pointer); - } - - let firstMouseMoveHandled = false; - function handleMouseMove(e) { - let pointer = pointers[0]; - let posX = scaleByPixelRatio(e.clientX); - let posY = scaleByPixelRatio(e.clientY); - if (!firstMouseMoveHandled) { - let color = generateColor(); - updatePointerMoveData(pointer, posX, posY, color); - firstMouseMoveHandled = true; - } else { - updatePointerMoveData(pointer, posX, posY, pointer.color); - } - } - - function handleTouchStart(e) { - const touches = e.targetTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - let posX = scaleByPixelRatio(touches[i].clientX); - let posY = scaleByPixelRatio(touches[i].clientY); - updatePointerDownData(pointer, touches[i].identifier, posX, posY); - } - } - - function handleTouchMove(e) { - const touches = e.targetTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - let posX = scaleByPixelRatio(touches[i].clientX); - let posY = scaleByPixelRatio(touches[i].clientY); - updatePointerMoveData(pointer, posX, posY, pointer.color); - } - } - - function handleTouchEnd(e) { - const touches = e.changedTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - updatePointerUpData(pointer); - } - } - - // Add event listeners - window.addEventListener('mousedown', handleMouseDown); - window.addEventListener('mousemove', handleMouseMove); - window.addEventListener('touchstart', handleTouchStart); - window.addEventListener('touchmove', handleTouchMove, false); - window.addEventListener('touchend', handleTouchEnd); - - updateFrame(); - - // Cleanup function - return () => { - isActive = false; - - // Cancel animation frame - if (animationFrameId.current) { - cancelAnimationFrame(animationFrameId.current); - animationFrameId.current = null; - } - - // Remove event listeners - window.removeEventListener('mousedown', handleMouseDown); - window.removeEventListener('mousemove', handleMouseMove); - window.removeEventListener('touchstart', handleTouchStart); - window.removeEventListener('touchmove', handleTouchMove); - window.removeEventListener('touchend', handleTouchEnd); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return ( -
    - -
    - ); -} - -export default SplashCursor; diff --git a/src/components/backgrounds/BackgroundWrapper.jsx b/src/components/backgrounds/BackgroundWrapper.tsx similarity index 96% rename from src/components/backgrounds/BackgroundWrapper.jsx rename to src/components/backgrounds/BackgroundWrapper.tsx index e66b112..2915684 100644 --- a/src/components/backgrounds/BackgroundWrapper.jsx +++ b/src/components/backgrounds/BackgroundWrapper.tsx @@ -11,7 +11,6 @@ export default function BackgroundWrapper() { return ( <> - {/* 1. COUCHE CURSEURS */}
    - {/* 2. COUCHE BACKGROUNDS */}
    0.0) { - vec2 centerUV = vec2(0.0, 0.0); - float centerDist = length(uv - centerUV); - vec2 repulsion = normalize(uv - centerUV) * (uAutoCenterRepulsion / (centerDist + 0.1)); + float centerDist = length(uv); + vec2 repulsion = normalize(uv) * (uAutoCenterRepulsion / (centerDist + 0.1)); uv += repulsion * 0.05; } else if (uMouseRepulsion) { vec2 mousePosUV = (uMouse * uResolution.xy - focalPx) / uResolution.y; @@ -139,36 +115,49 @@ void main() { vec2 repulsion = normalize(uv - mousePosUV) * (uRepulsionStrength / (mouseDist + 0.1)); uv += repulsion * 0.05 * uMouseActiveFactor; } else { - vec2 mouseOffset = mouseNorm * 0.1 * uMouseActiveFactor; - uv += mouseOffset; + uv += mouseNorm * 0.1 * uMouseActiveFactor; } - float autoRotAngle = uTime * uRotationSpeed; mat2 autoRot = mat2(cos(autoRotAngle), -sin(autoRotAngle), sin(autoRotAngle), cos(autoRotAngle)); uv = autoRot * uv; - uv = mat2(uRotation.x, -uRotation.y, uRotation.y, uRotation.x) * uv; - vec3 col = vec3(0.0); - for (float i = 0.0; i < 1.0; i += 1.0 / NUM_LAYER) { float depth = fract(i + uStarSpeed * uSpeed); float scale = mix(20.0 * uDensity, 0.5 * uDensity, depth); float fade = depth * smoothstep(1.0, 0.9, depth); - col += StarLayer(uv * scale + i * 453.32) * fade; + col += StarLayer(uv * scale + i * 453.32, uTime, uSpeed, uStarSpeed, uHueShift, uSaturation, uGlowIntensity, uTwinkleIntensity) * fade; } - if (uTransparent) { - float alpha = length(col); - alpha = smoothstep(0.0, 0.3, alpha); - alpha = min(alpha, 1.0); - gl_FragColor = vec4(col, alpha); + float alpha = smoothstep(0.0, 0.3, length(col)); + gl_FragColor = vec4(col, min(alpha, 1.0)); } else { gl_FragColor = vec4(col, 1.0); } } `; +// --- INTERFACE DES PROPS --- +interface GalaxyProps { + focal?: [number, number]; + rotation?: [number, number]; + starSpeed?: number; + density?: number; + hueShift?: number; + disableAnimation?: boolean; + speed?: number; + mouseInteraction?: boolean; + glowIntensity?: number; + saturation?: number; + mouseRepulsion?: boolean; + repulsionStrength?: number; + twinkleIntensity?: number; + rotationSpeed?: number; + autoCenterRepulsion?: number; + transparent?: boolean; + [key: string]: any; +} + export default function Galaxy({ focal = [0.5, 0.5], rotation = [0.5, 0.5], @@ -187,8 +176,9 @@ export default function Galaxy({ autoCenterRepulsion = 10, transparent = true, ...rest -}) { - const ctnDom = useRef(null); +}: GalaxyProps) { + const ctnDom = useRef(null); + const [opacity, setOpacity] = useState(0); const targetMousePos = useRef({ x: 0.5, y: 0.5 }); const smoothMousePos = useRef({ x: 0.5, y: 0.5 }); const targetMouseActive = useRef(0.0); @@ -197,6 +187,7 @@ export default function Galaxy({ useEffect(() => { if (!ctnDom.current) return; const ctn = ctnDom.current; + const renderer = new Renderer({ alpha: transparent, premultipliedAlpha: false, @@ -206,16 +197,13 @@ export default function Galaxy({ if (transparent) { gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); - gl.clearColor(0, 0, 0, 0); - } else { - gl.clearColor(0, 0, 0, 1); } - let program; + let program: Program; function resize() { - const scale = 1; - renderer.setSize(ctn.offsetWidth * scale, ctn.offsetHeight * scale); + if (!ctn) return; + renderer.setSize(ctn.offsetWidth, ctn.offsetHeight); if (program) { program.uniforms.uResolution.value = new Color( gl.canvas.width, @@ -224,8 +212,8 @@ export default function Galaxy({ ); } } - window.addEventListener("resize", resize, false); - resize(); + + window.addEventListener("resize", resize); const geometry = new Triangle(gl); program = new Program(gl, { @@ -233,25 +221,14 @@ export default function Galaxy({ fragment: fragmentShader, uniforms: { uTime: { value: 0 }, - uResolution: { - value: new Color( - gl.canvas.width, - gl.canvas.height, - gl.canvas.width / gl.canvas.height, - ), - }, + uResolution: { value: new Color(1, 1, 1) }, uFocal: { value: new Float32Array(focal) }, uRotation: { value: new Float32Array(rotation) }, uStarSpeed: { value: starSpeed }, uDensity: { value: density }, uHueShift: { value: hueShift }, uSpeed: { value: speed }, - uMouse: { - value: new Float32Array([ - smoothMousePos.current.x, - smoothMousePos.current.y, - ]), - }, + uMouse: { value: new Float32Array([0.5, 0.5]) }, uGlowIntensity: { value: glowIntensity }, uSaturation: { value: saturation }, uMouseRepulsion: { value: mouseRepulsion }, @@ -264,41 +241,43 @@ export default function Galaxy({ }, }); - const mesh = new Mesh(gl, { geometry, program }); - let animateId; + resize(); - function update(t) { + const mesh = new Mesh(gl, { geometry, program }); + let animateId: number; + + function update(t: number) { animateId = requestAnimationFrame(update); if (!disableAnimation) { program.uniforms.uTime.value = t * 0.001; program.uniforms.uStarSpeed.value = (t * 0.001 * starSpeed) / 10.0; } - - const lerpFactor = 0.05; + const lerp = 0.05; smoothMousePos.current.x += - (targetMousePos.current.x - smoothMousePos.current.x) * lerpFactor; + (targetMousePos.current.x - smoothMousePos.current.x) * lerp; smoothMousePos.current.y += - (targetMousePos.current.y - smoothMousePos.current.y) * lerpFactor; - + (targetMousePos.current.y - smoothMousePos.current.y) * lerp; smoothMouseActive.current += - (targetMouseActive.current - smoothMouseActive.current) * lerpFactor; - + (targetMouseActive.current - smoothMouseActive.current) * lerp; program.uniforms.uMouse.value[0] = smoothMousePos.current.x; program.uniforms.uMouse.value[1] = smoothMousePos.current.y; program.uniforms.uMouseActiveFactor.value = smoothMouseActive.current; - renderer.render({ scene: mesh }); } + animateId = requestAnimationFrame(update); ctn.appendChild(gl.canvas); - // --- CORRECTION MAJEURE ICI --- - function handleMouseMove(e) { - // On calcule par rapport à la fenêtre globale - const x = e.clientX / window.innerWidth; - const y = 1.0 - e.clientY / window.innerHeight; + // 2. DÉCLENCHEMENT DU FADE IN + const timer = setTimeout(() => { + setOpacity(1); + }, 100); - targetMousePos.current = { x, y }; + function handleMouseMove(e: MouseEvent) { + targetMousePos.current = { + x: e.clientX / window.innerWidth, + y: 1.0 - e.clientY / window.innerHeight, + }; targetMouseActive.current = 1.0; } @@ -307,18 +286,16 @@ export default function Galaxy({ } return () => { + clearTimeout(timer); cancelAnimationFrame(animateId); window.removeEventListener("resize", resize); - - // NETTOYAGE CORRECT : On enlève l'écouteur de window, pas de ctn - if (mouseInteraction) { - window.removeEventListener("mousemove", handleMouseMove); - } - + window.removeEventListener("mousemove", handleMouseMove); + const extension = gl.getExtension("WEBGL_lose_context"); + if (extension) extension.loseContext(); if (ctn.contains(gl.canvas)) { ctn.removeChild(gl.canvas); } - gl.getExtension("WEBGL_lose_context")?.loseContext(); + geometry.remove(); }; }, [ focal, @@ -339,5 +316,19 @@ export default function Galaxy({ transparent, ]); - return
    ; + return ( +
    + ); } diff --git a/src/components/backgrounds/LightPillar.css b/src/components/backgrounds/LightPillar.css deleted file mode 100644 index 718d072..0000000 --- a/src/components/backgrounds/LightPillar.css +++ /dev/null @@ -1,21 +0,0 @@ -.light-pillar-fallback { - width: 100%; - height: 100%; - position: absolute; - top: 0; - left: 0; - display: flex; - align-items: center; - justify-content: center; - background-color: rgba(0, 0, 0, 0.1); - color: #888; - font-size: 14px; -} - -.light-pillar-container { - width: 100%; - height: 100%; - position: absolute; - top: 0; - left: 0; -} diff --git a/src/components/backgrounds/LightPillar.jsx b/src/components/backgrounds/LightPillar.tsx similarity index 78% rename from src/components/backgrounds/LightPillar.jsx rename to src/components/backgrounds/LightPillar.tsx index cb7afe5..0950dd9 100644 --- a/src/components/backgrounds/LightPillar.jsx +++ b/src/components/backgrounds/LightPillar.tsx @@ -1,8 +1,23 @@ -import { useRef, useEffect, useState } from "react"; +import React, { useRef, useEffect, useState, CSSProperties } from "react"; import * as THREE from "three"; -import "./LightPillar.css"; -const LightPillar = ({ +interface LightPillarProps { + topColor?: string; + bottomColor?: string; + intensity?: number; + rotationSpeed?: number; + interactive?: boolean; + className?: string; + glowAmount?: number; + pillarWidth?: number; + pillarHeight?: number; + noiseIntensity?: number; + mixBlendMode?: CSSProperties["mixBlendMode"]; + pillarRotation?: number; + quality?: "low" | "medium" | "high"; +} + +const LightPillar: React.FC = ({ topColor = "#5227FF", bottomColor = "#FF9FFC", intensity = 1.0, @@ -17,15 +32,16 @@ const LightPillar = ({ pillarRotation = 0, quality = "high", }) => { - const containerRef = useRef(null); - const rendererRef = useRef(null); - const materialRef = useRef(null); - const sceneRef = useRef(null); - const cameraRef = useRef(null); - const geometryRef = useRef(null); + const containerRef = useRef(null); + const rendererRef = useRef(null); + const materialRef = useRef(null); + const sceneRef = useRef(null); + const cameraRef = useRef(null); + const geometryRef = useRef(null); const mouseRef = useRef(new THREE.Vector2(0, 0)); const timeRef = useRef(0); - const rafRef = useRef(null); + const rafRef = useRef(null); + const [opacity, setOpacity] = useState(0); const [webGLSupported, setWebGLSupported] = useState(() => { try { @@ -46,6 +62,8 @@ const LightPillar = ({ /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent, ); + const effectiveQuality = + isMobile && quality === "high" ? "medium" : quality; const effectivelyInteractive = interactive && !isMobile; const container = containerRef.current; @@ -57,7 +75,15 @@ const LightPillar = ({ const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1); cameraRef.current = camera; - const qualitySettings = { + type QualityConfig = { + iterations: number; + waveIterations: number; + pixelRatio: number; + precision: "mediump" | "highp"; + stepMultiplier: number; + }; + + const qualitySettings: Record<"low" | "medium" | "high", QualityConfig> = { low: { iterations: 24, waveIterations: 1, @@ -81,14 +107,16 @@ const LightPillar = ({ }, }; - const settings = qualitySettings[quality] || qualitySettings.medium; + const settings = + qualitySettings[effectiveQuality] || qualitySettings.medium; - let renderer; + let renderer: THREE.WebGLRenderer; try { renderer = new THREE.WebGLRenderer({ antialias: false, alpha: true, - powerPreference: quality === "high" ? "high-performance" : "low-power", + powerPreference: + effectiveQuality === "high" ? "high-performance" : "low-power", precision: settings.precision, stencil: false, depth: false, @@ -97,13 +125,14 @@ const LightPillar = ({ setTimeout(() => setWebGLSupported(false), 0); return; } + setTimeout(() => setOpacity(1), 100); renderer.setSize(width, height); renderer.setPixelRatio(settings.pixelRatio); container.appendChild(renderer.domElement); rendererRef.current = renderer; - const parseColor = (hex) => { + const parseColor = (hex: string) => { const color = new THREE.Color(hex); return new THREE.Vector3(color.r, color.g, color.b); }; @@ -144,15 +173,9 @@ const LightPillar = ({ void main() { vec2 uv = vUv * 2.0 - 1.0; float aspect = uResolution.x / uResolution.y; - - if (aspect > 1.0) { - uv.x *= aspect; - } else { - uv.y /= aspect; - } + if (aspect > 1.0) uv.x *= aspect; else uv.y /= aspect; uv = vec2(uPillarRotCos * uv.x - uPillarRotSin * uv.y, uPillarRotSin * uv.x + uPillarRotCos * uv.y); - vec3 ro = vec3(0.0, 0.0, -10.0); vec3 rd = normalize(vec3(uv, 1.0)); @@ -167,49 +190,36 @@ const LightPillar = ({ vec3 col = vec3(0.0); float t = 0.1; - for(int i = 0; i < MAX_ITER; i++) { vec3 p = ro + rd * t; p.xz = vec2(rotC * p.x - rotS * p.z, rotS * p.x + rotC * p.z); vec3 q = p; q.y = p.y * uPillarHeight + uTime; - - float freq = 1.0; - float amp = 1.0; - + float freq = 1.0; float amp = 1.0; for(int j = 0; j < WAVE_ITER; j++) { q.xz = vec2(uWaveCos * q.x - uWaveSin * q.z, uWaveSin * q.x + uWaveCos * q.z); q += cos(q.zxy * freq - uTime * float(j) * 2.0) * amp; - freq *= 2.0; - amp *= 0.5; + freq *= 2.0; amp *= 0.5; } - float d = length(cos(q.xz)) - 0.2; float bound = length(p.xz) - uPillarWidth; float k = 4.0; float h = max(k - abs(d - bound), 0.0); d = max(d, bound) + h * h * 0.0625 / k; d = abs(d) * 0.15 + 0.01; - float grad = clamp((15.0 - p.y) / 30.0, 0.0, 1.0); col += mix(uBottomColor, uTopColor, grad) / d; - t += d * STEP_MULT; if(t > 50.0) break; } - float widthNorm = uPillarWidth / 3.0; col = tanh(col * uGlowAmount / widthNorm); col -= fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453) / 15.0 * uNoiseIntensity; - gl_FragColor = vec4(col * uIntensity, 1.0); } `; const pillarRotRad = (pillarRotation * Math.PI) / 180; - const waveSin = Math.sin(0.4); - const waveCos = Math.cos(0.4); - const material = new THREE.ShaderMaterial({ vertexShader, fragmentShader, @@ -229,8 +239,8 @@ const LightPillar = ({ uRotSin: { value: 0.0 }, uPillarRotCos: { value: Math.cos(pillarRotRad) }, uPillarRotSin: { value: Math.sin(pillarRotRad) }, - uWaveSin: { value: waveSin }, - uWaveCos: { value: waveCos }, + uWaveSin: { value: Math.sin(0.4) }, + uWaveCos: { value: Math.cos(0.4) }, }, transparent: true, depthWrite: false, @@ -243,21 +253,19 @@ const LightPillar = ({ const mesh = new THREE.Mesh(geometry, material); scene.add(mesh); - const handleMouseMove = (event) => { + const handleMouseMove = (event: MouseEvent) => { if (!effectivelyInteractive) return; const x = (event.clientX / window.innerWidth) * 2 - 1; const y = -(event.clientY / window.innerHeight) * 2 + 1; mouseRef.current.set(x, y); }; + if (effectivelyInteractive) { window.addEventListener("mousemove", handleMouseMove, { passive: true }); } let lastTime = performance.now(); - const targetFPS = 60; - const frameTime = 1000 / targetFPS; - - const animate = (currentTime) => { + const animate = (currentTime: number) => { if ( !materialRef.current || !rendererRef.current || @@ -267,7 +275,7 @@ const LightPillar = ({ return; const deltaTime = currentTime - lastTime; - if (deltaTime >= frameTime) { + if (deltaTime >= 16.6) { timeRef.current += 0.016 * rotationSpeed; const t = timeRef.current; materialRef.current.uniforms.uTime.value = t; @@ -275,9 +283,8 @@ const LightPillar = ({ materialRef.current.uniforms.uRotCos.value = Math.cos(t * 0.6); materialRef.current.uniforms.uRotSin.value = Math.sin(t * 0.6); } - rendererRef.current.render(sceneRef.current, cameraRef.current); - lastTime = currentTime - (deltaTime % frameTime); + lastTime = currentTime - (deltaTime % 16.6); } rafRef.current = requestAnimationFrame(animate); }; @@ -296,16 +303,13 @@ const LightPillar = ({ return () => { window.removeEventListener("resize", handleResize); - if (effectivelyInteractive) { + if (effectivelyInteractive) window.removeEventListener("mousemove", handleMouseMove); - } if (rafRef.current) cancelAnimationFrame(rafRef.current); if (rendererRef.current) { rendererRef.current.dispose(); - rendererRef.current.forceContextLoss(); - if (container.contains(rendererRef.current.domElement)) { + if (container.contains(rendererRef.current.domElement)) container.removeChild(rendererRef.current.domElement); - } } if (materialRef.current) materialRef.current.dispose(); if (geometryRef.current) geometryRef.current.dispose(); @@ -325,28 +329,24 @@ const LightPillar = ({ quality, ]); - if (!webGLSupported) { + if (!webGLSupported) return (
    WebGL not supported
    ); - } return (
    ); diff --git a/src/components/cursors/SplashCursor.jsx b/src/components/cursors/SplashCursor.jsx deleted file mode 100644 index d2fe1ec..0000000 --- a/src/components/cursors/SplashCursor.jsx +++ /dev/null @@ -1,1257 +0,0 @@ -"use client"; -import { useEffect, useRef } from "react"; - -function SplashCursor({ - SIM_RESOLUTION = 128, - DYE_RESOLUTION = 1440, - CAPTURE_RESOLUTION = 512, - DENSITY_DISSIPATION = 3.5, - VELOCITY_DISSIPATION = 2, - PRESSURE = 0.5, - PRESSURE_ITERATIONS = 10, - CURL = 3, - SPLAT_RADIUS = 0.2, - SPLAT_FORCE = 6000, - SHADING = true, - COLOR_UPDATE_SPEED = 10, - BACK_COLOR = { r: 138, g: 20, b: 20 }, - TRANSPARENT = true, -}) { - const canvasRef = useRef(null); - const animationFrameId = useRef(null); - - useEffect(() => { - const canvas = canvasRef.current; - if (!canvas) return; - let isActive = true; - - function pointerPrototype() { - this.id = -1; - this.texcoordX = 0; - this.texcoordY = 0; - this.prevTexcoordX = 0; - this.prevTexcoordY = 0; - this.deltaX = 0; - this.deltaY = 0; - this.down = false; - this.moved = false; - this.color = [0, 0, 0]; - } - - let config = { - SIM_RESOLUTION, - DYE_RESOLUTION, - CAPTURE_RESOLUTION, - DENSITY_DISSIPATION, - VELOCITY_DISSIPATION, - PRESSURE, - PRESSURE_ITERATIONS, - CURL, - SPLAT_RADIUS, - SPLAT_FORCE, - SHADING, - COLOR_UPDATE_SPEED, - PAUSED: false, - BACK_COLOR, - TRANSPARENT, - }; - - let pointers = [new pointerPrototype()]; - - const { gl, ext } = getWebGLContext(canvas); - if (!ext.supportLinearFiltering) { - config.DYE_RESOLUTION = 256; - config.SHADING = false; - } - - function getWebGLContext(canvas) { - const params = { - alpha: true, - depth: false, - stencil: false, - antialias: false, - preserveDrawingBuffer: false, - }; - let gl = canvas.getContext("webgl2", params); - const isWebGL2 = !!gl; - if (!isWebGL2) - gl = - canvas.getContext("webgl", params) || - canvas.getContext("experimental-webgl", params); - - let halfFloat; - let supportLinearFiltering; - if (isWebGL2) { - gl.getExtension("EXT_color_buffer_float"); - supportLinearFiltering = gl.getExtension("OES_texture_float_linear"); - } else { - halfFloat = gl.getExtension("OES_texture_half_float"); - supportLinearFiltering = gl.getExtension( - "OES_texture_half_float_linear", - ); - } - gl.clearColor(0.0, 0.0, 0.0, 1.0); - - const halfFloatTexType = isWebGL2 - ? gl.HALF_FLOAT - : halfFloat && halfFloat.HALF_FLOAT_OES; - let formatRGBA; - let formatRG; - let formatR; - - if (isWebGL2) { - formatRGBA = getSupportedFormat( - gl, - gl.RGBA16F, - gl.RGBA, - halfFloatTexType, - ); - formatRG = getSupportedFormat(gl, gl.RG16F, gl.RG, halfFloatTexType); - formatR = getSupportedFormat(gl, gl.R16F, gl.RED, halfFloatTexType); - } else { - formatRGBA = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - formatRG = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - formatR = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); - } - - return { - gl, - ext: { - formatRGBA, - formatRG, - formatR, - halfFloatTexType, - supportLinearFiltering, - }, - }; - } - - function getSupportedFormat(gl, internalFormat, format, type) { - if (!supportRenderTextureFormat(gl, internalFormat, format, type)) { - switch (internalFormat) { - case gl.R16F: - return getSupportedFormat(gl, gl.RG16F, gl.RG, type); - case gl.RG16F: - return getSupportedFormat(gl, gl.RGBA16F, gl.RGBA, type); - default: - return null; - } - } - return { internalFormat, format }; - } - - function supportRenderTextureFormat(gl, internalFormat, format, type) { - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D( - gl.TEXTURE_2D, - 0, - internalFormat, - 4, - 4, - 0, - format, - type, - null, - ); - const fbo = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0, - gl.TEXTURE_2D, - texture, - 0, - ); - const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); - return status === gl.FRAMEBUFFER_COMPLETE; - } - - class Material { - constructor(vertexShader, fragmentShaderSource) { - this.vertexShader = vertexShader; - this.fragmentShaderSource = fragmentShaderSource; - this.programs = []; - this.activeProgram = null; - this.uniforms = []; - } - setKeywords(keywords) { - let hash = 0; - for (let i = 0; i < keywords.length; i++) hash += hashCode(keywords[i]); - let program = this.programs[hash]; - if (program == null) { - let fragmentShader = compileShader( - gl.FRAGMENT_SHADER, - this.fragmentShaderSource, - keywords, - ); - program = createProgram(this.vertexShader, fragmentShader); - this.programs[hash] = program; - } - if (program === this.activeProgram) return; - this.uniforms = getUniforms(program); - this.activeProgram = program; - } - bind() { - gl.useProgram(this.activeProgram); - } - } - - class Program { - constructor(vertexShader, fragmentShader) { - this.uniforms = {}; - this.program = createProgram(vertexShader, fragmentShader); - this.uniforms = getUniforms(this.program); - } - bind() { - gl.useProgram(this.program); - } - } - - function createProgram(vertexShader, fragmentShader) { - let program = gl.createProgram(); - gl.attachShader(program, vertexShader); - gl.attachShader(program, fragmentShader); - gl.linkProgram(program); - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) - console.trace(gl.getProgramInfoLog(program)); - return program; - } - - function getUniforms(program) { - let uniforms = []; - let uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (let i = 0; i < uniformCount; i++) { - let uniformName = gl.getActiveUniform(program, i).name; - uniforms[uniformName] = gl.getUniformLocation(program, uniformName); - } - return uniforms; - } - - function compileShader(type, source, keywords) { - source = addKeywords(source, keywords); - const shader = gl.createShader(type); - gl.shaderSource(shader, source); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) - console.trace(gl.getShaderInfoLog(shader)); - return shader; - } - - function addKeywords(source, keywords) { - if (!keywords) return source; - let keywordsString = ""; - keywords.forEach((keyword) => { - keywordsString += "#define " + keyword + "\n"; - }); - return keywordsString + source; - } - - const baseVertexShader = compileShader( - gl.VERTEX_SHADER, - ` - precision highp float; - attribute vec2 aPosition; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform vec2 texelSize; - - void main () { - vUv = aPosition * 0.5 + 0.5; - vL = vUv - vec2(texelSize.x, 0.0); - vR = vUv + vec2(texelSize.x, 0.0); - vT = vUv + vec2(0.0, texelSize.y); - vB = vUv - vec2(0.0, texelSize.y); - gl_Position = vec4(aPosition, 0.0, 1.0); - } - `, - ); - - const copyShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - uniform sampler2D uTexture; - - void main () { - gl_FragColor = texture2D(uTexture, vUv); - } - `, - ); - - const clearShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - uniform sampler2D uTexture; - uniform float value; - - void main () { - gl_FragColor = value * texture2D(uTexture, vUv); - } - `, - ); - - const displayShaderSource = ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform sampler2D uTexture; - uniform sampler2D uDithering; - uniform vec2 ditherScale; - uniform vec2 texelSize; - - vec3 linearToGamma (vec3 color) { - color = max(color, vec3(0)); - return max(1.055 * pow(color, vec3(0.416666667)) - 0.055, vec3(0)); - } - - void main () { - vec3 c = texture2D(uTexture, vUv).rgb; - #ifdef SHADING - vec3 lc = texture2D(uTexture, vL).rgb; - vec3 rc = texture2D(uTexture, vR).rgb; - vec3 tc = texture2D(uTexture, vT).rgb; - vec3 bc = texture2D(uTexture, vB).rgb; - - float dx = length(rc) - length(lc); - float dy = length(tc) - length(bc); - - vec3 n = normalize(vec3(dx, dy, length(texelSize))); - vec3 l = vec3(0.0, 0.0, 1.0); - - float diffuse = clamp(dot(n, l) + 0.7, 0.7, 1.0); - c *= diffuse; - #endif - - float a = max(c.r, max(c.g, c.b)); - gl_FragColor = vec4(c, a); - } - `; - - const splatShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D uTarget; - uniform float aspectRatio; - uniform vec3 color; - uniform vec2 point; - uniform float radius; - - void main () { - vec2 p = vUv - point.xy; - p.x *= aspectRatio; - vec3 splat = exp(-dot(p, p) / radius) * color; - vec3 base = texture2D(uTarget, vUv).xyz; - gl_FragColor = vec4(base + splat, 1.0); - } - `, - ); - - const advectionShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - uniform sampler2D uVelocity; - uniform sampler2D uSource; - uniform vec2 texelSize; - uniform vec2 dyeTexelSize; - uniform float dt; - uniform float dissipation; - - vec4 bilerp (sampler2D sam, vec2 uv, vec2 tsize) { - vec2 st = uv / tsize - 0.5; - vec2 iuv = floor(st); - vec2 fuv = fract(st); - - vec4 a = texture2D(sam, (iuv + vec2(0.5, 0.5)) * tsize); - vec4 b = texture2D(sam, (iuv + vec2(1.5, 0.5)) * tsize); - vec4 c = texture2D(sam, (iuv + vec2(0.5, 1.5)) * tsize); - vec4 d = texture2D(sam, (iuv + vec2(1.5, 1.5)) * tsize); - - return mix(mix(a, b, fuv.x), mix(c, d, fuv.x), fuv.y); - } - - void main () { - #ifdef MANUAL_FILTERING - vec2 coord = vUv - dt * bilerp(uVelocity, vUv, texelSize).xy * texelSize; - vec4 result = bilerp(uSource, coord, dyeTexelSize); - #else - vec2 coord = vUv - dt * texture2D(uVelocity, vUv).xy * texelSize; - vec4 result = texture2D(uSource, coord); - #endif - float decay = 1.0 + dissipation * dt; - gl_FragColor = result / decay; - } - `, - ext.supportLinearFiltering ? null : ["MANUAL_FILTERING"], - ); - - const divergenceShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uVelocity, vL).x; - float R = texture2D(uVelocity, vR).x; - float T = texture2D(uVelocity, vT).y; - float B = texture2D(uVelocity, vB).y; - - vec2 C = texture2D(uVelocity, vUv).xy; - if (vL.x < 0.0) { L = -C.x; } - if (vR.x > 1.0) { R = -C.x; } - if (vT.y > 1.0) { T = -C.y; } - if (vB.y < 0.0) { B = -C.y; } - - float div = 0.5 * (R - L + T - B); - gl_FragColor = vec4(div, 0.0, 0.0, 1.0); - } - `, - ); - - const curlShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uVelocity, vL).y; - float R = texture2D(uVelocity, vR).y; - float T = texture2D(uVelocity, vT).x; - float B = texture2D(uVelocity, vB).x; - float vorticity = R - L - T + B; - gl_FragColor = vec4(0.5 * vorticity, 0.0, 0.0, 1.0); - } - `, - ); - - const vorticityShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision highp float; - precision highp sampler2D; - varying vec2 vUv; - varying vec2 vL; - varying vec2 vR; - varying vec2 vT; - varying vec2 vB; - uniform sampler2D uVelocity; - uniform sampler2D uCurl; - uniform float curl; - uniform float dt; - - void main () { - float L = texture2D(uCurl, vL).x; - float R = texture2D(uCurl, vR).x; - float T = texture2D(uCurl, vT).x; - float B = texture2D(uCurl, vB).x; - float C = texture2D(uCurl, vUv).x; - - vec2 force = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L)); - force /= length(force) + 0.0001; - force *= curl * C; - force.y *= -1.0; - - vec2 velocity = texture2D(uVelocity, vUv).xy; - velocity += force * dt; - velocity = min(max(velocity, -1000.0), 1000.0); - gl_FragColor = vec4(velocity, 0.0, 1.0); - } - `, - ); - - const pressureShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uPressure; - uniform sampler2D uDivergence; - - void main () { - float L = texture2D(uPressure, vL).x; - float R = texture2D(uPressure, vR).x; - float T = texture2D(uPressure, vT).x; - float B = texture2D(uPressure, vB).x; - float C = texture2D(uPressure, vUv).x; - float divergence = texture2D(uDivergence, vUv).x; - float pressure = (L + R + B + T - divergence) * 0.25; - gl_FragColor = vec4(pressure, 0.0, 0.0, 1.0); - } - `, - ); - - const gradientSubtractShader = compileShader( - gl.FRAGMENT_SHADER, - ` - precision mediump float; - precision mediump sampler2D; - varying highp vec2 vUv; - varying highp vec2 vL; - varying highp vec2 vR; - varying highp vec2 vT; - varying highp vec2 vB; - uniform sampler2D uPressure; - uniform sampler2D uVelocity; - - void main () { - float L = texture2D(uPressure, vL).x; - float R = texture2D(uPressure, vR).x; - float T = texture2D(uPressure, vT).x; - float B = texture2D(uPressure, vB).x; - vec2 velocity = texture2D(uVelocity, vUv).xy; - velocity.xy -= vec2(R - L, T - B); - gl_FragColor = vec4(velocity, 0.0, 1.0); - } - `, - ); - - const blit = (() => { - gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); - gl.bufferData( - gl.ARRAY_BUFFER, - new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), - gl.STATIC_DRAW, - ); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); - gl.bufferData( - gl.ELEMENT_ARRAY_BUFFER, - new Uint16Array([0, 1, 2, 0, 2, 3]), - gl.STATIC_DRAW, - ); - gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); - gl.enableVertexAttribArray(0); - return (target, clear = false) => { - if (target == null) { - gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - } else { - gl.viewport(0, 0, target.width, target.height); - gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo); - } - if (clear) { - gl.clearColor(0.0, 0.0, 0.0, 1.0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); - }; - })(); - - let dye, velocity, divergence, curl, pressure; - - const copyProgram = new Program(baseVertexShader, copyShader); - const clearProgram = new Program(baseVertexShader, clearShader); - const splatProgram = new Program(baseVertexShader, splatShader); - const advectionProgram = new Program(baseVertexShader, advectionShader); - const divergenceProgram = new Program(baseVertexShader, divergenceShader); - const curlProgram = new Program(baseVertexShader, curlShader); - const vorticityProgram = new Program(baseVertexShader, vorticityShader); - const pressureProgram = new Program(baseVertexShader, pressureShader); - const gradienSubtractProgram = new Program( - baseVertexShader, - gradientSubtractShader, - ); - const displayMaterial = new Material(baseVertexShader, displayShaderSource); - - function initFramebuffers() { - let simRes = getResolution(config.SIM_RESOLUTION); - let dyeRes = getResolution(config.DYE_RESOLUTION); - const texType = ext.halfFloatTexType; - const rgba = ext.formatRGBA; - const rg = ext.formatRG; - const r = ext.formatR; - const filtering = ext.supportLinearFiltering ? gl.LINEAR : gl.NEAREST; - gl.disable(gl.BLEND); - - if (!dye) - dye = createDoubleFBO( - dyeRes.width, - dyeRes.height, - rgba.internalFormat, - rgba.format, - texType, - filtering, - ); - else - dye = resizeDoubleFBO( - dye, - dyeRes.width, - dyeRes.height, - rgba.internalFormat, - rgba.format, - texType, - filtering, - ); - - if (!velocity) - velocity = createDoubleFBO( - simRes.width, - simRes.height, - rg.internalFormat, - rg.format, - texType, - filtering, - ); - else - velocity = resizeDoubleFBO( - velocity, - simRes.width, - simRes.height, - rg.internalFormat, - rg.format, - texType, - filtering, - ); - - divergence = createFBO( - simRes.width, - simRes.height, - r.internalFormat, - r.format, - texType, - gl.NEAREST, - ); - curl = createFBO( - simRes.width, - simRes.height, - r.internalFormat, - r.format, - texType, - gl.NEAREST, - ); - pressure = createDoubleFBO( - simRes.width, - simRes.height, - r.internalFormat, - r.format, - texType, - gl.NEAREST, - ); - } - - function createFBO(w, h, internalFormat, format, type, param) { - gl.activeTexture(gl.TEXTURE0); - let texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, param); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, param); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D( - gl.TEXTURE_2D, - 0, - internalFormat, - w, - h, - 0, - format, - type, - null, - ); - - let fbo = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); - gl.framebufferTexture2D( - gl.FRAMEBUFFER, - gl.COLOR_ATTACHMENT0, - gl.TEXTURE_2D, - texture, - 0, - ); - gl.viewport(0, 0, w, h); - gl.clear(gl.COLOR_BUFFER_BIT); - - let texelSizeX = 1.0 / w; - let texelSizeY = 1.0 / h; - return { - texture, - fbo, - width: w, - height: h, - texelSizeX, - texelSizeY, - attach(id) { - gl.activeTexture(gl.TEXTURE0 + id); - gl.bindTexture(gl.TEXTURE_2D, texture); - return id; - }, - }; - } - - function createDoubleFBO(w, h, internalFormat, format, type, param) { - let fbo1 = createFBO(w, h, internalFormat, format, type, param); - let fbo2 = createFBO(w, h, internalFormat, format, type, param); - return { - width: w, - height: h, - texelSizeX: fbo1.texelSizeX, - texelSizeY: fbo1.texelSizeY, - get read() { - return fbo1; - }, - set read(value) { - fbo1 = value; - }, - get write() { - return fbo2; - }, - set write(value) { - fbo2 = value; - }, - swap() { - let temp = fbo1; - fbo1 = fbo2; - fbo2 = temp; - }, - }; - } - - function resizeFBO(target, w, h, internalFormat, format, type, param) { - let newFBO = createFBO(w, h, internalFormat, format, type, param); - copyProgram.bind(); - gl.uniform1i(copyProgram.uniforms.uTexture, target.attach(0)); - blit(newFBO); - return newFBO; - } - - function resizeDoubleFBO( - target, - w, - h, - internalFormat, - format, - type, - param, - ) { - if (target.width === w && target.height === h) return target; - target.read = resizeFBO( - target.read, - w, - h, - internalFormat, - format, - type, - param, - ); - target.write = createFBO(w, h, internalFormat, format, type, param); - target.width = w; - target.height = h; - target.texelSizeX = 1.0 / w; - target.texelSizeY = 1.0 / h; - return target; - } - - function updateKeywords() { - let displayKeywords = []; - if (config.SHADING) displayKeywords.push("SHADING"); - displayMaterial.setKeywords(displayKeywords); - } - - updateKeywords(); - initFramebuffers(); - let lastUpdateTime = Date.now(); - let colorUpdateTimer = 0.0; - - function updateFrame() { - if (!isActive) return; - const dt = calcDeltaTime(); - if (resizeCanvas()) initFramebuffers(); - updateColors(dt); - applyInputs(); - step(dt); - render(null); - animationFrameId.current = requestAnimationFrame(updateFrame); - } - - function calcDeltaTime() { - let now = Date.now(); - let dt = (now - lastUpdateTime) / 1000; - dt = Math.min(dt, 0.016666); - lastUpdateTime = now; - return dt; - } - - function resizeCanvas() { - let width = scaleByPixelRatio(canvas.clientWidth); - let height = scaleByPixelRatio(canvas.clientHeight); - if (canvas.width !== width || canvas.height !== height) { - canvas.width = width; - canvas.height = height; - return true; - } - return false; - } - - function updateColors(dt) { - colorUpdateTimer += dt * config.COLOR_UPDATE_SPEED; - if (colorUpdateTimer >= 1) { - colorUpdateTimer = wrap(colorUpdateTimer, 0, 1); - pointers.forEach((p) => { - p.color = generateColor(); - }); - } - } - - function applyInputs() { - pointers.forEach((p) => { - if (p.moved) { - p.moved = false; - splatPointer(p); - } - }); - } - - function step(dt) { - gl.disable(gl.BLEND); - curlProgram.bind(); - gl.uniform2f( - curlProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - gl.uniform1i(curlProgram.uniforms.uVelocity, velocity.read.attach(0)); - blit(curl); - - vorticityProgram.bind(); - gl.uniform2f( - vorticityProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - gl.uniform1i( - vorticityProgram.uniforms.uVelocity, - velocity.read.attach(0), - ); - gl.uniform1i(vorticityProgram.uniforms.uCurl, curl.attach(1)); - gl.uniform1f(vorticityProgram.uniforms.curl, config.CURL); - gl.uniform1f(vorticityProgram.uniforms.dt, dt); - blit(velocity.write); - velocity.swap(); - - divergenceProgram.bind(); - gl.uniform2f( - divergenceProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - gl.uniform1i( - divergenceProgram.uniforms.uVelocity, - velocity.read.attach(0), - ); - blit(divergence); - - clearProgram.bind(); - gl.uniform1i(clearProgram.uniforms.uTexture, pressure.read.attach(0)); - gl.uniform1f(clearProgram.uniforms.value, config.PRESSURE); - blit(pressure.write); - pressure.swap(); - - pressureProgram.bind(); - gl.uniform2f( - pressureProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - gl.uniform1i(pressureProgram.uniforms.uDivergence, divergence.attach(0)); - for (let i = 0; i < config.PRESSURE_ITERATIONS; i++) { - gl.uniform1i( - pressureProgram.uniforms.uPressure, - pressure.read.attach(1), - ); - blit(pressure.write); - pressure.swap(); - } - - gradienSubtractProgram.bind(); - gl.uniform2f( - gradienSubtractProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - gl.uniform1i( - gradienSubtractProgram.uniforms.uPressure, - pressure.read.attach(0), - ); - gl.uniform1i( - gradienSubtractProgram.uniforms.uVelocity, - velocity.read.attach(1), - ); - blit(velocity.write); - velocity.swap(); - - advectionProgram.bind(); - gl.uniform2f( - advectionProgram.uniforms.texelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - if (!ext.supportLinearFiltering) - gl.uniform2f( - advectionProgram.uniforms.dyeTexelSize, - velocity.texelSizeX, - velocity.texelSizeY, - ); - let velocityId = velocity.read.attach(0); - gl.uniform1i(advectionProgram.uniforms.uVelocity, velocityId); - gl.uniform1i(advectionProgram.uniforms.uSource, velocityId); - gl.uniform1f(advectionProgram.uniforms.dt, dt); - gl.uniform1f( - advectionProgram.uniforms.dissipation, - config.VELOCITY_DISSIPATION, - ); - blit(velocity.write); - velocity.swap(); - - if (!ext.supportLinearFiltering) - gl.uniform2f( - advectionProgram.uniforms.dyeTexelSize, - dye.texelSizeX, - dye.texelSizeY, - ); - gl.uniform1i( - advectionProgram.uniforms.uVelocity, - velocity.read.attach(0), - ); - gl.uniform1i(advectionProgram.uniforms.uSource, dye.read.attach(1)); - gl.uniform1f( - advectionProgram.uniforms.dissipation, - config.DENSITY_DISSIPATION, - ); - blit(dye.write); - dye.swap(); - } - - function render(target) { - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - gl.enable(gl.BLEND); - drawDisplay(target); - } - - function drawDisplay(target) { - let width = target == null ? gl.drawingBufferWidth : target.width; - let height = target == null ? gl.drawingBufferHeight : target.height; - displayMaterial.bind(); - if (config.SHADING) - gl.uniform2f( - displayMaterial.uniforms.texelSize, - 1.0 / width, - 1.0 / height, - ); - gl.uniform1i(displayMaterial.uniforms.uTexture, dye.read.attach(0)); - blit(target); - } - - function splatPointer(pointer) { - let dx = pointer.deltaX * config.SPLAT_FORCE; - let dy = pointer.deltaY * config.SPLAT_FORCE; - splat(pointer.texcoordX, pointer.texcoordY, dx, dy, pointer.color); - } - - function clickSplat(pointer) { - const color = generateColor(); - color.r *= 10.0; - color.g *= 10.0; - color.b *= 10.0; - let dx = 10 * (Math.random() - 0.5); - let dy = 30 * (Math.random() - 0.5); - splat(pointer.texcoordX, pointer.texcoordY, dx, dy, color); - } - - function splat(x, y, dx, dy, color) { - splatProgram.bind(); - gl.uniform1i(splatProgram.uniforms.uTarget, velocity.read.attach(0)); - gl.uniform1f( - splatProgram.uniforms.aspectRatio, - canvas.width / canvas.height, - ); - gl.uniform2f(splatProgram.uniforms.point, x, y); - gl.uniform3f(splatProgram.uniforms.color, dx, dy, 0.0); - gl.uniform1f( - splatProgram.uniforms.radius, - correctRadius(config.SPLAT_RADIUS / 100.0), - ); - blit(velocity.write); - velocity.swap(); - - gl.uniform1i(splatProgram.uniforms.uTarget, dye.read.attach(0)); - gl.uniform3f(splatProgram.uniforms.color, color.r, color.g, color.b); - blit(dye.write); - dye.swap(); - } - - function correctRadius(radius) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio > 1) radius *= aspectRatio; - return radius; - } - - function updatePointerDownData(pointer, id, posX, posY) { - pointer.id = id; - pointer.down = true; - pointer.moved = false; - pointer.texcoordX = posX / canvas.width; - pointer.texcoordY = 1.0 - posY / canvas.height; - pointer.prevTexcoordX = pointer.texcoordX; - pointer.prevTexcoordY = pointer.texcoordY; - pointer.deltaX = 0; - pointer.deltaY = 0; - pointer.color = generateColor(); - } - - function updatePointerMoveData(pointer, posX, posY, color) { - pointer.prevTexcoordX = pointer.texcoordX; - pointer.prevTexcoordY = pointer.texcoordY; - pointer.texcoordX = posX / canvas.width; - pointer.texcoordY = 1.0 - posY / canvas.height; - pointer.deltaX = correctDeltaX(pointer.texcoordX - pointer.prevTexcoordX); - pointer.deltaY = correctDeltaY(pointer.texcoordY - pointer.prevTexcoordY); - pointer.moved = - Math.abs(pointer.deltaX) > 0 || Math.abs(pointer.deltaY) > 0; - pointer.color = color; - } - - function updatePointerUpData(pointer) { - pointer.down = false; - } - - function correctDeltaX(delta) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio < 1) delta *= aspectRatio; - return delta; - } - - function correctDeltaY(delta) { - let aspectRatio = canvas.width / canvas.height; - if (aspectRatio > 1) delta /= aspectRatio; - return delta; - } - - function generateColor() { - let c = HSVtoRGB(Math.random(), 1.0, 1.0); - c.r *= 0.15; - c.g *= 0.15; - c.b *= 0.15; - return c; - } - - function HSVtoRGB(h, s, v) { - let r, g, b, i, f, p, q, t; - i = Math.floor(h * 6); - f = h * 6 - i; - p = v * (1 - s); - q = v * (1 - f * s); - t = v * (1 - (1 - f) * s); - switch (i % 6) { - case 0: - r = v; - g = t; - b = p; - break; - case 1: - r = q; - g = v; - b = p; - break; - case 2: - r = p; - g = v; - b = t; - break; - case 3: - r = p; - g = q; - b = v; - break; - case 4: - r = t; - g = p; - b = v; - break; - case 5: - r = v; - g = p; - b = q; - break; - default: - break; - } - return { r, g, b }; - } - - function wrap(value, min, max) { - const range = max - min; - if (range === 0) return min; - return ((value - min) % range) + min; - } - - function getResolution(resolution) { - let aspectRatio = gl.drawingBufferWidth / gl.drawingBufferHeight; - if (aspectRatio < 1) aspectRatio = 1.0 / aspectRatio; - const min = Math.round(resolution); - const max = Math.round(resolution * aspectRatio); - if (gl.drawingBufferWidth > gl.drawingBufferHeight) - return { width: max, height: min }; - else return { width: min, height: max }; - } - - function scaleByPixelRatio(input) { - const pixelRatio = window.devicePixelRatio || 1; - return Math.floor(input * pixelRatio); - } - - function hashCode(s) { - if (s.length === 0) return 0; - let hash = 0; - for (let i = 0; i < s.length; i++) { - hash = (hash << 5) - hash + s.charCodeAt(i); - hash |= 0; - } - return hash; - } - - // Named event handlers for proper cleanup - function handleMouseDown(e) { - let pointer = pointers[0]; - let posX = scaleByPixelRatio(e.clientX); - let posY = scaleByPixelRatio(e.clientY); - updatePointerDownData(pointer, -1, posX, posY); - clickSplat(pointer); - } - - let firstMouseMoveHandled = false; - function handleMouseMove(e) { - let pointer = pointers[0]; - let posX = scaleByPixelRatio(e.clientX); - let posY = scaleByPixelRatio(e.clientY); - if (!firstMouseMoveHandled) { - let color = generateColor(); - updatePointerMoveData(pointer, posX, posY, color); - firstMouseMoveHandled = true; - } else { - updatePointerMoveData(pointer, posX, posY, pointer.color); - } - } - - function handleTouchStart(e) { - const touches = e.targetTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - let posX = scaleByPixelRatio(touches[i].clientX); - let posY = scaleByPixelRatio(touches[i].clientY); - updatePointerDownData(pointer, touches[i].identifier, posX, posY); - } - } - - function handleTouchMove(e) { - const touches = e.targetTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - let posX = scaleByPixelRatio(touches[i].clientX); - let posY = scaleByPixelRatio(touches[i].clientY); - updatePointerMoveData(pointer, posX, posY, pointer.color); - } - } - - function handleTouchEnd(e) { - const touches = e.changedTouches; - let pointer = pointers[0]; - for (let i = 0; i < touches.length; i++) { - updatePointerUpData(pointer); - } - } - - // Add event listeners - window.addEventListener("mousedown", handleMouseDown); - window.addEventListener("mousemove", handleMouseMove); - window.addEventListener("touchstart", handleTouchStart); - window.addEventListener("touchmove", handleTouchMove, false); - window.addEventListener("touchend", handleTouchEnd); - - updateFrame(); - - // Cleanup function - return () => { - isActive = false; - - // Cancel animation frame - if (animationFrameId.current) { - cancelAnimationFrame(animationFrameId.current); - animationFrameId.current = null; - } - - // Remove event listeners - window.removeEventListener("mousedown", handleMouseDown); - window.removeEventListener("mousemove", handleMouseMove); - window.removeEventListener("touchstart", handleTouchStart); - window.removeEventListener("touchmove", handleTouchMove); - window.removeEventListener("touchend", handleTouchEnd); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return ( -
    - -
    - ); -} - -export default SplashCursor; diff --git a/src/components/cursors/SplashCursor.tsx b/src/components/cursors/SplashCursor.tsx new file mode 100644 index 0000000..6d1610a --- /dev/null +++ b/src/components/cursors/SplashCursor.tsx @@ -0,0 +1,1521 @@ +"use client"; +import React, { useEffect, useRef } from "react"; + +interface ColorRGB { + r: number; + g: number; + b: number; +} + +interface SplashCursorProps { + SIM_RESOLUTION?: number; + DYE_RESOLUTION?: number; + CAPTURE_RESOLUTION?: number; + DENSITY_DISSIPATION?: number; + VELOCITY_DISSIPATION?: number; + PRESSURE?: number; + PRESSURE_ITERATIONS?: number; + CURL?: number; + SPLAT_RADIUS?: number; + SPLAT_FORCE?: number; + SHADING?: boolean; + COLOR_UPDATE_SPEED?: number; + BACK_COLOR?: ColorRGB; + TRANSPARENT?: boolean; +} + +interface Pointer { + id: number; + texcoordX: number; + texcoordY: number; + prevTexcoordX: number; + prevTexcoordY: number; + deltaX: number; + deltaY: number; + down: boolean; + moved: boolean; + color: ColorRGB; +} + +function pointerPrototype(): Pointer { + return { + id: -1, + texcoordX: 0, + texcoordY: 0, + prevTexcoordX: 0, + prevTexcoordY: 0, + deltaX: 0, + deltaY: 0, + down: false, + moved: false, + color: { r: 0, g: 0, b: 0 }, + }; +} + +export default function SplashCursor({ + SIM_RESOLUTION = 128, + DYE_RESOLUTION = 1440, + CAPTURE_RESOLUTION = 512, + DENSITY_DISSIPATION = 3.5, + VELOCITY_DISSIPATION = 2, + PRESSURE = 0.1, + PRESSURE_ITERATIONS = 20, + CURL = 3, + SPLAT_RADIUS = 0.2, + SPLAT_FORCE = 6000, + SHADING = true, + COLOR_UPDATE_SPEED = 10, + BACK_COLOR = { r: 0.5, g: 0, b: 0 }, + TRANSPARENT = true, +}: SplashCursorProps) { + const canvasRef = useRef(null); + + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + + let pointers: Pointer[] = [pointerPrototype()]; + + let config = { + SIM_RESOLUTION: SIM_RESOLUTION!, + DYE_RESOLUTION: DYE_RESOLUTION!, + CAPTURE_RESOLUTION: CAPTURE_RESOLUTION!, + DENSITY_DISSIPATION: DENSITY_DISSIPATION!, + VELOCITY_DISSIPATION: VELOCITY_DISSIPATION!, + PRESSURE: PRESSURE!, + PRESSURE_ITERATIONS: PRESSURE_ITERATIONS!, + CURL: CURL!, + SPLAT_RADIUS: SPLAT_RADIUS!, + SPLAT_FORCE: SPLAT_FORCE!, + SHADING, + COLOR_UPDATE_SPEED: COLOR_UPDATE_SPEED!, + PAUSED: false, + BACK_COLOR, + TRANSPARENT, + }; + + const { gl, ext } = getWebGLContext(canvas); + if (!gl || !ext) return; + + if (!ext.supportLinearFiltering) { + config.DYE_RESOLUTION = 256; + config.SHADING = false; + } + + function getWebGLContext(canvas: HTMLCanvasElement) { + const params = { + alpha: true, + depth: false, + stencil: false, + antialias: false, + preserveDrawingBuffer: false, + }; + + let gl = canvas.getContext( + "webgl2", + params, + ) as WebGL2RenderingContext | null; + + if (!gl) { + gl = (canvas.getContext("webgl", params) || + canvas.getContext( + "experimental-webgl", + params, + )) as WebGL2RenderingContext | null; + } + + if (!gl) { + throw new Error("Unable to initialize WebGL."); + } + + const isWebGL2 = "drawBuffers" in gl; + + let supportLinearFiltering = false; + let halfFloat = null; + + if (isWebGL2) { + (gl as WebGL2RenderingContext).getExtension("EXT_color_buffer_float"); + supportLinearFiltering = !!(gl as WebGL2RenderingContext).getExtension( + "OES_texture_float_linear", + ); + } else { + halfFloat = gl.getExtension("OES_texture_half_float"); + supportLinearFiltering = !!gl.getExtension( + "OES_texture_half_float_linear", + ); + } + + gl.clearColor(0, 0, 0, 1); + + const halfFloatTexType = isWebGL2 + ? (gl as WebGL2RenderingContext).HALF_FLOAT + : (halfFloat && (halfFloat as any).HALF_FLOAT_OES) || 0; + + let formatRGBA: any; + let formatRG: any; + let formatR: any; + + if (isWebGL2) { + formatRGBA = getSupportedFormat( + gl, + (gl as WebGL2RenderingContext).RGBA16F, + gl.RGBA, + halfFloatTexType, + ); + formatRG = getSupportedFormat( + gl, + (gl as WebGL2RenderingContext).RG16F, + (gl as WebGL2RenderingContext).RG, + halfFloatTexType, + ); + formatR = getSupportedFormat( + gl, + (gl as WebGL2RenderingContext).R16F, + (gl as WebGL2RenderingContext).RED, + halfFloatTexType, + ); + } else { + formatRGBA = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); + formatRG = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); + formatR = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType); + } + + return { + gl, + ext: { + formatRGBA, + formatRG, + formatR, + halfFloatTexType, + supportLinearFiltering, + }, + }; + } + + function getSupportedFormat( + gl: WebGLRenderingContext | WebGL2RenderingContext, + internalFormat: number, + format: number, + type: number, + ): { internalFormat: number; format: number } | null { + if (!supportRenderTextureFormat(gl, internalFormat, format, type)) { + if ("drawBuffers" in gl) { + const gl2 = gl as WebGL2RenderingContext; + switch (internalFormat) { + case gl2.R16F: + return getSupportedFormat(gl2, gl2.RG16F, gl2.RG, type); + case gl2.RG16F: + return getSupportedFormat(gl2, gl2.RGBA16F, gl2.RGBA, type); + default: + return null; + } + } + return null; + } + return { internalFormat, format }; + } + + function supportRenderTextureFormat( + gl: WebGLRenderingContext | WebGL2RenderingContext, + internalFormat: number, + format: number, + type: number, + ) { + const texture = gl.createTexture(); + if (!texture) return false; + + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D( + gl.TEXTURE_2D, + 0, + internalFormat, + 4, + 4, + 0, + format, + type, + null, + ); + + const fbo = gl.createFramebuffer(); + if (!fbo) return false; + + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); + gl.framebufferTexture2D( + gl.FRAMEBUFFER, + gl.COLOR_ATTACHMENT0, + gl.TEXTURE_2D, + texture, + 0, + ); + const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + return status === gl.FRAMEBUFFER_COMPLETE; + } + + function hashCode(s: string) { + if (!s.length) return 0; + let hash = 0; + for (let i = 0; i < s.length; i++) { + hash = (hash << 5) - hash + s.charCodeAt(i); + hash |= 0; + } + return hash; + } + + function addKeywords(source: string, keywords: string[] | null) { + if (!keywords) return source; + let keywordsString = ""; + for (const keyword of keywords) { + keywordsString += `#define ${keyword}\n`; + } + return keywordsString + source; + } + + function compileShader( + type: number, + source: string, + keywords: string[] | null = null, + ): WebGLShader | null { + const shaderSource = addKeywords(source, keywords); + const shader = gl.createShader(type); + if (!shader) return null; + gl.shaderSource(shader, shaderSource); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + console.trace(gl.getShaderInfoLog(shader)); + } + return shader; + } + + function createProgram( + vertexShader: WebGLShader | null, + fragmentShader: WebGLShader | null, + ): WebGLProgram | null { + if (!vertexShader || !fragmentShader) return null; + const program = gl.createProgram(); + if (!program) return null; + gl.attachShader(program, vertexShader); + gl.attachShader(program, fragmentShader); + gl.linkProgram(program); + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + console.trace(gl.getProgramInfoLog(program)); + } + return program; + } + + function getUniforms(program: WebGLProgram) { + let uniforms: Record = {}; + const uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0; i < uniformCount; i++) { + const uniformInfo = gl.getActiveUniform(program, i); + if (uniformInfo) { + uniforms[uniformInfo.name] = gl.getUniformLocation( + program, + uniformInfo.name, + ); + } + } + return uniforms; + } + + class Program { + program: WebGLProgram | null; + uniforms: Record; + + constructor( + vertexShader: WebGLShader | null, + fragmentShader: WebGLShader | null, + ) { + this.program = createProgram(vertexShader, fragmentShader); + this.uniforms = this.program ? getUniforms(this.program) : {}; + } + + bind() { + if (this.program) gl.useProgram(this.program); + } + } + + class Material { + vertexShader: WebGLShader | null; + fragmentShaderSource: string; + programs: Record; + activeProgram: WebGLProgram | null; + uniforms: Record; + + constructor( + vertexShader: WebGLShader | null, + fragmentShaderSource: string, + ) { + this.vertexShader = vertexShader; + this.fragmentShaderSource = fragmentShaderSource; + this.programs = {}; + this.activeProgram = null; + this.uniforms = {}; + } + + setKeywords(keywords: string[]) { + let hash = 0; + for (const kw of keywords) { + hash += hashCode(kw); + } + let program = this.programs[hash]; + if (program == null) { + const fragmentShader = compileShader( + gl.FRAGMENT_SHADER, + this.fragmentShaderSource, + keywords, + ); + program = createProgram(this.vertexShader, fragmentShader); + this.programs[hash] = program; + } + if (program === this.activeProgram) return; + if (program) { + this.uniforms = getUniforms(program); + } + this.activeProgram = program; + } + + bind() { + if (this.activeProgram) { + gl.useProgram(this.activeProgram); + } + } + } + + const baseVertexShader = compileShader( + gl.VERTEX_SHADER, + ` + precision highp float; + attribute vec2 aPosition; + varying vec2 vUv; + varying vec2 vL; + varying vec2 vR; + varying vec2 vT; + varying vec2 vB; + uniform vec2 texelSize; + + void main () { + vUv = aPosition * 0.5 + 0.5; + vL = vUv - vec2(texelSize.x, 0.0); + vR = vUv + vec2(texelSize.x, 0.0); + vT = vUv + vec2(0.0, texelSize.y); + vB = vUv - vec2(0.0, texelSize.y); + gl_Position = vec4(aPosition, 0.0, 1.0); + } + `, + ); + + const copyShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + uniform sampler2D uTexture; + + void main () { + gl_FragColor = texture2D(uTexture, vUv); + } + `, + ); + + const clearShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + uniform sampler2D uTexture; + uniform float value; + + void main () { + gl_FragColor = value * texture2D(uTexture, vUv); + } + `, + ); + + const displayShaderSource = ` + precision highp float; + precision highp sampler2D; + varying vec2 vUv; + varying vec2 vL; + varying vec2 vR; + varying vec2 vT; + varying vec2 vB; + uniform sampler2D uTexture; + uniform sampler2D uDithering; + uniform vec2 ditherScale; + uniform vec2 texelSize; + + vec3 linearToGamma (vec3 color) { + color = max(color, vec3(0)); + return max(1.055 * pow(color, vec3(0.416666667)) - 0.055, vec3(0)); + } + + void main () { + vec3 c = texture2D(uTexture, vUv).rgb; + #ifdef SHADING + vec3 lc = texture2D(uTexture, vL).rgb; + vec3 rc = texture2D(uTexture, vR).rgb; + vec3 tc = texture2D(uTexture, vT).rgb; + vec3 bc = texture2D(uTexture, vB).rgb; + + float dx = length(rc) - length(lc); + float dy = length(tc) - length(bc); + + vec3 n = normalize(vec3(dx, dy, length(texelSize))); + vec3 l = vec3(0.0, 0.0, 1.0); + + float diffuse = clamp(dot(n, l) + 0.7, 0.7, 1.0); + c *= diffuse; + #endif + + float a = max(c.r, max(c.g, c.b)); + gl_FragColor = vec4(c, a); + } + `; + + const splatShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision highp float; + precision highp sampler2D; + varying vec2 vUv; + uniform sampler2D uTarget; + uniform float aspectRatio; + uniform vec3 color; + uniform vec2 point; + uniform float radius; + + void main () { + vec2 p = vUv - point.xy; + p.x *= aspectRatio; + vec3 splat = exp(-dot(p, p) / radius) * color; + vec3 base = texture2D(uTarget, vUv).xyz; + gl_FragColor = vec4(base + splat, 1.0); + } + `, + ); + + const advectionShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision highp float; + precision highp sampler2D; + varying vec2 vUv; + uniform sampler2D uVelocity; + uniform sampler2D uSource; + uniform vec2 texelSize; + uniform vec2 dyeTexelSize; + uniform float dt; + uniform float dissipation; + + vec4 bilerp (sampler2D sam, vec2 uv, vec2 tsize) { + vec2 st = uv / tsize - 0.5; + vec2 iuv = floor(st); + vec2 fuv = fract(st); + + vec4 a = texture2D(sam, (iuv + vec2(0.5, 0.5)) * tsize); + vec4 b = texture2D(sam, (iuv + vec2(1.5, 0.5)) * tsize); + vec4 c = texture2D(sam, (iuv + vec2(0.5, 1.5)) * tsize); + vec4 d = texture2D(sam, (iuv + vec2(1.5, 1.5)) * tsize); + + return mix(mix(a, b, fuv.x), mix(c, d, fuv.x), fuv.y); + } + + void main () { + #ifdef MANUAL_FILTERING + vec2 coord = vUv - dt * bilerp(uVelocity, vUv, texelSize).xy * texelSize; + vec4 result = bilerp(uSource, coord, dyeTexelSize); + #else + vec2 coord = vUv - dt * texture2D(uVelocity, vUv).xy * texelSize; + vec4 result = texture2D(uSource, coord); + #endif + float decay = 1.0 + dissipation * dt; + gl_FragColor = result / decay; + } + `, + ext.supportLinearFiltering ? null : ["MANUAL_FILTERING"], + ); + + const divergenceShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + varying highp vec2 vL; + varying highp vec2 vR; + varying highp vec2 vT; + varying highp vec2 vB; + uniform sampler2D uVelocity; + + void main () { + float L = texture2D(uVelocity, vL).x; + float R = texture2D(uVelocity, vR).x; + float T = texture2D(uVelocity, vT).y; + float B = texture2D(uVelocity, vB).y; + + vec2 C = texture2D(uVelocity, vUv).xy; + if (vL.x < 0.0) { L = -C.x; } + if (vR.x > 1.0) { R = -C.x; } + if (vT.y > 1.0) { T = -C.y; } + if (vB.y < 0.0) { B = -C.y; } + + float div = 0.5 * (R - L + T - B); + gl_FragColor = vec4(div, 0.0, 0.0, 1.0); + } + `, + ); + + const curlShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + varying highp vec2 vL; + varying highp vec2 vR; + varying highp vec2 vT; + varying highp vec2 vB; + uniform sampler2D uVelocity; + + void main () { + float L = texture2D(uVelocity, vL).y; + float R = texture2D(uVelocity, vR).y; + float T = texture2D(uVelocity, vT).x; + float B = texture2D(uVelocity, vB).x; + float vorticity = R - L - T + B; + gl_FragColor = vec4(0.5 * vorticity, 0.0, 0.0, 1.0); + } + `, + ); + + const vorticityShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision highp float; + precision highp sampler2D; + varying vec2 vUv; + varying vec2 vL; + varying vec2 vR; + varying vec2 vT; + varying vec2 vB; + uniform sampler2D uVelocity; + uniform sampler2D uCurl; + uniform float curl; + uniform float dt; + + void main () { + float L = texture2D(uCurl, vL).x; + float R = texture2D(uCurl, vR).x; + float T = texture2D(uCurl, vT).x; + float B = texture2D(uCurl, vB).x; + float C = texture2D(uCurl, vUv).x; + + vec2 force = 0.5 * vec2(abs(T) - abs(B), abs(R) - abs(L)); + force /= length(force) + 0.0001; + force *= curl * C; + force.y *= -1.0; + + vec2 velocity = texture2D(uVelocity, vUv).xy; + velocity += force * dt; + velocity = min(max(velocity, -1000.0), 1000.0); + gl_FragColor = vec4(velocity, 0.0, 1.0); + } + `, + ); + + const pressureShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + varying highp vec2 vL; + varying highp vec2 vR; + varying highp vec2 vT; + varying highp vec2 vB; + uniform sampler2D uPressure; + uniform sampler2D uDivergence; + + void main () { + float L = texture2D(uPressure, vL).x; + float R = texture2D(uPressure, vR).x; + float T = texture2D(uPressure, vT).x; + float B = texture2D(uPressure, vB).x; + float C = texture2D(uPressure, vUv).x; + float divergence = texture2D(uDivergence, vUv).x; + float pressure = (L + R + B + T - divergence) * 0.25; + gl_FragColor = vec4(pressure, 0.0, 0.0, 1.0); + } + `, + ); + + const gradientSubtractShader = compileShader( + gl.FRAGMENT_SHADER, + ` + precision mediump float; + precision mediump sampler2D; + varying highp vec2 vUv; + varying highp vec2 vL; + varying highp vec2 vR; + varying highp vec2 vT; + varying highp vec2 vB; + uniform sampler2D uPressure; + uniform sampler2D uVelocity; + + void main () { + float L = texture2D(uPressure, vL).x; + float R = texture2D(uPressure, vR).x; + float T = texture2D(uPressure, vT).x; + float B = texture2D(uPressure, vB).x; + vec2 velocity = texture2D(uVelocity, vUv).xy; + velocity.xy -= vec2(R - L, T - B); + gl_FragColor = vec4(velocity, 0.0, 1.0); + } + `, + ); + + const blit = (() => { + const buffer = gl.createBuffer()!; + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + gl.bufferData( + gl.ARRAY_BUFFER, + new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), + gl.STATIC_DRAW, + ); + const elemBuffer = gl.createBuffer()!; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, elemBuffer); + gl.bufferData( + gl.ELEMENT_ARRAY_BUFFER, + new Uint16Array([0, 1, 2, 0, 2, 3]), + gl.STATIC_DRAW, + ); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + gl.enableVertexAttribArray(0); + + return (target: FBO | null, doClear = false) => { + if (!gl) return; + if (!target) { + gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } else { + gl.viewport(0, 0, target.width, target.height); + gl.bindFramebuffer(gl.FRAMEBUFFER, target.fbo); + } + if (doClear) { + gl.clearColor(0, 0, 0, 1); + gl.clear(gl.COLOR_BUFFER_BIT); + } + gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0); + }; + })(); + + interface FBO { + texture: WebGLTexture; + fbo: WebGLFramebuffer; + width: number; + height: number; + texelSizeX: number; + texelSizeY: number; + attach: (id: number) => number; + } + + interface DoubleFBO { + width: number; + height: number; + texelSizeX: number; + texelSizeY: number; + read: FBO; + write: FBO; + swap: () => void; + } + + let dye: DoubleFBO; + let velocity: DoubleFBO; + let divergence: FBO; + let curl: FBO; + let pressure: DoubleFBO; + + const copyProgram = new Program(baseVertexShader, copyShader); + const clearProgram = new Program(baseVertexShader, clearShader); + const splatProgram = new Program(baseVertexShader, splatShader); + const advectionProgram = new Program(baseVertexShader, advectionShader); + const divergenceProgram = new Program(baseVertexShader, divergenceShader); + const curlProgram = new Program(baseVertexShader, curlShader); + const vorticityProgram = new Program(baseVertexShader, vorticityShader); + const pressureProgram = new Program(baseVertexShader, pressureShader); + const gradienSubtractProgram = new Program( + baseVertexShader, + gradientSubtractShader, + ); + const displayMaterial = new Material(baseVertexShader, displayShaderSource); + + function createFBO( + w: number, + h: number, + internalFormat: number, + format: number, + type: number, + param: number, + ): FBO { + gl.activeTexture(gl.TEXTURE0); + const texture = gl.createTexture()!; + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, param); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, param); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D( + gl.TEXTURE_2D, + 0, + internalFormat, + w, + h, + 0, + format, + type, + null, + ); + const fbo = gl.createFramebuffer()!; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); + gl.framebufferTexture2D( + gl.FRAMEBUFFER, + gl.COLOR_ATTACHMENT0, + gl.TEXTURE_2D, + texture, + 0, + ); + gl.viewport(0, 0, w, h); + gl.clear(gl.COLOR_BUFFER_BIT); + + const texelSizeX = 1 / w; + const texelSizeY = 1 / h; + + return { + texture, + fbo, + width: w, + height: h, + texelSizeX, + texelSizeY, + attach(id: number) { + gl.activeTexture(gl.TEXTURE0 + id); + gl.bindTexture(gl.TEXTURE_2D, texture); + return id; + }, + }; + } + + function createDoubleFBO( + w: number, + h: number, + internalFormat: number, + format: number, + type: number, + param: number, + ): DoubleFBO { + const fbo1 = createFBO(w, h, internalFormat, format, type, param); + const fbo2 = createFBO(w, h, internalFormat, format, type, param); + return { + width: w, + height: h, + texelSizeX: fbo1.texelSizeX, + texelSizeY: fbo1.texelSizeY, + read: fbo1, + write: fbo2, + swap() { + const tmp = this.read; + this.read = this.write; + this.write = tmp; + }, + }; + } + + function resizeFBO( + target: FBO, + w: number, + h: number, + internalFormat: number, + format: number, + type: number, + param: number, + ) { + const newFBO = createFBO(w, h, internalFormat, format, type, param); + copyProgram.bind(); + if (copyProgram.uniforms.uTexture) + gl.uniform1i(copyProgram.uniforms.uTexture, target.attach(0)); + blit(newFBO, false); + return newFBO; + } + + function resizeDoubleFBO( + target: DoubleFBO, + w: number, + h: number, + internalFormat: number, + format: number, + type: number, + param: number, + ) { + if (target.width === w && target.height === h) return target; + target.read = resizeFBO( + target.read, + w, + h, + internalFormat, + format, + type, + param, + ); + target.write = createFBO(w, h, internalFormat, format, type, param); + target.width = w; + target.height = h; + target.texelSizeX = 1 / w; + target.texelSizeY = 1 / h; + return target; + } + + function initFramebuffers() { + const simRes = getResolution(config.SIM_RESOLUTION!); + const dyeRes = getResolution(config.DYE_RESOLUTION!); + + const texType = ext.halfFloatTexType; + const rgba = ext.formatRGBA; + const rg = ext.formatRG; + const r = ext.formatR; + const filtering = ext.supportLinearFiltering ? gl.LINEAR : gl.NEAREST; + gl.disable(gl.BLEND); + + if (!dye) { + dye = createDoubleFBO( + dyeRes.width, + dyeRes.height, + rgba.internalFormat, + rgba.format, + texType, + filtering, + ); + } else { + dye = resizeDoubleFBO( + dye, + dyeRes.width, + dyeRes.height, + rgba.internalFormat, + rgba.format, + texType, + filtering, + ); + } + + if (!velocity) { + velocity = createDoubleFBO( + simRes.width, + simRes.height, + rg.internalFormat, + rg.format, + texType, + filtering, + ); + } else { + velocity = resizeDoubleFBO( + velocity, + simRes.width, + simRes.height, + rg.internalFormat, + rg.format, + texType, + filtering, + ); + } + + divergence = createFBO( + simRes.width, + simRes.height, + r.internalFormat, + r.format, + texType, + gl.NEAREST, + ); + curl = createFBO( + simRes.width, + simRes.height, + r.internalFormat, + r.format, + texType, + gl.NEAREST, + ); + pressure = createDoubleFBO( + simRes.width, + simRes.height, + r.internalFormat, + r.format, + texType, + gl.NEAREST, + ); + } + + function updateKeywords() { + const displayKeywords: string[] = []; + if (config.SHADING) displayKeywords.push("SHADING"); + displayMaterial.setKeywords(displayKeywords); + } + + function getResolution(resolution: number) { + const w = gl.drawingBufferWidth; + const h = gl.drawingBufferHeight; + const aspectRatio = w / h; + let aspect = aspectRatio < 1 ? 1 / aspectRatio : aspectRatio; + const min = Math.round(resolution); + const max = Math.round(resolution * aspect); + if (w > h) { + return { width: max, height: min }; + } + return { width: min, height: max }; + } + + function scaleByPixelRatio(input: number) { + const pixelRatio = window.devicePixelRatio || 1; + return Math.floor(input * pixelRatio); + } + + updateKeywords(); + initFramebuffers(); + + let lastUpdateTime = Date.now(); + let colorUpdateTimer = 0.0; + + function updateFrame() { + const dt = calcDeltaTime(); + if (resizeCanvas()) initFramebuffers(); + updateColors(dt); + applyInputs(); + step(dt); + render(null); + requestAnimationFrame(updateFrame); + } + + function calcDeltaTime() { + const now = Date.now(); + let dt = (now - lastUpdateTime) / 1000; + dt = Math.min(dt, 0.016666); + lastUpdateTime = now; + return dt; + } + + function resizeCanvas() { + const width = scaleByPixelRatio(canvas!.clientWidth); + const height = scaleByPixelRatio(canvas!.clientHeight); + if (canvas!.width !== width || canvas!.height !== height) { + canvas!.width = width; + canvas!.height = height; + return true; + } + return false; + } + + function updateColors(dt: number) { + colorUpdateTimer += dt * config.COLOR_UPDATE_SPEED; + if (colorUpdateTimer >= 1) { + colorUpdateTimer = wrap(colorUpdateTimer, 0, 1); + pointers.forEach((p) => { + p.color = generateColor(); + }); + } + } + + function applyInputs() { + for (const p of pointers) { + if (p.moved) { + p.moved = false; + splatPointer(p); + } + } + } + + function step(dt: number) { + gl.disable(gl.BLEND); + + curlProgram.bind(); + if (curlProgram.uniforms.texelSize) { + gl.uniform2f( + curlProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if (curlProgram.uniforms.uVelocity) { + gl.uniform1i(curlProgram.uniforms.uVelocity, velocity.read.attach(0)); + } + blit(curl); + + vorticityProgram.bind(); + if (vorticityProgram.uniforms.texelSize) { + gl.uniform2f( + vorticityProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if (vorticityProgram.uniforms.uVelocity) { + gl.uniform1i( + vorticityProgram.uniforms.uVelocity, + velocity.read.attach(0), + ); + } + if (vorticityProgram.uniforms.uCurl) { + gl.uniform1i(vorticityProgram.uniforms.uCurl, curl.attach(1)); + } + if (vorticityProgram.uniforms.curl) { + gl.uniform1f(vorticityProgram.uniforms.curl, config.CURL); + } + if (vorticityProgram.uniforms.dt) { + gl.uniform1f(vorticityProgram.uniforms.dt, dt); + } + blit(velocity.write); + velocity.swap(); + + divergenceProgram.bind(); + if (divergenceProgram.uniforms.texelSize) { + gl.uniform2f( + divergenceProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if (divergenceProgram.uniforms.uVelocity) { + gl.uniform1i( + divergenceProgram.uniforms.uVelocity, + velocity.read.attach(0), + ); + } + blit(divergence); + + clearProgram.bind(); + if (clearProgram.uniforms.uTexture) { + gl.uniform1i(clearProgram.uniforms.uTexture, pressure.read.attach(0)); + } + if (clearProgram.uniforms.value) { + gl.uniform1f(clearProgram.uniforms.value, config.PRESSURE); + } + blit(pressure.write); + pressure.swap(); + + pressureProgram.bind(); + if (pressureProgram.uniforms.texelSize) { + gl.uniform2f( + pressureProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if (pressureProgram.uniforms.uDivergence) { + gl.uniform1i( + pressureProgram.uniforms.uDivergence, + divergence.attach(0), + ); + } + for (let i = 0; i < config.PRESSURE_ITERATIONS; i++) { + if (pressureProgram.uniforms.uPressure) { + gl.uniform1i( + pressureProgram.uniforms.uPressure, + pressure.read.attach(1), + ); + } + blit(pressure.write); + pressure.swap(); + } + + gradienSubtractProgram.bind(); + if (gradienSubtractProgram.uniforms.texelSize) { + gl.uniform2f( + gradienSubtractProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if (gradienSubtractProgram.uniforms.uPressure) { + gl.uniform1i( + gradienSubtractProgram.uniforms.uPressure, + pressure.read.attach(0), + ); + } + if (gradienSubtractProgram.uniforms.uVelocity) { + gl.uniform1i( + gradienSubtractProgram.uniforms.uVelocity, + velocity.read.attach(1), + ); + } + blit(velocity.write); + velocity.swap(); + + advectionProgram.bind(); + if (advectionProgram.uniforms.texelSize) { + gl.uniform2f( + advectionProgram.uniforms.texelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + if ( + !ext.supportLinearFiltering && + advectionProgram.uniforms.dyeTexelSize + ) { + gl.uniform2f( + advectionProgram.uniforms.dyeTexelSize, + velocity.texelSizeX, + velocity.texelSizeY, + ); + } + const velocityId = velocity.read.attach(0); + if (advectionProgram.uniforms.uVelocity) { + gl.uniform1i(advectionProgram.uniforms.uVelocity, velocityId); + } + if (advectionProgram.uniforms.uSource) { + gl.uniform1i(advectionProgram.uniforms.uSource, velocityId); + } + if (advectionProgram.uniforms.dt) { + gl.uniform1f(advectionProgram.uniforms.dt, dt); + } + if (advectionProgram.uniforms.dissipation) { + gl.uniform1f( + advectionProgram.uniforms.dissipation, + config.VELOCITY_DISSIPATION, + ); + } + blit(velocity.write); + velocity.swap(); + + if ( + !ext.supportLinearFiltering && + advectionProgram.uniforms.dyeTexelSize + ) { + gl.uniform2f( + advectionProgram.uniforms.dyeTexelSize, + dye.texelSizeX, + dye.texelSizeY, + ); + } + if (advectionProgram.uniforms.uVelocity) { + gl.uniform1i( + advectionProgram.uniforms.uVelocity, + velocity.read.attach(0), + ); + } + if (advectionProgram.uniforms.uSource) { + gl.uniform1i(advectionProgram.uniforms.uSource, dye.read.attach(1)); + } + if (advectionProgram.uniforms.dissipation) { + gl.uniform1f( + advectionProgram.uniforms.dissipation, + config.DENSITY_DISSIPATION, + ); + } + blit(dye.write); + dye.swap(); + } + + function render(target: FBO | null) { + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.BLEND); + drawDisplay(target); + } + + function drawDisplay(target: FBO | null) { + const width = target ? target.width : gl.drawingBufferWidth; + const height = target ? target.height : gl.drawingBufferHeight; + displayMaterial.bind(); + if (config.SHADING && displayMaterial.uniforms.texelSize) { + gl.uniform2f(displayMaterial.uniforms.texelSize, 1 / width, 1 / height); + } + if (displayMaterial.uniforms.uTexture) { + gl.uniform1i(displayMaterial.uniforms.uTexture, dye.read.attach(0)); + } + blit(target, false); + } + + function splatPointer(pointer: Pointer) { + const dx = pointer.deltaX * config.SPLAT_FORCE; + const dy = pointer.deltaY * config.SPLAT_FORCE; + splat(pointer.texcoordX, pointer.texcoordY, dx, dy, pointer.color); + } + + function clickSplat(pointer: Pointer) { + const color = generateColor(); + color.r *= 10; + color.g *= 10; + color.b *= 10; + const dx = 10 * (Math.random() - 0.5); + const dy = 30 * (Math.random() - 0.5); + splat(pointer.texcoordX, pointer.texcoordY, dx, dy, color); + } + + function splat( + x: number, + y: number, + dx: number, + dy: number, + color: ColorRGB, + ) { + splatProgram.bind(); + if (splatProgram.uniforms.uTarget) { + gl.uniform1i(splatProgram.uniforms.uTarget, velocity.read.attach(0)); + } + if (splatProgram.uniforms.aspectRatio) { + gl.uniform1f( + splatProgram.uniforms.aspectRatio, + canvas!.width / canvas!.height, + ); + } + if (splatProgram.uniforms.point) { + gl.uniform2f(splatProgram.uniforms.point, x, y); + } + if (splatProgram.uniforms.color) { + gl.uniform3f(splatProgram.uniforms.color, dx, dy, 0); + } + if (splatProgram.uniforms.radius) { + gl.uniform1f( + splatProgram.uniforms.radius, + correctRadius(config.SPLAT_RADIUS / 100)!, + ); + } + blit(velocity.write); + velocity.swap(); + + if (splatProgram.uniforms.uTarget) { + gl.uniform1i(splatProgram.uniforms.uTarget, dye.read.attach(0)); + } + if (splatProgram.uniforms.color) { + gl.uniform3f(splatProgram.uniforms.color, color.r, color.g, color.b); + } + blit(dye.write); + dye.swap(); + } + + function correctRadius(radius: number) { + const aspectRatio = canvas!.width / canvas!.height; + if (aspectRatio > 1) radius *= aspectRatio; + return radius; + } + + function updatePointerDownData( + pointer: Pointer, + id: number, + posX: number, + posY: number, + ) { + pointer.id = id; + pointer.down = true; + pointer.moved = false; + pointer.texcoordX = posX / canvas!.width; + pointer.texcoordY = 1 - posY / canvas!.height; + pointer.prevTexcoordX = pointer.texcoordX; + pointer.prevTexcoordY = pointer.texcoordY; + pointer.deltaX = 0; + pointer.deltaY = 0; + pointer.color = generateColor(); + } + + function updatePointerMoveData( + pointer: Pointer, + posX: number, + posY: number, + color: ColorRGB, + ) { + pointer.prevTexcoordX = pointer.texcoordX; + pointer.prevTexcoordY = pointer.texcoordY; + pointer.texcoordX = posX / canvas!.width; + pointer.texcoordY = 1 - posY / canvas!.height; + pointer.deltaX = correctDeltaX( + pointer.texcoordX - pointer.prevTexcoordX, + )!; + pointer.deltaY = correctDeltaY( + pointer.texcoordY - pointer.prevTexcoordY, + )!; + pointer.moved = + Math.abs(pointer.deltaX) > 0 || Math.abs(pointer.deltaY) > 0; + pointer.color = color; + } + + function updatePointerUpData(pointer: Pointer) { + pointer.down = false; + } + + function correctDeltaX(delta: number) { + const aspectRatio = canvas!.width / canvas!.height; + if (aspectRatio < 1) delta *= aspectRatio; + return delta; + } + + function correctDeltaY(delta: number) { + const aspectRatio = canvas!.width / canvas!.height; + if (aspectRatio > 1) delta /= aspectRatio; + return delta; + } + + function generateColor(): ColorRGB { + const c = HSVtoRGB(Math.random(), 1.0, 1.0); + c.r *= 0.15; + c.g *= 0.15; + c.b *= 0.15; + return c; + } + + function HSVtoRGB(h: number, s: number, v: number): ColorRGB { + let r = 0, + g = 0, + b = 0; + const i = Math.floor(h * 6); + const f = h * 6 - i; + const p = v * (1 - s); + const q = v * (1 - f * s); + const t = v * (1 - (1 - f) * s); + + switch (i % 6) { + case 0: + r = v; + g = t; + b = p; + break; + case 1: + r = q; + g = v; + b = p; + break; + case 2: + r = p; + g = v; + b = t; + break; + case 3: + r = p; + g = q; + b = v; + break; + case 4: + r = t; + g = p; + b = v; + break; + case 5: + r = v; + g = p; + b = q; + break; + } + return { r, g, b }; + } + + function wrap(value: number, min: number, max: number) { + const range = max - min; + if (range === 0) return min; + return ((value - min) % range) + min; + } + + window.addEventListener("mousedown", (e) => { + const pointer = pointers[0]; + const posX = scaleByPixelRatio(e.clientX); + const posY = scaleByPixelRatio(e.clientY); + updatePointerDownData(pointer, -1, posX, posY); + clickSplat(pointer); + }); + + function handleFirstMouseMove(e: MouseEvent) { + const pointer = pointers[0]; + const posX = scaleByPixelRatio(e.clientX); + const posY = scaleByPixelRatio(e.clientY); + const color = generateColor(); + updateFrame(); + updatePointerMoveData(pointer, posX, posY, color); + document.body.removeEventListener("mousemove", handleFirstMouseMove); + } + document.body.addEventListener("mousemove", handleFirstMouseMove); + + window.addEventListener("mousemove", (e) => { + const pointer = pointers[0]; + const posX = scaleByPixelRatio(e.clientX); + const posY = scaleByPixelRatio(e.clientY); + const color = pointer.color; + updatePointerMoveData(pointer, posX, posY, color); + }); + + function handleFirstTouchStart(e: TouchEvent) { + const touches = e.targetTouches; + const pointer = pointers[0]; + for (let i = 0; i < touches.length; i++) { + const posX = scaleByPixelRatio(touches[i].clientX); + const posY = scaleByPixelRatio(touches[i].clientY); + updateFrame(); + updatePointerDownData(pointer, touches[i].identifier, posX, posY); + } + document.body.removeEventListener("touchstart", handleFirstTouchStart); + } + document.body.addEventListener("touchstart", handleFirstTouchStart); + + window.addEventListener( + "touchstart", + (e) => { + const touches = e.targetTouches; + const pointer = pointers[0]; + for (let i = 0; i < touches.length; i++) { + const posX = scaleByPixelRatio(touches[i].clientX); + const posY = scaleByPixelRatio(touches[i].clientY); + updatePointerDownData(pointer, touches[i].identifier, posX, posY); + } + }, + false, + ); + + window.addEventListener( + "touchmove", + (e) => { + const touches = e.targetTouches; + const pointer = pointers[0]; + for (let i = 0; i < touches.length; i++) { + const posX = scaleByPixelRatio(touches[i].clientX); + const posY = scaleByPixelRatio(touches[i].clientY); + updatePointerMoveData(pointer, posX, posY, pointer.color); + } + }, + false, + ); + + window.addEventListener("touchend", (e) => { + const touches = e.changedTouches; + const pointer = pointers[0]; + for (let i = 0; i < touches.length; i++) { + updatePointerUpData(pointer); + } + }); + }, [ + SIM_RESOLUTION, + DYE_RESOLUTION, + CAPTURE_RESOLUTION, + DENSITY_DISSIPATION, + VELOCITY_DISSIPATION, + PRESSURE, + PRESSURE_ITERATIONS, + CURL, + SPLAT_RADIUS, + SPLAT_FORCE, + SHADING, + COLOR_UPDATE_SPEED, + BACK_COLOR, + TRANSPARENT, + ]); + + return ( +
    + +
    + ); +} diff --git a/src/components/cursors/TargetCursor.css b/src/components/cursors/TargetCursor.css deleted file mode 100644 index b5cd06a..0000000 --- a/src/components/cursors/TargetCursor.css +++ /dev/null @@ -1,57 +0,0 @@ -.target-cursor-wrapper { - position: fixed; - top: 0; - left: 0; - width: 0; - height: 0; - pointer-events: none; - z-index: 9999; - mix-blend-mode: difference; - transform: translate(-50%, -50%); -} - -.target-cursor-dot { - position: absolute; - left: 50%; - top: 50%; - width: 4px; - height: 4px; - background: #fff; - border-radius: 50%; - transform: translate(-50%, -50%); - will-change: transform; -} - -.target-cursor-corner { - position: absolute; - left: 50%; - top: 50%; - width: 12px; - height: 12px; - border: 3px solid #fff; - will-change: transform; -} - -.corner-tl { - transform: translate(-150%, -150%); - border-right: none; - border-bottom: none; -} - -.corner-tr { - transform: translate(50%, -150%); - border-left: none; - border-bottom: none; -} - -.corner-br { - transform: translate(50%, 50%); - border-left: none; - border-top: none; -} - -.corner-bl { - transform: translate(-150%, 50%); - border-right: none; - border-top: none; -} diff --git a/src/components/cursors/TargetCursor.jsx b/src/components/cursors/TargetCursor.tsx similarity index 63% rename from src/components/cursors/TargetCursor.jsx rename to src/components/cursors/TargetCursor.tsx index 0f46e14..7e298ea 100644 --- a/src/components/cursors/TargetCursor.jsx +++ b/src/components/cursors/TargetCursor.tsx @@ -1,51 +1,50 @@ -import { useEffect, useRef, useCallback, useMemo } from "react"; +import React, { useEffect, useRef, useCallback, useMemo } from "react"; import { gsap } from "gsap"; -import "./TargetCursor.css"; -const TargetCursor = ({ +export interface TargetCursorProps { + targetSelector?: string; + spinDuration?: number; + hideDefaultCursor?: boolean; + hoverDuration?: number; + parallaxOn?: boolean; +} + +const TargetCursor: React.FC = ({ targetSelector = ".cursor-target", spinDuration = 2, hideDefaultCursor = true, hoverDuration = 0.2, parallaxOn = true, }) => { - const cursorRef = useRef(null); - const cornersRef = useRef(null); - const spinTl = useRef(null); - const dotRef = useRef(null); + const cursorRef = useRef(null); + const cornersRef = useRef | null>(null); + const spinTl = useRef(null); + const dotRef = useRef(null); const isActiveRef = useRef(false); - const targetCornerPositionsRef = useRef(null); - const tickerFnRef = useRef(null); - const activeStrengthRef = useRef(0); + const targetCornerPositionsRef = useRef<{ x: number; y: number }[] | null>( + null, + ); + const tickerFnRef = useRef<(() => void) | null>(null); + const activeStrengthRef = useRef({ current: 0 }); const isMobile = useMemo(() => { const hasTouchScreen = "ontouchstart" in window || navigator.maxTouchPoints > 0; const isSmallScreen = window.innerWidth <= 768; - const userAgent = navigator.userAgent || navigator.vendor || window.opera; + const userAgent = + navigator.userAgent || navigator.vendor || (window as any).opera; const mobileRegex = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i; const isMobileUserAgent = mobileRegex.test(userAgent.toLowerCase()); return (hasTouchScreen && isSmallScreen) || isMobileUserAgent; }, []); - const constants = useMemo( - () => ({ - borderWidth: 3, - cornerSize: 12, - }), - [], - ); + const constants = useMemo(() => ({ borderWidth: 3, cornerSize: 12 }), []); - const moveCursor = useCallback((x, y) => { + const moveCursor = useCallback((x: number, y: number) => { if (!cursorRef.current) return; - gsap.to(cursorRef.current, { - x, - y, - duration: 0.1, - ease: "power3.out", - }); + gsap.to(cursorRef.current, { x, y, duration: 0.1, ease: "power3.out" }); }, []); useEffect(() => { @@ -57,13 +56,15 @@ const TargetCursor = ({ } const cursor = cursorRef.current; - cornersRef.current = cursor.querySelectorAll(".target-cursor-corner"); + cornersRef.current = cursor.querySelectorAll( + ".target-cursor-corner", + ); - let activeTarget = null; - let currentLeaveHandler = null; - let resumeTimeout = null; + let activeTarget: Element | null = null; + let currentLeaveHandler: (() => void) | null = null; + let resumeTimeout: ReturnType | null = null; - const cleanupTarget = (target) => { + const cleanupTarget = (target: Element) => { if (currentLeaveHandler) { target.removeEventListener("mouseleave", currentLeaveHandler); } @@ -81,13 +82,11 @@ const TargetCursor = ({ if (spinTl.current) { spinTl.current.kill(); } - spinTl.current = gsap - .timeline({ repeat: -1 }) - .to(cursor, { - rotation: "+=360", - duration: spinDuration, - ease: "none", - }); + spinTl.current = gsap.timeline({ repeat: -1 }).to(cursor, { + rotation: "+=360", + duration: spinDuration, + ease: "none", + }); }; createSpinTimeline(); @@ -100,26 +99,19 @@ const TargetCursor = ({ ) { return; } - - const strength = activeStrengthRef.current; + const strength = activeStrengthRef.current.current; if (strength === 0) return; - - const cursorX = gsap.getProperty(cursorRef.current, "x"); - const cursorY = gsap.getProperty(cursorRef.current, "y"); - + const cursorX = gsap.getProperty(cursorRef.current, "x") as number; + const cursorY = gsap.getProperty(cursorRef.current, "y") as number; const corners = Array.from(cornersRef.current); corners.forEach((corner, i) => { - const currentX = gsap.getProperty(corner, "x"); - const currentY = gsap.getProperty(corner, "y"); - - const targetX = targetCornerPositionsRef.current[i].x - cursorX; - const targetY = targetCornerPositionsRef.current[i].y - cursorY; - + const currentX = gsap.getProperty(corner, "x") as number; + const currentY = gsap.getProperty(corner, "y") as number; + const targetX = targetCornerPositionsRef.current![i].x - cursorX; + const targetY = targetCornerPositionsRef.current![i].y - cursorY; const finalX = currentX + (targetX - currentX) * strength; const finalY = currentY + (targetY - currentY) * strength; - const duration = strength >= 0.99 ? (parallaxOn ? 0.2 : 0) : 0.05; - gsap.to(corner, { x: finalX, y: finalY, @@ -132,22 +124,20 @@ const TargetCursor = ({ tickerFnRef.current = tickerFn; - const moveHandler = (e) => moveCursor(e.clientX, e.clientY); + const moveHandler = (e: MouseEvent) => moveCursor(e.clientX, e.clientY); window.addEventListener("mousemove", moveHandler); const scrollHandler = () => { if (!activeTarget || !cursorRef.current) return; - const mouseX = gsap.getProperty(cursorRef.current, "x"); - const mouseY = gsap.getProperty(cursorRef.current, "y"); + const mouseX = gsap.getProperty(cursorRef.current, "x") as number; + const mouseY = gsap.getProperty(cursorRef.current, "y") as number; const elementUnderMouse = document.elementFromPoint(mouseX, mouseY); const isStillOverTarget = elementUnderMouse && (elementUnderMouse === activeTarget || elementUnderMouse.closest(targetSelector) === activeTarget); if (!isStillOverTarget) { - if (currentLeaveHandler) { - currentLeaveHandler(); - } + currentLeaveHandler?.(); } }; window.addEventListener("scroll", scrollHandler, { passive: true }); @@ -167,10 +157,10 @@ const TargetCursor = ({ window.addEventListener("mousedown", mouseDownHandler); window.addEventListener("mouseup", mouseUpHandler); - const enterHandler = (e) => { - const directTarget = e.target; - const allTargets = []; - let current = directTarget; + const enterHandler = (e: MouseEvent) => { + const directTarget = e.target as Element; + const allTargets: Element[] = []; + let current: Element | null = directTarget; while (current && current !== document.body) { if (current.matches(targetSelector)) { allTargets.push(current); @@ -191,15 +181,14 @@ const TargetCursor = ({ activeTarget = target; const corners = Array.from(cornersRef.current); corners.forEach((corner) => gsap.killTweensOf(corner)); - gsap.killTweensOf(cursorRef.current, "rotation"); spinTl.current?.pause(); gsap.set(cursorRef.current, { rotation: 0 }); const rect = target.getBoundingClientRect(); const { borderWidth, cornerSize } = constants; - const cursorX = gsap.getProperty(cursorRef.current, "x"); - const cursorY = gsap.getProperty(cursorRef.current, "y"); + const cursorX = gsap.getProperty(cursorRef.current, "x") as number; + const cursorY = gsap.getProperty(cursorRef.current, "y") as number; targetCornerPositionsRef.current = [ { x: rect.left - borderWidth, y: rect.top - borderWidth }, @@ -215,9 +204,9 @@ const TargetCursor = ({ ]; isActiveRef.current = true; - gsap.ticker.add(tickerFnRef.current); + gsap.ticker.add(tickerFnRef.current!); - gsap.to(activeStrengthRef, { + gsap.to(activeStrengthRef.current, { current: 1, duration: hoverDuration, ease: "power2.out", @@ -225,21 +214,19 @@ const TargetCursor = ({ corners.forEach((corner, i) => { gsap.to(corner, { - x: targetCornerPositionsRef.current[i].x - cursorX, - y: targetCornerPositionsRef.current[i].y - cursorY, + x: targetCornerPositionsRef.current![i].x - cursorX, + y: targetCornerPositionsRef.current![i].y - cursorY, duration: 0.2, ease: "power2.out", }); }); const leaveHandler = () => { - gsap.ticker.remove(tickerFnRef.current); - + gsap.ticker.remove(tickerFnRef.current!); isActiveRef.current = false; targetCornerPositionsRef.current = null; - gsap.set(activeStrengthRef, { current: 0, overwrite: true }); + gsap.set(activeStrengthRef.current, { current: 0, overwrite: true }); activeTarget = null; - if (cornersRef.current) { const corners = Array.from(cornersRef.current); gsap.killTweensOf(corners); @@ -264,13 +251,12 @@ const TargetCursor = ({ ); }); } - resumeTimeout = setTimeout(() => { if (!activeTarget && cursorRef.current && spinTl.current) { const currentRotation = gsap.getProperty( cursorRef.current, "rotation", - ); + ) as number; const normalizedRotation = currentRotation % 360; spinTl.current.kill(); spinTl.current = gsap @@ -291,37 +277,31 @@ const TargetCursor = ({ } resumeTimeout = null; }, 50); - cleanupTarget(target); }; - currentLeaveHandler = leaveHandler; target.addEventListener("mouseleave", leaveHandler); }; - window.addEventListener("mouseover", enterHandler, { passive: true }); + window.addEventListener("mouseover", enterHandler as EventListener); return () => { if (tickerFnRef.current) { gsap.ticker.remove(tickerFnRef.current); } - window.removeEventListener("mousemove", moveHandler); - window.removeEventListener("mouseover", enterHandler); + window.removeEventListener("mouseover", enterHandler as EventListener); window.removeEventListener("scroll", scrollHandler); window.removeEventListener("mousedown", mouseDownHandler); window.removeEventListener("mouseup", mouseUpHandler); - if (activeTarget) { cleanupTarget(activeTarget); } - spinTl.current?.kill(); document.body.style.cursor = originalCursor; - isActiveRef.current = false; targetCornerPositionsRef.current = null; - activeStrengthRef.current = 0; + activeStrengthRef.current.current = 0; }; }, [ targetSelector, @@ -338,13 +318,11 @@ const TargetCursor = ({ if (isMobile || !cursorRef.current || !spinTl.current) return; if (spinTl.current.isActive()) { spinTl.current.kill(); - spinTl.current = gsap - .timeline({ repeat: -1 }) - .to(cursorRef.current, { - rotation: "+=360", - duration: spinDuration, - ease: "none", - }); + spinTl.current = gsap.timeline({ repeat: -1 }).to(cursorRef.current, { + rotation: "+=360", + duration: spinDuration, + ease: "none", + }); } }, [spinDuration, isMobile]); @@ -353,12 +331,32 @@ const TargetCursor = ({ } return ( -
    -
    -
    -
    -
    -
    +
    +
    +
    +
    +
    +
    ); }; diff --git a/src/index.css b/src/index.css index 450e4c6..5638536 100644 --- a/src/index.css +++ b/src/index.css @@ -59,8 +59,7 @@ body { margin: 0; min-height: 100vh; font-family: "Orbitron", sans-serif; - overflow-x: hidden; - + /* overflow-x: hidden; */ pointer-events: auto; } diff --git a/src/main.jsx b/src/main.jsx deleted file mode 100644 index b9a1a6d..0000000 --- a/src/main.jsx +++ /dev/null @@ -1,10 +0,0 @@ -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.jsx' - -createRoot(document.getElementById('root')).render( - - - , -) diff --git a/src/main.tsx b/src/main.tsx new file mode 100644 index 0000000..d9a1cf3 --- /dev/null +++ b/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import "./index.css"; +import App from "./App.js"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/src/pages/Contact.jsx b/src/pages/Contact.tsx similarity index 100% rename from src/pages/Contact.jsx rename to src/pages/Contact.tsx diff --git a/src/pages/Home.jsx b/src/pages/Home.tsx similarity index 96% rename from src/pages/Home.jsx rename to src/pages/Home.tsx index c9aef9e..3a60f9e 100644 --- a/src/pages/Home.jsx +++ b/src/pages/Home.tsx @@ -13,7 +13,6 @@ export default function Home() {

    Overview

    + +declare module "*.css" { + const content: { [className: string]: string }; + export default content; +} + +declare module "*.png"; +declare module "*.jpg"; +declare module "*.jpeg"; +declare module "*.svg"; +declare module "*.glb";