3D 리플레이 1단계: .vrf 변환기(tools/replay-extract) · 사이트 3D 재생기 · 대화 동기화

- tools/replay-extract: ValorantReplayParser(MIT, 고정 커밋) → gvr-replay JSON v1
  (선수 이동 10Hz · 라운드 · 킬 · 사격 · 스킬/설치물 · 녹화 시작 시각)
- 사이트: 경기 화면 '3D 리플레이' 칸 (three.js 지연 로드). 미니맵 바닥 + 실제 높이,
  회전 · 확대 · 선수 선택 · 따라가기 · 킬피드 · 자막 · 말하는 사람 표시
- 동기화: 같은 킬의 경기 기록 시각과 리플레이 시각 차이 중앙값 (못 맞추면 라운드 시작)
  현장 모드 시계에 묶어 재생 · 멈춤 · 이동 · 배속이 대화와 같이 움직임
- 목 서버 데모(GVR_MOCK_REPLAY), 동기화 테스트 4개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 03:56:43 +09:00
parent 50fc90070b
commit 9592efeff6
18 changed files with 1539 additions and 1 deletions

View File

@@ -0,0 +1,58 @@
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
import type { MatchDetail } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { computeSync, type ReplayFile } from '../lib/replay';
import { Panel, Spinner } from './common';
// three.js 는 크므로 3D 리플레이를 열 때만 받는다
const ReplayViewer = lazy(() => import('./ReplayViewer'));
/** 경기 화면의 "3D 리플레이" 칸. 열면 게임 PC 에서 리플레이 데이터를 받아 온다 */
export function ReplayPanel({ m }: { m: MatchDetail }) {
const [open, setOpen] = useState(false);
const [replay, setReplay] = useState<ReplayFile | null>(null);
const [err, setErr] = useState<unknown>(null);
useEffect(() => {
if (!open || replay) return;
let alive = true;
setErr(null);
api
.replay(m.id)
.then((r) => alive && setReplay(r))
.catch((e) => alive && setErr(e));
return () => {
alive = false;
};
}, [open, m.id, replay]);
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
const missing = err instanceof ApiError && err.status === 404;
return (
<Panel
className={`replay-panel${open ? ' open' : ''}`}
title="3D 리플레이 · 대화 동기화"
right={
<button className="mini-btn" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
{open ? '닫기' : '열기'}
</button>
}
>
{!open ? (
<div className="dim small">
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
</div>
) : missing ? (
<div className="dim small">
이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림).
</div>
) : err ? (
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
) : !replay || !sync ? (
<Spinner label="리플레이 불러오는 중" />
) : (
<Suspense fallback={<Spinner label="3D 화면 준비 중" />}>
<ReplayViewer m={m} replay={replay} sync={sync} />
</Suspense>
)}
</Panel>
);
}

View File

@@ -0,0 +1,510 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import type { MatchDetail, MatchPlayer } from '@gvr/shared';
import { player } from '../store/player';
import { settings, useSettings } from '../store/settings';
import { useData } from '../store/app';
import { fmtClock } from '../lib/format';
import { isDead, roundAt, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
/**
* 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON).
* 바닥은 미니맵, 선수는 실제 높이(z)에 세운다. 맵 벽 · 지형 3D 모델은 없다.
* 시계는 플레이어 "현장 모드"(대화를 실제 시각대로 겹쳐 재생)와 같은 값을 쓴다:
* 기록 시각 ts = recordedAt + t + sync.offset
* 그래서 재생 · 멈춤 · 시간 옮기기 · 배속이 대화와 같이 움직인다.
*/
export const REPLAY_SCENE_LABEL = '3D 리플레이';
const S = 100; // 미니맵 한 변 (3D 단위)
const VEX = 1; // 높이 배율 (1 = 실제 비율)
const ALLY = 0x3fb6ff;
const ENEMY = 0xff4d5e;
const RATES = [0.5, 1, 1.5, 2];
type T4 = { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number };
interface Props {
m: MatchDetail;
replay: ReplayFile;
sync: ReplaySync;
}
function labelSprite(text: string, color: string) {
const c = document.createElement('canvas');
const ctx = c.getContext('2d')!;
const font = '600 44px Pretendard, "Noto Sans KR", sans-serif';
ctx.font = font;
const w = Math.ceil(ctx.measureText(text).width) + 36;
c.width = w;
c.height = 68;
ctx.font = font;
ctx.fillStyle = 'rgba(8,14,20,0.78)';
ctx.beginPath();
ctx.roundRect(0, 0, w, 68, 18);
ctx.fill();
ctx.fillStyle = color;
ctx.textBaseline = 'middle';
ctx.fillText(text, 18, 36);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false, transparent: true }));
sp.scale.set((w / 68) * 2.2, 2.2, 1);
sp.renderOrder = 10;
return sp;
}
interface PlayerView {
idx: number;
info: MatchPlayer | null;
name: string;
ally: boolean;
group: THREE.Group;
body: THREE.Mesh;
cone: THREE.Mesh;
label: THREE.Sprite;
voice: THREE.Sprite;
ring: THREE.Mesh;
/** 바닥(미니맵)까지 내린 선과 그림자 점: 높이가 있어도 평면 위치가 보이게 */
drop: THREE.Line;
shadow: THREE.Mesh;
}
export default function ReplayViewer({ m, replay, sync }: Props) {
const mountRef = useRef<HTMLDivElement>(null);
const cfg = useSettings();
const { userById } = useData();
const base = replay.recordedAt + sync.offset;
const firstCombat = replay.rounds.find((r) => r.combat >= 0)?.combat ?? 0;
const localT = useRef(firstCombat);
const [ui, setUi] = useState({ t: firstCombat, playing: false });
const [sel, setSel] = useState<number | null>(null);
const [follow, setFollow] = useState(false);
const selRef = useRef(sel);
const followRef = useRef(follow);
selRef.current = sel;
followRef.current = follow;
const resetCam = useRef<() => void>(() => {});
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
const zBase = useMemo(() => {
const zs: number[] = [];
for (const p of replay.players) for (let i = 0; i < p.track.z.length; i += 40) if (p.track.z[i] > -1500) zs.push(p.track.z[i]);
zs.sort((a, b) => a - b);
return zs.length ? zs[Math.floor(zs.length * 0.05)] : 0;
}, [replay]);
const T = (m.mapTransform && 'valorant' in m.mapTransform ? m.mapTransform.valorant : null) as T4 | null;
// 리플레이 선수 ↔ 경기 기록 선수 (puuid)
const roster = useMemo(
() =>
replay.players.map((p, idx) => {
const info = m.players.find((x) => x.puuid === p.puuid) ?? null;
return { idx, info, name: info?.name ?? p.character?.replace(/_PC_C$/, '') ?? `선수 ${idx + 1}`, ally: info?.ally ?? false };
}),
[m, replay],
);
// 디스코드 유저 → 리플레이 선수 (말하는 사람 표시)
const playerByUser = useMemo(() => {
const map = new Map<string, number>();
for (const r of roster) if (r.info?.userId) map.set(r.info.userId, r.idx);
return map;
}, [roster]);
useEffect(() => {
const mount = mountRef.current;
if (!mount || !T) return;
const toWorld = (x: number, y: number, z: number, zBase: number) =>
new THREE.Vector3((y * T.xMultiplier + T.xScalarToAdd - 0.5) * S, (z - zBase) * Math.abs(T.xMultiplier) * S * VEX, (x * T.yMultiplier + T.yScalarToAdd - 0.5) * S);
const dirOf = (yaw: number) => {
const a = (yaw * Math.PI) / 180;
return new THREE.Vector3(Math.sin(a) * Math.sign(T.xMultiplier), 0, Math.cos(a) * Math.sign(T.yMultiplier)).normalize();
};
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x0b141c);
renderer.outputColorSpace = THREE.SRGBColorSpace;
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, 1, 0.5, 2000);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI * 0.49;
controls.minDistance = 8;
controls.maxDistance = 260;
resetCam.current = () => {
camera.position.set(0, 122, 34);
controls.target.set(0, 0, 0);
controls.update();
};
resetCam.current();
scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.6));
const sun = new THREE.DirectionalLight(0xffffff, 1.2);
sun.position.set(30, 80, 20);
scene.add(sun);
// 바닥 미니맵
const floorMat = new THREE.MeshBasicMaterial({ color: 0x5a6b7a, transparent: true });
const floor = new THREE.Mesh(new THREE.PlaneGeometry(S, S), floorMat);
floor.rotation.x = -Math.PI / 2;
scene.add(floor);
if (m.map.image) {
const loader = new THREE.TextureLoader();
loader.setCrossOrigin('anonymous');
loader.load(m.map.image, (tex) => {
tex.colorSpace = THREE.SRGBColorSpace;
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
floorMat.map = tex;
floorMat.color.set(0xffffff);
floorMat.needsUpdate = true;
});
}
const grid = new THREE.GridHelper(S, 20, 0x1d2c3a, 0x15212c);
grid.position.y = -0.05;
scene.add(grid);
// 선수
const views: PlayerView[] = roster.map((r) => {
const color = r.ally ? ALLY : ENEMY;
const group = new THREE.Group();
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 0.9, 2.4, 20), new THREE.MeshStandardMaterial({ color, roughness: 0.5, transparent: true }));
body.position.y = 1.2;
body.userData.idx = r.idx;
const cone = new THREE.Mesh(new THREE.ConeGeometry(0.55, 3.2, 12), new THREE.MeshStandardMaterial({ color: 0xffffff, transparent: true, opacity: 0.85 }));
cone.geometry.rotateX(Math.PI / 2);
cone.geometry.translate(0, 0, 2.2);
cone.position.y = 1.9;
const label = labelSprite(r.info?.character?.name ? `${r.name} · ${r.info.character.name}` : r.name, r.ally ? '#8fd8ff' : '#ff9aa5');
label.position.y = 4.4;
label.userData.idx = r.idx;
const voice = labelSprite('🔊 말하는 중', '#ffe08a');
voice.position.y = 6.6;
voice.visible = false;
const ring = new THREE.Mesh(new THREE.RingGeometry(1.4, 1.8, 32), new THREE.MeshBasicMaterial({ color: 0xffe08a, side: THREE.DoubleSide }));
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.05;
ring.visible = false;
group.add(body, cone, label, voice, ring);
scene.add(group);
const dropGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);
const drop = new THREE.Line(dropGeo, new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.7 }));
drop.frustumCulled = false;
const shadow = new THREE.Mesh(new THREE.CircleGeometry(0.75, 20), new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.85 }));
shadow.rotation.x = -Math.PI / 2;
scene.add(drop, shadow);
return { idx: r.idx, info: r.info, name: r.name, ally: r.ally, group, body, cone, label, voice, ring, drop, shadow };
});
// 선택한 선수 이동 경로 (최근 6초)
const trailGeo = new THREE.BufferGeometry();
trailGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * 80), 3));
const trail = new THREE.Line(trailGeo, new THREE.LineBasicMaterial({ color: 0xffe08a }));
trail.frustumCulled = false;
scene.add(trail);
// 사격 궤적 (최근 150ms)
const MAX_SHOTS = 48;
const shotGeo = new THREE.BufferGeometry();
shotGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(MAX_SHOTS * 6), 3));
const shots = new THREE.LineSegments(shotGeo, new THREE.LineBasicMaterial({ color: 0xfff1a8, transparent: true, opacity: 0.9 }));
shots.frustumCulled = false;
scene.add(shots);
// 킬 표시 (죽은 자리 X)
const killGroup = new THREE.Group();
scene.add(killGroup);
const xGeo = new THREE.TorusGeometry(1.1, 0.22, 6, 4);
const killMarks = replay.kills.map(([kt, ki, vi]) => {
const v = replay.players[vi];
const p = v ? samplePlayer(v.track, kt, 1500) : null;
const ally = roster[vi]?.ally ?? false;
const mk = new THREE.Mesh(xGeo, new THREE.MeshBasicMaterial({ color: ally ? ALLY : ENEMY, transparent: true }));
mk.rotation.x = -Math.PI / 2;
mk.rotation.z = Math.PI / 4;
if (p) mk.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase), zBase)).add(new THREE.Vector3(0, 0.2, 0));
mk.visible = false;
killGroup.add(mk);
return { t: kt, killer: ki, victim: vi, mk };
});
// 스킬 · 설치물
const objMeshes = new Map<number, THREE.Mesh>();
const objMesh = (i: number) => {
let mesh = objMeshes.get(i);
if (mesh) return mesh;
const [, , kind, x, y, z] = replay.objects[i];
const name = replay.objectKinds[kind] ?? '';
const smoke = /Smoke/i.test(name) && !/Projectile/.test(name);
const spike = name === 'TimedBomb_C';
const geo = smoke ? new THREE.SphereGeometry(3.6, 20, 14) : spike ? new THREE.OctahedronGeometry(1.2) : new THREE.SphereGeometry(0.45, 10, 8);
const color = spike ? 0xff2d3d : smoke ? 0xb9c4cf : /Patch|Molotov|Fire/i.test(name) ? 0xff8a3d : /Trap|Wire|Tether/i.test(name) ? 0xc58bff : 0x9fffe0;
mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color, transparent: true, opacity: smoke ? 0.38 : 0.9, depthWrite: !smoke }));
mesh.position.copy(toWorld(x, y, z, zBase));
if (smoke) mesh.position.y += 1.5;
scene.add(mesh);
objMeshes.set(i, mesh);
return mesh;
};
// 크기
const resize = () => {
const w = mount.clientWidth;
const h = mount.clientHeight;
renderer.setSize(w, h, false);
camera.aspect = w / Math.max(1, h);
camera.updateProjectionMatrix();
};
const ro = new ResizeObserver(resize);
ro.observe(mount);
resize();
// 선수 눌러서 고르기
const ray = new THREE.Raycaster();
const down = { x: 0, y: 0 };
const onDown = (e: PointerEvent) => {
down.x = e.clientX;
down.y = e.clientY;
};
const onUp = (e: PointerEvent) => {
if (Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) return; // 끌기(회전)는 고르기 아님
const r = renderer.domElement.getBoundingClientRect();
ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera);
// 몸통은 위에서 보면 작아서 이름표를 눌러도 고른다
const hit = ray.intersectObjects(views.flatMap((v) => (v.group.visible ? [v.body, v.label] : [])))[0];
setSel(hit ? (hit.object.userData.idx as number) : null);
};
renderer.domElement.addEventListener('pointerdown', onDown);
renderer.domElement.addEventListener('pointerup', onUp);
let raf = 0;
let lastUi = 0;
const tmp = new THREE.Vector3();
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const ps = player.state;
const inScene = ps.mode === 'scene' && ps.scene?.label === REPLAY_SCENE_LABEL && ps.sceneTs != null;
const t = inScene ? ps.sceneTs! - base : localT.current;
if (!inScene) localT.current = t;
const ts = base + t;
// 지금 말하는 사람
const speaking = new Set<number>();
for (const u of m.utterances) if (u.ts <= ts && ts <= u.endTs && !u.noise) {
const i = playerByUser.get(u.userId);
if (i != null) speaking.add(i);
}
const selIdx = selRef.current;
for (const v of views) {
const tr = replay.players[v.idx].track;
const p = samplePlayer(tr, t, replay.sampleMs * 6);
if (!p) {
v.group.visible = v.drop.visible = v.shadow.visible = false;
continue;
}
v.group.visible = v.drop.visible = v.shadow.visible = true;
v.group.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400), zBase));
v.shadow.position.set(v.group.position.x, 0.04, v.group.position.z);
const dp = v.drop.geometry.getAttribute('position') as THREE.BufferAttribute;
dp.setXYZ(0, v.group.position.x, v.group.position.y, v.group.position.z);
dp.setXYZ(1, v.group.position.x, 0.04, v.group.position.z);
dp.needsUpdate = true;
const d = dirOf(p.yaw);
v.cone.rotation.y = Math.atan2(d.x, d.z);
const dead = isDead(replay, v.idx, t);
const op = dead ? 0.22 : 1;
(v.body.material as THREE.MeshStandardMaterial).opacity = op;
(v.cone.material as THREE.MeshStandardMaterial).opacity = dead ? 0 : 0.85;
v.label.material.opacity = dead ? 0.35 : 1;
(v.shadow.material as THREE.MeshBasicMaterial).opacity = dead ? 0.25 : 0.85;
v.voice.visible = speaking.has(v.idx) && !dead;
v.ring.visible = v.idx === selIdx;
}
// 경로
if (selIdx != null) {
const tr = replay.players[selIdx].track;
const pos = trailGeo.getAttribute('position') as THREE.BufferAttribute;
let n = 0;
for (let k = 0; k < 80; k++) {
const p = samplePlayer(tr, t - 6000 + (6000 * k) / 79, replay.sampleMs * 6);
if (!p) continue;
tmp.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400), zBase));
pos.setXYZ(n++, tmp.x, tmp.y + 0.3, tmp.z);
}
trailGeo.setDrawRange(0, n);
pos.needsUpdate = true;
trail.visible = n > 1;
if (followRef.current && views[selIdx].group.visible) {
const target = views[selIdx].group.position;
tmp.copy(target).sub(controls.target);
controls.target.add(tmp.multiplyScalar(0.15));
camera.position.add(tmp);
}
} else trail.visible = false;
// 사격
const sp = shotGeo.getAttribute('position') as THREE.BufferAttribute;
let ns = 0;
for (let i = lowerBound(replay.shots, t - 150); i < replay.shots.length && replay.shots[i][0] <= t && ns < MAX_SHOTS; i++) {
const [, , x, y, z, yaw, pitch] = replay.shots[i];
const a = toWorld(x, y, z, zBase);
const d = dirOf(yaw);
const len = 26;
const b = a.clone().add(d.multiplyScalar(len * Math.cos((pitch * Math.PI) / 180))).add(new THREE.Vector3(0, len * Math.sin((pitch * Math.PI) / 180) * 0.3, 0));
sp.setXYZ(ns * 2, a.x, a.y + 1.6, a.z);
sp.setXYZ(ns * 2 + 1, b.x, b.y + 1.6, b.z);
ns++;
}
shotGeo.setDrawRange(0, ns * 2);
sp.needsUpdate = true;
// 킬 표시: 이 라운드에서 이미 난 킬
const rd = roundAt(replay, t);
for (const k of killMarks) {
const on = !!rd && k.t >= rd.buy && k.t <= t;
k.mk.visible = on;
if (on) {
const age = t - k.t;
const s = age < 600 ? 1 + (600 - age) / 300 : 1;
k.mk.scale.setScalar(s);
}
}
// 스킬 · 설치물: 생긴 뒤 사라질 때까지 (사라진 시각을 모르면 12초)
for (let i = 0; i < replay.objects.length; i++) {
const [t0, t1] = replay.objects[i];
const end = t1 >= 0 ? t1 : t0 + 12000;
const on = t >= t0 && t <= end;
if (on) objMesh(i).visible = true;
else {
const mesh = objMeshes.get(i);
if (mesh) mesh.visible = false;
}
}
controls.update();
renderer.render(scene, camera);
if (now - lastUi > 100) {
lastUi = now;
setUi((u) => (Math.abs(u.t - t) < 50 && u.playing === (inScene && ps.playing) ? u : { t, playing: inScene && ps.playing }));
}
};
raf = requestAnimationFrame(frame);
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
renderer.domElement.removeEventListener('pointerdown', onDown);
renderer.domElement.removeEventListener('pointerup', onUp);
controls.dispose();
scene.traverse((o) => {
const mesh = o as THREE.Mesh;
mesh.geometry?.dispose?.();
const mat = mesh.material as THREE.Material | THREE.Material[] | undefined;
(Array.isArray(mat) ? mat : mat ? [mat] : []).forEach((mm) => {
(mm as THREE.MeshBasicMaterial).map?.dispose();
mm.dispose();
});
});
renderer.dispose();
renderer.domElement.remove();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [m, replay, base, roster, playerByUser, zBase]);
const inScene = () => player.state.mode === 'scene' && player.state.scene?.label === REPLAY_SCENE_LABEL;
const seek = (t: number) => {
const v = Math.max(0, Math.min(replay.durationMs, t));
if (inScene()) player.seekScene(v);
else localT.current = v;
setUi((u) => ({ ...u, t: v }));
};
const togglePlay = () => {
if (inScene()) player.toggle();
else {
const from = localT.current;
player.startScene({ start: base, end: base + replay.durationMs, label: REPLAY_SCENE_LABEL, items: m.utterances });
player.seekScene(from);
}
};
const rd = roundAt(replay, ui.t);
const mr = rd ? m.rounds?.find((r) => r.num === rd.num) : undefined;
const clock = !rd ? '' : rd.combat >= 0 && ui.t >= rd.combat ? fmtClock(ui.t - rd.combat) : `구매 ${fmtClock(Math.max(0, (rd.combat >= 0 ? rd.combat : rd.buy + 30000) - ui.t))}`;
const ts = base + ui.t;
const captions = m.utterances.filter((u) => !u.noise && u.text && u.ts <= ts && ts <= u.endTs + 1500).slice(-3);
const feed = replay.kills.filter(([kt]) => kt <= ui.t && ui.t - kt < 6000).slice(-5);
const selInfo = sel != null ? roster[sel] : null;
const selPos = sel != null ? samplePlayer(replay.players[sel].track, ui.t, replay.sampleMs * 6) : null;
const jumpRound = (dir: -1 | 1) => {
const i = rd ? replay.rounds.indexOf(rd) : 0;
const to = replay.rounds[Math.max(0, Math.min(replay.rounds.length - 1, i + dir))];
if (to) seek(to.combat >= 0 ? to.combat - 3000 : to.buy);
};
if (!T) return <div className="map-missing">이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다</div>;
return (
<div className="r3d">
<div className="r3d-stage" ref={mountRef}>
<div className="r3d-hud tl">
<b>{rd ? `R${rd.num}` : ''}</b> <span className="mono">{clock}</span>
{mr && <span className="muted"> · {mr.score.ally}:{mr.score.enemy} 후 {mr.win ? '승리' : '패배'}</span>}
</div>
<div className="r3d-hud tr">
{feed.map(([kt, ki, vi]) => (
<div key={`${kt}:${vi}`} className="r3d-kill">
<span className={roster[ki]?.ally ? 'a' : 'e'}>{roster[ki]?.name ?? '?'}</span> ✕ <span className={roster[vi]?.ally ? 'a' : 'e'}>{roster[vi]?.name ?? '?'}</span>
</div>
))}
</div>
{captions.length > 0 && (
<div className="r3d-cap">
{captions.map((u) => (
<div key={u.id}>
<b>{userById(u.userId)?.name ?? '알 수 없음'}</b> {u.text}
</div>
))}
</div>
)}
{selInfo && (
<div className="r3d-hud bl">
<b className={selInfo.ally ? 'a' : 'e'}>{selInfo.name}</b>
{selInfo.info?.character?.name && <span className="muted"> · {selInfo.info.character.name}</span>}
{selPos && <div className="mono muted">가장 낮은 층보다 {Math.max(0, Math.round((selPos.z - zBase) / 100))}m 위 · 보는 방향 {Math.round(((selPos.yaw % 360) + 360) % 360)}°</div>}
<label className="r3d-follow">
<input type="checkbox" checked={follow} onChange={(e) => setFollow(e.target.checked)} /> 따라가기
</label>
</div>
)}
</div>
<div className="r3d-bar">
<button className="chip" onClick={() => jumpRound(-1)} title="이전 라운드">⏮</button>
<button className="chip r3d-play" onClick={togglePlay} title="대화와 같이 재생 / 멈춤">{ui.playing ? '⏸' : '▶'}</button>
<button className="chip" onClick={() => jumpRound(1)} title="다음 라운드">⏭</button>
<div className="r3d-scrub">
{replay.rounds.map((r) => (
<i key={r.num} style={{ left: `${(r.buy / replay.durationMs) * 100}%` }} data-tip={`R${r.num}`} />
))}
<input type="range" min={0} max={replay.durationMs} step={100} value={ui.t} onChange={(e) => seek(Number(e.target.value))} aria-label="리플레이 시간" />
</div>
<span className="mono muted">{fmtClock(ui.t)} / {fmtClock(replay.durationMs)}</span>
<button className="chip mono" onClick={() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] ?? 1 })} title="재생 속도">
{cfg.rate}x
</button>
<button className="chip" onClick={() => resetCam.current()} title="카메라 처음 위치로">전체 보기</button>
</div>
<div className="r3d-foot muted">
마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택 ·{' '}
{sync.matched >= 3
? `대화 동기화: 킬 ${sync.matched}개로 맞춤 (최대 오차 ${((sync.spreadMs ?? 0) / 1000).toFixed(2)}초)`
: '대화 동기화: 라운드 시작으로 대략 맞춤'}
</div>
</div>
);
}
function lowerBound(a: [number, ...number[]][], t: number) {
let lo = 0;
let hi = a.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (a[mid][0] < t) lo = mid + 1;
else hi = mid;
}
return lo;
}