"use client"; /** * HyperspaceModel — 1:1 port of the original `cx` (chunk * 4d3f3b68dbbde33a.js): the cursor.glb arrow whose scale and stripe shader * build the "hyper-space" scroll sequence. The original caller mounts it as * ` rectMap("hyper-space")} * scaleSpinDegrees={180} />` — here the DOM target comes from the shared * layer registry ("hyper-space" key, set by HyperSpaceSection). * * Behavior (all from the original useFrame, priority -2): * - DOM rect tracking: cached for 11 frames, re-measured every 12th frame * or on any scroll delta (rect shifted by the scroll difference). * - Visibility: rect.top < viewportBottom + max(2·refMarginPx, 480) * (approach) and rect.bottom > -(6·refMarginPx) unless fully below the * leave cap min(0.35vh, restRadius·cssH/vpH·0.45); outside → hidden + * store reset. * - Scale: rest 0.1 → peak lerp by reveal = smoothstep01(clamp((vpMid - * (rect.top + margin))/vpH)); beforeShrink holds the reveal scale, * shrinking folds back to rest by shrinkT; damped at 32/s. * - Peak = hypot(vpW, vpH)·autoPeakPadding(1.64)/radius (hyperspace engulf). * - Stripe reveal uniform + arrowFullscreenProgressStore.setDampedScaleT * share the same normalized t. * - Spin: rotY = 180°·clamp(eR/0.4) while approaching; during shrink * 180°·(1 + clamp((shrinkT-0.6)/0.4)). * - Shader iTime: 2·clamp01((vpBottom - rect.top)/(vpBottom + rect.h)) — * the star-field travel time (uScrollDuration = 2). */ import { useEffect, useLayoutEffect, useMemo, useRef } from "react"; import * as THREE from "three"; import { useFrame, useLoader, useThree } from "@react-three/fiber"; import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js"; import { usePointer } from "@/lib/pointer"; import { useIsMobile } from "@/lib/useIsMobile"; import { useLightController } from "@/components/canvas/GlassModels"; import { arrowFullscreenProgressStore, } from "@/lib/arrowFullscreen"; import { getLayerTarget } from "@/lib/imageLayers"; import { scrollBus } from "@/lib/scrollBus"; const ACCENT = "#009dff"; const STRIPE_A = "#009dff"; const STRIPE_B = "#64c3ff"; const REST_SCALE = 0.1; const SCALE_SMOOTHING = 32; const AUTO_PEAK_PADDING = 1.64; const REF_MARGIN_PX = 120; const SCALE_SPIN_DEGREES = 180; // original caller prop const TILT: [number, number, number] = [0, 0, 45]; // rotationAxisTilt (cy) const MODEL_POSITION: [number, number, number] = [0, 0, 0]; const LIGHT_Z = 0.5; const rad = THREE.MathUtils.degToRad; const SPIN_RADIANS = rad(SCALE_SPIN_DEGREES); const TILT_RAD: [number, number, number] = [rad(TILT[0]), rad(TILT[1]), rad(TILT[2])]; const NEG_TILT_RAD: [number, number, number] = [-TILT_RAD[0], -TILT_RAD[1], -TILT_RAD[2]]; const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); function centerGeometry(geometry: THREE.BufferGeometry) { geometry.computeBoundingBox(); const bb = geometry.boundingBox; if (!bb) return; const cx = (bb.min.x + bb.max.x) / 2; const cy = (bb.min.y + bb.max.y) / 2; const cz = (bb.min.z + bb.max.z) / 2; if (Math.abs(cx) + Math.abs(cy) + Math.abs(cz) < 1e-8) return; geometry.translate(-cx, -cy, -cz); geometry.computeBoundingSphere(); } const vert = /* glsl */ ` varying vec3 vWorldNormal; varying vec3 vEyeVector; void main() { vec4 worldPos = modelMatrix * vec4(position, 1.0); vec4 mvPosition = viewMatrix * worldPos; gl_Position = projectionMatrix * mvPosition; vWorldNormal = normalize(modelMatrix * vec4(normal, 0.0)).xyz; vEyeVector = normalize(worldPos.xyz - cameraPosition); } `; const frag = /* glsl */ ` uniform vec3 iResolution; uniform float iTime; uniform float uScrollDuration; uniform vec3 uAccentColor; uniform vec3 uStripeColorA; uniform vec3 uStripeColorB; uniform float uStripeReveal; uniform float uOpacity; uniform vec3 uLight; uniform float uShininess; uniform float uDiffuseness; uniform float uSpecularStrength; uniform float uFresnelPower; uniform float uFresnelStrength; uniform vec3 uFresnelSideDir; varying vec3 vWorldNormal; varying vec3 vEyeVector; float hash21(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); } vec3 rgb2hsv(vec3 c) { vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y); float e = 1.0e-10; return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); } vec3 hsv2rgb(vec3 c) { vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); } vec3 sampleHyperspace(vec2 fragCoord) { vec2 R = iResolution.xy; float baseScale = max(1.0, min(R.x, R.y)); vec2 u = (fragCoord * 2.0 - R) / baseScale; float dur = max(uScrollDuration, 1e-4); float time = clamp(iTime, 0.0, dur); float t = clamp(time / dur, 0.0, 1.0); const float cellDensity = 100.0; vec2 polar = vec2(atan(u.y, u.x) / 3.0, length(u)); float angleCoord = (6.0 - polar.x) * cellDensity; float angleId = floor(angleCoord) + 0.5; float angleCell = abs(fract(angleCoord) - 0.5); float radialCoord = (6.0 - polar.y) * cellDensity; vec2 q = vec2(angleId, radialCoord); float travel = smoothstep(0.0, 1.0, t); float keepProbability = mix(0.18, 1.0, travel); float scrollSpeed = mix(0.7, 3.6, travel); float trailLength = mix(2.7, 0.975, travel); float raySeq = fract((angleId + 0.5) * 0.61803398875); float keepEdge = 0.025; float keepMask = 1.0 - smoothstep(keepProbability - keepEdge, keepProbability + keepEdge, raySeq); float phaseBase = (q.y * 0.02 + q.x * 0.4) * fract(q.x * 0.61); vec4 spark = max( 1.0 - fract(vec4(7.0, 6.0, 4.0, 0.0) * 0.02 + phaseBase + time * scrollSpeed) * trailLength, 0.0 ); float channelMix = max(max(spark.r, spark.g), spark.b); float edge = max(fwidth(channelMix) * 1.5, 2.0 / max(iResolution.y, 1.0)); float star = smoothstep(0.12 - edge, 0.12 + edge, channelMix); const float starThinness = 0.13; float thinEdge = max(fwidth(angleCell) * 1.5, 0.002); float thinMask = 1.0 - smoothstep(starThinness - thinEdge, starThinness + thinEdge, angleCell); star *= thinMask * keepMask; float radialBoost = pow(smoothstep(0.1, 1.0, polar.y), 1.25); float intensity = mix(0.0, 6.5, t * 1.2); float stripeBlend = hash21(vec2(angleId, 19.713)); vec3 stripeRgb = mix(uStripeColorA, uStripeColorB, stripeBlend); vec3 hsvA = rgb2hsv(max(uStripeColorA, vec3(1e-5))); vec3 hsvB = rgb2hsv(max(uStripeColorB, vec3(1e-5))); float dh = abs(hsvA.x - hsvB.x); dh = min(dh, 1.0 - dh); float hueBand = clamp(dh * 1.25 + 0.04, 0.07, 0.24); vec3 hsv = rgb2hsv(max(stripeRgb, vec3(1e-5))); float idHash = hash21(vec2(angleId, 6.18)); float idHash2 = hash21(vec2(angleId, 91.7)); float scrollPhase = time * scrollSpeed; float hueAnim = sin(scrollPhase * 0.52 + angleId * 0.29 + idHash * 6.2831853) * (hueBand * 0.85); float hueStripe = (idHash - 0.5) * hueBand * 2.0; hsv.x = fract(hsv.x + hueStripe + hueAnim); hsv.y = clamp(hsv.y * mix(0.96, 1.06, idHash2), 0.0, 1.0); hsv.z = clamp(hsv.z * mix(0.97, 1.05, idHash), 0.0, 1.0); vec3 sparkColor = hsv2rgb(hsv); float pulse = mix(0.78, 1.0, smoothstep(0.14, 0.5, channelMix)); sparkColor *= pulse; return intensity * radialBoost * sparkColor * star; } float fresnel(vec3 eyeDir, vec3 normal, float power) { float fresnelFactor = abs(dot(eyeDir, normal)); float inversefresnelFactor = 1.0 - fresnelFactor; return pow(inversefresnelFactor, power); } float specular(vec3 light, vec3 normal, vec3 eyeDir, float shininess, float diffuseness) { vec3 lightVector = normalize(-light); vec3 halfVector = normalize(eyeDir + lightVector); float NdotL = dot(normal, lightVector); float NdotH = abs(dot(normal, halfVector)); float kDiffuse = max(0.0, NdotL); float kSpecular = pow(NdotH, shininess); return kSpecular + kDiffuse * diffuseness; } void main() { vec2 fragCoord = gl_FragCoord.xy; vec3 stripes = sampleHyperspace(fragCoord); float reveal = clamp(uStripeReveal, 0.0, 1.0); float stripeLuma = dot(stripes, vec3(0.299, 0.587, 0.114)); // 蓝→黑:全屏前压到纯黑底;满 reveal 不再填 accent,间隙为 #000 float darken = smoothstep(0.0, 0.88, reveal); vec3 darkBase = mix(uAccentColor, vec3(0.0), darken); float gapMask = (1.0 - smoothstep(0.035, 0.12, stripeLuma)) * reveal; float crackGuard = 1.0 - smoothstep(0.68, 0.94, reveal); vec3 rgb = darkBase + stripes * reveal + uAccentColor * gapMask * 0.07 * crackGuard; vec3 normal = normalize(vWorldNormal); // 背面须翻转法线,否则高光/Fresnel 在背对相机时会错且易像「穿模」 if (!gl_FrontFacing) { normal = -normal; } vec3 eyeDir = normalize(vEyeVector); float glossMask = mix(1.0, smoothstep(0.1, 0.48, stripeLuma), reveal); float specularLight = specular(uLight, normal, eyeDir, uShininess, uDiffuseness); rgb += specularLight * uSpecularStrength * glossMask; float f = fresnel(eyeDir, normal, uFresnelPower); float sideDot = dot(normal, normalize(uFresnelSideDir)); float sideMask = smoothstep(-0.5, 0.5, sideDot); rgb += f * sideMask * vec3(uFresnelStrength) * glossMask; float alpha = clamp(uOpacity, 0.0, 1.0); if (alpha <= 0.0001) discard; gl_FragColor = vec4(rgb, alpha); #include #include } `; type TrackedRect = { left: number; top: number; width: number; height: number; right: number; bottom: number; }; export function HyperspaceModel() { const gltf = useLoader(GLTFLoader, "/model/cursor.glb"); const groupRef = useRef(null!); const spinRef = useRef(null!); const meshRef = useRef(null!); const materialRef = useRef(null!); const { size, gl, camera } = useThree(); const { uv, insideRef } = usePointer(); const isMobile = useIsMobile(); const mergedGeometry = useMemo(() => { gltf.scene.updateMatrixWorld(true); const geometries: THREE.BufferGeometry[] = []; gltf.scene.traverse((obj: THREE.Object3D) => { if ((obj as THREE.Mesh).isMesh && (obj as THREE.Mesh).geometry) { const geo = (obj as THREE.Mesh).geometry.clone(); geo.applyMatrix4((obj as THREE.Mesh).matrixWorld); geometries.push(geo); } }); if (geometries.length === 0) return null; let merged: THREE.BufferGeometry | null = null; try { merged = mergeGeometries(geometries, false); } catch { merged = null; } if (!merged && geometries.length >= 1) merged = geometries[0]; if (!merged) return null; centerGeometry(merged); return merged; }, [gltf]); useEffect(() => { return () => { mergedGeometry?.dispose(); }; }, [mergedGeometry]); const uniforms = useMemo( () => ({ iResolution: { value: new THREE.Vector3(1, 1, 1) }, iTime: { value: 0 }, uScrollDuration: { value: 2 }, uOpacity: { value: 1 }, uAccentColor: { value: new THREE.Color(ACCENT) }, uStripeColorA: { value: new THREE.Color(STRIPE_A) }, uStripeColorB: { value: new THREE.Color(STRIPE_B) }, uStripeReveal: { value: 0 }, uLight: { value: new THREE.Vector3(4, 9, LIGHT_Z) }, uShininess: { value: 40 }, uDiffuseness: { value: 0.1 }, uSpecularStrength: { value: 1.2 }, uFresnelPower: { value: 6 }, uFresnelStrength: { value: 1 }, uFresnelSideDir: { value: new THREE.Vector3(-1, 0.3, 1) }, }), [] ); // Cached canvas layout (original L) + rect cache (original G/H/_/j). const layoutRef = useRef<{ cssH: number; topY: number; bottomY: number } | null>( null ); const rectCacheRef = useRef(null); const frameCountRef = useRef(0); const lastScrollRef = useRef({ top: 0, left: 0 }); const layoutSigRef = useRef(""); const scaleRef = useRef(REST_SCALE); const dampInitRef = useRef(false); const lightCtl = useLightController(); const worldPos = useMemo(() => new THREE.Vector3(), []); useEffect(() => { const invalidate = () => { layoutRef.current = null; rectCacheRef.current = null; layoutSigRef.current = ""; }; window.addEventListener("resize", invalidate); window.addEventListener("orientationchange", invalidate); window.visualViewport?.addEventListener("resize", invalidate); const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(invalidate) : null; if (ro) { ro.observe(gl.domElement); if (gl.domElement.parentElement) ro.observe(gl.domElement.parentElement); } return () => { window.removeEventListener("resize", invalidate); window.removeEventListener("orientationchange", invalidate); window.visualViewport?.removeEventListener("resize", invalidate); ro?.disconnect(); arrowFullscreenProgressStore.reset(); }; }, [gl]); const targetRef = getLayerTarget("hyper-space"); useFrame((state, rawDelta) => { const delta = Math.min(rawDelta, 0.1); const group = groupRef.current; const mesh = meshRef.current; const u = materialRef.current?.uniforms; if (!group || !mesh || !mergedGeometry || !u) return; const [px, py, pz] = MODEL_POSITION; const pixelRatio = Math.max(1, gl.getPixelRatio()); const canvasRect = gl.domElement.getBoundingClientRect(); const vv = window.visualViewport ?? null; const sig = [ Math.round(canvasRect.top), Math.round(canvasRect.left), Math.round(canvasRect.width), Math.round(canvasRect.height), pixelRatio, Math.round(size.width), Math.round(size.height), vv ? Math.round(100 * vv.height) / 100 : -1, vv ? Math.round(100 * vv.offsetTop) / 100 : -1, vv ? Math.round(1e3 * vv.scale) / 1e3 : -1, ].join("|"); if (sig !== layoutSigRef.current) { layoutSigRef.current = sig; layoutRef.current = null; rectCacheRef.current = null; } if (!layoutRef.current) { const cssH = canvasRect.height > 0 ? canvasRect.height : Math.max(1, size.height); const topY = canvasRect.height > 0 ? canvasRect.top : 0; layoutRef.current = { cssH, topY, bottomY: canvasRect.height > 0 ? canvasRect.bottom : topY + cssH, }; } const { cssH, topY, bottomY } = layoutRef.current; const vw = Math.max(1, size.width); // --- DOM rect tracking (original: 11-frame cache + scroll-delta shift) --- const el = targetRef.current; const scrollTop = Math.max(0, scrollBus.current); let rect: TrackedRect | null = null; if (el) { const n = frameCountRef.current++; if (rectCacheRef.current && n % 12 !== 0) { const dTop = scrollTop - lastScrollRef.current.top; const dLeft = scrollTop - lastScrollRef.current.left; lastScrollRef.current = { top: scrollTop, left: scrollTop }; if (dTop !== 0 || dLeft !== 0) { const r = rectCacheRef.current; r.top -= dTop; r.bottom -= dTop; r.left -= dLeft; r.right -= dLeft; } } else { const b = el.getBoundingClientRect(); rectCacheRef.current = { left: b.left, top: b.top, width: b.width, height: b.height, right: b.right, bottom: b.bottom, }; lastScrollRef.current = { top: scrollTop, left: scrollTop }; } rect = rectCacheRef.current; } else { rectCacheRef.current = null; } if (!(el && rect && rect.width > 0 && rect.height > 0) || !rect) { group.visible = false; arrowFullscreenProgressStore.reset(); return; } const approachMargin = Math.max(2 * REF_MARGIN_PX, 480); const viewportMidY = topY + 0.5 * cssH; const vpWorld = state.viewport.getCurrentViewport( camera, worldPos.set(px, py, pz) ); // Shrink state (original eh): the (margin-shrunk) rect top passing the // point where it would end folds the arrow back down to rest. const shrinkStart = viewportMidY + REF_MARGIN_PX - rect.height; const shrinkEnd = Math.min(bottomY, shrinkStart + cssH); const shrinkT = rect.top <= shrinkStart ? 1 : rect.top >= shrinkEnd ? 0 : 1 - THREE.MathUtils.smoothstep(rect.top, shrinkStart, shrinkEnd); const beforeShrink = rect.top > shrinkEnd; const shrinking = rect.top <= shrinkEnd && rect.top > shrinkStart; const leaveCap = Math.min( 0.35 * cssH, (mergedGeometry.boundingSphere?.radius ?? 1) * REST_SCALE * (cssH / Math.max(vpWorld.height, 1e-4)) * 0.45 ); const leftViewport = rect.bottom < -leaveCap; const inRange = rect.top < bottomY + approachMargin && rect.bottom > -(6 * REF_MARGIN_PX) && !leftViewport; group.visible = inRange; if (!inRange) { arrowFullscreenProgressStore.reset(); return; } // iTime: 2 × clamp01 — hyperspace star-field travel (uScrollDuration=2). const canvasH = Math.max(1, size.height); u.iResolution.value.set(vw * pixelRatio, canvasH * pixelRatio, 1); const timeSpan = Math.max(1, bottomY + rect.height); u.iTime.value = 2 * clamp01((bottomY - rect.top) / timeSpan); // Reveal: smoothstep over (vpMid - (rect.top + margin)) / cssH. const reveal = THREE.MathUtils.smoothstep( clamp01((viewportMidY - (rect.top + REF_MARGIN_PX)) / cssH), 0, 1 ); // Vertical anchor: the model rides the clamped rect top/bottom (ex). const rectTopAdj = rect.top + REF_MARGIN_PX; const rectBottomAdj = rect.bottom - REF_MARGIN_PX; const anchorNorm = ((beforeShrink ? Math.max(viewportMidY, rectTopAdj) : shrinking ? viewportMidY : Math.min(viewportMidY, rectBottomAdj)) - topY) / cssH; group.position.set(px, (0.5 - anchorNorm) * vpWorld.height + py, pz); // Scale: rest→peak by reveal, then fold back down (original eE/ew). const autoPeak = (Math.hypot(vpWorld.width, vpWorld.height) * AUTO_PEAK_PADDING) / (mergedGeometry.boundingSphere?.radius ?? 1); const peak = autoPeak; const revealed = THREE.MathUtils.lerp(REST_SCALE, peak, reveal); const targetScale = beforeShrink ? revealed : shrinking ? THREE.MathUtils.lerp(revealed, REST_SCALE, shrinkT) : REST_SCALE; let scaleNow: number; if (SCALE_SMOOTHING <= 0) { scaleNow = targetScale; scaleRef.current = targetScale; } else if (dampInitRef.current) { scaleRef.current = THREE.MathUtils.damp( scaleRef.current, targetScale, SCALE_SMOOTHING, delta ); scaleNow = scaleRef.current; } else { dampInitRef.current = true; scaleNow = targetScale; scaleRef.current = targetScale; } mesh.scale.setScalar(scaleNow); // Stripe reveal + store share the same normalized t (original eR). const scaleSpan = Math.max(peak - REST_SCALE, 1e-6); const scaleT = clamp01((scaleNow - REST_SCALE) / scaleSpan); u.uStripeReveal.value = scaleT; arrowFullscreenProgressStore.setDampedScaleT(scaleT); // Spin (original eS): wind up while approaching, extra turn in shrink. let spinY = 0; if (shrinking) { spinY = SPIN_RADIANS + clamp01((shrinkT - 0.6) / 0.4) * SPIN_RADIANS; } else if (beforeShrink) { spinY = clamp01(scaleT / 0.4) * SPIN_RADIANS; } const spinGroup = spinRef.current; if (spinGroup) { spinGroup.rotation.x = 0; spinGroup.rotation.y = spinY; spinGroup.rotation.z = 0; } // Pointer-following specular light (original I.update). const { x: lx, y: ly } = lightCtl.update({ uv, inside: insideRef.current && !isMobile, camera, delta, }); u.uLight.value.set(lx, ly, LIGHT_Z); }, -2); if (!mergedGeometry) return null; return ( ); }