Files
virtheart 76168b6927 perf: 玻璃模型 3.18MB→1.53MB / 1.44MB→0.75MB — gltf→glb+KHR 顶点量化
gltf-transform dedup/prune/weld/quantize/sparse,几何未简化(simplify 会伤玻璃折射精度)。KHR_mesh_quantization 为 GLTFLoader 原生支持,无需 Draco/Meshopt 解码器;base64 内嵌 buffer 转 glb 二进制直接省 33% 开销。同步更新 GlassModels URL 与 loadingBus REQUIRED key。
2026-09-04 17:05:37 +08:00

820 lines
30 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useMemo, useRef } from "react";
import { useFrame, useLoader, useThree } from "@react-three/fiber";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";
import { scrollBus } from "@/lib/scrollBus";
import { usePointer } from "@/lib/pointer";
import { loadingBus } from "@/lib/loadingBus";
import { useResolvedTheme } from "@/lib/shellMedia";
/**
* Glass models for the hero section, reverse-engineered 1:1 from the
* production bundle (chunk 4d3f3b68dbbde33a.js).
*
* Both models share one refractive-glass shader: a screen-space scene-texture
* refraction (FBO of layers 1..9 rendered at half resolution) + Beer-Lambert
* tint gradient along local Y + specular + directional fresnel.
*
* Params (light theme defaults from the cloned controls):
* refractPower .72 | chromaticAberration .14 | loop 3 (RGB path)
* shininess 120 | diffuseness .1 | fresnelPower 1 | fresnelStrength .24
* brightness .78 | contrast .9 | saturation 1.2 | specularStrength 1.2
* tint A #009dff / B #ffffff, tintMix 1, thicknessMaxAlpha .92, minAlpha 1
*/
const VERT = /* glsl */ `
varying vec3 worldNormal;
varying vec3 eyeVector;
varying float modelLocalY;
void main() {
vec4 worldPos = modelMatrix * vec4(position, 1.0);
vec4 mvPosition = viewMatrix * worldPos;
gl_Position = projectionMatrix * mvPosition;
worldNormal = normalize(modelMatrix * vec4(normal, 0.0)).xyz;
eyeVector = normalize(worldPos.xyz - cameraPosition);
modelLocalY = position.y;
}
`;
const FRAG = /* glsl */ `
uniform float uIorR;
uniform float uIorY;
uniform float uIorG;
uniform float uIorC;
uniform float uIorB;
uniform float uIorP;
uniform float uSaturation;
uniform float uChromaticAberration;
uniform float uRefractPower;
uniform float uFresnelPower;
uniform float uShininess;
uniform float uDiffuseness;
uniform vec3 uLight;
uniform float uBrightness;
uniform float uContrast;
uniform float uGamma;
uniform float uSpecularStrength;
uniform float uFresnelStrength;
uniform vec3 uFresnelSideDir;
uniform vec4 uTintColorA;
uniform vec4 uTintColorB;
uniform vec2 uTintLocalYRange;
uniform float uTintEnabled;
uniform float uTintMix;
uniform float uTintThicknessMinAlpha;
uniform float uTintThicknessMaxAlpha;
uniform vec2 uScreenResolutionPx;
uniform sampler2D uTexture;
uniform float uSceneRefractionEnabled;
uniform float uRgbRefraction;
uniform float uDark;
varying vec3 worldNormal;
varying vec3 eyeVector;
varying float modelLocalY;
float random(vec2 p) {
return fract(sin(dot(p.xy, vec2(12.9898, 78.233))) * 43758.5453);
}
vec3 sat(vec3 rgb, float adjustment) {
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
vec3 intensity = vec3(dot(rgb, W));
return mix(intensity, rgb, adjustment);
}
float fresnel(vec3 eyeDir, vec3 normal, float power) {
float f = abs(dot(eyeDir, normal));
return pow(1.0 - f, 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;
}
uniform int uLoop;
void main() {
vec2 uv = gl_FragCoord.xy / uScreenResolutionPx.xy;
vec3 normal = normalize(worldNormal);
vec3 eyeDir = normalize(eyeVector);
vec3 color;
if (uSceneRefractionEnabled > 0.5) {
color = vec3(0.0);
float noise = random(uv) * 0.025;
if (uRgbRefraction > 0.5) {
vec3 refractVecR = refract(eyeDir, normal, (1.0 / uIorR));
vec3 refractVecG = refract(eyeDir, normal, (1.0 / uIorG));
vec3 refractVecB = refract(eyeDir, normal, (1.0 / uIorB));
for (int i = 0; i < uLoop; i++) {
float slide = float(i) / float(uLoop) * 0.1 + noise;
float offset = (uRefractPower + slide) * uChromaticAberration;
color.r += texture2D(uTexture, uv + refractVecR.xy * offset).r;
color.g += texture2D(uTexture, uv + refractVecG.xy * offset).g;
color.b += texture2D(uTexture, uv + refractVecB.xy * offset).b;
}
} else {
vec3 refractVecR = refract(eyeDir, normal, (1.0 / uIorR));
vec3 refractVecY = refract(eyeDir, normal, (1.0 / uIorY));
vec3 refractVecG = refract(eyeDir, normal, (1.0 / uIorG));
vec3 refractVecC = refract(eyeDir, normal, (1.0 / uIorC));
vec3 refractVecB = refract(eyeDir, normal, (1.0 / uIorB));
vec3 refractVecP = refract(eyeDir, normal, (1.0 / uIorP));
for (int i = 0; i < uLoop; i++) {
float slide = float(i) / float(uLoop) * 0.1 + noise;
float offsetR = (uRefractPower + slide * 1.0) * uChromaticAberration;
float offsetY = (uRefractPower + slide * 1.0) * uChromaticAberration;
float offsetG = (uRefractPower + slide * 2.0) * uChromaticAberration;
float offsetC = (uRefractPower + slide * 2.5) * uChromaticAberration;
float offsetB = (uRefractPower + slide * 3.0) * uChromaticAberration;
float offsetP = (uRefractPower + slide * 1.0) * uChromaticAberration;
float r = texture2D(uTexture, uv + refractVecR.xy * offsetR).x * 0.5;
vec3 ySample = texture2D(uTexture, uv + refractVecY.xy * offsetY).xyz;
float y = (ySample.x * 2.0 + ySample.y * 2.0 - ySample.z) / 6.0;
float g = texture2D(uTexture, uv + refractVecG.xy * offsetG).y * 0.5;
vec3 cSample = texture2D(uTexture, uv + refractVecC.xy * offsetC).xyz;
float c = (cSample.y * 2.0 + cSample.z * 2.0 - cSample.x) / 6.0;
float b = texture2D(uTexture, uv + refractVecB.xy * offsetB).z * 0.5;
vec3 pSample = texture2D(uTexture, uv + refractVecP.xy * offsetP).xyz;
float p = (pSample.z * 2.0 + pSample.x * 2.0 - pSample.y) / 6.0;
float R = r + (2.0 * p + 2.0 * y - c) / 3.0;
float G = g + (2.0 * y + 2.0 * c - p) / 3.0;
float B = b + (2.0 * c + 2.0 * p - y) / 3.0;
color.r += R;
color.g += G;
color.b += B;
}
}
color /= float(uLoop);
} else {
color = texture2D(uTexture, uv).rgb;
}
color = sat(color, uSaturation);
color *= uBrightness;
color = (color - 0.5) * uContrast + 0.5;
float invGamma = 1.0 / max(uGamma, 0.0001);
color = pow(max(color, 0.0), vec3(invGamma));
float mode = clamp(uDark, 0.0, 1.0);
// --- Beer-Lambert ---
float localYMin = uTintLocalYRange.x;
float localYMax = uTintLocalYRange.y;
float localYDenominator = max(localYMax - localYMin, 1e-5);
float tintGradientFactor = clamp((modelLocalY - localYMin) / localYDenominator, 0.0, 1.0);
vec4 tintColorGradient = mix(uTintColorB, uTintColorA, tintGradientFactor);
float ndotv = abs(dot(normal, eyeDir));
float thicknessMask = clamp(1.0 - ndotv, 0.0, 1.0);
float tintAlpha = clamp(tintColorGradient.a, 0.0, 1.0);
float minAlpha = clamp(uTintThicknessMinAlpha, 0.0, 1.0);
float maxAlpha = clamp(uTintThicknessMaxAlpha, 0.0, 1.0);
tintAlpha *= mix(maxAlpha, minAlpha, thicknessMask);
float tintK_beer = clamp(uTintEnabled, 0.0, 1.0) * tintAlpha;
vec3 tintColorClamped = clamp(tintColorGradient.rgb, 0.001, 1.0);
float thickness = clamp(uTintMix, 0.01, 3.0);
vec3 transmittance = pow(tintColorClamped, vec3(thickness));
vec3 beerColor = mix(color, color * transmittance, tintK_beer);
// --- Hard Light ---
float tintK_hard = clamp(uTintEnabled, 0.0, 1.0) * clamp(uTintMix, 0.0, 1.0) * tintAlpha;
vec3 baseClamped = clamp(color, 0.0, 1.0);
vec3 blendClamped = clamp(tintColorGradient.rgb, 0.0, 1.0);
// Hard Light blend(原版逐通道):blend 通道 > 0.5 → screen,否则 multiply。
// 注意选择器是 blend(tint 色)而非 base —— 暗色主题的 #64c3ff/#8e9dc4
// 各通道跨 0.5,选错变量会导致 Dark 下模型颜色整体偏差。
vec3 h = step(vec3(0.5), blendClamped);
vec3 hard = mix(
2.0 * baseClamped * blendClamped,
1.0 - 2.0 * (1.0 - blendClamped) * (1.0 - baseClamped),
h
);
vec3 hardColor = mix(color, hard, tintK_hard);
color = mix(beerColor, hardColor, mode);
float specularLight = specular(uLight, normal, eyeDir, uShininess, uDiffuseness);
color += specularLight * uSpecularStrength;
float f = fresnel(eyeDir, normal, uFresnelPower);
float sideDot = dot(normal, normalize(uFresnelSideDir));
float sideMask = smoothstep(-0.5, 0.5, sideDot);
color.rgb += f * sideMask * vec3(uFresnelStrength);
gl_FragColor = vec4(color, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`;
// Light-theme control defaults (cloned controls, light branch)
const LIGHT_PARAMS = {
refractPower: 0.72,
chromaticAberration: 0.14,
shininess: 120,
diffuseness: 0.1,
fresnelPower: 1,
fresnelStrength: 0.24,
brightness: 0.78,
contrast: 0.9,
gamma: 1,
saturation: 1.2,
specularStrength: 1.2,
loop: 3,
tintMix: 1,
tintColorA: "#009dff",
tintColorB: "#ffffff",
tintThicknessMinAlpha: 1,
tintThicknessMaxAlpha: 0.92,
fresnelSideDir: [-1, 1, -1] as [number, number, number],
lightZ: 0.5,
};
// Dark-theme branch of the same cloned controls (original dark* control
// values): the glass switches to Hard-Light duotone mixing (uDark 1) with a
// different highlight/fresnel response.
const DARK_PARAMS = {
shininess: 100,
diffuseness: 0.05,
fresnelPower: 3,
fresnelStrength: 0.72,
brightness: 0.6,
contrast: 0.98,
gamma: 1,
saturation: 1.2,
tintMix: 1,
tintThicknessMinAlpha: 1,
tintThicknessMaxAlpha: 0.4,
tintColorA: "#64c3ff",
tintColorB: "#8e9dc4",
};
// Default uniforms from the bundle's uniform factory
const IOR = { R: 1.15, Y: 1.16, G: 1.18, C: 1.22, B: 1.22, P: 1.22 };
function hexToVec4(hex: string, alpha = 1): THREE.Vector4 {
const c = new THREE.Color(hex);
return new THREE.Vector4(c.r, c.g, c.b, alpha);
}
type GlassModelProps = {
url: string;
position?: [number, number, number];
beforeRotation?: [number, number, number];
rotation?: [number, number, number];
afterRotation?: [number, number, number];
rotationAxisTilt?: [number, number, number];
scale?: number;
tintColors?: [string, string] | [string, string, string, string];
tintEnabled?: boolean;
scrollSyncFactor?: number;
floating?: boolean;
isMobile?: boolean;
/**
* Document-space geometry of the section the model belongs to.
* The banner sits at the top of the page and is h-dvh tall, so the defaults
* (top 0, height = viewport height) match the original "banner" section.
*/
sectionTopDocY?: number;
sectionHeightPx?: number;
/**
* Live-read the section's document geometry by element id EVERY frame
* (original sX readSectionContentLayout: getBoundingClientRect +
* scrollTop). Required on mobile: dvh shrinks/grows as the URL bar
* collapses/expands, every h-dvh section (hero, footer) reflows, and some
* browsers never fire window resize for it — one-shot offsetTop
* measurements go stale and the model drifts off its section. Falls back
* to the static props above while the element is missing.
*/
sectionElId?: string;
};
function useFloatOffset(enabled: boolean) {
const t = useRef(0);
useFrame((state, delta) => {
t.current += delta;
});
return useMemo(
() => (time: number) =>
enabled ? 0.18 * Math.sin(1.2 * time) + 0.06 * Math.sin(0.6 * time) : 0,
[enabled]
);
}
/**
* Specular light controller — 1:1 port of the original `ca()`: a light that
* orbits at radius hypot(4, 9) in the XY plane, its azimuth following the
* pointer (raycast onto the z=0 plane) with exponential damping (6/s), and
* falling back to the initial azimuth when the pointer leaves.
*/
export function useLightController() {
return useMemo(() => {
const initialAzimuth = Math.atan2(9, 4);
const radius = Math.hypot(4, 9);
let azimuth = initialAzimuth;
let current = initialAzimuth;
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const hit = new THREE.Vector3();
return {
update({
uv,
inside,
camera,
delta,
}: {
uv: { x: number; y: number };
inside: boolean;
camera: THREE.Camera;
delta: number;
}) {
ndc.set(2 * uv.x - 1, 2 * uv.y - 1);
raycaster.setFromCamera(ndc, camera);
const intersected = raycaster.ray.intersectPlane(plane, hit) !== null;
const tx = -hit.x;
const ty = -hit.y;
if (inside && intersected && tx * tx + ty * ty > 1e-6) {
azimuth = Math.atan2(ty, tx);
}
const target = inside ? azimuth : initialAzimuth;
const diff = Math.atan2(Math.sin(target - current), Math.cos(target - current));
current += diff * (1 - Math.exp(-6 * delta));
return { x: radius * Math.cos(current), y: radius * Math.sin(current) };
},
};
}, []);
}
function GlassModel({
url,
position = [0, 0, 0],
beforeRotation,
rotation = [0, 0, 0],
afterRotation,
rotationAxisTilt = [0, 0, 0],
scale = 1,
tintColors,
tintEnabled = false,
scrollSyncFactor = 0.72,
floating = true,
isMobile = false,
sectionTopDocY = 0,
sectionHeightPx,
sectionElId,
}: GlassModelProps) {
const gltf = useLoader(GLTFLoader, url);
const groupRef = useRef<THREE.Group>(null!);
const spinRef = useRef<THREE.Group>(null!);
const materialRef = useRef<THREE.ShaderMaterial>(null!);
const meshLayerRef = useRef<THREE.Mesh>(null!);
const scene = useThree((s) => s.scene);
const gl = useThree((s) => s.gl);
const size = useThree((s) => s.size);
const camera = useThree((s) => s.camera);
// Merge all mesh geometries into one, centered (same as original cb/cd)
const mergedGeometry = useMemo(() => {
gltf.scene.updateMatrixWorld(true);
const geometries: THREE.BufferGeometry[] = [];
gltf.scene.traverse((obj) => {
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;
merged.computeBoundingBox();
const bb = merged.boundingBox!;
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) {
merged.translate(-cx, -cy, -cz);
merged.computeBoundingSphere();
}
return merged;
}, [gltf]);
// Glass renders ONLY on layer 10: the FBO refraction pass forces the camera
// mask to layer 0, so the glass mesh is excluded from its own refraction
// texture (an object with layer 0 kept enabled would pass the mask test and
// draw into the FBO it samples — a GL feedback loop, GL_INVALID_OPERATION
// every frame). The main camera enables layer 10 below, so glass stays
// visible in the normal pass. Matches the original GlassSystem.
useEffect(() => {
const mesh = meshLayerRef.current;
if (!mesh) return;
mesh.layers.set(10);
camera.layers.enable(10);
}, [mergedGeometry, camera]);
const tintYRange = useMemo<[number, number]>(() => {
if (!mergedGeometry) return [0, 1];
if (!mergedGeometry.boundingBox) mergedGeometry.computeBoundingBox();
const bb = mergedGeometry.boundingBox!;
return Math.abs(bb.max.y - bb.min.y) < 1e-6
? [bb.min.y, bb.min.y + 1]
: [bb.min.y, bb.max.y];
}, [mergedGeometry]);
// Scene-texture FBO: render layer 0 (background + stickers) at half res.
// Same as the original GlassSystem: one shared pass, camera mask forced to
// layer 0 so glass meshes (layer 10) are excluded from their own refraction.
// ⚠ type: HalfFloatType —— 原版 sb() 工厂创建的所有 RT 均为 HalfFloat
// (4d3f3b68 @200877: {minFilter,magFilter,type:HalfFloatType,...})。
// UnsignedByte 的默认 RT 会让折射纹理的暗部量化/截断,Dark 主题下
// Hard-Light 着色的底色因此偏灰(模型"发透明感"而非饱和蓝)。
const fbo = useMemo(() => {
const dpr = gl.getPixelRatio();
const w = Math.max(2, Math.floor((size.width * dpr) / 2));
const h = Math.max(2, Math.floor((size.height * dpr) / 2));
const target = new THREE.WebGLRenderTarget(w, h, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
type: THREE.HalfFloatType,
stencilBuffer: false,
depthBuffer: true,
samples: 0,
});
return target;
}, [gl, size.width, size.height]);
useEffect(() => {
return () => {
fbo.dispose();
};
}, [fbo]);
const uniforms = useMemo(
() => ({
uIorR: { value: IOR.R },
uIorY: { value: IOR.Y },
uIorG: { value: IOR.G },
uIorC: { value: IOR.C },
uIorB: { value: IOR.B },
uIorP: { value: IOR.P },
uRefractPower: { value: LIGHT_PARAMS.refractPower },
uChromaticAberration: { value: LIGHT_PARAMS.chromaticAberration },
uSaturation: { value: LIGHT_PARAMS.saturation },
uShininess: { value: LIGHT_PARAMS.shininess },
uDiffuseness: { value: LIGHT_PARAMS.diffuseness },
uFresnelPower: { value: LIGHT_PARAMS.fresnelPower },
uBrightness: { value: LIGHT_PARAMS.brightness },
uContrast: { value: LIGHT_PARAMS.contrast },
uGamma: { value: LIGHT_PARAMS.gamma },
uSpecularStrength: { value: LIGHT_PARAMS.specularStrength },
uFresnelStrength: { value: LIGHT_PARAMS.fresnelStrength },
uFresnelSideDir: {
value: new THREE.Vector3(...LIGHT_PARAMS.fresnelSideDir),
},
uTintColorA: {
value: hexToVec4(tintColors ? tintColors[0] : LIGHT_PARAMS.tintColorA),
},
uTintColorB: {
value: hexToVec4(tintColors ? tintColors[1] : LIGHT_PARAMS.tintColorB),
},
uTintLocalYRange: { value: new THREE.Vector2(0, 1) },
uTintEnabled: { value: tintEnabled ? 1 : 0 },
uTintMix: { value: LIGHT_PARAMS.tintMix },
uTintThicknessMinAlpha: { value: LIGHT_PARAMS.tintThicknessMinAlpha },
uTintThicknessMaxAlpha: { value: LIGHT_PARAMS.tintThicknessMaxAlpha },
uDark: { value: 0 },
uLoop: { value: LIGHT_PARAMS.loop },
uSceneRefractionEnabled: { value: 1 },
uRgbRefraction: { value: 1 },
uLight: { value: new THREE.Vector3(4, 9, LIGHT_PARAMS.lightZ) },
uScreenResolutionPx: { value: new THREE.Vector2(1, 1) },
uTexture: { value: fbo.texture },
}),
[tintColors, tintEnabled, fbo]
);
useEffect(() => {
uniforms.uTintLocalYRange.value.set(tintYRange[0], tintYRange[1]);
}, [tintYRange, uniforms]);
// Theme branch (original cf(controls, theme) + E useMemo): swap the
// highlight/fresnel response and tint colors when the resolved theme
// flips. Per-model tingColor overrides: m[0]/m[1] light A/B,
// m[2]/m[3] dark A/B, missing entries fall back to the theme defaults.
const isDark = useResolvedTheme() === "dark";
// ⚠ R3F 对 ShaderMaterial 的 `uniforms` prop 做的是「按键浅合并」:
// material.uniforms 是独立容器,标量按值拷贝、Vector4/Texture 共享引用,
// 且仅在 prop 引用变化时重新合并。材质创建后再改 memo 对象,标量
// (uDark、brightness、thickness alpha、loop…)永远到不了 GPU —— Dark
// 主题下 uDark 卡在 0、参数卡在 light 值,模型因此失色。原版所有
// apply 都写 T.current.uniforms(材质 ref);这里同样穿透到材质,
// 材质未挂载时回落到 memo(创建时会被拷贝进去),并以 mergedGeometry
// 作为「材质已存在」信号重跑(原版靠 tintYRange Y 的变化触发同一效果)。
const matUniforms = () =>
(materialRef.current?.uniforms ?? uniforms) as typeof uniforms;
// 原版移动端钳制 loop(apply effect: t=O?Math.min(B.loop,2):B.loop)——
// 折射采样少一轮,色散/亮度观感随设备宽度变化;桌面 3、移动 2。
const loop = isMobile ? Math.min(LIGHT_PARAMS.loop, 2) : LIGHT_PARAMS.loop;
useEffect(() => {
const u = matUniforms();
u.uLoop.value = loop;
u.uRgbRefraction.value = +(loop <= 3);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [loop, uniforms, mergedGeometry]);
useEffect(() => {
const u = matUniforms();
const P = isDark ? DARK_PARAMS : LIGHT_PARAMS;
u.uShininess.value = P.shininess;
u.uDiffuseness.value = P.diffuseness;
u.uFresnelPower.value = P.fresnelPower;
u.uFresnelStrength.value = P.fresnelStrength;
u.uBrightness.value = P.brightness;
u.uContrast.value = P.contrast;
u.uGamma.value = P.gamma;
u.uSaturation.value = P.saturation;
u.uTintMix.value = P.tintMix;
u.uTintThicknessMinAlpha.value = P.tintThicknessMinAlpha;
u.uTintThicknessMaxAlpha.value = P.tintThicknessMaxAlpha;
const tintA = isDark
? (tintColors?.[2] ?? DARK_PARAMS.tintColorA)
: (tintColors?.[0] ?? LIGHT_PARAMS.tintColorA);
const tintB = isDark
? (tintColors?.[3] ?? DARK_PARAMS.tintColorB)
: (tintColors?.[1] ?? LIGHT_PARAMS.tintColorB);
u.uTintColorA.value.copy(hexToVec4(tintA));
u.uTintColorB.value.copy(hexToVec4(tintB));
u.uDark.value = isDark ? 1 : 0;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDark, tintColors, uniforms, mergedGeometry]);
useEffect(() => {
const drawingBufferSize = gl.getDrawingBufferSize(new THREE.Vector2());
matUniforms().uScreenResolutionPx.value.set(
drawingBufferSize.x,
drawingBufferSize.y
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [gl, size, uniforms, mergedGeometry]);
// Float bob: desktop only in the original (floatingMotion && !isMobileWidth)
const floatEnabled = floating && !isMobile;
const getFloat = useFloatOffset(floatEnabled);
const lightController = useLightController();
const { uv: pointerUv, insideRef: pointerInsideRef } = usePointer();
// Heavy-asset readiness for the entrance (original onReady → load progress).
useEffect(() => {
if (mergedGeometry) {
loadingBus.mark(`model:${url.split("/").pop()}`);
}
}, [mergedGeometry, url]);
// Counter tilt: cancels rotationAxisTilt so the model's static orientation
// is upright; the tilt only skews the spin axis (original nests -tilt
// INSIDE the spin group).
const negatedTilt = useMemo<[number, number, number]>(
() => [-rotationAxisTilt[0], -rotationAxisTilt[1], -rotationAxisTilt[2]],
[rotationAxisTilt]
);
const rad = (v: number) => THREE.MathUtils.degToRad(v);
const before = beforeRotation ?? rotation;
useFrame((state, rawDelta) => {
const delta = Math.min(rawDelta, 0.1);
// Render the scene (layer 0 mask) into the FBO for refraction.
// Stickers/background live on layer 0; glass models render on layer 0+10
// and are excluded by the layer-0 mask (no self-refraction). Original:
// `camera.layers.mask = 1; render; restore`.
const prevTarget = gl.getRenderTarget();
const prevAutoClear = gl.autoClear;
const prevMask = camera.layers.mask;
gl.setRenderTarget(fbo);
gl.clear();
camera.layers.set(0);
gl.render(scene, camera);
camera.layers.mask = prevMask;
gl.setRenderTarget(prevTarget);
gl.autoClear = prevAutoClear;
const g = groupRef.current;
const spin = spinRef.current;
if (!g) return;
// --- Section geometry: live DOM read (original sX
// readSectionContentLayout) ---
// 原版每帧 getBoundingClientRect + scrollTop 重算 section 文档坐标。
// 移动端 dvh 随地址栏收起/展开变化,hero/footer 均为 h-dvh,布局随之
// 平移;部分浏览器不为此派发 window resize,一次性 offsetTop 测量会
// 过期导致锚点漂移(真机偏移、PC 模拟正常的根源)。元素缺失时回落
// 到静态测量值。
let secTop = sectionTopDocY;
let secHeight = sectionHeightPx;
if (sectionElId) {
const el = document.getElementById(sectionElId);
if (el) {
const rect = el.getBoundingClientRect();
secTop = rect.top + window.scrollY;
secHeight = rect.height;
}
}
// --- Section-anchored scroll state (banner: top 0, h-dvh) ---
const vh = Math.max(1, state.size.height);
const sectionH = Math.max(1, secHeight ?? vh);
const scrollTop = Math.max(0, scrollBus.current);
// Original X(): hide the model once its section leaves the viewport.
const deltaTop = secTop - scrollTop;
g.visible = deltaTop + sectionH > 0 && deltaTop < vh;
// Original position sync:
// worldY = (0.5 - anchorDocY/vh) * viewportWorldH
// + (scrollTop/vh) * viewportWorldH * scrollSyncFactor
// where anchorDocY = section top + half height. For the banner at page
// top this reduces to (scrollTop/vh) * worldH * factor — i.e. the model
// tracks the first viewport of scrolling, NOT whole-page progress.
const viewportWorldHeight = state.viewport.getCurrentViewport(
camera,
new THREE.Vector3(0, 0, position[2])
).height;
const anchorDocY = secTop + sectionH / 2;
const syncWorldY =
(0.5 - anchorDocY / vh) * viewportWorldHeight +
(scrollTop / vh) * viewportWorldHeight * scrollSyncFactor;
const float = getFloat(state.clock.getElapsedTime());
g.position.y = syncWorldY + position[1] + float;
g.position.x = position[0];
g.position.z = position[2];
// --- Scroll-driven rotation targets (original Z()) ---
// i = (scrollTop + vh - sectionTop) / vh
// entry = clamp(i, 0, 1) after = clamp(i - 1, 0, 1)
// At page top entry=1 / after=0, so nothing animates until the user
// scrolls; `after` then ramps over the first viewport height.
let entry = 1;
let after = afterRotation ? 1 : 0;
if (vh > 0) {
const i = (scrollTop + vh - secTop) / vh;
entry = THREE.MathUtils.clamp(i, 0, 1);
after = THREE.MathUtils.clamp(i - 1, 0, 1);
}
let tx = THREE.MathUtils.lerp(rad(before[0]), rad(rotation[0]), entry);
let ty = THREE.MathUtils.lerp(rad(before[1]), rad(rotation[1]), entry);
let tz = THREE.MathUtils.lerp(rad(before[2]), rad(rotation[2]), entry);
if (afterRotation) {
tx = THREE.MathUtils.lerp(tx, rad(afterRotation[0]), after);
ty = THREE.MathUtils.lerp(ty, rad(afterRotation[1]), after);
tz = THREE.MathUtils.lerp(tz, rad(afterRotation[2]), after);
}
if (spin) {
spin.rotation.x = THREE.MathUtils.damp(spin.rotation.x, tx, 6, delta);
spin.rotation.y = THREE.MathUtils.damp(spin.rotation.y, ty, 6, delta);
spin.rotation.z = THREE.MathUtils.damp(spin.rotation.z, tz, 6, delta);
}
// Pointer-following specular light (original ca() + uLight.set(x, y, lightZ))
const light = lightController.update({
uv: pointerUv,
inside: pointerInsideRef.current && !isMobile,
camera,
delta,
});
materialRef.current?.uniforms.uLight.value.set(
light.x,
light.y,
LIGHT_PARAMS.lightZ
);
}, -2);
if (!mergedGeometry) return null;
return (
<group ref={groupRef} position={position}>
{/* rotationAxisTilt group ... then counter-tilt INSIDE the spin group:
tilt * spin * (-tilt) keeps the model upright at rest while the spin
happens around the tilted axis — exactly the original hierarchy. */}
<group rotation={rotationAxisTilt}>
<group ref={spinRef} rotation={rotation}>
<group rotation={negatedTilt}>
<mesh
ref={meshLayerRef}
geometry={mergedGeometry}
scale={[scale, scale, scale]}
>
<shaderMaterial
ref={materialRef}
vertexShader={VERT}
fragmentShader={FRAG}
uniforms={uniforms}
toneMapped={false}
transparent
/>
</mesh>
</group>
</group>
</group>
</group>
);
}
export function HelloModel({ isMobile = false }: { isMobile?: boolean }) {
return (
<GlassModel
url="/model/hello.glb"
position={[-0.1, 0, 2]}
beforeRotation={[0, 240, 0]}
afterRotation={[0, 90, 0]}
rotation={[0, 4, 0]}
scale={isMobile ? 19 : 22}
tintEnabled
isMobile={isMobile}
scrollSyncFactor={0.72}
/>
);
}
export function CursorStar({ isMobile = false }: { isMobile?: boolean }) {
return (
<GlassModel
url="/model/cursor.glb"
position={isMobile ? [6.6, -5.6, -3] : [11.6, -4.2, -3]}
rotationAxisTilt={[0, 0, 45]}
beforeRotation={[0, 0, 0]}
afterRotation={[0, 720, 0]}
rotation={[0, 0, 0]}
scale={0.1}
// Original tingColor: light m[0]/m[1] both #009dff, dark m[2]/m[3]
// both #64c3ff.
tintColors={["#009dff", "#009dff", "#64c3ff", "#64c3ff"]}
tintEnabled
isMobile={isMobile}
scrollSyncFactor={0.72}
/>
);
}
/**
* #contact footer model (original cp call: model/cnt.gltf, scale 19,
* beforeRotation [-180,0,0], scrollSyncFactor 1 — the cp default — and
* light-theme tingColor m[0]/m[1] = #FFFFFF/#009dff). Anchored to the
* footer section via live per-frame DOM reads (original sX), so mobile
* URL-bar dvh reflows can't drift the anchor.
*/
export function FooterModel() {
return (
<GlassModel
url="/model/cnt.glb"
position={[0, 0, 0]}
beforeRotation={[-180, 0, 0]}
rotation={[0, 0, 0]}
scale={19}
tintColors={["#FFFFFF", "#009dff", "#8e9dc4", "#64c3ff"]}
tintEnabled
sectionElId="contact"
scrollSyncFactor={1}
/>
);
}