Publish verified live restoration source snapshot and known limits

This commit is contained in:
0xcjy
2026-10-01 19:42:22 +08:00
parent 0dd0d3bdaa
commit d70a65c7ce
896 changed files with 105420 additions and 12745 deletions
+99
View File
@@ -0,0 +1,99 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#131b24">
<title>无声铃鹿 · PMX 模型查看器</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="./style.css">
<script type="importmap">
{ "imports": { "three": "/vendor/three/build/three.module.js", "three/addons/": "/vendor/three/examples/jsm/" } }
</script>
</head>
<body>
<header class="topbar">
<a class="brand" href="/" aria-label="PMX 查看器首页"><span class="brand-icon">U</span> UMA <span>MODEL VIEWER</span></a>
<span class="format-label">PMX 2.0 <span class="divider">/</span> WEBGL</span>
</header>
<main>
<aside class="sidebar">
<div class="eyebrow">CHARACTER / 1002</div>
<h1>无声铃鹿</h1>
<p class="subtitle">サイレンススズカ<br><span>Silence Suzuka</span></p>
<div class="tags"><span>普通角色</span><span>服装 00</span><span>VMD 动作</span></div>
<section class="section motion-section" aria-labelledby="motion-heading">
<h2 id="motion-heading">动作播放 <span>MOTION</span></h2>
<fieldset id="motion-sources" disabled>
<button id="motion-demo" type="button">载入待机动作 <span>DEMO</span></button>
<button id="motion-import" type="button">导入本地 VMD <span>+</span></button>
<input id="motion-file" type="file" accept=".vmd" aria-label="选择 VMD 动作文件" hidden>
</fieldset>
<p id="motion-name" class="motion-name">尚未选择动作</p>
<p id="motion-status" class="motion-status" role="status" aria-live="polite">可载入待机动作,或导入本地角色 VMD。</p>
<fieldset id="motion-controls" disabled>
<div class="playback-buttons">
<button id="motion-play" type="button">播放</button>
<button id="motion-restart" type="button">从头播放</button>
</div>
<label class="timeline-label" for="motion-time">动作进度 <output id="motion-time-text">00:00.00 / 00:00.00</output></label>
<input id="motion-time" type="range" min="0" max="0" step="any" value="0">
<div class="motion-options">
<label class="toggle">循环<input id="motion-loop" type="checkbox" checked><span class="switch"></span></label>
<label class="speed-label" for="motion-speed">速度
<select id="motion-speed">
<option value="0.25">0.25×</option>
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
</label>
</div>
<button id="motion-clear" type="button">清除动作 / 还原姿势</button>
</fieldset>
<p class="download-note">VMD 仅在本机浏览器解析,不上传。支持角色骨骼与顶点表情,不含镜头、音乐与物理。</p>
</section>
<section class="section">
<h2>模型信息 <span>MODEL</span></h2>
<dl class="stats">
<div><dt>顶点</dt><dd id="vertices">—</dd></div>
<div><dt>三角形</dt><dd id="triangles">—</dd></div>
<div><dt>骨骼</dt><dd id="bones">—</dd></div>
<div><dt>表情</dt><dd id="morphs">—</dd></div>
</dl>
</section>
<section class="section">
<h2>显示设置 <span>DISPLAY</span></h2>
<fieldset id="display-controls" disabled>
<label class="toggle">自动旋转<input id="rotate" type="checkbox"><span class="switch"></span></label>
<label class="toggle">地面网格<input id="grid" type="checkbox" checked><span class="switch"></span></label>
<label class="toggle">线框模式<input id="wireframe" type="checkbox"><span class="switch"></span></label>
<button id="reset" type="button">重置视角 <span>↺</span></button>
</fieldset>
</section>
<p class="note">直接读取导出的 PMX、贴图与 VMD。<br>使用网页材质显示,不含 Unity 原版着色器与物理模拟。</p>
<a class="download" href="./model/1002_00.pmx" download>下载 PMX <span>↗</span></a>
<p class="download-note">贴图位于导出目录的 Texture2D 文件夹;使用模型时请一并保留。</p>
</aside>
<section id="viewport" aria-label="可交互的角色三维模型">
<div class="view-label"><span class="dot"></span> MODEL PREVIEW</div>
<div id="loading" class="loading" role="status" aria-live="polite">
<div class="spinner" aria-hidden="true"></div>
<strong id="loading-title">正在加载模型</strong>
<p id="loading-detail">读取 PMX 与本地贴图…</p>
</div>
<div class="view-footer"><span id="status" role="status">准备加载</span><span>左键旋转 · 滚轮缩放 · 右键平移<br class="mobile-break">触屏:单指旋转 · 双指缩放 / 平移</span></div>
</section>
</main>
<script type="module">
import('./viewer.js').catch(error => {
console.error(error);
document.querySelector('.spinner').hidden = true;
document.querySelector('#loading-title').textContent = '查看器启动失败';
document.querySelector('#loading-detail').textContent = '请通过 npm start 启动后访问网页,并确认浏览器支持 WebGL。' + error.message;
document.querySelector('#status').textContent = '加载失败';
});
</script>
</body>
</html>
+337
View File
@@ -0,0 +1,337 @@
import { LoopOnce, LoopRepeat } from 'three';
import { MMDAnimationHelper } from 'three/addons/animation/MMDAnimationHelper.js';
import { MMDLoader } from 'three/addons/loaders/MMDLoader.js';
import { MMDParser } from 'three/addons/libs/mmdparser.module.js';
const parser = new MMDParser.Parser();
const animationBuilder = new MMDLoader().animationBuilder;
const shiftJis = new TextDecoder('shift_jis');
// MMDParser.parseVmd stops after the camera records. Read the optional VMD footer
// separately so its per-frame IK on/off switches are not lost (notably FK leg VMDs).
function readIkTracks(buffer, metadata, ikNames) {
const view = new DataView(buffer);
let offset = 50 + 4 + metadata.motionCount * 111 + 4 + metadata.morphCount * 23
+ 4 + metadata.cameraCount * 61;
const tracks = new Map();
function skipRecords(size) {
if (offset === view.byteLength) return false; // Older VMDs can omit the footer.
if (view.byteLength - offset < 4) throw new Error('VMD 附加数据不完整。');
const count = view.getUint32(offset, true);
offset += 4;
if (count > Math.floor((view.byteLength - offset) / size)) {
throw new Error('VMD 附加数据已截断。');
}
offset += count * size;
return true;
}
if (!skipRecords(28) || !skipRecords(9) || offset === view.byteLength) return tracks;
if (view.byteLength - offset < 4) throw new Error('VMD IK 数据不完整。');
const frameCount = view.getUint32(offset, true);
offset += 4;
for (let frame = 0; frame < frameCount; frame++) {
if (view.byteLength - offset < 9) throw new Error('VMD IK 帧已截断。');
const time = view.getUint32(offset, true) / 30;
const count = view.getUint32(offset + 5, true);
offset += 9; // frame number, model display flag, IK switch count
if (count > Math.floor((view.byteLength - offset) / 21)) {
throw new Error('VMD IK 开关已截断。');
}
for (let i = 0; i < count; i++) {
const bytes = new Uint8Array(buffer, offset, 20);
const terminator = bytes.indexOf(0);
const name = shiftJis.decode(bytes.subarray(0, terminator < 0 ? 20 : terminator));
const index = ikNames.get(name);
if (index !== undefined) {
let keys = tracks.get(index);
if (!keys) {
keys = [];
tracks.set(index, keys);
}
keys.push({ time, enabled: view.getUint8(offset + 20) !== 0 });
}
offset += 21;
}
}
for (const keys of tracks.values()) keys.sort((a, b) => a.time - b.time);
return tracks;
}
function capturePose(mesh) {
const bones = mesh.skeleton.bones;
const pose = new Float64Array(bones.length * 10);
for (let i = 0; i < bones.length; i++) {
const bone = bones[i];
bone.position.toArray(pose, i * 10);
bone.quaternion.toArray(pose, i * 10 + 3);
bone.scale.toArray(pose, i * 10 + 7);
}
return { bones: pose, morphs: mesh.morphTargetInfluences.slice() };
}
function restorePose(mesh, snapshot) {
const bones = mesh.skeleton.bones;
for (let i = 0; i < bones.length; i++) {
const bone = bones[i];
bone.position.fromArray(snapshot.bones, i * 10);
bone.quaternion.fromArray(snapshot.bones, i * 10 + 3);
bone.scale.fromArray(snapshot.bones, i * 10 + 7);
}
const influences = mesh.morphTargetInfluences;
for (let i = 0; i < influences.length; i++) influences[i] = snapshot.morphs[i];
mesh.updateMatrixWorld(true);
}
function releaseMotion(helper, mixer, clip, mesh) {
if (!helper) return;
mixer.stopAllAction();
mixer.uncacheClip(clip);
mixer.uncacheRoot(mesh);
helper.remove(mesh);
}
export class MotionPlayer {
constructor(mesh, onChange = () => {}) {
if (!mesh?.isSkinnedMesh || !mesh.geometry?.userData?.MMD || !mesh.skeleton) {
throw new Error('动画播放器需要已加载的 PMX 骨骼模型。');
}
this.mesh = mesh;
this.onChange = onChange;
this._helper = null;
this._mixer = null;
this._action = null;
this._clip = null;
this._name = '';
this._time = 0;
this._playing = false;
this._loop = true;
this._speed = 1;
this._boneTrackCount = 0;
this._morphTrackCount = 0;
this._disposed = false;
this._ikTracks = new Map();
this._iks = mesh.geometry.userData.MMD.iks || [];
this._originalIkLinks = this._iks.map(ik => ik.links.map(link => link.enabled));
this._ikNames = new Map(this._iks.map((ik, index) => [mesh.skeleton.bones[ik.target].name, index]));
}
get state() {
return {
name: this._name,
duration: this._clip?.duration || 0,
time: this._time,
playing: this._playing,
loop: this._loop,
speed: this._speed,
trackCount: this._clip?.tracks.length || 0,
boneTrackCount: this._boneTrackCount,
morphTrackCount: this._morphTrackCount,
};
}
load(buffer, name) {
if (this._disposed) throw new Error('动画播放器已释放,无法加载 VMD。');
if (!(buffer instanceof ArrayBuffer)) throw new Error('请选择有效的 VMD 文件(二进制数据)。');
let vmd;
try {
vmd = parser.parseVmd(buffer, true);
} catch (error) {
throw new Error(`VMD 格式无效或文件已损坏:${String(error.message || error)}`);
}
if (vmd.metadata.motionCount === 0 && vmd.metadata.morphCount === 0) {
throw new Error(vmd.metadata.cameraCount > 0
? '这是仅含镜头的 VMD,不能用于角色骨骼或表情动画。'
: 'VMD 不包含角色骨骼或表情动画。');
}
const bones = new Set(this.mesh.skeleton.bones.map(bone => bone.name));
const morphs = this.mesh.morphTargetDictionary;
if (!vmd.motions.some(motion => bones.has(motion.boneName))
&& !vmd.morphs.some(morph => Object.hasOwn(morphs, morph.morphName))) {
throw new Error('VMD 中没有与当前 PMX 模型匹配的骨骼或表情轨道,请选择对应角色的动作。');
}
let ikTracks;
try {
ikTracks = readIkTracks(buffer, vmd.metadata, this._ikNames);
} catch (error) {
throw new Error(`VMD 格式无效或文件已损坏:${error.message}`);
}
const snapshot = capturePose(this.mesh);
let helper, mixer, clip, action;
let boneTrackCount = 0;
let morphTrackCount = 0;
try {
// MMDLoader builds absolute bone positions from the current local pose.
// Always build against the bind pose, not the preceding clip's last frame.
this.mesh.pose();
clip = animationBuilder.build(vmd, this.mesh);
clip.name = name || '未命名动作';
for (const track of clip.tracks) {
if (track.name.startsWith('.bones[')) boneTrackCount++;
else if (track.name.startsWith('.morphTargetInfluences[')) morphTrackCount++;
for (const value of track.values) {
if (!Number.isFinite(value)) throw new Error('VMD 关键帧包含无效数字。');
}
}
if (!clip.tracks.length || !Number.isFinite(clip.duration)) {
throw new Error('VMD 没有可播放的骨骼或表情轨道。');
}
for (const keys of ikTracks.values()) {
clip.duration = Math.max(clip.duration, keys[keys.length - 1].time);
}
this.mesh.morphTargetInfluences.fill(0);
helper = new MMDAnimationHelper({ sync: false, pmxAnimation: true });
helper.enable('physics', false);
helper.add(this.mesh, { animation: clip, physics: false });
mixer = helper.objects.get(this.mesh).mixer;
action = mixer.existingAction(clip);
action.setLoop(this._loop ? LoopRepeat : LoopOnce, this._loop ? Infinity : 1);
action.clampWhenFinished = true;
action.paused = true;
} catch (error) {
if (helper?.meshes.includes(this.mesh)) {
if (mixer) releaseMotion(helper, mixer, clip, this.mesh);
else helper.remove(this.mesh);
}
restorePose(this.mesh, snapshot);
throw new Error(`无法加载 VMD 动画:${error.message || error}`);
}
releaseMotion(this._helper, this._mixer, this._clip, this.mesh);
this.mesh.pose();
this.mesh.morphTargetInfluences.fill(0);
// With no physics, every IK link is available unless the VMD turns it off.
helper.enable('physics', false);
this._helper = helper;
this._mixer = mixer;
this._clip = clip;
this._action = action;
this._ikTracks = ikTracks;
this._name = name || '未命名动作';
this._time = 0;
this._playing = false;
this._boneTrackCount = boneTrackCount;
this._morphTrackCount = morphTrackCount;
this._sample();
this.onChange();
}
play() {
if (!this._clip || this._playing || this._clip.duration === 0) return;
if (this._time >= this._clip.duration) this._setTime(0);
this._playing = true;
this.onChange();
}
pause() {
if (!this._playing) return;
this._playing = false;
this.onChange();
}
restart() {
if (!this._clip) return;
this._setTime(0);
this._playing = this._clip.duration > 0;
this.onChange();
}
seek(seconds) {
if (!this._clip) return;
if (!Number.isFinite(seconds)) throw new Error('定位时间必须是有限的秒数。');
this._setTime(Math.max(0, Math.min(seconds, this._clip.duration)));
this.onChange();
}
setLoop(loop) {
if (this._loop === Boolean(loop)) return;
this._loop = Boolean(loop);
if (this._action) this._action.setLoop(this._loop ? LoopRepeat : LoopOnce, this._loop ? Infinity : 1);
this.onChange();
}
setSpeed(speed) {
if (!Number.isFinite(speed) || speed <= 0) throw new Error('播放速度必须是大于零的有限数字。');
if (this._speed === speed) return;
this._speed = speed;
this.onChange();
}
clear() {
if (this._disposed) return;
releaseMotion(this._helper, this._mixer, this._clip, this.mesh);
this._helper = this._mixer = this._clip = this._action = null;
this._ikTracks = new Map();
this._name = '';
this._time = 0;
this._playing = false;
this._boneTrackCount = this._morphTrackCount = 0;
for (let i = 0; i < this._iks.length; i++) {
for (let j = 0; j < this._iks[i].links.length; j++) {
this._iks[i].links[j].enabled = this._originalIkLinks[i][j];
}
}
this.mesh.pose();
this.mesh.morphTargetInfluences.fill(0);
this.mesh.updateMatrixWorld(true);
this.onChange();
}
update(deltaSeconds) {
if (!this._playing || !Number.isFinite(deltaSeconds) || deltaSeconds <= 0) return;
const duration = this._clip.duration;
const next = this._time + deltaSeconds * this._speed;
if (this._loop) {
this._setTime(next % duration);
} else if (next >= duration) {
this._setTime(duration);
this._playing = false;
this.onChange();
} else {
this._setTime(next);
}
}
dispose() {
if (this._disposed) return;
this.clear();
this._disposed = true;
}
_setTime(seconds) {
this._time = seconds;
this._sample();
}
_sample() {
this._applyIk(this._time);
// The helper restores pre-IK/grant bones, resamples the mixer, then applies
// IK/grants once. Setting the action's absolute time and updating by zero
// also works when paused or seeking backwards, without cumulative offsets.
this._action.time = this._time;
this._helper.update(0);
this.mesh.updateMatrixWorld(true);
}
_applyIk(time) {
for (let i = 0; i < this._iks.length; i++) {
const keys = this._ikTracks.get(i);
let enabled = true;
if (keys) {
let low = 0, high = keys.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (keys[middle].time <= time + 1e-7) low = middle + 1;
else high = middle;
}
if (low) enabled = keys[low - 1].enabled;
}
for (const link of this._iks[i].links) link.enabled = enabled;
}
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"name": "umaviewer-pmx-web-viewer",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "umaviewer-pmx-web-viewer",
"version": "1.0.0",
"dependencies": {
"three": "0.160.1"
}
},
"node_modules/three": {
"version": "0.160.1",
"resolved": "https://registry.npmmirror.com/three/-/three-0.160.1.tgz",
"integrity": "sha512-Bgl2wPJypDOZ1stAxwfWAcJ0WQf7QzlptsxkjYiURPz+n5k4RBDLsq+6f9Y75TYxn6aHLcWz+JNmwTOXWrQTBQ==",
"license": "MIT"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "umaviewer-pmx-web-viewer",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "node server.mjs"
},
"dependencies": {
"three": "0.160.1"
}
}
+65
View File
@@ -0,0 +1,65 @@
import http from 'node:http';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const modelRoot = path.resolve(root, '../../exports/pmx-test/1002_00_20260926-221744');
const mime = {
'.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8', '.png': 'image/png',
'.pmx': 'application/octet-stream', '.vmd': 'application/octet-stream',
};
const pages = new Set(['/index.html', '/viewer.js', '/motion-player.js', '/style.css']);
const server = http.createServer(async (request, response) => {
try {
if (request.method !== 'GET' && request.method !== 'HEAD') {
response.writeHead(405, { Allow: 'GET, HEAD' }).end();
return;
}
let urlPath = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
if (urlPath === '/') urlPath = '/index.html';
let base, relative;
if (urlPath.startsWith('/model/')) {
base = modelRoot;
relative = urlPath.slice('/model/'.length);
} else if (urlPath.startsWith('/vendor/three/')) {
base = path.join(root, 'node_modules/three');
relative = urlPath.slice('/vendor/three/'.length);
} else if (pages.has(urlPath)) {
base = root;
relative = urlPath.slice(1);
} else {
response.writeHead(404).end('Not found');
return;
}
const file = path.resolve(base, relative);
const within = path.relative(base, file);
if (within.startsWith('..') || path.isAbsolute(within)) {
response.writeHead(403).end('Forbidden');
return;
}
const info = await stat(file);
if (!info.isFile()) { response.writeHead(404).end('Not found'); return; }
response.writeHead(200, {
'Content-Type': mime[path.extname(file)] || 'application/octet-stream',
'Content-Length': info.size,
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-cache',
});
if (request.method === 'HEAD') { response.end(); return; }
const stream = createReadStream(file);
stream.on('error', () => response.destroy());
response.on('close', () => stream.destroy());
stream.pipe(response);
} catch (error) {
const status = error.code === 'ENOENT' || error.code === 'ENOTDIR' ? 404 : error instanceof URIError ? 400 : 500;
response.writeHead(status).end(status === 404 ? 'Not found' : 'Request failed');
}
});
server.on('error', error => { console.error(error.message); process.exitCode = 1; });
server.listen(8765, '127.0.0.1', () => {
console.log('PMX viewer: http://127.0.0.1:8765');
console.log(`Model directory: ${modelRoot}`);
});
+88
View File
@@ -0,0 +1,88 @@
* { box-sizing: border-box; }
:root { color-scheme: dark; font-family: Inter, "Segoe UI", "Microsoft YaHei", sans-serif; color: #eaf0f3; background: #131b24; }
body { margin: 0; }
button, input, select { font: inherit; }
.topbar { height: 68px; padding: 0 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #ffffff12; }
.brand { display: flex; align-items: center; gap: 12px; color: #edf6f5; text-decoration: none; font-weight: 750; letter-spacing: 2px; font-size: 16px; }
.brand > span:last-child { font-size: 10px; font-weight: 500; color: #98a9b5; letter-spacing: 2px; }
.brand-icon { display: grid; place-items: center; width: 30px; height: 30px; background: #b9e7d3; color: #192b2a; border-radius: 9px 9px 9px 2px; font-size: 21px; }
.format-label { font-size: 10px; letter-spacing: 1.5px; color: #98a9b5; }
.divider { margin: 0 12px; color: #4e5d69; }
main { display: grid; grid-template-columns: 290px minmax(0, 1fr); height: calc(100dvh - 68px); min-height: 610px; }
.sidebar { padding: 35px 26px 24px; overflow-y: auto; }
.eyebrow { color: #8ac9b1; letter-spacing: 2px; font-size: 10px; font-weight: 600; }
h1 { margin: 17px 0 10px; font-weight: 600; font-size: 32px; letter-spacing: 2px; }
.subtitle { margin: 0; font-size: 12px; color: #a8b5bf; line-height: 1.8; }
.subtitle span { color: #748796; font-size: 11px; letter-spacing: .6px; }
.tags { display: flex; gap: 7px; margin: 21px 0 26px; }
.tags span { font-size: 10px; border: 1px solid #ffffff16; border-radius: 4px; padding: 5px 7px; color: #aebdc6; }
.section { border-top: 1px solid #ffffff12; padding-top: 20px; margin-top: 24px; }
h2 { margin: 0 0 19px; font-size: 12px; font-weight: 500; display: flex; justify-content: space-between; }
h2 span { font-size: 9px; color: #617887; letter-spacing: 1.5px; }
.stats { margin: 0; display: grid; grid-template-columns: 1fr 1fr; row-gap: 20px; }
dt { color: #8a9da9; font-size: 11px; }
dd { margin: 6px 0 0; font-size: 20px; font-variant-numeric: tabular-nums; letter-spacing: .3px; }
fieldset { padding: 0; margin: 0; border: none; }
fieldset:disabled { opacity: .4; }
.toggle { display: flex; align-items: center; justify-content: space-between; position: relative; font-size: 12px; margin-bottom: 19px; color: #b5c3cc; cursor: pointer; }
.toggle input { position: absolute; right: 0; opacity: 0; width: 34px; height: 24px; margin: 0; }
.switch { width: 30px; height: 17px; border-radius: 12px; background: #3a4956; pointer-events: none; transition: background .15s; }
.switch::after { content: ""; display: block; background: #c3cbd1; width: 11px; height: 11px; margin: 3px; border-radius: 50%; transition: transform .15s; }
input:checked + .switch { background: #86c9ac; }
input:checked + .switch::after { background: #162b24; transform: translateX(13px); }
input:focus-visible + .switch, button:focus-visible, a:focus-visible { outline: 2px solid #b9e7d3; outline-offset: 4px; }
button { background: #ffffff07; border: 1px solid #ffffff20; color: #e0ebe8; width: 100%; padding: 11px 13px; border-radius: 6px; font-size: 12px; display: flex; justify-content: space-between; cursor: pointer; }
button:hover { background: #ffffff10; }
button:disabled { cursor: default; }
.motion-section { margin-top: 0; }
#motion-sources { display: grid; gap: 8px; }
#motion-demo { background: #b9e7d312; border-color: #8ac9b140; }
#motion-demo span { font-size: 9px; color: #8ac9b1; letter-spacing: 1px; }
.motion-name { margin: 16px 0 6px; font-size: 12px; color: #cfe1dc; overflow-wrap: anywhere; }
.motion-status { font-size: 10px; line-height: 1.8; color: #8da59e; min-height: 18px; margin: 0 0 12px; }
.motion-status.error { color: #f0b0a3; }
.playback-buttons { display: flex; gap: 8px; }
.playback-buttons button { justify-content: center; }
#motion-play { background: #b9e7d3; color: #192b2a; border-color: #b9e7d3; }
.timeline-label { display: flex; justify-content: space-between; align-items: center; font-size: 10px; color: #aabcb5; margin-top: 18px; gap: 6px; }
#motion-time-text { font-variant-numeric: tabular-nums; font-size: 9px; white-space: nowrap; }
#motion-time { width: 100%; accent-color: #a0d8c1; margin: 12px 0 16px; cursor: pointer; }
#motion-time:disabled { cursor: default; }
.motion-options { display: flex; align-items: center; gap: 24px; margin-bottom: 15px; }
.motion-options .toggle { flex: 1; margin-bottom: 0; gap: 10px; }
.speed-label { display: flex; gap: 8px; align-items: center; font-size: 12px; color: #b5c3cc; }
#motion-speed { background: #1b2932; color: #d0e4db; border: 1px solid #ffffff25; padding: 5px 3px; border-radius: 4px; font-size: 11px; }
#motion-clear { font-size: 11px; justify-content: center; color: #aebdc6; }
select:focus-visible, input[type="range"]:focus-visible { outline: 2px solid #b9e7d3; outline-offset: 3px; }
.note, .download-note { font-size: 10px; line-height: 1.9; color: #8497a5; }
.note { margin: 25px 0 20px; }
.download { display: flex; justify-content: space-between; font-size: 11px; color: #a0d8c1; text-decoration: none; }
.download:hover { text-decoration: underline; }
.download-note { font-size: 9px; }
#viewport { position: relative; overflow: hidden; min-width: 0; background: #e1e8e8; }
canvas { display: block; width: 100%; height: 100%; touch-action: none; outline: none; }
canvas:focus-visible { outline: 2px solid #438771; outline-offset: -3px; }
.view-label { position: absolute; z-index: 1; top: 25px; left: 26px; font-size: 10px; letter-spacing: 2px; color: #566e6a; pointer-events: none; display: flex; align-items: center; gap: 8px; }
.dot { width: 5px; height: 5px; border-radius: 50%; background: #588c78; }
.view-footer { position: absolute; bottom: 0; padding: 24px 26px; width: 100%; display: flex; justify-content: space-between; gap: 16px; color: #536b67; font-size: 10px; pointer-events: none; background: linear-gradient(transparent, #e1e8e8e8); }
.view-footer > span:last-child { text-align: right; line-height: 1.7; }
#status { white-space: nowrap; }
.mobile-break { display: none; }
.loading { position: absolute; z-index: 2; inset: 0; display: flex; justify-content: center; align-items: center; flex-direction: column; background: #e1e8e8f2; color: #304841; text-align: center; padding: 35px; }
.loading[hidden], [hidden] { display: none !important; }
.loading strong { font-size: 17px; font-weight: 500; }
.loading p { font-size: 12px; max-width: 430px; line-height: 1.8; overflow-wrap: anywhere; }
.spinner { width: 30px; height: 30px; border: 2px solid #bdceca; border-top-color: #438771; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 25px; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 700px) {
.topbar { height: 56px; padding: 0 17px; }
.brand > span:last-child { display: none; }
main { height: auto; min-height: 0; grid-template-columns: 1fr; }
#viewport { grid-row: 1; height: 66dvh; min-height: 400px; }
.sidebar { padding: 25px; }
.stats { grid-template-columns: repeat(4, 1fr); }
.view-label { left: 18px; top: 20px; }
.view-footer { padding: 18px; font-size: 9px; }
.mobile-break { display: inline; }
}
@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } .switch, .switch::after { transition: none; } }
+230
View File
@@ -0,0 +1,230 @@
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { MMDLoader } from 'three/addons/loaders/MMDLoader.js';
import { MotionPlayer } from './motion-player.js';
const modelUrl = file => new URL(`./model/${file}`, import.meta.url).href;
const viewport = document.querySelector('#viewport');
const loading = document.querySelector('#loading');
const status = document.querySelector('#status');
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0xe1e8e8);
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute('aria-label', '无声铃鹿三维模型,拖动旋转,滚轮缩放;可用重置视角按钮恢复');
viewport.append(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(32, 1, 0.1, 1000);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.autoRotateSpeed = 1.2;
controls.maxPolarAngle = Math.PI * 0.94;
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x8c9a9a, 2.1);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 2.5);
key.position.set(-15, 25, 30);
scene.add(key);
let model, grid, bounds, failed = false;
let motionPlayer, modelReady = false, motionLoading = false, resumeAfterSeek = false;
const motionSources = document.querySelector('#motion-sources');
const motionControls = document.querySelector('#motion-controls');
const motionStatus = document.querySelector('#motion-status');
const motionTime = document.querySelector('#motion-time');
const motionTimeText = document.querySelector('#motion-time-text');
const motionFile = document.querySelector('#motion-file');
function formatTime(seconds) {
const ticks = Math.round(Math.max(0, seconds) * 100);
return `${String(Math.floor(ticks / 6000)).padStart(2, '0')}:${String(Math.floor(ticks / 100) % 60).padStart(2, '0')}.${String(ticks % 100).padStart(2, '0')}`;
}
function updateMotionTime(state) {
motionTime.value = state.time;
const text = `${formatTime(state.time)} / ${formatTime(state.duration)}`;
if (motionTimeText.textContent !== text) motionTimeText.textContent = text;
motionTime.setAttribute('aria-valuetext', text);
}
function refreshMotionControls() {
motionSources.disabled = !modelReady || failed || motionLoading;
const state = motionPlayer?.state;
motionControls.disabled = !state?.name || failed || motionLoading;
if (!state) return;
document.querySelector('#motion-name').textContent = state.name || '尚未选择动作';
document.querySelector('#motion-play').textContent = state.playing ? '暂停' : '播放';
document.querySelector('#motion-loop').checked = state.loop;
document.querySelector('#motion-speed').value = String(state.speed);
motionTime.max = state.duration;
updateMotionTime(state);
motionStatus.classList.remove('error');
motionStatus.textContent = motionLoading ? '正在读取动作…' : state.name
? `${state.playing ? '播放中' : state.time >= state.duration ? '播放结束' : '已暂停'} · ${state.boneTrackCount} 条骨骼轨道 / ${state.morphTrackCount} 条表情轨道`
: '可载入待机动作,或导入本地角色 VMD。';
}
async function importMotion(readBuffer, name) {
if (!modelReady || failed || motionLoading) return;
motionLoading = true;
refreshMotionControls();
let message = '';
try {
const buffer = await readBuffer();
if (!failed) motionPlayer.load(buffer, name);
} catch (error) {
message = `动作加载失败:${error.message || error}。原动作保持不变。`;
} finally {
motionLoading = false;
refreshMotionControls();
if (message) {
motionStatus.textContent = message;
motionStatus.classList.add('error');
}
}
}
document.querySelector('#motion-demo').addEventListener('click', () => importMotion(async () => {
const response = await fetch(modelUrl('1002_idle.vmd'));
if (!response.ok) throw new Error(`待机动作文件不可用(HTTP ${response.status})`);
return response.arrayBuffer();
}, '无声铃鹿 · 待机'));
document.querySelector('#motion-import').addEventListener('click', () => motionFile.click());
motionFile.addEventListener('change', () => {
const file = motionFile.files[0];
motionFile.value = '';
if (file) importMotion(() => file.arrayBuffer(), file.name);
});
document.querySelector('#motion-play').addEventListener('click', () => {
if (motionPlayer.state.playing) motionPlayer.pause();
else motionPlayer.play();
});
document.querySelector('#motion-restart').addEventListener('click', () => motionPlayer.restart());
document.querySelector('#motion-clear').addEventListener('click', () => motionPlayer.clear());
document.querySelector('#motion-loop').addEventListener('change', event => motionPlayer.setLoop(event.target.checked));
document.querySelector('#motion-speed').addEventListener('change', event => motionPlayer.setSpeed(Number(event.target.value)));
motionTime.addEventListener('pointerdown', () => {
resumeAfterSeek = motionPlayer.state.playing;
motionPlayer.pause();
});
motionTime.addEventListener('input', () => motionPlayer.seek(Number(motionTime.value)));
function finishSeek() {
if (resumeAfterSeek) motionPlayer.play();
resumeAfterSeek = false;
}
motionTime.addEventListener('change', finishSeek);
motionTime.addEventListener('pointerup', finishSeek);
motionTime.addEventListener('pointercancel', finishSeek);
const failedResources = new Set();
function fail(message) {
failed = true;
loading.hidden = false;
document.querySelector('.spinner').hidden = true;
document.querySelector('#loading-title').textContent = '模型未完整加载';
document.querySelector('#loading-detail').textContent = message;
status.textContent = '加载失败';
document.querySelector('#display-controls').disabled = true;
motionPlayer?.pause();
refreshMotionControls();
}
renderer.domElement.addEventListener('webglcontextlost', event => {
event.preventDefault();
fail('图形上下文已丢失。请刷新页面重新加载。');
});
function frameModel() {
if (!bounds) return;
const size = bounds.getSize(new THREE.Vector3());
const center = bounds.getCenter(new THREE.Vector3());
const halfFov = THREE.MathUtils.degToRad(camera.fov / 2);
const distance = Math.max(size.y / 2 / Math.tan(halfFov), size.x / 2 / (Math.tan(halfFov) * camera.aspect)) * 1.25 + size.z / 2;
camera.near = Math.max(size.y / 1000, 0.001);
camera.far = Math.max(distance * 20, size.y * 100);
camera.position.copy(center).add(new THREE.Vector3(0, size.y * 0.025, distance));
camera.updateProjectionMatrix();
controls.target.copy(center);
controls.minDistance = size.y * 0.15;
controls.maxDistance = distance * 5;
controls.update();
controls.saveState();
}
const manager = new THREE.LoadingManager();
manager.onProgress = (_url, done, total) => {
if (!failed) document.querySelector('#loading-detail').textContent = `正在读取模型与贴图 ${done} / ${total}`;
};
manager.onError = url => {
failedResources.add(url);
fail('无法读取资源:' + [...failedResources].join('、') + '。请确认 PMX 及 Texture2D 文件夹完整。');
};
manager.onLoad = () => {
if (failed || !model) return;
loading.hidden = true;
status.textContent = '模型与贴图已就绪';
document.querySelector('#display-controls').disabled = false;
modelReady = true;
refreshMotionControls();
};
const loader = new MMDLoader(manager);
loader.load(modelUrl('1002_00.pmx'), mesh => {
model = mesh;
scene.add(model);
model.updateMatrixWorld(true);
motionPlayer = new MotionPlayer(model, refreshMotionControls);
bounds = new THREE.Box3().setFromObject(model);
const size = bounds.getSize(new THREE.Vector3());
const center = bounds.getCenter(new THREE.Vector3());
grid = new THREE.GridHelper(size.y * 3, 30, 0x9eafaa, 0xc2ceca);
grid.position.set(center.x, bounds.min.y - size.y * 0.002, center.z);
grid.material.transparent = true;
grid.material.opacity = 0.55;
scene.add(grid);
frameModel();
const values = {
vertices: model.geometry.attributes.position.count,
triangles: model.geometry.index.count / 3,
bones: model.skeleton.bones.length,
morphs: model.morphTargetInfluences.length,
};
for (const [id, value] of Object.entries(values)) {
document.getElementById(id).textContent = value.toLocaleString('en-US');
}
}, undefined, error => {
console.error(error);
fail('PMX 加载失败。请确认导出文件存在且格式有效。' + (error.message || ''));
});
document.querySelector('#rotate').addEventListener('change', event => { controls.autoRotate = event.target.checked; });
document.querySelector('#grid').addEventListener('change', event => { grid.visible = event.target.checked; });
document.querySelector('#wireframe').addEventListener('change', event => {
for (const material of model.material) material.wireframe = event.target.checked;
});
document.querySelector('#reset').addEventListener('click', () => {
controls.autoRotate = false;
document.querySelector('#rotate').checked = false;
controls.reset();
frameModel();
});
new ResizeObserver(() => {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
frameModel();
}).observe(viewport);
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.1);
if (document.hidden || failed) return;
if (motionPlayer) {
motionPlayer.update(delta);
if (motionPlayer.state.name) updateMotionTime(motionPlayer.state);
}
controls.update(delta);
renderer.render(scene, camera);
});