portal: 金钻宇宙换成星系图(three.js 懒加载)+ 推送前审查 + 总交接文档
- 门户「金钻宇宙」:删掉启动仪式 / 宇宙首屏晶体 / 盘符机架 / 读盘舱及其 CSS、图标; 换成星系图(portal/assets/universe/,three.js r170 自托管于 assets/vendor/,第一次打开板块才下载) + 窗下世界线卡片;#0001 深链飞到对应世界线;世界线数据只留 config.js 一份 - 像素字子集重做(旧字全保留 + 新字);其余板块与改动前逐像素一致 - 后端审查:add_call 写库失败不再打断渲染机回传;多进程同时首启只导入一次(+1 条测试,共 38); 撤销「处理过了」清掉 handled_at - 交接文档-2026-10.md:变更清单 / 功能增删 / 接口与数据格式变更 / 设计规范 / 业务逻辑 / 部署运维 - 交付清单哈希重算;README、旧交接说明指路 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,310 @@
|
||||
/* =============================================================================
|
||||
* 金钻宇宙 · 星系图引擎(galaxy.js)
|
||||
* -----------------------------------------------------------------------------
|
||||
* 读 window.JZ_UNIVERSE(config.js)→ 画旋臂星系、星云、扇区、补给线、星系(卡通星球 + 卫星)、
|
||||
* 散落的无名星球;处理拖动 / 滚轮 / 双指缩放 / 点星系飞过去 / 档案卡。
|
||||
* 只依赖 three.js 和 planets.js。挂载:mountGalaxy({ stage, canvas, labels, panel, ... })
|
||||
* 嵌进普通页面时可选:
|
||||
* onFocus(u|null) 选中 / 取消选中某条世界线时回调(页面下方的列表可以跟着高亮)
|
||||
* layout() 返回 { x, y }:选中时星球往左 / 往上挪多少(屏宽 / 屏高的比例),给档案卡让位
|
||||
* wheelZoom() 返回 true 时滚轮直接缩放;false 时只有按住 Ctrl 才缩放(嵌在页面里别抢页面滚动)
|
||||
* 返回 { fly(no), home(), resize() }。画面滚出视口时自动暂停渲染。
|
||||
* ============================================================================= */
|
||||
import * as THREE from 'three';
|
||||
import { makePlanet } from './planets.js?v=1';
|
||||
|
||||
export function mountGalaxy(el) {
|
||||
const CFG = window.JZ_UNIVERSE, G = CFG.GALAXY, C = G.colors;
|
||||
const { stage, canvas, labels, panel, back, hud } = el;
|
||||
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const isMob = () => stage.clientWidth < 760;
|
||||
const MOB = isMob();
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
|
||||
renderer.setPixelRatio(Math.min(devicePixelRatio, MOB ? 1.5 : 2));
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.setClearColor(C.bg, 1);
|
||||
const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(42, 1, 0.1, 2000);
|
||||
const R = G.radius, ARMS = G.arms;
|
||||
const rnd = (a = 0, b = 1) => a + Math.random() * (b - a);
|
||||
const gauss = () => { let u = 0, v = 0; while (!u) u = Math.random(); while (!v) v = Math.random(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); };
|
||||
const armAngle = (r, arm) => arm * Math.PI * 2 / ARMS + r * G.twist;
|
||||
const LIGHT = new THREE.Vector3(-1, 0.55, 0.6).normalize();
|
||||
|
||||
// ============================================================ 旋臂星系(粒子)—— 星点大小有上限,离镜头很近的也不会糊成大光斑
|
||||
const galaxy = (() => {
|
||||
const N = MOB ? G.particles.mobile : G.particles.desktop, pos = new Float32Array(N * 3), col = new Float32Array(N * 3), sz = new Float32Array(N);
|
||||
const cCore = new THREE.Color(C.core), cIn = new THREE.Color(C.armInner), cOut = new THREE.Color(C.armOuter), cAcc = new THREE.Color(C.accentStar), c = new THREE.Color();
|
||||
for (let i = 0; i < N; i++) {
|
||||
const r = Math.pow(Math.random(), 0.55) * R, arm = i % ARMS, spread = (0.6 + r * 0.09) * gauss();
|
||||
const a = armAngle(r, arm) + spread / Math.max(r, 3) + (Math.random() < 0.22 ? rnd(-Math.PI, Math.PI) : 0);
|
||||
pos.set([Math.cos(a) * r + gauss() * 0.8, gauss() * (2.2 * Math.exp(-r / 18) + 0.35), Math.sin(a) * r + gauss() * 0.8], i * 3);
|
||||
const t = r / R; c.copy(cCore).lerp(cIn, Math.min(1, t * 2.4)).lerp(cOut, Math.max(0, t * 1.5 - 0.5));
|
||||
if (Math.random() < 0.04) c.copy(cAcc);
|
||||
col.set([c.r, c.g, c.b], i * 3); sz[i] = Math.random() < 0.012 ? rnd(3, 5.5) : rnd(0.6, 2.0);
|
||||
}
|
||||
const g = new THREE.BufferGeometry();
|
||||
g.setAttribute('position', new THREE.BufferAttribute(pos, 3)); g.setAttribute('color', new THREE.BufferAttribute(col, 3)); g.setAttribute('size', new THREE.BufferAttribute(sz, 1));
|
||||
const m = new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, vertexColors: true,
|
||||
uniforms: { uPx: { value: renderer.getPixelRatio() }, uDim: { value: 1 }, uK: { value: 1 } },
|
||||
vertexShader: `attribute float size; varying vec3 vC; uniform float uPx; uniform float uK;
|
||||
void main(){ vC = color; vec4 mv = modelViewMatrix*vec4(position,1.0); gl_PointSize = clamp(size*uPx*uK*(150.0/-mv.z), 1.1, 7.0*uPx); gl_Position = projectionMatrix*mv; }`,
|
||||
fragmentShader: `varying vec3 vC; uniform float uDim; void main(){ vec2 p = gl_PointCoord-0.5; float d = length(p); if(d>0.5) discard;
|
||||
float a = smoothstep(0.5,0.0,d); gl_FragColor = vec4(vC*(0.55+a*1.1), a*0.85*uDim); }` });
|
||||
const pts = new THREE.Points(g, m); scene.add(pts); return pts;
|
||||
})();
|
||||
|
||||
// ============================================================ 星云(噪声云,沿旋臂;颜色只取 config 里那几组)
|
||||
const nebulaMat = (c1, c2, seed, alpha) => new THREE.ShaderMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
|
||||
uniforms: { uT: { value: 0 }, uA: { value: new THREE.Color(c1) }, uB: { value: new THREE.Color(c2) }, uS: { value: seed }, uO: { value: alpha }, uDim: { value: 1 } },
|
||||
vertexShader: `varying vec2 vU; void main(){ vU = uv; gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.0); }`,
|
||||
fragmentShader: `uniform float uT; uniform vec3 uA; uniform vec3 uB; uniform float uS; uniform float uO; uniform float uDim; varying vec2 vU;
|
||||
float h(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7))+uS)*43758.5453); }
|
||||
float n(vec2 p){ vec2 i=floor(p), f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(h(i),h(i+vec2(1,0)),f.x),mix(h(i+vec2(0,1)),h(i+vec2(1,1)),f.x),f.y); }
|
||||
float fbm(vec2 p){ float v=0.0, a=0.5; for(int i=0;i<6;i++){ v+=a*n(p); p=p*2.03+vec2(1.7,9.2); a*=0.5; } return v; }
|
||||
void main(){ vec2 p = vU-0.5; float r = length(p)*2.0; if(r>1.0) discard;
|
||||
vec2 q = vU*3.0 + uS; float w = fbm(q + vec2(uT*0.02, -uT*0.015)); float d = fbm(q*1.7 + w*2.4 + vec2(-uT*0.01, uT*0.02));
|
||||
float shape = smoothstep(1.0, 0.15, r) * smoothstep(0.32, 0.85, d); float dust = smoothstep(0.55, 0.75, fbm(q*3.1 - w));
|
||||
gl_FragColor = vec4(mix(uA, uB, smoothstep(0.3, 0.9, d)) * (0.6 + d), shape * (1.0 - dust*0.6) * uO * uDim); }` });
|
||||
const nebulae = [];
|
||||
{ const n = MOB ? G.nebulae.mobile : G.nebulae.desktop;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const r = rnd(8, R * 0.95), a = armAngle(r, i % ARMS) + rnd(-0.35, 0.35), pal = C.nebula[i % C.nebula.length], s = rnd(14, 34) * (1.1 - r / R * 0.4);
|
||||
const m = new THREE.Mesh(new THREE.PlaneGeometry(s, s), nebulaMat(pal[0], pal[1], rnd(0, 100), rnd(0.32, 0.55)));
|
||||
m.position.set(Math.cos(a) * r, rnd(-1.5, 1.5), Math.sin(a) * r); m.rotation.set(-Math.PI / 2 + rnd(-0.25, 0.25), 0, rnd(0, Math.PI)); scene.add(m); nebulae.push(m);
|
||||
}
|
||||
const core = new THREE.Mesh(new THREE.PlaneGeometry(34, 34), nebulaMat(C.coreNebula[0], C.coreNebula[1], 7, 0.5)); core.rotation.x = -Math.PI / 2; scene.add(core); nebulae.push(core); }
|
||||
const glow = (color, size, op = 1) => { const c = document.createElement('canvas'); c.width = c.height = 128; const x = c.getContext('2d');
|
||||
const g = x.createRadialGradient(64, 64, 0, 64, 64, 64); g.addColorStop(0, 'rgba(255,255,255,1)'); g.addColorStop(0.22, color); g.addColorStop(1, 'rgba(0,0,0,0)'); x.fillStyle = g; x.fillRect(0, 0, 128, 128);
|
||||
const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, opacity: op })); s.scale.setScalar(size); return s; };
|
||||
scene.add(glow('rgba(255,215,150,.28)', 15, 0.7)); // 核心的柔光(收着点,之前太曝)
|
||||
{ const N = MOB ? 1100 : 2400, p = new Float32Array(N * 3); // 远处整球背景星
|
||||
for (let i = 0; i < N; i++) { const u = rnd(-1, 1), t = rnd(0, Math.PI * 2), s = Math.sqrt(1 - u * u), r = rnd(500, 900); p.set([Math.cos(t) * s * r, u * r, Math.sin(t) * s * r], i * 3); }
|
||||
const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(p, 3));
|
||||
scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0xC9D3FF, size: 1.2, sizeAttenuation: false, transparent: true, opacity: 0.6 }))); }
|
||||
|
||||
// ============================================================ 扇区:同心环 + 分隔虚线 + 扇区名
|
||||
const lineCol = new THREE.Color(C.line), guides = [];
|
||||
const addLine = (pts, dashed, op) => { const g = new THREE.BufferGeometry().setFromPoints(pts);
|
||||
const m = dashed ? new THREE.LineDashedMaterial({ color: lineCol, dashSize: 1.2, gapSize: 1.4, transparent: true, opacity: op, depthWrite: false })
|
||||
: new THREE.LineBasicMaterial({ color: lineCol, transparent: true, opacity: op, depthWrite: false });
|
||||
const l = new THREE.Line(g, m); if (dashed) l.computeLineDistances(); l.userData.op = op; scene.add(l); guides.push(l); return l; };
|
||||
for (const [rr, op] of [[16, 0.16], [32, 0.11], [48, 0.09], [R + 4, 0.16]]) { const pts = []; for (let k = 0; k <= 256; k++) { const a = k / 256 * Math.PI * 2; pts.push(new THREE.Vector3(Math.cos(a) * rr, 0, Math.sin(a) * rr)); } addLine(pts, false, op); }
|
||||
for (let k = 0; k < 6; k++) { const a = k / 6 * Math.PI * 2 + 0.3; addLine([new THREE.Vector3(Math.cos(a) * 16, 0, Math.sin(a) * 16), new THREE.Vector3(Math.cos(a) * (R + 4), 0, Math.sin(a) * (R + 4))], true, 0.12); }
|
||||
const sectorTags = G.sectors.map((name, k) => { const d = document.createElement('div'); d.className = 'sector'; d.textContent = name; labels.appendChild(d);
|
||||
const a = (k + 0.5) / 6 * Math.PI * 2 + 0.3; return { el: d, p: new THREE.Vector3(Math.cos(a) * (R + 9), 0, Math.sin(a) * (R + 9)) }; });
|
||||
|
||||
// ============================================================ 星系(每条世界线一颗卡通星球 + 卫星)
|
||||
const systems = [], planets = [];
|
||||
const lit = CFG.UNIVERSES.filter(u => !u.empty), empty = CFG.UNIVERSES.filter(u => u.empty);
|
||||
CFG.UNIVERSES.forEach((u, i) => {
|
||||
const ei = empty.indexOf(u);
|
||||
const L = Object.assign({}, CFG.EMPTY_LOOK, CFG.LOOKS[u.no] || {});
|
||||
if (!CFG.LOOKS[u.no]) L.orbit = [R * (0.8 + 0.12 * (ei % 2)), ei % ARMS]; // 空槽放在外圈,按顺序分到各条旋臂
|
||||
const [r, arm] = L.orbit || [R * 0.85, i % ARMS];
|
||||
const a = r ? armAngle(r, arm) + (u.empty ? 0.32 * Math.floor(ei / ARMS) : 0) : 0;
|
||||
const g = new THREE.Group(); g.position.set(Math.cos(a) * r, 0, Math.sin(a) * r); scene.add(g);
|
||||
const p = makePlanet(THREE, Object.assign({ seed: i * 7.3 + 1 }, L)); g.add(p.group); planets.push(p);
|
||||
const moons = (L.moons || []).map((m, k) => { const piv = new THREE.Group(); piv.rotation.x = 0.35 - k * 0.2; piv.rotation.y = k * 2.1; g.add(piv);
|
||||
const mp = makePlanet(THREE, Object.assign({ seed: i * 13 + k * 3.1, spin: 0.4 }, m)); mp.group.position.x = m.d; piv.add(mp.group); planets.push(mp); return { piv, speed: Math.abs(m.speed || 0.3) }; }); // 卫星一律同一个方向转(和星系自转同向)
|
||||
const tag = document.createElement('button'); tag.type = 'button'; tag.className = 'tag' + (u.empty ? ' empty' : ''); tag.style.setProperty('--c', L.accent || C.ui);
|
||||
tag.innerHTML = '<span class="t"><b>' + (u.empty ? '空槽' : u.name) + '</b><em>' + u.no + (u.empty ? ' · 未点亮' : ' · ' + u.kind) + '</em></span>';
|
||||
labels.appendChild(tag);
|
||||
const s = { u, L, g, planet: p, moons, tag }; p.body.userData.s = s; systems.push(s);
|
||||
tag.addEventListener('click', () => fly(s));
|
||||
});
|
||||
// 补给线:核心 → 每个星系,虚线往外流
|
||||
const supply = [];
|
||||
for (const s of systems) { if (s.u.no === '0000') continue;
|
||||
const b = s.g.position.clone(), mid = b.clone().multiplyScalar(0.5); mid.y += b.length() * 0.12;
|
||||
const l = new THREE.Line(new THREE.BufferGeometry().setFromPoints(new THREE.QuadraticBezierCurve3(new THREE.Vector3(), mid, b).getPoints(80)),
|
||||
new THREE.LineDashedMaterial({ color: s.u.empty ? lineCol : new THREE.Color(C.ui), dashSize: 0.9, gapSize: 0.8, transparent: true, opacity: s.u.empty ? 0.14 : 0.42, depthWrite: false }));
|
||||
l.computeLineDistances(); l.userData.op = l.material.opacity; scene.add(l); supply.push(l); }
|
||||
// 散落的无名星球(只是让星系看起来有人住;不进档案、不能点)
|
||||
// 位置挑过:离核心、离每个星系(含它的卫星轨道)、彼此之间都留足距离,不会叠在一起
|
||||
{ const n = MOB ? G.decorPlanets.mobile : G.decorPlanets.desktop, styles = ['gas', 'rock', 'gas', 'rock', 'ice'];
|
||||
const pals = [['#F2D7A6', '#D99A6C', '#8E6BBF', '#FFF2D6'], ['#BFD0FF', '#7C8FD6', '#4A5BA8', '#FFFFFF'], ['#9FE3D6', '#4FB8A8', '#2F6F8C', '#E6FFF8'], ['#D6C2FF', '#9B8BFF', '#5B3FB8', '#FFFFFF']];
|
||||
const taken = systems.map(s => ({ p: s.g.position, r: s.L.r * 3 + Math.max(0, ...(s.L.moons || []).map(m => m.d + m.r)) + 3 }));
|
||||
taken.push({ p: new THREE.Vector3(), r: 14 });
|
||||
let made = 0;
|
||||
for (let tries = 0; made < n && tries < n * 60; tries++) {
|
||||
const r = rnd(16, R * 0.96), a = armAngle(r, Math.floor(rnd(0, ARMS))) + rnd(-0.45, 0.45), size = rnd(0.35, 0.8);
|
||||
const pos = new THREE.Vector3(Math.cos(a) * r, rnd(-0.8, 0.8), Math.sin(a) * r);
|
||||
if (taken.some(o => o.p.distanceTo(pos) < o.r + size + 2.5)) continue;
|
||||
const p = makePlanet(THREE, { style: styles[made % styles.length], r: size, colors: pals[made % pals.length], seed: made * 5.1, outline: '#141833', spin: rnd(0.05, 0.2) });
|
||||
p.group.position.copy(pos); scene.add(p.group); planets.push(p); taken.push({ p: pos, r: size + 2 }); made++;
|
||||
} }
|
||||
el.counts && el.counts(CFG.UNIVERSES.length, lit.length, empty.length);
|
||||
|
||||
// ============================================================ 相机 + 交互(拖动、滚轮、双指缩放)
|
||||
const HOME = () => ({ az: 0.7, el: isMob() ? 1.08 : 0.62, dist: isMob() ? 155 : 112 });
|
||||
// ============================================================ 运镜库(全部按时间走,和帧率无关)
|
||||
// 每个运镜 = 时长 + 一条路径函数 path(from, to, k):k 是 0→1 的进度,往 view 里写这一刻的相机状态。
|
||||
// 相机状态:az 方位角 / el 仰角 / dist 距离 / tx,ty,tz 看向哪 / fov 视角 / roll 滚转。
|
||||
// 加一种新运镜:往 MOVES 里加一项,然后在 config.js 的 LOOKS[编号].enter 里写它的名字。
|
||||
const FOV = 42;
|
||||
const lerp = (a, b, k) => a + (b - a) * k, clamp01 = k => Math.max(0, Math.min(1, k));
|
||||
const E = {
|
||||
io: k => k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2, // 缓入缓出
|
||||
out: k => 1 - Math.pow(1 - k, 3), // 先快后慢
|
||||
in: k => k * k * k,
|
||||
io5: k => k < 0.5 ? 16 * k ** 5 : 1 - Math.pow(-2 * k + 2, 5) / 2, // 更「沉」的缓入缓出
|
||||
expo: k => k === 0 ? 0 : k === 1 ? 1 : k < 0.5 ? Math.pow(2, 20 * k - 10) / 2 : (2 - Math.pow(2, -20 * k + 10)) / 2,
|
||||
};
|
||||
const KEYS = ['az', 'el', 'dist', 'tx', 'ty', 'tz', 'fov', 'roll'];
|
||||
const mix = (f, to, k, keys = KEYS) => { for (const key of keys) view[key] = lerp(f[key], to[key], k); };
|
||||
const MOVES = {
|
||||
// 绕行:边飞边绕过去,中途抬高拉远一点(原来那种)
|
||||
orbit: { dur: 1700, path(f, to, k) { const e = E.io(k); mix(f, to, e); view.el += Math.sin(Math.PI * e) * 0.28; view.dist *= 1 + Math.sin(Math.PI * e) * 0.22; } },
|
||||
// 推进:镜头先转过去对准(前 40%),再笔直推进去(不绕圈)
|
||||
push: { dur: 1600, path(f, to, k) { const look = E.out(clamp01(k / 0.45)), go = E.io5(k);
|
||||
mix(f, to, look, ['tx', 'ty', 'tz', 'az', 'el']); mix(f, to, go, ['dist']); view.fov = FOV; view.roll = 0; } },
|
||||
// 放大:先用「长焦」把它拉近(视角收窄),再一边推进一边把视角放回来 —— 有点希区柯克变焦的味道
|
||||
zoom: { dur: 2000, path(f, to, k) { const k1 = clamp01(k / 0.45), k2 = clamp01((k - 0.45) / 0.55);
|
||||
mix(f, to, E.out(clamp01(k / 0.35)), ['tx', 'ty', 'tz']); mix(f, to, E.io(k), ['az', 'el']);
|
||||
view.fov = k < 0.45 ? lerp(f.fov, 14, E.out(k1)) : lerp(14, to.fov, E.io(k2));
|
||||
view.dist = lerp(f.dist, to.dist, E.io(k2)); view.roll = 0; } },
|
||||
// 升空俯冲:先拉高到几乎俯视,再从上面扎下去
|
||||
rise: { dur: 2100, path(f, to, k) { const e = E.io(k); mix(f, to, e);
|
||||
const up = Math.sin(Math.PI * clamp01(k * 1.15)); view.el = lerp(view.el, 1.35, up * 0.85); view.dist *= 1 + up * 0.55; } },
|
||||
// 跃迁:慢起步、中段猛冲、末段刹住;冲的时候视角张开、镜头轻轻一滚
|
||||
warp: { dur: 1800, path(f, to, k) { const e = E.expo(k), s = Math.sin(Math.PI * k);
|
||||
mix(f, to, e); view.fov = to.fov + s * s * 34; view.roll = s * 0.18 * (f.az > to.az ? 1 : -1); } },
|
||||
// 拉远:回星系图用 —— 先往后退,再抬头看全景
|
||||
pull: { dur: 1700, path(f, to, k) { mix(f, to, E.io5(k), ['dist']); mix(f, to, E.out(clamp01((k - 0.15) / 0.85)), ['tx', 'ty', 'tz', 'el', 'az']);
|
||||
view.fov = lerp(f.fov, to.fov, E.io(k)); view.roll = lerp(f.roll, 0, E.io(k)); } },
|
||||
// 开场 A · 盘旋落下:从高空、更远处绕半圈落到正常视角
|
||||
introSweep: { dur: 3600, path(f, to, k) { mix(f, to, E.io(k)); } },
|
||||
// 开场 B · 垂直坠入:从正上方很远的地方直着往下落,最后才抬起镜头、星系转正
|
||||
introDive: { dur: 3400, path(f, to, k) { const d = E.io5(k); view.dist = lerp(f.dist, to.dist, d); view.el = lerp(f.el, to.el, E.in(clamp01((k - 0.35) / 0.65)));
|
||||
view.az = lerp(f.az, to.az, E.io(k)); view.fov = lerp(f.fov, to.fov, E.out(k)); view.tx = view.ty = view.tz = 0; view.roll = 0; } },
|
||||
};
|
||||
const h0 = HOME();
|
||||
const introKind = (G.intro === 'dive' || G.intro === 'sweep') ? G.intro : (Math.random() < 0.5 ? 'dive' : 'sweep');
|
||||
const START = introKind === 'dive' ? { az: h0.az + 0.6, el: 1.52, dist: h0.dist * 3.2, fov: 30 } : { az: h0.az - 1.5, el: 1.42, dist: h0.dist * 2.4, fov: FOV };
|
||||
const view = Object.assign({ tx: 0, ty: 0, tz: 0, roll: 0, fov: FOV }, reduce ? h0 : START);
|
||||
const want = Object.assign({ fov: FOV, roll: 0 }, h0);
|
||||
let anim = null, intro = !reduce;
|
||||
// 用户中途拖动 / 缩放:运镜立刻停在原地交还控制权,但没出来的档案卡要马上补上(不然卡就丢了)
|
||||
function cancelAnim() { if (!anim) return; const f = anim.onArrive; anim = null; f && f(); }
|
||||
// to 里没写的 fov / roll 默认回到正常;az 走最近的那一边转
|
||||
function animate(to, move = 'orbit', onArrive = null, arriveAt = 0.8) {
|
||||
to = Object.assign({ fov: FOV, roll: 0 }, to);
|
||||
if (reduce) { Object.assign(view, to); Object.assign(want, to); anim = null; onArrive && onArrive(); return; }
|
||||
const daz = ((to.az - view.az) % (Math.PI * 2) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
|
||||
const M = MOVES[move] || MOVES.orbit;
|
||||
anim = { t0: performance.now(), M, from: Object.assign({}, view), to: Object.assign({}, to, { az: view.az + daz }), onArrive, arriveAt };
|
||||
}
|
||||
let focus = null, hover = null;
|
||||
function fit() { const w = stage.clientWidth, h = stage.clientHeight; renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix(); }
|
||||
addEventListener('resize', fit); fit();
|
||||
const ptrs = new Map(); let drag = null, pinch = null;
|
||||
canvas.addEventListener('pointerdown', e => { canvas.setPointerCapture(e.pointerId); ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (ptrs.size === 2) { const [a, b] = [...ptrs.values()]; pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), dist: want.dist }; drag = null; }
|
||||
else drag = { x: e.clientX, y: e.clientY, az: want.az, el: want.el, moved: false }; });
|
||||
canvas.addEventListener('pointermove', e => {
|
||||
if (ptrs.has(e.pointerId)) ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pinch && ptrs.size === 2) { const [a, b] = [...ptrs.values()]; zoomTo(pinch.dist * pinch.d / Math.max(20, Math.hypot(a.x - b.x, a.y - b.y))); return; }
|
||||
if (drag) { const dx = e.clientX - drag.x, dy = e.clientY - drag.y; if (Math.abs(dx) + Math.abs(dy) > 6) drag.moved = true;
|
||||
if (drag.moved) { if (anim) { cancelAnim(); Object.assign(want, view); drag.az = view.az + dx * 0.005; drag.el = view.el - dy * 0.004; } /* 从镜头现在的位置接着拖,不跳 */ want.az = drag.az - dx * 0.005; want.el = THREE.MathUtils.clamp(drag.el + dy * 0.004, 0.08, 1.45); } return; }
|
||||
if (e.pointerType === 'mouse') { hover = pick(e); canvas.style.cursor = hover ? 'pointer' : 'grab'; } });
|
||||
const end = e => { ptrs.delete(e.pointerId); if (ptrs.size < 2) pinch = null;
|
||||
const d = drag; drag = null; if (d && !d.moved && e.type === 'pointerup') { const s = pick(e); if (s) fly(s); else if (focus) home(); } };
|
||||
canvas.addEventListener('pointerup', end); canvas.addEventListener('pointercancel', end);
|
||||
const zoomTo = d => { if (anim) { cancelAnim(); Object.assign(want, view); } want.dist = THREE.MathUtils.clamp(d, focus ? focus.L.r * 2.6 : 32, focus ? focus.L.r * 16 : 230); };
|
||||
canvas.addEventListener('wheel', e => {
|
||||
if (el.wheelZoom && !el.wheelZoom() && !e.ctrlKey) return; // 嵌在页面里:普通滚轮留给页面滚动
|
||||
e.preventDefault(); zoomTo(want.dist * (1 + Math.sign(e.deltaY) * 0.1)); }, { passive: false });
|
||||
addEventListener('keydown', e => { if (e.key === 'Escape') home(); if (focus && e.key === 'ArrowRight') step(1); if (focus && e.key === 'ArrowLeft') step(-1); });
|
||||
back && (back.onclick = () => home());
|
||||
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), tmp = new THREE.Vector3();
|
||||
function pick(e) {
|
||||
const r = canvas.getBoundingClientRect(); ptr.set((e.clientX - r.left) / r.width * 2 - 1, -(e.clientY - r.top) / r.height * 2 + 1);
|
||||
ray.setFromCamera(ptr, camera); const hit = ray.intersectObjects(systems.map(s => s.planet.body), false)[0]; if (hit) return hit.object.userData.s;
|
||||
let best = null, bd = isMob() ? 34 : 28;
|
||||
for (const s of systems) { s.g.getWorldPosition(tmp).project(camera); const d = Math.hypot((tmp.x - ptr.x) * r.width / 2, (tmp.y - ptr.y) * r.height / 2); if (d < bd && tmp.z < 1) { bd = d; best = s; } }
|
||||
return best;
|
||||
}
|
||||
const esc = x => String(x || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
function card(s) { const u = s.u, nav = '<div class="nav"><button class="btn" type="button" data-s="-1">上一个</button><button class="btn" type="button" data-s="1">下一个</button></div>';
|
||||
if (u.empty) return '<div class="card" style="--pc:' + (s.L.accent) + '"><div class="k">UNIVERSE ' + u.no + ' · 未点亮</div><h2>空槽</h2><div class="tg">这条世界线还没写出来,星系还没被点亮。</div><div class="acts">' + nav + '<button class="btn" type="button" data-home>回到星系图</button></div></div>';
|
||||
return '<div class="card" style="--pc:' + s.L.accent + '"><div class="k">UNIVERSE ' + u.no + ' · ' + esc(u.kind) + ' · 已点亮</div><h2>' + esc(u.name) + '</h2><div class="tg">' + esc(u.tag) + '</div>' +
|
||||
'<p class="ds">' + esc(u.desc) + '</p><div class="tags">' + (u.tags || []).map(t => '<span>' + esc(t) + '</span>').join('') + '</div><div class="acts">' + nav + '<button class="btn pri" type="button" data-home>回到星系图</button></div></div>'; }
|
||||
panel && panel.addEventListener('click', e => { const b = e.target.closest('[data-s]'); if (b) step(+b.dataset.s); if (e.target.closest('[data-home]')) home(); });
|
||||
function step(d) { const i = systems.indexOf(focus); fly(systems[(i + d + systems.length) % systems.length]); }
|
||||
// 飞过去:先把旧档案卡收起来 → 镜头按这颗星的「入场运镜」飞 → 快到(80%)的时候档案卡才滑出来,和星球落定同步
|
||||
const ENTER_CYCLE = ['push', 'zoom', 'rise', 'warp', 'orbit'];
|
||||
function fly(s) { const was = focus; focus = s; intro = false; stage.classList.add('ready'); stage.classList.add('focus');
|
||||
panel && panel.classList.remove('on'); el.onFocus && el.onFocus(s.u, 'start');
|
||||
const p = s.g.position, dist = s.L.r * (isMob() ? 9 : 5.6) + (s.moons.length ? s.L.r * 1.5 : 0);
|
||||
const i = systems.indexOf(s), move = s.L.enter || ENTER_CYCLE[i % ENTER_CYCLE.length];
|
||||
// 推进 / 放大:沿着现在的视线方向过去(不绕);其它运镜:落到「从星系中心那一侧看过去」的角度,背景是星系盘
|
||||
const az = (move === 'push' || move === 'zoom') ? view.az + 0.12 : Math.atan2(p.x, p.z) + 0.35;
|
||||
animate({ az, el: 0.24, dist, tx: p.x, ty: p.y, tz: p.z }, was && was !== s && move !== 'warp' ? 'orbit' : move, () => {
|
||||
if (focus !== s) return;
|
||||
panel && (panel.innerHTML = card(s), panel.classList.add('on')); el.onFocus && el.onFocus(s.u, 'arrive'); }, 0.78); }
|
||||
function home() { if (!focus) return; focus = null; panel && panel.classList.remove('on'); stage.classList.remove('focus'); el.onFocus && el.onFocus(null, 'start');
|
||||
animate(Object.assign(HOME(), { tx: 0, ty: 0, tz: 0, az: view.az - 0.3 }), 'pull'); }
|
||||
|
||||
// ============================================================ 循环
|
||||
const clock = new THREE.Clock(), tgt = new THREE.Vector3();
|
||||
let hudBottom = 0; const measureHud = () => { hudBottom = hud ? hud.getBoundingClientRect().bottom - stage.getBoundingClientRect().top : 0; }; measureHud(); addEventListener('resize', measureHud);
|
||||
let visible = true, started = false, tIntro = 0;
|
||||
if ('IntersectionObserver' in window) new IntersectionObserver(es => { visible = es[0].isIntersecting; }, { threshold: 0.05 }).observe(stage);
|
||||
function loop() {
|
||||
requestAnimationFrame(loop);
|
||||
if (!visible) { clock.getDelta(); return; } // 滚出视口:不渲染,省电
|
||||
if (!started) { started = true; tIntro = clock.elapsedTime; if (intro) animate(Object.assign({}, h0, { tx: 0, ty: 0, tz: 0 }), introKind === 'dive' ? 'introDive' : 'introSweep'); else stage.classList.add('ready'); }
|
||||
const dt = Math.min(clock.getDelta(), 0.05), t = clock.elapsedTime, mob = isMob();
|
||||
if (!reduce) { galaxy.rotation.y += dt * 0.004; for (const n of nebulae) n.material.uniforms.uT.value = t; }
|
||||
for (const l of supply) l.material.dashOffset -= dt * 2;
|
||||
for (const p of planets) p.update(reduce ? 0 : dt, t, LIGHT);
|
||||
// 星系在总览里放大一点(不然在手机上只是一个小点),飞近时恢复真实大小
|
||||
const sysK = focus ? 1 : (mob ? 1.9 : 1.35);
|
||||
for (const s of systems) { for (const m of s.moons) m.piv.rotation.y += (reduce ? 0 : dt) * m.speed;
|
||||
const sc = s.g.scale.x + (sysK - s.g.scale.x) * (reduce ? 1 : Math.min(1, dt * 3)); s.g.scale.setScalar(sc); }
|
||||
// 开场:星系从暗处亮起来(0 → 1,大约 2.4 秒);飞近一颗星时:星云、粒子、扇区线退后一点,别抢主角
|
||||
const introK = intro ? Math.min(1, (t - tIntro) / 2.4) : 1;
|
||||
const dimT = (focus ? 0.45 : 1) * introK;
|
||||
galaxy.material.uniforms.uDim.value += (dimT - galaxy.material.uniforms.uDim.value) * (intro ? 1 : Math.min(1, dt * 3));
|
||||
galaxy.material.uniforms.uK.value = 112 / HOME().dist;
|
||||
for (const n of nebulae) n.material.uniforms.uDim.value = galaxy.material.uniforms.uDim.value;
|
||||
for (const l of guides.concat(supply)) l.material.opacity += (l.userData.op * (focus ? 0.25 : 1) * introK - l.material.opacity) * Math.min(1, dt * 3);
|
||||
// 相机:有补间就按时间走补间(不受帧率影响,一条连贯的弧线);没有就柔和地跟着拖动 / 缩放
|
||||
if (anim) {
|
||||
const a = anim, kk = Math.min(1, (performance.now() - a.t0) / a.M.dur);
|
||||
a.M.path(a.from, a.to, kk);
|
||||
if (a.onArrive && kk >= a.arriveAt) { const f = a.onArrive; a.onArrive = null; f(); } // 档案卡和星球落定同步出现
|
||||
if (kk >= 1) { Object.assign(view, a.to); Object.assign(want, a.to); if (anim === a) anim = null; if (!focus) stage.classList.add('ready'); }
|
||||
} else {
|
||||
view.fov += (FOV - view.fov) * Math.min(1, dt * 4); view.roll += (0 - view.roll) * Math.min(1, dt * 4);
|
||||
if (focus) focus.g.getWorldPosition(tgt); else tgt.set(0, 0, 0);
|
||||
const k = 1 - Math.exp(-dt * 6);
|
||||
view.tx += (tgt.x - view.tx) * k; view.ty += (tgt.y - view.ty) * k; view.tz += (tgt.z - view.tz) * k;
|
||||
for (const key of ['az', 'el', 'dist']) view[key] += (want[key] - view[key]) * k;
|
||||
if (!drag && !pinch && !focus && !reduce) want.az += dt * 0.02;
|
||||
}
|
||||
camera.position.set(view.tx + Math.sin(view.az) * Math.cos(view.el) * view.dist, view.ty + Math.sin(view.el) * view.dist, view.tz + Math.cos(view.az) * Math.cos(view.el) * view.dist);
|
||||
camera.lookAt(view.tx, view.ty, view.tz);
|
||||
if (view.roll) camera.rotateZ(view.roll);
|
||||
if (Math.abs(camera.fov - view.fov) > 0.01) { camera.fov = view.fov; camera.updateProjectionMatrix(); }
|
||||
// 选中时把星球挪开,给档案卡让位:桌面往左挪,手机往上挪(档案卡在下半屏)
|
||||
const w = stage.clientWidth, h = stage.clientHeight;
|
||||
const lay = el.layout ? el.layout() : { x: mob ? 0 : 0.16, y: mob ? 0.22 : 0 };
|
||||
if (focus && (lay.x || lay.y)) camera.setViewOffset(w, h, w * lay.x, h * lay.y, w, h); else camera.clearViewOffset();
|
||||
// 名牌:跟着星系走;贴边夹住不出屏;手机上压到 HUD 下面的藏起来
|
||||
for (const s of systems) { s.g.getWorldPosition(tmp); tmp.project(camera);
|
||||
let x = (tmp.x + 1) / 2 * w + 10, y = (1 - tmp.y) / 2 * h - 12;
|
||||
const tw = s.tag.offsetWidth || 90; x = Math.min(Math.max(x, 6), w - tw - 6);
|
||||
const vis = tmp.z < 1 && Math.abs(tmp.x) < 1.05 && Math.abs(tmp.y) < 1.05 && !(mob && y < hudBottom + 4) && focus !== s;
|
||||
s.tag.style.transform = 'translate(' + x.toFixed(1) + 'px,' + y.toFixed(1) + 'px)';
|
||||
s.tag.classList.toggle('hot', s === hover); s.tag.classList.toggle('dim', !!focus); s.tag.style.visibility = vis ? '' : 'hidden'; }
|
||||
for (const st of sectorTags) { tmp.copy(st.p).project(camera); st.el.style.transform = 'translate(' + ((tmp.x + 1) / 2 * w) + 'px,' + ((1 - tmp.y) / 2 * h) + 'px) translate(-50%,-50%)'; st.el.style.opacity = (tmp.z < 1 && !focus) ? '' : 0; }
|
||||
renderer.render(scene, camera);
|
||||
if (firstFrame) { firstFrame = false; el.onReady && el.onReady(); } // 第一帧画好了,外面的「载入中」再淡出
|
||||
}
|
||||
// 开场:第一帧画出来再开始(外面的「载入中」此时淡出,镜头接着就开始动,中间不留空白)
|
||||
let firstFrame = true;
|
||||
loop();
|
||||
return { resize: fit, fly: no => { const s = systems.find(x => x.u.no === no); if (s) fly(s); }, home };
|
||||
}
|
||||
Reference in New Issue
Block a user