Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
adc1c66f47 | ||
|
|
cba50d60ab | ||
|
|
0c1e726168 | ||
|
|
86f422e8f0 | ||
|
|
c5100bce75 | ||
|
|
84fa8e4a71 | ||
|
|
001788b7fb | ||
|
|
9592efeff6 | ||
|
|
50fc90070b | ||
|
|
010d2475cc | ||
|
|
a4511a8eaf | ||
|
|
0b8789c895 | ||
|
|
79d6bb2aad | ||
|
|
c6a8721fce | ||
|
|
df0c8267c9 | ||
|
|
a6c681e44e | ||
|
|
3115337706 | ||
|
|
8047a2e948 | ||
|
|
55ec58f343 | ||
|
|
6a32bedfe3 |
28
README.md
28
README.md
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.3.8](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.3.8) (`GameVoiceRecorder-1.3.8-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.3.8-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.4.2](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.4.3) (`GameVoiceRecorder-1.4.3-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.4.3-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
@@ -19,6 +19,32 @@
|
||||
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
|
||||
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
|
||||
|
||||
## v1.4.3 바뀐 점
|
||||
|
||||
- 상대 닉네임을 말로 적던 문제 (예: 말소리가 "QQQWWWQ"로 나옴): 그 경기 선수 이름을 모두 핫워드로 넣어서, 말을 못 알아들으면 Whisper 가 닉네임을 그대로 적었다. 이제
|
||||
- 선수 이름은 한글이 들어간 것만 핫워드로 넣는다 (영문 · 숫자 닉네임은 한국어 말로 나올 일이 거의 없음)
|
||||
- 결과가 선수 이름(또는 그 조각)뿐이면 워커가 선수 이름을 빼고 한 번 더 변환한다 (`worker/gvr_worker/stt.py` `is_name_echo`, 앱이 `player_names` 로 넘김)
|
||||
- 한 번만: 예전에 이렇게 적힌 발화를 정밀 모델로 다시 변환한다 (음성 파일이 지워졌으면 숨김, 사람이 고친 발화는 그대로). `app/src/core/stt/pipeline.ts` `recheckNameEchoes`
|
||||
|
||||
## v1.4.2 바뀐 점
|
||||
|
||||
- 녹음 중에 음성채널에 들어온 사람이 사이트에서 "알 수 없음"으로 뜨던 문제: 앱이 그 사람을 유저로 저장만 하고 `users.updated` 를 보내지 않았다. 이제 들어올 때 보낸다 (`app/src/core/discord/bot.ts` onVoiceState)
|
||||
- 사이트도 실시간 발화 · 녹음 상태에 처음 보는 사람 아이디가 오면 유저 목록을 한 번 다시 받아 온다 (v1.4.1 이하 앱에서도 이름이 뜸)
|
||||
|
||||
## v1.4.1 바뀐 점
|
||||
|
||||
- 잡음으로 배운 문장 비교: v1.4.0 은 편집 거리로 비교해서, 배운 문장 뒤에 짧은 실제 말("네", "가자", "아니")이 붙은 발화까지 잡음으로 지웠다. 이제 글자 수가 같고 15% 안 글자만 바뀐 것(인식이 한두 글자 다르게 나온 것)만 같은 문장으로 본다
|
||||
|
||||
## v1.4.0 바뀐 점
|
||||
|
||||
- 사이트 발화 우클릭 → **삭제…**: 확인 창에서 "잡음이라 삭제" 또는 "그냥 삭제". 관리자나 말한 사람만 지울 수 있고, 글 · 음성 파일 · 교정 학습 데이터를 게임 PC 에서 지운다 (`POST /api/utterances/:id/delete`)
|
||||
- "잡음이라 삭제"는 인식된 문장을 `noise_phrases` 에 배운다. 다음에 같은 문장(띄어쓰기 · 문장부호 무시, 8글자 이상이면 글자 수가 같고 15% 안 글자만 바뀐 것까지. 앞뒤에 말이 붙으면 그대로)이 인식되면 잡음(`noise_reason='learned'`)으로 숨기고 파일을 지운다. 배운 문장은 단어사전 화면에서 보고 지운다 (`GET/DELETE /api/noise-phrases`)
|
||||
- 사이트 효과음: "새 발화 알림" · "재생 시작"을 기본으로 끈다 (예전에 저장한 설정도 한 번 꺼 줌, 그 뒤 다시 켜면 그대로)
|
||||
|
||||
## v1.3.9 바뀐 점
|
||||
|
||||
- 기록 zip 받아오기: 표시 이름에 `..` 이 있으면(예: `하늘..별`) 그 이름이 들어간 녹음 파일을 "음성 파일 이름이 잘못되었습니다"로 거절해, 내보낸 zip 을 다시 넣지 못했다. zip 안 이름은 꺼낼 때 찾는 열쇠로만 쓰고 이 PC 에 쓸 경로는 발화 ID 로 만들므로, 폴더 구분자(`/`, `\`)만 막는다
|
||||
|
||||
## v1.3.8 바뀐 점
|
||||
|
||||
- **녹음 파일 이름**: `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (예: `2026-10-16_04-03-16_사금향_발로란트_경쟁전_어센트_R7_0mv9….ogg`, 롤은 라운드 대신 게임 시간 `12분30초`, 경기 밖은 `…_사금향_경기밖_….ogg`). 시각은 게임 PC 시각, Windows 에서 못 쓰는 글자는 뺀다. `app/src/core/audio-names.ts`
|
||||
|
||||
10
app/package-lock.json
generated
10
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.8",
|
||||
"version": "1.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.3.8",
|
||||
"version": "1.5.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
@@ -3897,7 +3897,7 @@
|
||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
|
||||
},
|
||||
"node_modules/ini": {
|
||||
"version": "1.3.8",
|
||||
"version": "1.3.9",
|
||||
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
|
||||
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
|
||||
},
|
||||
@@ -4677,7 +4677,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prism-media": {
|
||||
"version": "1.3.8",
|
||||
"version": "1.3.9",
|
||||
"resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz",
|
||||
"integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==",
|
||||
"peerDependencies": {
|
||||
@@ -4782,7 +4782,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/pvtsutils": {
|
||||
"version": "1.3.8",
|
||||
"version": "1.3.9",
|
||||
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
|
||||
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
|
||||
"dev": true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.3.8",
|
||||
"version": "1.5.0",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
@@ -76,6 +76,13 @@
|
||||
"from": "../worker/dist/gvr-worker",
|
||||
"to": "worker"
|
||||
},
|
||||
{
|
||||
"from": "../tools/replay-extract/out/win",
|
||||
"to": "replay",
|
||||
"filter": [
|
||||
"gvr-replay.exe"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "../assets/app",
|
||||
"to": "brand",
|
||||
|
||||
@@ -3,13 +3,27 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { CulpritAnalysis, CulpritResult, MatchDetail, MatchPlayer, Overview, User, UserProfile, UtteranceInfo, Word } from '@gvr/shared';
|
||||
import type { Culprit } from '../culprit.js';
|
||||
import type { Store, UserRow } from '../db/db.js';
|
||||
import { normalizePhrase, type Store, type UserRow } from '../db/db.js';
|
||||
import type { Dictionary } from '../dict/dictionary.js';
|
||||
import type { GameManager } from '../games/manager.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
|
||||
import type { Bus } from '../util/events.js';
|
||||
import { BundleError, type Bundles } from '../bundles.js';
|
||||
import type { Replays } from '../replays.js';
|
||||
import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('api');
|
||||
|
||||
/** 파일 지우기. 음성 인식 · 다른 프로그램이 열고 있으면(Windows) 5초마다 다시 (1분까지) */
|
||||
export function removeFile(f: string, tries = 12): void {
|
||||
try {
|
||||
fs.rmSync(f, { force: true });
|
||||
} catch (e: any) {
|
||||
if (tries <= 1) return void log.warn(`파일 삭제 실패 ${path.basename(f)}: ${e?.code ?? e?.message}`);
|
||||
setTimeout(() => removeFile(f, tries - 1), 5000).unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApiDeps {
|
||||
store: Store;
|
||||
@@ -24,6 +38,8 @@ export interface ApiDeps {
|
||||
version: string;
|
||||
/** 기록 묶음 (없으면 /api/bundles 없음) */
|
||||
bundles?: Bundles;
|
||||
/** 발로란트 리플레이 (없으면 /api/replays 없음) */
|
||||
replays?: Replays;
|
||||
}
|
||||
|
||||
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
|
||||
@@ -171,6 +187,17 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
reply.code(403).send({ error: 'forbidden', message: '기록 지우기 · 받아오기는 관리자만 할 수 있습니다' });
|
||||
return false;
|
||||
};
|
||||
/** 발화 지우기: 이 PC 안에서 부른 것 · 관리자 · 말한 사람 본인 */
|
||||
const canDelete = (req: any, speakerId: string): boolean => {
|
||||
const raw = req.headers['x-gvr-user'];
|
||||
if (!raw) return true;
|
||||
if (req.headers['x-gvr-role'] === 'admin') return true;
|
||||
try {
|
||||
return JSON.parse(decodeURIComponent(String(raw)))?.id === speakerId;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const exportZip = (reply: any, ids: string[]) => {
|
||||
const { zip, fileName } = d.bundles!.export(ids);
|
||||
return reply.header('content-type', 'application/zip').header('content-disposition', `attachment; filename="${fileName}"`).header('cache-control', 'no-store').send(zip);
|
||||
@@ -297,6 +324,31 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
};
|
||||
});
|
||||
|
||||
// 3D 리플레이 (v1.5.0): 이 PC 에 내려받은 발로란트 리플레이(.vrf)를 변환해 보낸다 (gzip JSON).
|
||||
// 처음 열 때 변환하느라 15초 넘게 걸리면 202 converting → 사이트가 몇 초 뒤 다시 묻는다
|
||||
app.get<{ Params: { id: string } }>('/api/matches/:id/replay', async (req, reply) => {
|
||||
const m = store.getMatch(req.params.id);
|
||||
if (!m) return reply.code(404).send({ error: 'not_found' });
|
||||
if (m.game !== 'valorant' || !d.replays) return reply.code(404).send({ error: 'replay_not_found' });
|
||||
const r = await d.replays.get(m.id.replace(/^val-/, ''));
|
||||
if (r.state === 'ready')
|
||||
return reply.header('content-type', 'application/json; charset=utf-8').header('content-encoding', 'gzip').header('cache-control', 'private, max-age=3600').send(fs.readFileSync(r.file));
|
||||
if (r.state === 'converting') return reply.code(202).send({ status: 'converting' });
|
||||
if (r.state === 'missing') return reply.code(404).send({ error: 'replay_not_found' });
|
||||
if (r.state === 'no_tool') return reply.code(500).send({ error: 'replay_tool_missing', message: '리플레이 변환기가 없습니다 (앱을 다시 설치해 주세요)' });
|
||||
return reply.code(422).send({ error: 'replay_failed', message: r.error });
|
||||
});
|
||||
|
||||
// 이 PC 에서 찾은 리플레이 목록 (경기 기록이 있는지 · 변환했는지)
|
||||
app.get('/api/replays', async (_req, reply) => {
|
||||
if (!d.replays) return reply.code(404).send({ error: 'not_found' });
|
||||
const rp = d.replays;
|
||||
return rp.list().map((r) => {
|
||||
const match = store.getMatch(`val-${r.matchId}`) ?? null;
|
||||
return { matchId: r.matchId, file: path.basename(r.file), size: r.size, mtime: r.mtimeMs, match: match ? match.id : null, converted: !!rp.cached(r) };
|
||||
});
|
||||
});
|
||||
|
||||
app.patch<{ Params: { id: string }; Body: { text?: string } }>('/api/utterances/:id', async (req, reply) => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found' });
|
||||
@@ -321,6 +373,35 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
return item;
|
||||
});
|
||||
|
||||
// 발화 지우기 (v1.4.0): 사이트 우클릭 메뉴. 관리자 또는 말한 사람만.
|
||||
// noise=true 면 "잡음이라 삭제": 인식된 문장을 배워서, 같은 문장이 다시 나오면 잡음으로 본다
|
||||
app.post<{ Params: { id: string }; Body: { noise?: boolean } }>('/api/utterances/:id/delete', async (req, reply) => {
|
||||
const u = store.getUtterance(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found', message: '이미 지워진 발화입니다' });
|
||||
if (!canDelete(req, u.user_id)) return reply.code(403).send({ error: 'forbidden', message: '발화는 관리자나 말한 사람만 지울 수 있습니다' });
|
||||
let learned: string | null = null;
|
||||
if (req.body?.noise) {
|
||||
const sample = (u.raw_text ?? u.text ?? '').trim();
|
||||
const phrase = normalizePhrase(sample);
|
||||
if (phrase) {
|
||||
store.addNoisePhrase(phrase, sample.slice(0, 200));
|
||||
learned = sample.slice(0, 200);
|
||||
}
|
||||
}
|
||||
const files = store.deleteUtterance(u.id);
|
||||
for (const f of files) removeFile(f);
|
||||
timeline.invalidate();
|
||||
d.bus.live({ type: 'utterance.deleted', data: { id: u.id, noise: !!req.body?.noise } });
|
||||
return { ok: true, learned };
|
||||
});
|
||||
app.get('/api/noise-phrases', async () => ({
|
||||
phrases: store.listNoisePhrases().map((r) => ({ id: r.id, text: r.sample, hits: r.hits, createdAt: r.created_at })),
|
||||
}));
|
||||
app.delete<{ Params: { id: string } }>('/api/noise-phrases/:id', async (req, reply) => {
|
||||
if (!store.deleteNoisePhrase(Number(req.params.id))) return reply.code(404).send({ error: 'not_found' });
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// 사이트에서 단어·교정 규칙 추가/삭제 (보고서 5-4: 사이트·설정에서 직접 추가·수정)
|
||||
app.post<{ Body: { word?: string; from?: string; to?: string } }>('/api/dictionary', async (req, reply) => {
|
||||
const b = req.body || {};
|
||||
|
||||
@@ -438,7 +438,9 @@ export function validate(files: Map<string, Buffer>, store?: Store): { manifest:
|
||||
if (u.match_id && !matchIds.has(u.match_id) && !store?.getMatch(u.match_id)) fail(`발화 ${u.id} 의 경기(${u.match_id})가 없습니다`);
|
||||
if (u.audio) {
|
||||
// v1.3.7: audio/<발화ID>.ogg, v1.3.8~: audio/<날짜_시각_말한사람_…_발화ID>.ogg
|
||||
if (typeof u.audio !== 'string' || !/^audio\/[^/\\]{1,200}\.ogg$/.test(u.audio) || u.audio.includes('..')) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
|
||||
// zip 안 이름은 zip 에서 꺼낼 때 찾는 열쇠로만 쓴다 (이 PC 에 쓸 경로는 발화 ID 로 만든다). 폴더 구분자만 막으면 상위 폴더로 갈 수 없다.
|
||||
// 이름 안의 ".." (예: 표시 이름 "하늘..별")은 정상 이름이다
|
||||
if (typeof u.audio !== 'string' || !/^audio\/[^/\\]{1,200}\.ogg$/.test(u.audio)) fail(`발화 ${u.id} 의 음성 파일 이름이 잘못되었습니다`);
|
||||
if (audioSeen.has(u.audio)) fail(`음성 파일 ${u.audio} 를 두 발화가 같이 씁니다`);
|
||||
audioSeen.add(u.audio);
|
||||
const a = files.get(u.audio);
|
||||
|
||||
@@ -33,6 +33,7 @@ async function main() {
|
||||
worker,
|
||||
version: process.env.npm_package_version || '1.0.0',
|
||||
apiPort: Number(process.env.GVR_API_PORT || 0),
|
||||
replayTool: process.env.GVR_REPLAY_TOOL || path.join(root, '..', 'tools', 'replay-extract', 'out', 'linux', 'gvr-replay'),
|
||||
});
|
||||
const shutdown = async () => {
|
||||
await core.stop();
|
||||
|
||||
@@ -87,6 +87,35 @@ export interface DictRow {
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
export interface NoisePhraseRow {
|
||||
id: number;
|
||||
phrase: string;
|
||||
sample: string;
|
||||
hits: number;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
/** 잡음 문장 비교용: 띄어쓰기 · 문장부호 · 기호를 빼고 소문자로 (워커 noise.normalize 와 같은 규칙) */
|
||||
export function normalizePhrase(text: string | null | undefined): string {
|
||||
return String(text ?? '')
|
||||
.replace(/[^\p{L}\p{N}\p{M}]+/gu, '')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 거의 같은 문장인가: 글자 수가 같고(8글자 이상) 다른 글자가 15% 이하 (글자 바뀜만).
|
||||
* Whisper 는 같은 잡음 · 같은 녹음에서도 한두 글자를 다르게 낸다 ("레이드 공" / "레이드 궁").
|
||||
* 글자가 더 붙거나 빠지면 다른 말로 본다: 배운 문장 앞뒤에 실제 말("네", "가자")이 붙은 발화는 지우지 않는다
|
||||
*/
|
||||
export function similarPhrase(a: string, b: string): boolean {
|
||||
const A = [...a];
|
||||
const B = [...b];
|
||||
if (A.length !== B.length || A.length < 8) return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < A.length; i++) if (A[i] !== B[i]) diff++;
|
||||
return diff <= Math.floor(A.length * 0.15);
|
||||
}
|
||||
|
||||
export class Store {
|
||||
readonly db: Database.Database;
|
||||
|
||||
@@ -482,6 +511,43 @@ export class Store {
|
||||
this.db.prepare('DELETE FROM training_samples').run();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 발화 지우기 · 잡음으로 배운 문장 (v1.4.0)
|
||||
/** 발화 하나를 지운다 (교정 학습 데이터 포함). 지울 파일 경로를 돌려준다 */
|
||||
deleteUtterance(id: string): string[] {
|
||||
const files: string[] = [];
|
||||
this.db.transaction(() => {
|
||||
const u = this.getUtterance(id);
|
||||
if (!u) return;
|
||||
if (u.audio_path && !u.audio_deleted) files.push(u.audio_path);
|
||||
for (const t of this.db.prepare('SELECT audio_path FROM training_samples WHERE utterance_id=?').all(id) as { audio_path: string }[]) files.push(t.audio_path);
|
||||
this.db.prepare('DELETE FROM training_samples WHERE utterance_id=?').run(id);
|
||||
this.db.prepare('DELETE FROM utterance_imports WHERE id=?').run(id);
|
||||
this.db.prepare('DELETE FROM utterances WHERE id=?').run(id);
|
||||
})();
|
||||
return files;
|
||||
}
|
||||
/** 잡음 문장 배우기. phrase 는 normalizePhrase 를 거친 값 */
|
||||
addNoisePhrase(phrase: string, sample: string): void {
|
||||
this.db
|
||||
.prepare('INSERT INTO noise_phrases(phrase,sample,created_at) VALUES(?,?,?) ON CONFLICT(phrase) DO UPDATE SET sample=excluded.sample')
|
||||
.run(phrase, sample, Date.now());
|
||||
}
|
||||
listNoisePhrases(): NoisePhraseRow[] {
|
||||
return this.db.prepare('SELECT * FROM noise_phrases ORDER BY created_at DESC').all() as NoisePhraseRow[];
|
||||
}
|
||||
deleteNoisePhrase(id: number): boolean {
|
||||
return this.db.prepare('DELETE FROM noise_phrases WHERE id=?').run(id).changes > 0;
|
||||
}
|
||||
/** 배운 잡음 문장과 같거나 거의 같으면 true (맞힌 횟수를 센다). phrase 는 normalizePhrase 를 거친 값 */
|
||||
hitNoisePhrase(phrase: string): boolean {
|
||||
if (!phrase) return false;
|
||||
const rows = this.db.prepare('SELECT id, phrase FROM noise_phrases').all() as { id: number; phrase: string }[];
|
||||
const hit = rows.find((r) => r.phrase === phrase) ?? rows.find((r) => similarPhrase(r.phrase, phrase));
|
||||
if (!hit) return false;
|
||||
this.db.prepare('UPDATE noise_phrases SET hits=hits+1 WHERE id=?').run(hit.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- stats
|
||||
counts(): { utterances: number; matches: number } {
|
||||
const u = (this.db.prepare('SELECT count(*) n FROM utterances WHERE noise=0 OR corrected=1').get() as any).n;
|
||||
|
||||
@@ -142,3 +142,12 @@ CREATE TABLE IF NOT EXISTS utterance_imports (
|
||||
id TEXT PRIMARY KEY,
|
||||
imported_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- 사이트에서 "잡음이라 삭제"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다
|
||||
CREATE TABLE IF NOT EXISTS noise_phrases (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
phrase TEXT NOT NULL UNIQUE,
|
||||
sample TEXT NOT NULL,
|
||||
hits INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
// 자동 생성: schema.sql 사본 (npm run build 가 다시 만든다)
|
||||
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n";
|
||||
export const SCHEMA_SQL = "PRAGMA journal_mode = WAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);\n\nCREATE TABLE IF NOT EXISTS users (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n color TEXT NOT NULL,\n avatar TEXT,\n excluded INTEGER NOT NULL DEFAULT 0,\n gain_lufs REAL,\n gain_n INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS game_accounts (\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n puuid TEXT NOT NULL,\n riot_id TEXT NOT NULL,\n PRIMARY KEY (user_id, puuid)\n);\nCREATE INDEX IF NOT EXISTS game_accounts_puuid ON game_accounts(puuid);\n\nCREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n guild_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n channel_name TEXT,\n started_at INTEGER NOT NULL,\n ended_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS utterances (\n id TEXT PRIMARY KEY,\n session_id TEXT,\n user_id TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n audio_path TEXT,\n audio_deleted INTEGER NOT NULL DEFAULT 0,\n text TEXT,\n raw_text TEXT,\n words TEXT NOT NULL DEFAULT '[]',\n noise INTEGER NOT NULL DEFAULT 0,\n noise_reason TEXT,\n confidence REAL,\n lufs REAL,\n gain_db REAL NOT NULL DEFAULT 0,\n model TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n match_id TEXT,\n corrected INTEGER NOT NULL DEFAULT 0,\n attempts INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS utterances_started ON utterances(started_at);\nCREATE INDEX IF NOT EXISTS utterances_user ON utterances(user_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_match ON utterances(match_id, started_at);\nCREATE INDEX IF NOT EXISTS utterances_status ON utterances(status);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS utterances_fts USING fts5(text, content='utterances', content_rowid='rowid', tokenize='trigram');\nCREATE TRIGGER IF NOT EXISTS utterances_ai AFTER INSERT ON utterances BEGIN\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_ad AFTER DELETE ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\nEND;\nCREATE TRIGGER IF NOT EXISTS utterances_au AFTER UPDATE OF text ON utterances BEGIN\n INSERT INTO utterances_fts(utterances_fts, rowid, text) VALUES ('delete', old.rowid, coalesce(old.text, ''));\n INSERT INTO utterances_fts(rowid, text) VALUES (new.rowid, coalesce(new.text, ''));\nEND;\n\nCREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n game TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n map TEXT,\n mode TEXT,\n queue TEXT,\n result TEXT,\n detail TEXT,\n status TEXT NOT NULL DEFAULT 'live',\n clock_offset INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);\n\nCREATE TABLE IF NOT EXISTS rounds (\n match_id TEXT NOT NULL REFERENCES matches(id) ON DELETE CASCADE,\n num INTEGER NOT NULL,\n started_at INTEGER NOT NULL,\n combat_at INTEGER NOT NULL,\n ended_at INTEGER NOT NULL,\n win INTEGER,\n result TEXT,\n ally_score INTEGER,\n enemy_score INTEGER,\n economy TEXT,\n PRIMARY KEY (match_id, num)\n);\n\nCREATE TABLE IF NOT EXISTS game_events (\n id TEXT PRIMARY KEY,\n match_id TEXT NOT NULL,\n game TEXT NOT NULL,\n type TEXT NOT NULL,\n ts INTEGER NOT NULL,\n game_time_ms INTEGER,\n round INTEGER,\n actor_puuid TEXT,\n target_puuid TEXT,\n data TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS game_events_ts ON game_events(ts);\nCREATE INDEX IF NOT EXISTS game_events_match ON game_events(match_id, ts);\n\nCREATE TABLE IF NOT EXISTS dictionary (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n word TEXT NOT NULL,\n pack TEXT NOT NULL,\n kind TEXT NOT NULL,\n from_text TEXT NOT NULL DEFAULT '',\n source TEXT NOT NULL,\n enabled INTEGER NOT NULL DEFAULT 1,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n UNIQUE (kind, word, from_text, pack)\n);\n\nCREATE TABLE IF NOT EXISTS training_samples (\n id TEXT PRIMARY KEY,\n utterance_id TEXT,\n text TEXT NOT NULL,\n audio_path TEXT NOT NULL,\n used INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\n-- 받아오기(zip)로 넣은 발화: 보관 기간은 녹음 날짜가 아니라 받아온 날부터 센다\nCREATE TABLE IF NOT EXISTS utterance_imports (\n id TEXT PRIMARY KEY,\n imported_at INTEGER NOT NULL\n);\n\n-- 사이트에서 \"잡음이라 삭제\"한 문장 (v1.4.0). 같은 문장(띄어쓰기 · 문장부호 무시, 긴 문장은 글자 한두 개 바뀐 것까지)이 다시 인식되면 잡음으로 본다\nCREATE TABLE IF NOT EXISTS noise_phrases (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n phrase TEXT NOT NULL UNIQUE,\n sample TEXT NOT NULL,\n hits INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n";
|
||||
|
||||
@@ -177,6 +177,8 @@ export class Bot {
|
||||
// 새 사람이 들어오면 안내를 다시 튼다
|
||||
if (e.newChannelId === myCh && e.oldChannelId !== myCh && (!e.member.bot || process.env.GVR_RECORD_BOTS === '1')) {
|
||||
this.touchUser(e.member);
|
||||
// 녹음 중에 들어온 사람도 사이트가 이름을 알게 한다 (안 보내면 그 사람 발화가 "알 수 없음"으로 뜸)
|
||||
this.bus.live({ type: 'users.updated', data: [] });
|
||||
this.updateParticipants();
|
||||
if (s.ttsEnabled && s.ttsOnNewMember) void this.announce();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Announcer } from './discord/tts.js';
|
||||
import { GameAssets } from './games/assets.js';
|
||||
import { GameManager } from './games/manager.js';
|
||||
import { RelayClient } from './relay/client.js';
|
||||
import { defaultReplayDirs, Replays } from './replays.js';
|
||||
import { Retention } from './retention.js';
|
||||
import { SettingsStore, resolvePaths, type SecretCodec } from './settings.js';
|
||||
import { SttPipeline } from './stt/pipeline.js';
|
||||
@@ -37,6 +38,8 @@ export interface CoreOptions {
|
||||
apiPort?: number;
|
||||
/** 겜녹이 봇 중계에서 로그인 만료 · 등록 해제를 알려 왔을 때 (Electron: 바로 다시 확인해서 잠근다) */
|
||||
onBotUnauthorized?: () => void;
|
||||
/** 발로란트 리플레이 변환기 (gvr-replay.exe). 없으면 3D 리플레이를 보내지 않는다 */
|
||||
replayTool?: string | null;
|
||||
}
|
||||
|
||||
export type Core = Awaited<ReturnType<typeof startCore>>;
|
||||
@@ -91,6 +94,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
});
|
||||
|
||||
const culprit = new Culprit(store, timeline, games);
|
||||
const replays = new Replays({ dirs: defaultReplayDirs, tool: opts.replayTool ?? null, cacheDir: () => path.join(opts.dataDir, 'replays'), version: opts.version });
|
||||
const api: FastifyInstance = await buildApi({
|
||||
store,
|
||||
timeline,
|
||||
@@ -101,6 +105,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
settings: S,
|
||||
trainingDir: () => paths().training,
|
||||
version: opts.version,
|
||||
replays,
|
||||
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
|
||||
overviewExtra: () => ({
|
||||
guild: bot.state.guild,
|
||||
@@ -171,6 +176,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
const g = s.discord.guildId;
|
||||
if (g === watchedGuild) return;
|
||||
watchedGuild = g;
|
||||
relay.sendHello();
|
||||
if (bot.state.status !== 'ready' || !g || bot.state.guild?.id === g) return;
|
||||
log.info('녹음할 서버가 바뀌어 봇을 다시 연결합니다');
|
||||
void bot.stop().then(startBot);
|
||||
@@ -188,5 +194,5 @@ export async function startCore(opts: CoreOptions) {
|
||||
store.close();
|
||||
};
|
||||
|
||||
return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
|
||||
return { settings, store, bus, timeline, dict, worker, stt, assets, games, audioNames, recorder, bot, api, relay, retention, replays, paths, startBot, stop, version: opts.version, resourcesDir: opts.resourcesDir };
|
||||
}
|
||||
|
||||
@@ -59,6 +59,12 @@ export class RelayClient {
|
||||
this.start();
|
||||
}
|
||||
|
||||
/** 녹음할 서버를 바꾸면 사이트 서버에 다시 알린다 (사이트 로그인은 이 서버 멤버만 된다) */
|
||||
sendHello(): void {
|
||||
const c = this.cfg();
|
||||
this.send({ t: 'hello', name: c.name, version: c.version, guildId: c.guildId });
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
const c = this.cfg();
|
||||
if (!c.deviceId || !c.deviceKey) {
|
||||
@@ -155,12 +161,13 @@ export class RelayClient {
|
||||
if (req.user) headers['x-gvr-user'] = encodeURIComponent(JSON.stringify(req.user));
|
||||
const res = await this.api.inject({ method: req.method as any, url: req.path, headers, payload: bin ?? req.body ?? undefined });
|
||||
const outHeaders: Record<string, string> = {};
|
||||
for (const k of ['content-type', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
|
||||
for (const k of ['content-type', 'content-encoding', 'content-range', 'accept-ranges', 'cache-control', 'content-length', 'content-disposition']) {
|
||||
const v = res.headers[k];
|
||||
if (v !== undefined) outHeaders[k] = String(v);
|
||||
}
|
||||
const ct = outHeaders['content-type'] || '';
|
||||
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip')) {
|
||||
// 압축한 본문(리플레이 gzip JSON)도 글자로 바꾸면 깨지므로 바이너리로 보낸다
|
||||
if (ct.startsWith('audio/') || ct.startsWith('application/octet-stream') || ct.startsWith('application/zip') || outHeaders['content-encoding']) {
|
||||
this.send({ t: 'res_head', id: req.id, status: res.statusCode, headers: outHeaders });
|
||||
const idBuf = Buffer.from(req.id, 'utf8');
|
||||
const head = Buffer.alloc(4);
|
||||
|
||||
203
app/src/core/replays.ts
Normal file
203
app/src/core/replays.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { logger } from './util/log.js';
|
||||
|
||||
const log = logger('replay');
|
||||
|
||||
/** 발로란트 경기 ID (리플레이 파일 이름이 `<경기 ID>.vrf`) */
|
||||
const MATCH_ID = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
|
||||
/** 리플레이를 찾지 않는 하위 폴더 (Saved 아래 로그 · 오류 덤프 · 설정 · 브라우저 캐시) */
|
||||
const SKIP_DIRS = new Set(['logs', 'crashes', 'config', 'webcache', 'webcache_4430', 'cefcache']);
|
||||
|
||||
export interface ReplayFileInfo {
|
||||
matchId: string;
|
||||
file: string;
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
}
|
||||
|
||||
export type ReplayState =
|
||||
| { state: 'ready'; file: string }
|
||||
| { state: 'converting' }
|
||||
| { state: 'missing' }
|
||||
| { state: 'no_tool' }
|
||||
| { state: 'failed'; error: string };
|
||||
|
||||
export interface ReplaysOptions {
|
||||
/** 리플레이(.vrf)를 찾을 폴더들 */
|
||||
dirs: () => string[];
|
||||
/** 변환기 (gvr-replay.exe). 없으면 변환하지 않는다 */
|
||||
tool: string | null;
|
||||
/** 변환 결과 보관 폴더 (<경기 ID>.json.gz) */
|
||||
cacheDir: () => string;
|
||||
/** 변환기가 바뀌면(앱 업데이트) 다시 변환한다 */
|
||||
version: string;
|
||||
/** 변환 시간 제한 (기본 3분) */
|
||||
timeoutMs?: number;
|
||||
/** 사이트 요청이 변환을 기다리는 시간 (기본 15초, 사이트 서버는 20초 뒤 시간 초과) */
|
||||
waitMs?: number;
|
||||
}
|
||||
|
||||
/** 발로란트가 리플레이를 내려받는 곳: %LOCALAPPDATA%\VALORANT\Saved (보통 Demos\<경기 ID>.vrf). GVR_REPLAY_DIRS 로 바꿀 수 있다 */
|
||||
export function defaultReplayDirs(): string[] {
|
||||
const env = process.env.GVR_REPLAY_DIRS;
|
||||
if (env) return env.split(path.delimiter).filter(Boolean);
|
||||
const local = process.env.LOCALAPPDATA;
|
||||
return local ? [path.join(local, 'VALORANT', 'Saved')] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 발로란트 리플레이(.vrf) 찾기 · 변환 (docs/dev/replay-3d.md).
|
||||
* 사이트에서 경기의 3D 리플레이를 열면 그때 이 PC 에서 `.vrf` 를 찾아 gvr-replay 로 변환하고 gzip 으로 보관해 둔다.
|
||||
* 변환은 한 번에 하나, 낮은 우선순위로 (게임 중일 수 있다). 실패하면 같은 파일 · 같은 앱 버전으로는 다시 하지 않는다.
|
||||
*/
|
||||
export class Replays {
|
||||
private scanCache: { at: number; list: ReplayFileInfo[] } | null = null;
|
||||
private running = new Map<string, Promise<void>>();
|
||||
private failed = new Map<string, string>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(private o: ReplaysOptions) {}
|
||||
|
||||
/** 찾은 리플레이 (새것부터). 10초 동안은 다시 훑지 않는다 */
|
||||
list(): ReplayFileInfo[] {
|
||||
if (this.scanCache && Date.now() - this.scanCache.at < 10000) return this.scanCache.list;
|
||||
const byId = new Map<string, ReplayFileInfo>();
|
||||
const walk = (dir: string, depth: number) => {
|
||||
let ents: fs.Dirent[];
|
||||
try {
|
||||
ents = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of ents) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) {
|
||||
if (depth > 0 && !SKIP_DIRS.has(e.name.toLowerCase())) walk(p, depth - 1);
|
||||
continue;
|
||||
}
|
||||
if (!(e.isFile() || e.isSymbolicLink()) || !e.name.toLowerCase().endsWith('.vrf')) continue;
|
||||
const m = MATCH_ID.exec(e.name);
|
||||
if (!m) continue;
|
||||
try {
|
||||
const st = fs.statSync(p);
|
||||
const info = { matchId: m[1].toLowerCase(), file: p, size: st.size, mtimeMs: Math.floor(st.mtimeMs) };
|
||||
const prev = byId.get(info.matchId);
|
||||
if (!prev || prev.mtimeMs < info.mtimeMs) byId.set(info.matchId, info);
|
||||
} catch {
|
||||
/* 그 사이 지워짐 */
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const d of this.o.dirs()) walk(d, 3);
|
||||
const list = [...byId.values()].sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||
this.scanCache = { at: Date.now(), list };
|
||||
return list;
|
||||
}
|
||||
|
||||
find(matchId: string): ReplayFileInfo | null {
|
||||
const id = matchId.toLowerCase();
|
||||
return this.list().find((r) => r.matchId === id) ?? null;
|
||||
}
|
||||
|
||||
/** 변환 결과 파일 (원본 · 변환기가 그대로일 때만) */
|
||||
cached(r: ReplayFileInfo): string | null {
|
||||
const out = this.outFile(r.matchId);
|
||||
try {
|
||||
if (fs.readFileSync(out + '.src', 'utf8') === this.stamp(r) && fs.existsSync(out)) return out;
|
||||
} catch {
|
||||
/* 아직 없음 */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 경기 리플레이 상태. 변환이 필요하면 시작하고 waitMs 까지 기다린다 (그때까지 안 끝나면 converting) */
|
||||
async get(matchId: string, waitMs = this.o.waitMs ?? 15000): Promise<ReplayState> {
|
||||
this.scanCache = null; // 사이트에서 열 때는 방금 내려받은 파일도 보이게
|
||||
const r = this.find(matchId);
|
||||
if (!r) return { state: 'missing' };
|
||||
const done = this.cached(r);
|
||||
if (done) return { state: 'ready', file: done };
|
||||
const key = this.stamp(r);
|
||||
const err = this.failed.get(key);
|
||||
if (err) return { state: 'failed', error: err };
|
||||
if (!this.o.tool || !fs.existsSync(this.o.tool)) return { state: 'no_tool' };
|
||||
let job = this.running.get(r.matchId);
|
||||
if (!job) {
|
||||
job = this.enqueue(r).finally(() => this.running.delete(r.matchId));
|
||||
this.running.set(r.matchId, job);
|
||||
}
|
||||
if (waitMs > 0) await Promise.race([job, new Promise((res) => setTimeout(res, waitMs).unref?.())]);
|
||||
if (this.running.has(r.matchId)) return { state: 'converting' };
|
||||
const out = this.cached(r);
|
||||
if (out) return { state: 'ready', file: out };
|
||||
return { state: 'failed', error: this.failed.get(key) ?? '변환 결과 없음' };
|
||||
}
|
||||
|
||||
private outFile(matchId: string): string {
|
||||
return path.join(this.o.cacheDir(), `${matchId}.json.gz`);
|
||||
}
|
||||
|
||||
private stamp(r: ReplayFileInfo): string {
|
||||
return `${r.size}:${r.mtimeMs}:${this.o.version}`;
|
||||
}
|
||||
|
||||
private enqueue(r: ReplayFileInfo): Promise<void> {
|
||||
const run = this.queue.then(() => this.convert(r));
|
||||
this.queue = run.catch(() => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
private async convert(r: ReplayFileInfo): Promise<void> {
|
||||
const dir = this.o.cacheDir();
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const out = this.outFile(r.matchId);
|
||||
const tmpJson = path.join(dir, `${r.matchId}.json.tmp-${process.pid}`);
|
||||
const t0 = Date.now();
|
||||
log.info(`리플레이 변환 시작 ${r.matchId} (${(r.size / 1048576).toFixed(1)}MB)`);
|
||||
try {
|
||||
const summary = await this.run([r.file, tmpJson]);
|
||||
if (!summary?.ok) throw new Error(summary?.error || '변환기가 결과를 알리지 않음');
|
||||
const gz = zlib.gzipSync(fs.readFileSync(tmpJson), { level: 6 });
|
||||
fs.writeFileSync(out + '.tmp', gz);
|
||||
fs.renameSync(out + '.tmp', out);
|
||||
fs.writeFileSync(out + '.src', this.stamp(r));
|
||||
log.info(
|
||||
`리플레이 변환 완료 ${r.matchId}: ${summary.map ?? '?'} · 선수 ${summary.players} · 라운드 ${summary.rounds} · 킬 ${summary.kills} · ${((Date.now() - t0) / 1000).toFixed(1)}초 · ${(gz.length / 1048576).toFixed(1)}MB`,
|
||||
);
|
||||
} catch (e: any) {
|
||||
const msg = String(e?.message ?? e).slice(0, 300);
|
||||
this.failed.set(this.stamp(r), msg);
|
||||
log.warn(`리플레이 변환 실패 ${r.matchId}: ${msg}`);
|
||||
} finally {
|
||||
fs.rmSync(tmpJson, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** 변환기 실행. 마지막 줄 JSON 요약을 돌려준다 */
|
||||
private run(args: string[]): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = execFile(this.o.tool!, args, { timeout: this.o.timeoutMs ?? 180000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
|
||||
const last = String(stdout).trim().split(/\r?\n/).pop() ?? '';
|
||||
let summary: any = null;
|
||||
try {
|
||||
summary = JSON.parse(last);
|
||||
} catch {
|
||||
/* JSON 아님 */
|
||||
}
|
||||
if (summary) return resolve(summary);
|
||||
if (err) return reject(new Error((err as any).killed ? '변환 시간 초과' : String(stderr).trim().split(/\r?\n/).pop() || err.message));
|
||||
reject(new Error('변환기 출력 없음'));
|
||||
});
|
||||
// 게임 중일 수 있으니 낮은 우선순위로
|
||||
try {
|
||||
if (child.pid) os.setPriority(child.pid, os.constants.priority.PRIORITY_BELOW_NORMAL);
|
||||
} catch {
|
||||
/* 권한 없음 */
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'node:fs';
|
||||
import type { Store, UtteranceRow } from '../db/db.js';
|
||||
import { normalizePhrase, type Store, type UtteranceRow } from '../db/db.js';
|
||||
import type { Dictionary, DictContext } from '../dict/dictionary.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { Timeline } from '../timeline.js';
|
||||
@@ -10,11 +10,44 @@ import { WorkerClient, WorkerError, type TranscribeResult } from './worker.js';
|
||||
|
||||
const log = logger('stt');
|
||||
|
||||
const HANGUL = /[가-힣]/;
|
||||
|
||||
/** 이 경기 상세에 나온 선수 이름 (양 팀 모두) */
|
||||
export function matchPlayerNames(store: Store, matchId: string | null): string[] {
|
||||
if (!matchId) return [];
|
||||
const m = store.getMatch(matchId);
|
||||
if (!m?.detail) return [];
|
||||
try {
|
||||
const det = JSON.parse(m.detail);
|
||||
return (det.players || []).map((p: any) => (typeof p.name === 'string' ? p.name.trim() : '')).filter((n: string) => n && n !== '?');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const normName = (s: string) => [...s.toLowerCase()].filter((ch) => /[\p{L}\p{N}]/u.test(ch)).join('');
|
||||
|
||||
/**
|
||||
* 인식 결과가 선수 이름(또는 그 조각)뿐인가. 워커의 is_name_echo 와 같은 기준.
|
||||
* 예: 이름 "QQQWWWQQQ" → "QQQWWWQ" 는 되풀이, "QQQ 잡았다" 는 아님.
|
||||
*/
|
||||
export function isNameEcho(text: string | null, names: string[]): boolean {
|
||||
if (!text) return false;
|
||||
const keys = names.map(normName).filter((k) => k.length >= 2);
|
||||
const toks = text.split(/\s+/).map(normName).filter(Boolean);
|
||||
if (!keys.length || !toks.length) return false;
|
||||
const whole = toks.join('');
|
||||
if (whole.length >= 2 && keys.some((k) => k.includes(whole))) return true;
|
||||
return toks.every((t) => t.length >= 2 && keys.some((k) => k.includes(t)));
|
||||
}
|
||||
|
||||
const NOISE_REASON: Record<string, string> = {
|
||||
vad: '목소리 없음',
|
||||
no_speech: '말소리 아님',
|
||||
hallucination: '잡음에서 지어낸 문장',
|
||||
repetition: '같은 말만 반복',
|
||||
learned: '잡음으로 배운 문장',
|
||||
name_echo: '선수 이름을 잘못 적음',
|
||||
};
|
||||
|
||||
type Slot = 'realtime' | 'precise';
|
||||
@@ -25,6 +58,8 @@ interface Job {
|
||||
prio: number;
|
||||
/** 예전 녹음 고친 뒤 다시 변환: 잡음으로 나오면 이전 결과를 지키고, 정밀 결과로만 덮는다 */
|
||||
repair?: boolean;
|
||||
/** 이미 정밀 모델로 변환한 발화도 다시 변환한다 (잡음으로 나오면 잡음으로 숨김) */
|
||||
redo?: boolean;
|
||||
}
|
||||
|
||||
export interface SttStatus {
|
||||
@@ -160,16 +195,17 @@ export class SttPipeline {
|
||||
resumePending(): void {
|
||||
this.purgeOldNoise();
|
||||
this.repairOldAudio();
|
||||
this.recheckNameEchoes();
|
||||
const rows = this.store.pendingUtterances();
|
||||
if (rows.length) log.info(`미처리 발화 ${rows.length}개 다시 대기열에 넣음`);
|
||||
for (const r of rows) this.enqueue(r.id, 'realtime', 5);
|
||||
}
|
||||
|
||||
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10, repair = false): void {
|
||||
enqueue(id: string, slot: Slot, prio = slot === 'realtime' ? 1 : 10, repair = false, redo = false): void {
|
||||
const key = `${slot}:${id}`;
|
||||
if (this.queued.has(key)) return;
|
||||
this.queued.add(key);
|
||||
this.queue.push({ id, slot, prio, ...(repair ? { repair } : {}) });
|
||||
this.queue.push({ id, slot, prio, ...(repair ? { repair } : {}), ...(redo ? { redo } : {}) });
|
||||
this.queue.sort((a, b) => a.prio - b.prio);
|
||||
this.status.queue = this.queue.length;
|
||||
this.pump();
|
||||
@@ -227,22 +263,23 @@ export class SttPipeline {
|
||||
});
|
||||
}
|
||||
|
||||
/** 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞 */
|
||||
private matchWords(u: UtteranceRow): string[] {
|
||||
if (!u.match_id) return [];
|
||||
const m = this.store.getMatch(u.match_id);
|
||||
if (!m?.detail) return [];
|
||||
try {
|
||||
const det = JSON.parse(m.detail);
|
||||
const out: string[] = [];
|
||||
for (const p of det.players || []) {
|
||||
if (p.character?.name && p.character.name !== '?') out.push(p.character.name);
|
||||
/**
|
||||
* 이 경기에 나온 요원·챔피언·선수 이름 → 핫워드 맨 앞.
|
||||
* 선수 이름은 한글이 들어간 것만 넣는다: "QQQWWWQQQ" 같은 영문 · 숫자 닉네임은 한국어 말로 나올 일이 거의 없고,
|
||||
* 말을 못 알아들을 때 Whisper 가 그 이름을 그대로 적어 버린다 (v1.4.3).
|
||||
*/
|
||||
private matchWords(u: UtteranceRow): { words: string[]; players: string[] } {
|
||||
const players = matchPlayerNames(this.store, u.match_id).filter((n) => HANGUL.test(n));
|
||||
const words: string[] = [];
|
||||
if (u.match_id) {
|
||||
try {
|
||||
const det = JSON.parse(this.store.getMatch(u.match_id)?.detail || '{}');
|
||||
for (const p of det.players || []) if (p.character?.name && p.character.name !== '?') words.push(p.character.name);
|
||||
} catch {
|
||||
/* 경기 상세가 깨졌으면 요원 이름 없이 */
|
||||
}
|
||||
for (const p of det.players || []) if (p.name && p.name !== '?') out.push(p.name);
|
||||
return out;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return { words: [...words, ...players], players };
|
||||
}
|
||||
|
||||
private dictContext(u: UtteranceRow): DictContext {
|
||||
@@ -257,10 +294,11 @@ export class SttPipeline {
|
||||
this.store.markUtteranceFailed(u.id);
|
||||
return;
|
||||
}
|
||||
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair))) return;
|
||||
if (job.slot === 'precise' && (u.corrected || (u.status === 'precise' && !job.repair && !job.redo))) return;
|
||||
const s = this.settings();
|
||||
const ctx = this.dictContext(u);
|
||||
const user = this.store.getUser(u.user_id);
|
||||
const mw = this.matchWords(u);
|
||||
let r: TranscribeResult;
|
||||
try {
|
||||
r = await this.worker.request<TranscribeResult>(
|
||||
@@ -268,7 +306,9 @@ export class SttPipeline {
|
||||
{
|
||||
slot,
|
||||
path: u.audio_path,
|
||||
hotwords: this.dict.hotwords(ctx, this.matchWords(u)),
|
||||
hotwords: this.dict.hotwords(ctx, mw.words),
|
||||
// 결과가 이 이름(조각)뿐이면 워커가 이름을 빼고 다시 변환한다
|
||||
player_names: mw.players,
|
||||
initial_prompt: null,
|
||||
corrections: this.dict.corrections(),
|
||||
dictionary: this.dict.candidates(ctx),
|
||||
@@ -291,6 +331,12 @@ export class SttPipeline {
|
||||
} else this.enqueue(u.id, job.slot, job.prio + 2);
|
||||
return;
|
||||
}
|
||||
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
|
||||
if (!this.store.getUtterance(u.id)) return;
|
||||
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)
|
||||
if (!r.noise && this.store.hitNoisePhrase(normalizePhrase(r.raw_text ?? r.text))) {
|
||||
r = { ...r, noise: true, noise_reason: 'learned', text: null, words: [] };
|
||||
}
|
||||
if (job.repair && r.noise) {
|
||||
log.info(`예전 녹음 다시 변환: ${u.id} 는 잡음으로 나와 이전 결과를 그대로 둠`);
|
||||
return;
|
||||
@@ -385,6 +431,49 @@ export class SttPipeline {
|
||||
step();
|
||||
}
|
||||
|
||||
/**
|
||||
* 한 번만 (v1.4.3): 예전 버전이 선수 이름 핫워드를 그대로 적은 발화(예: 상대 닉네임 "QQQWWWQ")를 다시 본다.
|
||||
* 음성 파일이 있으면 새 기준(한글 이름만 핫워드 · 이름 되풀이면 이름 없이 다시)으로 정밀 모델이 다시 변환하고,
|
||||
* 파일이 지워졌으면 다시 들을 수 없으니 잡음으로 숨긴다. 사람이 고친 발화는 건드리지 않는다.
|
||||
*/
|
||||
private recheckNameEchoes(): void {
|
||||
const KEY = 'name_echo_recheck_v143';
|
||||
if (this.store.meta(KEY)) return;
|
||||
const rows = this.store.db
|
||||
.prepare(`SELECT rowid,* FROM utterances WHERE noise=0 AND corrected=0 AND match_id IS NOT NULL AND text IS NOT NULL ORDER BY started_at`)
|
||||
.all() as UtteranceRow[];
|
||||
const names = new Map<string, string[]>();
|
||||
let redo = 0;
|
||||
let hidden = 0;
|
||||
for (const u of rows) {
|
||||
if (!names.has(u.match_id!)) names.set(u.match_id!, matchPlayerNames(this.store, u.match_id));
|
||||
if (!isNameEcho(u.text, names.get(u.match_id!)!)) continue;
|
||||
if (u.audio_path && !u.audio_deleted && fs.existsSync(u.audio_path)) {
|
||||
log.info(`선수 이름을 잘못 적은 발화 ${u.id} ("${u.text}") → 정밀 모델로 다시 변환`);
|
||||
this.enqueue(u.id, 'precise', 20, false, true);
|
||||
redo++;
|
||||
} else {
|
||||
log.info(`선수 이름을 잘못 적은 발화 ${u.id} ("${u.text}") → 음성 파일이 없어 숨김`);
|
||||
this.store.updateUtteranceResult(u.id, {
|
||||
text: null,
|
||||
raw_text: u.raw_text,
|
||||
words: [],
|
||||
noise: true,
|
||||
noise_reason: 'name_echo',
|
||||
confidence: u.confidence,
|
||||
lufs: u.lufs,
|
||||
gain_db: u.gain_db,
|
||||
model: u.model ?? '',
|
||||
status: u.status === 'precise' ? 'precise' : 'realtime',
|
||||
});
|
||||
this.emit(u.id);
|
||||
hidden++;
|
||||
}
|
||||
}
|
||||
this.store.setMeta(KEY, String(Date.now()));
|
||||
if (redo || hidden) log.info(`선수 이름을 잘못 적은 예전 발화: ${redo}개 다시 변환, ${hidden}개(음성 파일 없음) 숨김`);
|
||||
}
|
||||
|
||||
/** v1.3.5 이하에서 잡음으로 판정된 발화의 남은 파일 정리 */
|
||||
private purgeOldNoise(): void {
|
||||
const rows = this.store.noiseWithAudio();
|
||||
|
||||
@@ -11,7 +11,7 @@ import { hardenTlsEnv, secureFetch } from '../core/util/secure-http.js';
|
||||
import { Finetuner } from './finetune.js';
|
||||
import type { AuthView } from './api-types.js';
|
||||
import { buildState, registerIpc } from './ipc.js';
|
||||
import { brandDir, rendererDir, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
|
||||
import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
|
||||
|
||||
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
|
||||
hardenTlsEnv();
|
||||
@@ -217,7 +217,7 @@ async function smoke(): Promise<void> {
|
||||
const a = await new AppAuth(st, { version: app.getVersion(), openUrl: () => undefined }).check();
|
||||
out.auth = a.status;
|
||||
out.builtinBot = st.hasBuiltinBot;
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st });
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: st, replayTool: replayToolPath() });
|
||||
out.codec = c.settings.codecName;
|
||||
out.botMode = c.settings.get().discord.botMode;
|
||||
const ready = await new Promise<any>((res) => {
|
||||
@@ -244,7 +244,18 @@ async function smoke(): Promise<void> {
|
||||
out.dict = c.store.listDict().length;
|
||||
out.renderer = fs.existsSync(path.join(rendererDir(), 'index.html'));
|
||||
out.tray = fs.existsSync(path.join(brandDir(), 'tray.png'));
|
||||
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true ? 0 : 1;
|
||||
// 3D 리플레이 변환기 (v1.5.0): 배포본 안에 있어야 한다. GVR_SMOKE_VRF 가 있으면 실제로 변환해 본다
|
||||
out.replayTool = fs.existsSync(replayToolPath());
|
||||
if (process.env.GVR_SMOKE_VRF) {
|
||||
const vrf = process.env.GVR_SMOKE_VRF;
|
||||
const id = path.basename(vrf).replace(/\.vrf$/i, '');
|
||||
process.env.GVR_REPLAY_DIRS = path.dirname(vrf);
|
||||
const t0 = Date.now();
|
||||
const r = await c.replays.get(id, 170000);
|
||||
out.replayConvert = r.state === 'ready' ? { ok: true, ms: Date.now() - t0, gz: fs.statSync(r.file).size } : r;
|
||||
}
|
||||
const replayOk = out.replayTool === true && (!process.env.GVR_SMOKE_VRF || (out.replayConvert as any)?.ok === true);
|
||||
code = ready && botOk && out.secretRoundTrip && out.renderer && out.tray && out.siteTls === true && replayOk ? 0 : 1;
|
||||
await c.stop();
|
||||
} catch (e: any) {
|
||||
out.error = e.stack || e.message;
|
||||
@@ -293,7 +304,7 @@ function startApp(): Promise<void> {
|
||||
starting ??= (async () => {
|
||||
try {
|
||||
// 겜녹이 봇 중계가 로그인 만료 · 등록 해제를 알려 오면 10분을 기다리지 않고 바로 확인해서 잠근다
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check() });
|
||||
const c = await startCore({ dataDir, resourcesDir: resourcesDir(), worker: workerCommand(), version: app.getVersion(), settings: settings!, onBotUnauthorized: () => void auth?.check(), replayTool: replayToolPath() });
|
||||
core = c;
|
||||
void syncNames();
|
||||
ft = new Finetuner(c, pushState);
|
||||
|
||||
@@ -55,3 +55,10 @@ export function workerCommand(): { cmd: string; args: string[]; cwd?: string } {
|
||||
export function finetuneScriptsDir(): string {
|
||||
return app.isPackaged ? path.join(process.resourcesPath, 'worker', '_internal', 'gvr_worker', 'finetune') : path.join(appRoot, '..', 'worker', 'gvr_worker', 'finetune');
|
||||
}
|
||||
|
||||
/** 발로란트 리플레이 변환기 (tools/replay-extract, 배포본은 resources/replay/gvr-replay.exe) */
|
||||
export function replayToolPath(): string {
|
||||
if (process.env.GVR_REPLAY_TOOL) return process.env.GVR_REPLAY_TOOL;
|
||||
if (app.isPackaged) return path.join(process.resourcesPath, 'replay', process.platform === 'win32' ? 'gvr-replay.exe' : 'gvr-replay');
|
||||
return path.join(appRoot, '..', 'tools', 'replay-extract', 'out', process.platform === 'win32' ? 'win/gvr-replay.exe' : 'linux/gvr-replay');
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { AudioNamer, audioFileName, safePart } from '../src/core/audio-names.ts';
|
||||
import { Bundles } from '../src/core/bundles.ts';
|
||||
import { readZip } from '../src/core/util/zip.ts';
|
||||
import { readZip, writeZip } from '../src/core/util/zip.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-names-'));
|
||||
const at = (h: number, m: number, s: number) => new Date(2026, 9, 16, h, m, s).getTime();
|
||||
@@ -74,3 +74,52 @@ test('녹음 파일 이름: 실제 파일을 바꾸고, 경기 뒤 라운드 ·
|
||||
assert.ok(fs.existsSync(store.getUtterance('a1')!.audio_path!));
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('녹음 파일 이름: 표시 이름에 ".." 이 있어도 zip 내보내기 → 지우기 → 받아오기로 되살린다', () => {
|
||||
const dir = tmp();
|
||||
const audio = path.join(dir, 'audio');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘..별', avatar: null });
|
||||
const namer = new AudioNamer(store, { summary: () => ({ mode: '', map: { name: '' } }), liveRound: () => null } as any, () => false);
|
||||
const f = path.join(audio, 'day', 'x1.ogg');
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
const ts = at(5, 0, 0);
|
||||
store.insertUtterance({ id: 'x1', session_id: null, user_id: 'u1', started_at: ts, ended_at: ts + 1000, audio_path: f, match_id: null });
|
||||
store.updateUtteranceResult('x1', { text: '안녕', raw_text: null, words: [], noise: false, noise_reason: null, confidence: 1, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
|
||||
assert.equal(namer.refresh('x1'), true);
|
||||
assert.equal(path.basename(store.getUtterance('x1')!.audio_path!), '2026-10-16_05-00-00_하늘..별_경기밖_x1.ogg');
|
||||
const b = new Bundles(store, { summary: () => ({ mode: '', map: { name: '' }, score: null, win: null }) } as any, () => audio, 'test', (ids) => ids.forEach((id) => namer.refresh(id)));
|
||||
const id = b.list()[0].id;
|
||||
const { zip } = b.export([id]);
|
||||
assert.ok(readZip(zip).has('audio/2026-10-16_05-00-00_하늘..별_경기밖_x1.ogg'));
|
||||
b.delete([id]);
|
||||
assert.equal(store.getUtterance('x1'), undefined);
|
||||
const r = b.import(zip);
|
||||
assert.equal(r.added.utterances, 1);
|
||||
assert.equal(r.added.audio, 1);
|
||||
const back = store.getUtterance('x1')!;
|
||||
assert.equal(back.text, '안녕');
|
||||
assert.ok(fs.existsSync(back.audio_path!));
|
||||
assert.ok(back.audio_path!.startsWith(audio), '받은 파일은 이 PC 의 audio 폴더 안에만 쓴다');
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('받아오기: 폴더를 넘나드는 zip 안 이름은 막는다', () => {
|
||||
const dir = tmp();
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const b = new Bundles(store, { summary: () => ({ mode: '', map: { name: '' }, score: null, win: null }) } as any, () => path.join(dir, 'audio'), 'test');
|
||||
for (const bad of ['audio/../x1.ogg', 'audio/..\\x1.ogg', 'audio/sub/x1.ogg', '../x1.ogg']) {
|
||||
const data = { users: [{ id: 'u1', name: '하늘' }], utterances: [{ id: 'x1', user_id: 'u1', started_at: 1, ended_at: 2, audio: bad }] };
|
||||
const manifest = { format: 'gvr-bundle', version: 1, bundles: [{ kind: 'talk', id: 'talk-x1' }], counts: { utterances: 1 } };
|
||||
const zip = writeZip([
|
||||
{ name: 'manifest.json', data: Buffer.from(JSON.stringify(manifest)) },
|
||||
{ name: 'data.json', data: Buffer.from(JSON.stringify(data)) },
|
||||
{ name: bad, data: Buffer.from('OggS....') },
|
||||
]);
|
||||
assert.throws(() => b.import(zip), /음성 파일 이름이 잘못되었습니다/, bad);
|
||||
}
|
||||
assert.equal(store.getUtterance('x1'), undefined);
|
||||
store.close();
|
||||
});
|
||||
|
||||
@@ -296,6 +296,29 @@ test('users.updated: 보내는 쪽이 빈 목록을 줘도 실제 유저 목록
|
||||
assert.equal(got[0].data[0].name, '하늘');
|
||||
});
|
||||
|
||||
test('녹음 중에 들어온 사람: 유저로 저장하고 users.updated 를 보낸다 (중간 참여자 "알 수 없음" 버그)', async () => {
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const { Bot } = await import('../src/core/discord/bot.ts');
|
||||
const store = new Store(path.join(tmp(), 'db.sqlite'));
|
||||
const bus = new Bus();
|
||||
bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: false, riot: [] }));
|
||||
const got: any[] = [];
|
||||
bus.on('live', (e) => got.push(e));
|
||||
const settings = () => ({ discord: { followEnabled: false, followUserId: null, ttsEnabled: false, ttsOnNewMember: false } }) as any;
|
||||
const bot = new Bot(store, {} as any, {} as any, bus, settings);
|
||||
const late = { id: '42', name: '늦게온사람', avatar: null, bot: false };
|
||||
bot.gateway = { channelMembers: () => [late] } as any;
|
||||
bot.state.guild = { id: 'g', name: 'g', icon: null };
|
||||
bot.state.recording = { active: true, channel: '음성', channelId: 'vc', since: 1, participants: [], reason: 'command' };
|
||||
await (bot as any).onVoiceState({ guildId: 'g', member: late, oldChannelId: null, newChannelId: 'vc', channel: { id: 'vc', name: '음성' } });
|
||||
assert.equal(store.getUser('42')?.name, '늦게온사람');
|
||||
const upd = got.filter((e) => e.type === 'users.updated');
|
||||
assert.equal(upd.length, 1);
|
||||
assert.ok(upd[0].data.some((u: any) => u.id === '42' && u.name === '늦게온사람'));
|
||||
assert.deepEqual(bot.state.recording.participants, ['42']);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('녹음 안내 말 속도: 0.1~2.0 으로 자르고 속도마다 따로 캐시한다', async () => {
|
||||
const { Announcer, clampRate } = await import('../src/core/discord/tts.ts');
|
||||
assert.equal(clampRate(0.05), 0.1);
|
||||
|
||||
@@ -113,6 +113,24 @@ test('E2E: 발화 → STT 워커 → DB → 실시간 이벤트 → 기록 API',
|
||||
assert.equal(imp.added.utterances, 2, '잡음(keys)은 내보내지 않는다');
|
||||
assert.equal((await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.length, 2);
|
||||
assert.ok(live.some((e) => e.type === 'records.changed'));
|
||||
// 우클릭 → 삭제 → "잡음이라 삭제" (v1.4.0): 인식된 문장을 배우고, 같은 녹음이 다시 들어오면 잡음으로 숨긴다
|
||||
const heard = core.store.getUtterance('speech')!.raw_text!;
|
||||
const nd = await core.api.inject({ method: 'POST', url: '/api/utterances/speech/delete', headers: { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'u1', name: '하늘', avatar: null })), 'x-gvr-role': 'member' }, payload: { noise: true } });
|
||||
assert.deepEqual(nd.json(), { ok: true, learned: heard });
|
||||
assert.equal(core.store.getUtterance('speech'), undefined);
|
||||
const again = path.join(core.paths().audio, 'test', 'again.ogg');
|
||||
fs.copyFileSync(path.join(fx, 'speech_ko.ogg'), again);
|
||||
core.store.insertUtterance({ id: 'again', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 3000, audio_path: again, match_id: null });
|
||||
core.stt.enqueue('again', 'realtime');
|
||||
await wait(() => core.store.getUtterance('again')!.status !== 'pending', 60000, 'transcribe again');
|
||||
const ag = core.store.getUtterance('again')!;
|
||||
console.log('again →', ag.noise, ag.noise_reason, '| raw:', ag.raw_text);
|
||||
assert.equal(ag.noise, 1);
|
||||
assert.equal(ag.noise_reason, 'learned');
|
||||
assert.equal(ag.audio_deleted, 1);
|
||||
assert.ok(!fs.existsSync(again));
|
||||
assert.equal(core.store.listNoisePhrases()[0].hits, 1);
|
||||
assert.ok(!(await core.api.inject({ method: 'GET', url: '/api/timeline' })).json().items.some((i: any) => i.id === 'again'));
|
||||
} finally {
|
||||
await core.stop();
|
||||
}
|
||||
|
||||
113
app/test/name-echo.test.ts
Normal file
113
app/test/name-echo.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
// v1.4.3: 상대 닉네임("QQQWWWQQQ")을 핫워드로 넣었더니 말소리를 "QQQWWWQ" 로 적던 문제
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { SttPipeline, isNameEcho } from '../src/core/stt/pipeline.ts';
|
||||
|
||||
const NAMES = ['QQQWWWQQQ', '노곤노곤탐방가', '하늘 별'];
|
||||
|
||||
test('선수 이름 되풀이 판정: 이름(조각)만 있으면 되풀이, 실제 말이 붙으면 아님 (워커 is_name_echo 와 같은 기준)', () => {
|
||||
for (const t of ['QQQWWWQ', ' QQQWWWQ.', 'qqqwwwqqq', 'QQQWWWQ QQQWWWQ', '노곤노곤탐방가', '하늘 별']) assert.ok(isNameEcho(t, NAMES), t);
|
||||
for (const t of ['QQQ 잡았다', '노곤노곤탐방가 죽였어', '아이고, 점프티... 아, 갔다.', 'Q', '', null]) assert.ok(!isNameEcho(t, NAMES), String(t));
|
||||
assert.ok(!isNameEcho('QQQWWWQ', []));
|
||||
});
|
||||
|
||||
function setup() {
|
||||
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-echo-'));
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '안정우', avatar: null });
|
||||
const players = [
|
||||
{ name: 'QQQWWWQQQ', character: { name: '제트' } },
|
||||
{ name: '노곤노곤탐방가', character: { name: '레이즈' } },
|
||||
{ name: 'Sky', character: { name: '세이지' } },
|
||||
];
|
||||
store.upsertMatch({ id: 'm1', game: 'valorant', started_at: Date.now() - 60000, status: 'ended', detail: JSON.stringify({ players }) });
|
||||
const mk = (id: string, text: string | null) => {
|
||||
const f = path.join(dir, 'audio', `${id}.ogg`);
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: 'm1' });
|
||||
if (text !== null)
|
||||
store.updateUtteranceResult(id, { text, raw_text: text, words: [], noise: false, noise_reason: null, confidence: 0.4, lufs: -30, gain_db: 0, model: 'm', status: 'precise' });
|
||||
return f;
|
||||
};
|
||||
const reqs: any[] = [];
|
||||
const results: Record<string, any> = {};
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string, req: any) => {
|
||||
if (op === 'gpu_info') return { gpus: [] };
|
||||
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
||||
if (op === 'load') return {};
|
||||
reqs.push(req);
|
||||
const id = path.basename(req.path, '.ogg');
|
||||
return { text: '말', raw_text: '말', words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1, ...results[id] };
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm', device: 'cpu', computeType: 'int8', gameVramReserveMb: 0, reprocessAfterMatch: false }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
||||
const dict: any = { hotwords: (_ctx: string, extra: string[] = []) => [...extra, '로테'].join(' '), corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
||||
const wait = async (fn: () => boolean) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > 5000) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
};
|
||||
return { store, stt, mk, reqs, results, wait };
|
||||
}
|
||||
|
||||
test('핫워드: 선수 이름은 한글이 들어간 것만 넣고, 그 이름을 워커에 되풀이 확인용으로 넘긴다', async () => {
|
||||
const s = setup();
|
||||
await s.stt.load('realtime', 'm');
|
||||
s.mk('a1', null);
|
||||
s.stt.enqueue('a1', 'realtime');
|
||||
await s.wait(() => s.store.getUtterance('a1')!.status !== 'pending');
|
||||
const hw: string[] = s.reqs[0].hotwords.split(' ');
|
||||
assert.ok(hw.includes('제트') && hw.includes('레이즈') && hw.includes('세이지'), '요원 이름은 그대로');
|
||||
assert.ok(hw.includes('노곤노곤탐방가'));
|
||||
assert.ok(!hw.includes('QQQWWWQQQ') && !hw.includes('Sky'), '한글 없는 닉네임은 핫워드에 넣지 않는다');
|
||||
assert.deepEqual(s.reqs[0].player_names, ['노곤노곤탐방가']);
|
||||
});
|
||||
|
||||
test('예전 발화 다시 보기 (한 번만): 이름을 잘못 적은 발화는 정밀 모델로 다시 변환, 음성 파일이 없으면 숨김, 고친 발화 · 실제 말은 그대로', async () => {
|
||||
const s = setup();
|
||||
const fRedo = s.mk('e1', 'QQQWWWQ');
|
||||
s.mk('e2', 'QQQWWWQ');
|
||||
s.store.markAudioDeleted('e2');
|
||||
s.mk('e3', '아이고, 점프티... 아, 갔다.');
|
||||
s.mk('e4', 'QQQWWWQ');
|
||||
s.store.db.prepare('UPDATE utterances SET corrected=1 WHERE id=?').run('e4');
|
||||
const fFixed = s.mk('e5', 'QQQWWWQ');
|
||||
// e1: 다시 들어 보니 말소리가 아니었다 → 잡음으로 숨기고 파일 삭제. e5: 다시 들어 보니 실제 말
|
||||
s.results.e1 = { text: null, raw_text: null, noise: true, noise_reason: 'vad' };
|
||||
s.results.e5 = { text: '아 갔다', raw_text: '아 갔다' };
|
||||
await s.stt.load('precise', 'm');
|
||||
s.stt.resumePending();
|
||||
await s.wait(() => s.reqs.length >= 2 && !s.stt.status.processing && s.stt.status.queue === 0);
|
||||
assert.deepEqual(s.reqs.map((r) => path.basename(r.path, '.ogg')).sort(), ['e1', 'e5'], '정밀 모델로 이미 변환한 발화도 다시 변환');
|
||||
assert.equal(s.reqs[0].slot, 'precise');
|
||||
const e1 = s.store.getUtterance('e1')!;
|
||||
assert.equal(e1.noise, 1);
|
||||
assert.equal(e1.text, null);
|
||||
assert.ok(!fs.existsSync(fRedo));
|
||||
const e2 = s.store.getUtterance('e2')!;
|
||||
assert.equal(e2.noise, 1);
|
||||
assert.equal(e2.noise_reason, 'name_echo');
|
||||
assert.equal(e2.text, null);
|
||||
assert.equal(s.store.getUtterance('e3')!.text, '아이고, 점프티... 아, 갔다.');
|
||||
assert.equal(s.store.getUtterance('e4')!.text, 'QQQWWWQ', '사람이 고친 발화는 그대로');
|
||||
assert.equal(s.store.getUtterance('e5')!.text, '아 갔다');
|
||||
assert.ok(fs.existsSync(fFixed));
|
||||
// 두 번째 시작에서는 다시 보지 않는다
|
||||
s.mk('e6', 'QQQWWWQ');
|
||||
s.stt.resumePending();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
assert.equal(s.reqs.length, 2);
|
||||
});
|
||||
184
app/test/replays.test.ts
Normal file
184
app/test/replays.test.ts
Normal file
@@ -0,0 +1,184 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import WebSocket from 'ws';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { buildApi } from '../src/core/api/server.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { Replays } from '../src/core/replays.ts';
|
||||
import { RelayClient } from '../src/core/relay/client.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-replay-'));
|
||||
const ID = '4145f041-7d83-4785-ac4b-b532154f14a4';
|
||||
const ID2 = '0e1f2a3b-0000-4000-8000-000000000002';
|
||||
|
||||
/** 가짜 변환기: 호출 횟수를 세고, 모드 파일에 따라 성공 · 실패 · 느림 */
|
||||
function fakeTool(dir: string): { tool: string; calls: () => number; mode: (m: 'ok' | 'fail' | 'slow') => void } {
|
||||
const tool = path.join(dir, 'gvr-replay');
|
||||
const count = path.join(dir, 'calls');
|
||||
const modeFile = path.join(dir, 'mode');
|
||||
fs.writeFileSync(modeFile, 'ok');
|
||||
fs.writeFileSync(
|
||||
tool,
|
||||
`#!/bin/sh
|
||||
echo x >> "${count}"
|
||||
mode=$(cat "${modeFile}")
|
||||
if [ "$mode" = fail ]; then echo '{"ok":false,"error":"InvalidDataException: bad chunk"}'; exit 1; fi
|
||||
if [ "$mode" = slow ]; then sleep 2; fi
|
||||
printf '{"format":"gvr-replay","v":1,"matchId":"%s","players":[]}' "$(basename "$1" .vrf)" > "$2"
|
||||
echo '{"ok":true,"map":"/Game/Maps/Infinity/Infinity","players":10,"rounds":20,"kills":146}'
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
return { tool, calls: () => (fs.existsSync(count) ? fs.readFileSync(count, 'utf8').split('\n').filter(Boolean).length : 0), mode: (m) => fs.writeFileSync(modeFile, m) };
|
||||
}
|
||||
|
||||
function setup(waitMs = 15000) {
|
||||
const dir = tmp();
|
||||
const saved = path.join(dir, 'VALORANT', 'Saved');
|
||||
const demos = path.join(saved, 'Demos');
|
||||
fs.mkdirSync(demos, { recursive: true });
|
||||
const t = fakeTool(dir);
|
||||
const replays = new Replays({ dirs: () => [saved], tool: t.tool, cacheDir: () => path.join(dir, 'GVR-Data', 'replays'), version: '1.5.0', waitMs });
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertMatch({ id: `val-${ID}`, game: 'valorant', started_at: Date.now() - 3600000 });
|
||||
store.upsertMatch({ id: `val-${ID2}`, game: 'valorant', started_at: Date.now() - 7200000 });
|
||||
store.upsertMatch({ id: 'lol-KR_1', game: 'lol', started_at: Date.now() - 7200000 });
|
||||
return { dir, saved, demos, replays, store, ...t };
|
||||
}
|
||||
|
||||
const api = (s: ReturnType<typeof setup>) =>
|
||||
buildApi({
|
||||
store: s.store,
|
||||
timeline: new Timeline(s.store),
|
||||
games: {} as any,
|
||||
dict: {} as any,
|
||||
culprit: {} as any,
|
||||
bus: new Bus(),
|
||||
settings: () => ({}) as any,
|
||||
trainingDir: () => path.join(s.dir, 'training'),
|
||||
overviewExtra: () => ({ guild: null, recording: {} as any }),
|
||||
version: 'test',
|
||||
replays: s.replays,
|
||||
});
|
||||
|
||||
test('리플레이 찾기: Saved 아래 <경기 ID>.vrf (하위 폴더 포함), 로그 폴더 · 이름이 다른 파일은 무시', () => {
|
||||
const s = setup();
|
||||
fs.writeFileSync(path.join(s.demos, `${ID.toUpperCase()}.vrf`), 'a');
|
||||
fs.mkdirSync(path.join(s.demos, 'old'), { recursive: true });
|
||||
fs.writeFileSync(path.join(s.demos, 'old', `${ID2}.vrf`), 'b');
|
||||
fs.writeFileSync(path.join(s.demos, 'notes.vrf'), 'c');
|
||||
fs.mkdirSync(path.join(s.saved, 'Logs'), { recursive: true });
|
||||
fs.writeFileSync(path.join(s.saved, 'Logs', '11111111-1111-4111-8111-111111111111.vrf'), 'd');
|
||||
const ids = s.replays.list().map((r) => r.matchId);
|
||||
assert.deepEqual(ids.sort(), [ID, ID2].sort());
|
||||
assert.equal(s.replays.find(ID.toUpperCase())?.matchId, ID);
|
||||
});
|
||||
|
||||
test('3D 리플레이 API: 처음 열면 변환해서 gzip JSON, 다음부터는 보관본 (변환 한 번)', async () => {
|
||||
const s = setup();
|
||||
const app = await api(s);
|
||||
const miss = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(miss.statusCode, 404);
|
||||
assert.equal(miss.json().error, 'replay_not_found');
|
||||
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
|
||||
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(r.statusCode, 200);
|
||||
assert.equal(r.headers['content-encoding'], 'gzip');
|
||||
assert.match(String(r.headers['content-type']), /application\/json/);
|
||||
const body = JSON.parse(zlib.gunzipSync(r.rawPayload).toString('utf8'));
|
||||
assert.equal(body.format, 'gvr-replay');
|
||||
assert.equal(body.matchId, ID);
|
||||
const again = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(again.statusCode, 200);
|
||||
assert.equal(s.calls(), 1, '두 번째는 변환하지 않는다');
|
||||
// 목록: 경기 기록과 변환 여부
|
||||
const list = (await app.inject({ url: '/api/replays' })).json();
|
||||
assert.deepEqual(list.map((x: any) => [x.matchId, x.match, x.converted]), [[ID, `val-${ID}`, true]]);
|
||||
// 롤 경기 · 없는 경기
|
||||
assert.equal((await app.inject({ url: '/api/matches/lol-KR_1/replay' })).json().error, 'replay_not_found');
|
||||
assert.equal((await app.inject({ url: '/api/matches/val-nope/replay' })).statusCode, 404);
|
||||
});
|
||||
|
||||
test('변환 실패는 422 로 이유를 알리고, 같은 파일은 다시 변환하지 않는다 (파일이 바뀌면 다시)', async () => {
|
||||
const s = setup();
|
||||
const app = await api(s);
|
||||
const vrf = path.join(s.demos, `${ID}.vrf`);
|
||||
fs.writeFileSync(vrf, 'broken');
|
||||
s.mode('fail');
|
||||
const r = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(r.statusCode, 422);
|
||||
assert.equal(r.json().error, 'replay_failed');
|
||||
assert.match(r.json().message, /bad chunk/);
|
||||
await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(s.calls(), 1);
|
||||
// 다시 내려받음 (크기 · 시각이 바뀜) → 다시 변환
|
||||
s.mode('ok');
|
||||
fs.writeFileSync(vrf, 'fixed replay');
|
||||
fs.utimesSync(vrf, new Date(), new Date(Date.now() + 5000));
|
||||
const ok = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(ok.statusCode, 200);
|
||||
assert.equal(s.calls(), 2);
|
||||
});
|
||||
|
||||
test('변환이 기다리는 시간보다 길면 202 converting, 끝나면 200 (같은 파일을 두 번 변환하지 않음)', async () => {
|
||||
const s = setup(300);
|
||||
const app = await api(s);
|
||||
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
|
||||
s.mode('slow');
|
||||
const r1 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(r1.statusCode, 202);
|
||||
assert.equal(r1.json().status, 'converting');
|
||||
const r2 = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
assert.equal(r2.statusCode, 202);
|
||||
let last = r2;
|
||||
for (let i = 0; i < 20 && last.statusCode === 202; i++) {
|
||||
await new Promise((res) => setTimeout(res, 300));
|
||||
last = await app.inject({ url: `/api/matches/val-${ID}/replay` });
|
||||
}
|
||||
assert.equal(last.statusCode, 200);
|
||||
assert.equal(s.calls(), 1);
|
||||
});
|
||||
|
||||
test('변환기가 없으면 500 replay_tool_missing', async () => {
|
||||
const s = setup();
|
||||
const replays = new Replays({ dirs: () => [s.saved], tool: path.join(s.dir, 'none.exe'), cacheDir: () => path.join(s.dir, 'c'), version: '1' });
|
||||
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
|
||||
assert.deepEqual(await replays.get(ID), { state: 'no_tool' });
|
||||
});
|
||||
|
||||
test('중계: gzip 리플레이는 바이너리 조각 + content-encoding 으로 사이트 서버에 간다', async () => {
|
||||
const s = setup();
|
||||
const app = await api(s);
|
||||
fs.writeFileSync(path.join(s.demos, `${ID}.vrf`), 'vrf');
|
||||
const relay = new RelayClient(app, new Bus(), () => ({ serverUrl: 'https://x', deviceId: null, deviceKey: null, name: 'pc', version: 't', guildId: null }));
|
||||
const sent: any[] = [];
|
||||
(relay as any).ws = { readyState: WebSocket.OPEN, bufferedAmount: 0, send: (m: any) => sent.push(m) };
|
||||
await (relay as any).handle({ t: 'req', id: 'r1', method: 'GET', path: `/api/matches/val-${ID}/replay`, headers: {}, user: { id: 'u', name: 'u', avatar: null }, body: null });
|
||||
const head = JSON.parse(sent[0]);
|
||||
assert.equal(head.t, 'res_head');
|
||||
assert.equal(head.status, 200);
|
||||
assert.equal(head.headers['content-encoding'], 'gzip');
|
||||
const chunks = sent.slice(1, -1).map((b: Buffer) => b.subarray(4 + b.readUInt32BE(0)));
|
||||
assert.equal(JSON.parse(sent.at(-1)).t, 'res_end');
|
||||
assert.equal(JSON.parse(zlib.gunzipSync(Buffer.concat(chunks)).toString()).matchId, ID);
|
||||
});
|
||||
|
||||
test('실제 변환기 (tools/replay-extract 리눅스 빌드 + 13.08 리플레이가 있을 때만)', { skip: !fs.existsSync(path.join(os.homedir(), 'work/vrf/match.vrf')) || !fs.existsSync(path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay')) }, async () => {
|
||||
if (!process.env.DOTNET_ROOT && fs.existsSync(path.join(os.homedir(), '.dotnet'))) process.env.DOTNET_ROOT = path.join(os.homedir(), '.dotnet');
|
||||
const dir = tmp();
|
||||
const demos = path.join(dir, 'Demos');
|
||||
fs.mkdirSync(demos);
|
||||
fs.symlinkSync(path.join(os.homedir(), 'work/vrf/match.vrf'), path.join(demos, `${ID}.vrf`));
|
||||
const replays = new Replays({ dirs: () => [dir], tool: path.resolve(import.meta.dirname, '../../tools/replay-extract/out/linux/gvr-replay'), cacheDir: () => path.join(dir, 'c'), version: '1' });
|
||||
const r = await replays.get(ID, 120000);
|
||||
assert.equal(r.state, 'ready');
|
||||
const j = JSON.parse(zlib.gunzipSync(fs.readFileSync((r as any).file)).toString());
|
||||
assert.equal(j.matchId, ID);
|
||||
assert.equal(j.players.length, 10);
|
||||
assert.ok(j.kills.length > 100);
|
||||
});
|
||||
209
app/test/utterance-delete.test.ts
Normal file
209
app/test/utterance-delete.test.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store, normalizePhrase, similarPhrase } from '../src/core/db/db.ts';
|
||||
import { buildApi } from '../src/core/api/server.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { SttPipeline } from '../src/core/stt/pipeline.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-del-'));
|
||||
const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role });
|
||||
|
||||
function setup() {
|
||||
const dir = tmp();
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const timeline = new Timeline(store);
|
||||
const bus = new Bus();
|
||||
const live: any[] = [];
|
||||
bus.on('live', (e) => live.push(e));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const mk = (id: string, raw: string | null, text: string | null = raw) => {
|
||||
const f = path.join(dir, 'audio', `${id}.ogg`);
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
|
||||
if (raw !== null || text !== null)
|
||||
store.updateUtteranceResult(id, { text, raw_text: raw, words: [], noise: false, noise_reason: null, confidence: 0.4, lufs: -30, gain_db: 0, model: 'm', status: 'precise' });
|
||||
return f;
|
||||
};
|
||||
return { dir, store, timeline, bus, live, mk };
|
||||
}
|
||||
|
||||
const api = (s: ReturnType<typeof setup>) =>
|
||||
buildApi({
|
||||
store: s.store,
|
||||
timeline: s.timeline,
|
||||
games: {} as any,
|
||||
dict: { learn() {}, invalidate() {} } as any,
|
||||
culprit: {} as any,
|
||||
bus: s.bus,
|
||||
settings: () => ({ dictionary: { applySiteCorrections: false } }) as any,
|
||||
trainingDir: () => path.join(s.dir, 'training'),
|
||||
overviewExtra: () => ({ guild: null, recording: {} as any }),
|
||||
version: 'test',
|
||||
});
|
||||
|
||||
test('잡음 문장 비교: 띄어쓰기 · 문장부호 · 대소문자를 무시한다 (워커 noise.normalize 와 같게)', () => {
|
||||
assert.equal(normalizePhrase('자막 제공 및 자막을 사용하였습니다.'), '자막제공및자막을사용하였습니다');
|
||||
assert.equal(normalizePhrase(' 자막제공, 및 자막을...사용하였습니다!! '), '자막제공및자막을사용하였습니다');
|
||||
assert.equal(normalizePhrase('MBC 뉴스_이덕영입니다'), 'mbc뉴스이덕영입니다');
|
||||
assert.equal(normalizePhrase('ㅋㅋㅋ'), 'ㅋㅋㅋ');
|
||||
assert.equal(normalizePhrase('... !!'), '');
|
||||
assert.equal(normalizePhrase(null), '');
|
||||
});
|
||||
|
||||
test('거의 같은 문장: 글자 수가 같고(8글자 이상) 15% 이하 글자만 바뀐 것, 짧은 말은 통째로 같을 때만', () => {
|
||||
const n = normalizePhrase;
|
||||
assert.ok(similarPhrase(n('레이드 공 빠졌어 비 사이트로테 하자'), n('레이드 궁 빠졌어 비 사이트로테 하자')));
|
||||
assert.ok(similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 재공 및 자막을 사용하였습니다')));
|
||||
// 배운 잡음 문장 앞뒤에 실제 말이 붙으면 다른 말이다 (지우면 실제 음성을 잃는다)
|
||||
for (const real of ['네', '가자', '아니']) {
|
||||
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n(`자막 제공 및 자막을 사용하였습니다 ${real}`)), `뒤에 "${real}"`);
|
||||
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n(`${real} 자막 제공 및 자막을 사용하였습니다`)), `앞에 "${real}"`);
|
||||
}
|
||||
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 제공 및 자막을 사용했습니다')), '글자 수가 다르면 아니다');
|
||||
assert.ok(!similarPhrase(n('자막 제공 및 자막을 사용하였습니다'), n('자막 제공 및 자막을 사용하였습니다 그리고 레이즈 궁')));
|
||||
assert.ok(!similarPhrase(n('시청해 주셔서'), n('시청해 주셨어')), '8글자 미만은 거의 같아도 아니다');
|
||||
assert.ok(!similarPhrase(n('오늘 저녁 뭐 먹을래'), n('내일 아침 뭐 먹을래')));
|
||||
});
|
||||
|
||||
test('발화 지우기: 관리자 · 말한 사람만, 글 · 음성 · 학습 데이터를 지우고 실시간으로 알린다', async () => {
|
||||
const s = setup();
|
||||
const app = await api(s);
|
||||
const f1 = s.mk('a1', '그냥 말');
|
||||
// 교정해서 학습 데이터가 생긴 발화
|
||||
s.mk('a2', '레이저 궁', '레이저 궁');
|
||||
const patched = await app.inject({ method: 'PATCH', url: '/api/utterances/a2', payload: { text: '레이즈 궁' } });
|
||||
assert.equal(patched.statusCode, 200);
|
||||
const sample = s.store.trainingSamples()[0].audio_path;
|
||||
assert.ok(fs.existsSync(sample));
|
||||
s.mk('a3', '아무 말');
|
||||
|
||||
// 다른 멤버는 못 지운다 (사이트 서버가 붙인 역할 · 유저로 판단)
|
||||
const no = await app.inject({ method: 'POST', url: '/api/utterances/a1/delete', headers: as('m9'), payload: { noise: false } });
|
||||
assert.equal(no.statusCode, 403);
|
||||
assert.ok(s.store.getUtterance('a1'));
|
||||
// 말한 사람 본인
|
||||
const r1 = await app.inject({ method: 'POST', url: '/api/utterances/a1/delete', headers: as('u1'), payload: { noise: false } });
|
||||
assert.equal(r1.statusCode, 200);
|
||||
assert.deepEqual(r1.json(), { ok: true, learned: null });
|
||||
assert.equal(s.store.getUtterance('a1'), undefined);
|
||||
assert.ok(!fs.existsSync(f1));
|
||||
assert.deepEqual(s.live.at(-1), { type: 'utterance.deleted', data: { id: 'a1', noise: false } });
|
||||
// "그냥 삭제"는 아무것도 배우지 않는다
|
||||
assert.equal(s.store.listNoisePhrases().length, 0);
|
||||
// 관리자: 교정 학습 데이터(음성 조각)도 같이 지운다
|
||||
const r2 = await app.inject({ method: 'POST', url: '/api/utterances/a2/delete', headers: as('m9', 'admin'), payload: {} });
|
||||
assert.equal(r2.statusCode, 200);
|
||||
assert.equal(s.store.trainingSamples().length, 0);
|
||||
assert.ok(!fs.existsSync(sample));
|
||||
// 이 PC 안에서 부른 것 (설정 창)
|
||||
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a3/delete', payload: {} })).statusCode, 200);
|
||||
// 이미 지운 발화
|
||||
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a3/delete', payload: {} })).statusCode, 404);
|
||||
// 타임라인에서 빠진다
|
||||
assert.equal((await app.inject({ url: '/api/timeline' })).json().items.length, 0);
|
||||
// 잘못된 사용자 머리글은 거절
|
||||
s.mk('a4', '말');
|
||||
assert.equal((await app.inject({ method: 'POST', url: '/api/utterances/a4/delete', headers: { 'x-gvr-user': '%E0%A4%A' }, payload: {} })).statusCode, 403);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('잡음이라 삭제: 인식 문장을 배우고, 목록 · 지우기 API 로 볼 수 있다', async () => {
|
||||
const s = setup();
|
||||
const app = await api(s);
|
||||
s.mk('n1', '자막 제공 및 자막을 사용하였습니다.');
|
||||
s.mk('n2', null); // 아직 인식 전: 배울 문장 없음
|
||||
const r = await app.inject({ method: 'POST', url: '/api/utterances/n1/delete', headers: as('u1'), payload: { noise: true } });
|
||||
assert.deepEqual(r.json(), { ok: true, learned: '자막 제공 및 자막을 사용하였습니다.' });
|
||||
assert.deepEqual(s.live.at(-1), { type: 'utterance.deleted', data: { id: 'n1', noise: true } });
|
||||
const r2 = await app.inject({ method: 'POST', url: '/api/utterances/n2/delete', headers: as('u1'), payload: { noise: true } });
|
||||
assert.deepEqual(r2.json(), { ok: true, learned: null });
|
||||
const list = (await app.inject({ url: '/api/noise-phrases' })).json().phrases;
|
||||
assert.equal(list.length, 1);
|
||||
assert.equal(list[0].text, '자막 제공 및 자막을 사용하였습니다.');
|
||||
assert.equal(list[0].hits, 0);
|
||||
assert.equal(s.store.listNoisePhrases()[0].phrase, '자막제공및자막을사용하였습니다');
|
||||
// 같은 문장을 또 배우면 하나로
|
||||
s.mk('n3', '자막제공 및 자막을 사용하였습니다');
|
||||
await app.inject({ method: 'POST', url: '/api/utterances/n3/delete', payload: { noise: true } });
|
||||
assert.equal(s.store.listNoisePhrases().length, 1);
|
||||
assert.equal((await app.inject({ method: 'DELETE', url: `/api/noise-phrases/${list[0].id}` })).statusCode, 200);
|
||||
assert.equal((await app.inject({ method: 'DELETE', url: `/api/noise-phrases/${list[0].id}` })).statusCode, 404);
|
||||
assert.equal(s.store.listNoisePhrases().length, 0);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('음성 인식: 배운 잡음 문장과 같으면 잡음으로 숨기고 파일을 지운다 · 변환 중에 지운 발화는 결과를 버린다', async () => {
|
||||
const s = setup();
|
||||
s.store.addNoisePhrase(normalizePhrase('자막 제공 및 자막을 사용하였습니다.'), '자막 제공 및 자막을 사용하였습니다.');
|
||||
const results: Record<string, string> = { p1: '자막 재공 및 자막을 사용하였습니다', p2: '자막 제공 및 자막을 사용하였습니다. 그리고 레이즈 궁', p3: '아무 말' };
|
||||
let hold: (() => void) | null = null;
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string, req: any) => {
|
||||
if (op === 'gpu_info') return { gpus: [] };
|
||||
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
||||
if (op === 'load') return {};
|
||||
const id = path.basename(req.path, '.ogg');
|
||||
if (id === 'p3') await new Promise<void>((r) => (hold = r));
|
||||
const t = results[id];
|
||||
return { text: t, raw_text: t, words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 };
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm', device: 'cpu', computeType: 'int8', gameVramReserveMb: 0, reprocessAfterMatch: false }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
||||
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, s.store, dict, s.timeline, s.bus, settings);
|
||||
await stt.load('realtime', 'm');
|
||||
const f1 = s.mk('p1', null);
|
||||
const f2 = s.mk('p2', null);
|
||||
const f3 = s.mk('p3', null);
|
||||
const wait = async (fn: () => boolean) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > 5000) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
};
|
||||
stt.enqueue('p1', 'realtime');
|
||||
stt.enqueue('p2', 'realtime');
|
||||
await wait(() => s.store.getUtterance('p2')!.status !== 'pending');
|
||||
const p1 = s.store.getUtterance('p1')!;
|
||||
assert.equal(p1.noise, 1);
|
||||
assert.equal(p1.noise_reason, 'learned');
|
||||
assert.equal(p1.text, null);
|
||||
assert.equal(p1.audio_deleted, 1);
|
||||
assert.ok(!fs.existsSync(f1));
|
||||
assert.equal(s.store.listNoisePhrases()[0].hits, 1, '한두 글자 다른 문장도 거른다');
|
||||
// 문장이 더 붙으면 다른 말이다: 음성 · 글을 그대로 둔다
|
||||
const p2 = s.store.getUtterance('p2')!;
|
||||
assert.equal(p2.noise, 0);
|
||||
assert.ok(fs.existsSync(f2));
|
||||
for (const [i, real] of ['네', '가자', '아니'].entries()) {
|
||||
const id = `r${i}`;
|
||||
results[id] = `자막 제공 및 자막을 사용하였습니다. ${real}`;
|
||||
const f = s.mk(id, null);
|
||||
stt.enqueue(id, 'realtime');
|
||||
await wait(() => s.store.getUtterance(id)!.status !== 'pending');
|
||||
const u = s.store.getUtterance(id)!;
|
||||
assert.equal(u.noise, 0, `뒤에 "${real}" 이 붙은 발화는 잡음이 아니다`);
|
||||
assert.equal(u.text, results[id]);
|
||||
assert.ok(fs.existsSync(f), `뒤에 "${real}" 이 붙은 발화의 음성은 남는다`);
|
||||
}
|
||||
assert.equal(s.store.listNoisePhrases()[0].hits, 1);
|
||||
// 변환하는 동안 지우면 결과를 DB 에 되살리지 않는다
|
||||
stt.enqueue('p3', 'realtime');
|
||||
await wait(() => !!hold);
|
||||
s.store.deleteUtterance('p3');
|
||||
const gainN = s.store.getUser('u1')!.gain_n;
|
||||
hold!();
|
||||
await wait(() => !stt.isBusy('p3'));
|
||||
assert.equal(s.store.getUser('u1')!.gain_n, gainN, '지운 발화의 음량은 평소 음량에 넣지 않는다');
|
||||
assert.equal(s.store.getUtterance('p3'), undefined);
|
||||
assert.ok(!s.live.some((e) => e.type === 'utterance.updated' && e.data.id === 'p3'));
|
||||
assert.ok(fs.existsSync(f3), 'store.deleteUtterance 는 파일을 직접 지우지 않는다 (API 가 지움)');
|
||||
});
|
||||
@@ -114,6 +114,7 @@ GVR-Data/
|
||||
- `game_events(id PK, match_id, game, type, ts INT ms(real), game_time_ms, round, actor_puuid, target_puuid, data JSON)`
|
||||
- `dictionary(id PK, word, pack, kind ('hotword'|'correction'), from_text, source ('builtin'|'user'|'site'), enabled)`
|
||||
- `training_samples(id PK, utterance_id, text, audio_path, used INT, created_at)`
|
||||
- `noise_phrases(id PK, phrase UNIQUE (띄어쓰기 · 문장부호 뺀 값), sample, hits, created_at)` — "잡음이라 삭제"로 배운 문장 (v1.4.0)
|
||||
|
||||
## 4. 앱 HTTP API (코어 Fastify, 127.0.0.1) — 사이트 서버가 그대로 중계
|
||||
|
||||
@@ -131,6 +132,9 @@ GVR-Data/
|
||||
| GET | `/api/matches/:id` | `MatchDetail` |
|
||||
| PATCH | `/api/utterances/:id` | `{text}` → 교정 저장, 교정 사전·학습 데이터 반영. 응답 `TimelineItem` |
|
||||
| GET | `/api/dictionary` | 사전 목록 |
|
||||
| POST | `/api/utterances/:id/delete` | `{noise}` → 발화 · 음성 · 학습 데이터 지우기 (관리자 · 말한 사람). noise=true 면 문장을 잡음으로 배움. 응답 `{ok, learned}`, 실시간 `utterance.deleted` |
|
||||
| GET | `/api/noise-phrases` | `{phrases:[{id,text,hits,createdAt}]}` 잡음으로 배운 문장 |
|
||||
| DELETE | `/api/noise-phrases/:id` | 배운 문장 지우기 |
|
||||
|
||||
`/api/timeline` 쿼리: `users=a,b` · `game=valorant|lol|none` · `match=<id>` · `from=<ms>&to=<ms>` ·
|
||||
`q=<키워드>` · `types=utterance,kill,chat,object,round` · `hideNoise=1` · `cursor=<opaque>` · `limit=100` ·
|
||||
@@ -196,7 +200,7 @@ type TimelineItem =
|
||||
| Path | 설명 |
|
||||
|---|---|
|
||||
| `GET /auth/discord` | OAuth2 시작 (`identify guilds`) |
|
||||
| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키 |
|
||||
| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키. GUILD_ID = 게임 PC 앱에서 녹음할 서버로 고른 서버 (앱이 hello 로 알려 줌, 그 전에는 ALLOWED_GUILD_IDS). 아니면 `/?login=not_member` ("봇과 다른 서버") |
|
||||
| `POST /auth/logout` | |
|
||||
| `GET /auth/me` | `{user:{id,name,avatar}, isOwner}` 또는 401 |
|
||||
| `GET /api/status` | `{device:{registered, online, name, lastSeen, version}, server:{version}}` (로그인 필요) |
|
||||
@@ -212,6 +216,8 @@ type TimelineItem =
|
||||
| `GET /app/admin/users` | 관리자 이상 → `{users: AppUserRow[]}` (최고 관리자 고정 행 포함) |
|
||||
| `POST /app/admin/users` · `PATCH`/`DELETE /app/admin/users/:id` | 최고 관리자만: 등록(`{id, role:'admin'|'user'}`, 디스코드에서 계정 확인) · 역할 변경 · 등록 해제 |
|
||||
| `GET /game-assets/<source>/<path>` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 |
|
||||
| `GET /auth/guild` | 로그인 화면 안내용 `{name}`: 들어올 수 있는 서버 이름 |
|
||||
| `GET /site/maps3d` · `GET /site/maps3d/:dir/:code.glb` | 로그인 필요. 발로란트 맵 3D (data/maps3d, `tools/map-extract`). glb 는 gzip 그대로 보낸다 |
|
||||
|
||||
## 8. 겜녹이 봇 중계 (v1.2.1~)
|
||||
|
||||
|
||||
45
docs/dev/replay-3d.md
Normal file
45
docs/dev/replay-3d.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# 3D 리플레이 · 대화 동기화 (작업 노트, 2026-10-17)
|
||||
|
||||
## 결론 (조사)
|
||||
- 발로란트는 리플레이 재생 위치를 주는 API가 없다 (로컬 API는 "리플레이 보는 중"까지). 2026-10-17 사용자 ShooterGame.log 에도 재생 위치는 없다 (열기 · 닫기 · 매치 ID · 시간 옮길 때 선수 재생성만 남음).
|
||||
- 그래서 인게임 리플레이를 따라가지 않고, `.vrf` 를 풀어 **사이트에서 재생**한다. 대화는 사이트 플레이어 "현장 모드" 시계(sceneTs)에 묶여 재생 · 멈춤 · 이동 · 배속이 같이 움직인다.
|
||||
|
||||
## 구성
|
||||
- `tools/replay-extract/` (C#, net10): ValorantReplayParser(MIT, `fetch-parser.sh` 로 고정 커밋을 vendor/ 에 받음) → `gvr-replay` JSON v1
|
||||
- 선수 10명 이동 10Hz (x,y,z,yaw,pitch) · 라운드(구매/교전/끝) · 킬 · 사격 · 스킬/설치물(스파이크 TimedBomb_C 포함) · `recordedAt`(녹화 시작, ReplayInfo.Timestamp)
|
||||
- 13.08 실제 경기(73.8MB): 6초, JSON 5.3MB / gzip 1.4MB, 진단 0
|
||||
- 사이트 `site/web/src/lib/replay.ts` (동기화 · 보간 · 죽음 판정), `components/ReplayViewer.tsx` (three.js, 지연 로드), `ReplayPanel.tsx`
|
||||
- 동기화: `ts = recordedAt + t + offset`, offset = 같은 킬(죽인/죽은 puuid)의 경기 기록 ts − 리플레이 시각의 중앙값. 킬이 3개 미만이면 라운드 교전 시작으로.
|
||||
- 3D: 맵 3D 모양(아래 "맵 3D") 위에 선수를 실제 높이로. 맵 3D 가 없으면 미니맵 바닥
|
||||
- 목 서버: `GVR_MOCK_REPLAY=<json> GVR_MOCK_REPLAY_MAP_FILE=<어비스 png> npm run dev` → `/matches/val-replay-demo` (경기 기록 킬을 1234ms 늦게 찍어 동기화 확인)
|
||||
|
||||
## 맵 3D (2026-10-17, 모든 맵)
|
||||
- `tools/map-extract/` (C#, CUE4Parse 고정 커밋 `fetch-cue4parse.sh`): **게임 파일을 받지 않고** Riot CDN 번들에서 필요한 조각만 HTTP Range 로 읽는다 (매니페스트 RMAN 파싱 `src/Rman.cs`, 원격 임의 읽기 `src/Cdn.cs`, 메모리 캐시 1.5GB, 디스크 안 씀).
|
||||
- 맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록 맵 경로 `/Game/Maps/Ascent/Ascent` 와 같다). 하위 레벨 중 `LevelStreamingAlwaysLoaded` 이고 이름이 빛 · 소리 · 게임 규칙 · 부피 · 먼 배경 · 이벤트 장식이 아닌 것만 (`MapScene.NotVisual`).
|
||||
- StaticMesh(+인스턴스) 가장 낮은 LOD 를 월드 좌표(cm)로 구워 맵마다 glb 하나 (위치 + 삼각형만, 재질 없음). 사이트가 높이로 색칠.
|
||||
- 13.08 실측: 22개 맵(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트 1) 3.1분, 받은 양 587MB, 최대 메모리 약 1.9GB. `scripts/pack.py` → gltfpack `-cc` + gzip 으로 맵당 0.5~4.6MB (합계 52MB).
|
||||
- 사이트: 서버 `data/maps3d/index.json` + `<dir>/<code>.glb.gz`, `GET /site/maps3d*` (로그인 필요). 재생기 `lib/map3d.ts` 가 meshopt 로 풀어 리플레이와 같은 좌표 변환 행렬로 놓는다. 맵이 있으면 미니맵 바닥 · 선수 그림자는 숨긴다.
|
||||
- meshopt 는 WebAssembly 라 CSP `script-src` 에 `'wasm-unsafe-eval'` 가 필요하다 (없으면 미니맵으로 대체됨, 헤드리스 크롬으로 둘 다 확인).
|
||||
- 천장 자르기: 자동(고른 선수 · 없으면 가장 높은 산 선수 몸 중심 + 380cm 위를 자름) · 없음 · 직접(슬라이더).
|
||||
- 자동 갱신: `scripts/install.sh` 가 `~/gvr-maps` 에 설치, `gvr-maps-update.timer` 30분마다 `update.sh`: uedb 매핑(버전 · 갱신 시각) 또는 라이브 매니페스트가 바뀌면 매핑을 받아 `~/gvr-maps/mappings/` + nextcloud `claude/game-voice-recorder/valorant/mappings/` 에 보관 → 전체 추출 → .5 `data/maps3d` 에 올리고 index.json 교체 (이전 폴더 1개만 남김). 어느 단계든 실패하면 이전 맵 유지, 같은 조합은 30분 · 1 · 2 · 4 · 6시간 간격으로 재시도 (첫 실패 · 성공 때 이 방 채널에 한 줄 알림, uedb/패치 확인 자체는 6번 연속 실패 때 알림). 지금 사이트에 있는 맵이 하나라도 새 결과에 없으면 올리지 않는다 (추출기도 맵 찾기 중 레벨 읽기 실패를 실패로 친다). 강제(대기 · 누락 검사 무시): `~/gvr-maps/scripts/update.sh --force`. 시험: `scripts/test-update.sh`.
|
||||
|
||||
## 남은 일
|
||||
1. 앱: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<matchId>.vrf` 찾기 → `gvr-replay.exe` 실행 → `GVR-Data/replays/<matchId>.json.gz` → `GET /api/matches/:id/replay` (content-encoding gzip, 사이트는 /api/* 그대로 중계)
|
||||
2. 빌드: win-ci 에 .NET SDK 설치 · `dotnet publish -r win-x64` 단일 파일 → electron-builder extraResources `replay/`
|
||||
3. 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
|
||||
|
||||
## 완전 3D (맵 · 캐릭터 · 총 · 효과) 조사 (2026-10-17)
|
||||
- 게임 파일: Riot CDN 에서 바로 받을 수 있다 (게임 PC 불필요). 매니페스트는
|
||||
`https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines` 의 `*.manifest`,
|
||||
받기는 Morilli/ManifestDownloader (`-b https://valorant.secure.dyn.riotcdn.net/channels/public/bundles --no-langs -f 'ShooterGame/Content/Paks/(pakchunk|global)'`), 13.08 기준 34GB · 10분.
|
||||
- 열기: CUE4Parse (`EGame.GAME_Valorant`, 공개 AES 키, 리눅스 Oodle 자동 다운로드) → 파일 396,466개, `Maps/Infinity/*.umap` 확인.
|
||||
- 매핑: 13.08 부터 패키지가 unversioned → `.usmap` 필요. **공개 배포처가 있다**: `https://uedb.dev/svc/api/v1/valorant/mappings` (패치별 JSON → Brotli/ZStandard usmap URL, 13.08 은 2026-10-16 갱신), AES 는 `.../valorant/aes`. 출처: sinnafuls/cue4parse-mcp `games.example.json`.
|
||||
- 이전에 시도한 다른 게임 매핑(Remnant2 등)은 틀린 매핑이라 배열 길이를 잘못 읽어 메모리가 폭주했다 (17.6GB). 올바른 매핑으로는 어비스 전체 읽기 최대 1.3GB · 9초.
|
||||
- Uiana-MapImporter(djhaled) 는 UE4 시절(2023, 매핑 불필요) 코드라 그대로는 안 됨 (발로란트 UE5.3 전환은 11.02).
|
||||
- 어비스 결과 (2026-10-17): `Maps/Infinity/Infinity_Art_*.umap` 17개 → StaticMesh 컴포넌트 2,237 + ISM 인스턴스 1,833 = 배치 3,632, 고유 메시 991 (전부 pakchunk0/1 안, 받기 11GB · 3분), 삼각형 136만 (최저 LOD). glb 146MB.
|
||||
- 좌표: 리플레이 선수 x,y,z 와 맵 월드 좌표(UE cm)가 변환 없이 일치 (선수 점이 통로 위에만 찍힘). glb 는 (x,z,y)*0.01 로 저장되므로 되돌릴 때 주의.
|
||||
- 위에서 볼 때 지붕을 걸러야 한다 (Z 1500cm 이상 삼각형 제외로 미리보기 확인).
|
||||
- 추출기: `~/work/valoexp` (CUE4Parse, 명령 `where/deps/scene/export`), 합성 · 미리보기 `~/work/valomap/tools/compose.py`. CUE4Parse glTF 내보내기가 리눅스에서 `\` 경로로 파일을 쓰는 버그가 있어 옮겨야 함.
|
||||
- 보관: nextcloud `claude/game-voice-recorder/valorant/13.08/` (nextcloud 에서는 `claude/` 폴더 안만 다룬다, 사용자 규칙) (abyss-13.08.tar.gz = glb · scene.json · 미리보기 · usmap · 도구 사본, usmap 단독). 계정은 secrets `nextcloud.192.168.10.10`.
|
||||
- 실험은 반드시 `systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0` 안에서.
|
||||
- 디스크: .9 는 150GB 이상 비워 둔다 (사용자 요청). 게임 파일은 다시 받을 수 있으므로 지웠다. 큰 결과물은 nextcloud(.10:8080)로 (로그인 정보 필요).
|
||||
@@ -228,3 +228,47 @@ VOICE E2E PASS
|
||||
- 이름 규칙 `날짜_시각_말한사람_게임_모드_맵_라운드_발화ID.ogg` (롤은 게임 시간, 경기 밖은 `경기밖`). 테스트 `audio-names.test.ts`: 이름 만들기 · Windows 금지 글자, 실제 파일 바꾸기, 경기 중 지금 라운드 → 경기 뒤 라운드 표로 다시 맞춤, 음성 인식 중이면 건드리지 않음, 표시 이름 바뀌면 전체 다시, zip 안 이름 · 받아오기 뒤 이름
|
||||
- 실제 STT 워커 E2E: 변환이 끝난 뒤 파일 이름이 `…_하늘_경기밖_speech.ogg` 로 바뀌고 자세한 정보 경로도 같음
|
||||
- 사용자 데이터 사본: 21개 이름 바꿈 (`2026-10-16_04-05-52_사금향_발로란트_데스매치_어비스_0mv9wsvgh48a56ebde5.ogg`, 데스매치는 라운드 없음, 경기 전후는 `경기밖`)
|
||||
- 배포: 사이트 서버 다시 배포, Windows CI (249ead8, full) 7개 모두 PASS · 앱 버전 1.3.8 → Gitea 릴리스 v1.3.8 (v1.3.7 에 새 버전 안내)
|
||||
|
||||
## v1.3.9 — 받아오기: 이름 안의 ".." (2026-10-16)
|
||||
|
||||
- 원인: 받아오기 검사가 zip 안 음성 파일 이름에 `..` 이 있으면 거절했다. v1.3.8 부터 파일 이름에 표시 이름이 들어가므로 `하늘..별` 같은 이름이면 내보낸 zip 을 다시 넣지 못했다 (백업 뒤 지우면 되살릴 수 없음)
|
||||
- 고침: zip 안 이름은 zip 에서 꺼낼 열쇠로만 쓰고, 이 PC 에 쓰는 경로는 발화 ID 로 만든다. 폴더 구분자만 막는다
|
||||
- 테스트: `audio-names.test.ts` "표시 이름에 .. 이 있어도 내보내기 → 지우기 → 받아오기" (예전 코드에서 실패 확인 뒤 고침), "폴더를 넘나드는 zip 안 이름(audio/../, audio/..\, audio/sub/, ../)은 막는다". 앱 57 통과
|
||||
- 배포: Windows CI (55ec58f, full) 7개 모두 PASS · 앱 버전 1.3.9 → Gitea 릴리스 v1.3.9 (v1.3.8 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
|
||||
|
||||
## v1.4.0 — 발화 우클릭 삭제 · 잡음 문장 배우기 · 알림 기본 끄기 (2026-10-16)
|
||||
|
||||
- 사이트 우클릭 → 삭제… → "잡음이라 삭제" / "그냥 삭제" / 취소. 관리자 · 말한 사람만 (사이트 서버가 붙인 역할 · 유저로 앱이 확인)
|
||||
- 테스트 `utterance-delete.test.ts`: 다른 멤버 403 · 본인 · 관리자 · 이 PC 안에서는 지움, 글 · 음성 · 교정 학습 음성 조각까지 지움, `utterance.deleted` 실시간 이벤트, 이미 지운 발화 404, 잘못된 사용자 머리글 403. 잡음이라 삭제 → 문장 배움(같은 문장은 하나로) · 목록 · 지우기. 음성 인식: 배운 문장과 같거나 거의 같으면(`…사용하였습니다` / `…사용했습니다`) 잡음 · 파일 삭제, 문장이 더 붙으면 그대로, 변환하는 동안 지운 발화는 결과 · 평소 음량에 넣지 않음 (이 확인을 빼면 실패하는 것 확인)
|
||||
- 실제 STT 워커 E2E: "잡음이라 삭제"한 녹음을 다시 넣으니 인식이 한 글자 달랐다 ("레이드 공 빠졌어…" → "레이드 궁 빠졌어…", 교정 사전이 바뀌어 핫워드가 달라짐). 그래서 통째로 같을 때만이 아니라 8글자 이상이면 15% 안 글자 차이까지 같은 문장으로 본다 → `learned` 잡음, 파일 삭제, 타임라인에서 빠짐
|
||||
- 사이트(목 서버 + 실제 빌드, 브라우저): 우클릭 메뉴 삭제 → 확인 창 → 잡음이라 삭제 → 줄이 사라지고 "앞으로 … 는 잡음으로 거릅니다", 단어사전 "잡음으로 배운 문장"에 추가. 인식된 글이 없으면 "잡음이라 삭제" 꺼짐. 효과음: 저장된 설정이 없으면 새 기본값, 예전 설정(전부 켜짐)은 두 알림만 한 번 끄고, 그 뒤 다시 켠 것은 그대로
|
||||
- 테스트: 앱 62 · 사이트 서버 16 · 워커 42 통과, 앱 · 화면 · 서버 타입 검사 통과
|
||||
- 배포: 사이트 서버 다시 배포 (배포된 화면 번들에 "잡음이라 삭제" · `noise-phrases` 확인), Windows CI (3115337, full) 7개 모두 PASS · 앱 버전 1.4.0 → Gitea 릴리스 v1.4.0 (v1.3.9 에 새 버전 안내)
|
||||
|
||||
## v1.4.1 — 잡음 문장 비교: 앞뒤에 붙은 실제 말은 지우지 않음 (2026-10-16)
|
||||
|
||||
- 원인: v1.4.0 의 "거의 같은 문장"이 편집 거리 15% 였다. 배운 문장 `자막 제공 및 자막을 사용하였습니다`(15글자) 뒤에 `네` · `가자` · `아니`가 붙어도 거리 1~2 라 잡음으로 지워 실제 음성을 잃었다
|
||||
- 고침: 글자 수가 같고(8글자 이상) 바뀐 글자가 15% 이하일 때만 (실제 엔진에서 본 "레이드 공" / "레이드 궁" 은 그대로 잡음). 글자가 붙거나 빠지면 다른 말
|
||||
- 테스트 `utterance-delete.test.ts`: 앞뒤에 `네` · `가자` · `아니`를 붙인 문장은 비슷하지 않음, 음성 인식에서 그 발화들의 글 · 음성 파일이 남음 (v1.4.0 코드에서 실패 확인 뒤 고침)
|
||||
- 배포: 사이트 서버 다시 배포 (바뀐 안내 문구 확인), Windows CI (df0c826, full) 7개 모두 PASS · 앱 버전 1.4.1 → Gitea 릴리스 v1.4.1 (v1.4.0 에 새 버전 안내). 실제 STT 워커 E2E 에서 "레이드 공/궁" 은 그대로 learned 잡음
|
||||
|
||||
## v1.4.2 — 녹음 중에 들어온 사람이 "알 수 없음"으로 뜨던 문제 (2026-10-16)
|
||||
|
||||
- 원인: 녹음 시작 때 채널에 있던 사람만 `users.updated` 를 보냈다. 녹음 중에 들어온 사람은 `onVoiceState` 에서 DB 에 저장만 하고 알리지 않아, 사이트의 유저 목록에 없어 발화가 "알 수 없음"으로 떴다 (새로고침하면 보임)
|
||||
- 고침: 앱은 들어올 때 `users.updated` 를 보낸다. 사이트는 `utterance.created/updated` · `recording.state` 에 모르는 아이디가 오면 `/api/users` 를 한 번 다시 받는다 (같은 아이디는 한 번만)
|
||||
- 테스트 `core.test.ts` "녹음 중에 들어온 사람": 고치기 전 코드에서 실패(users.updated 0번) 확인 뒤 통과
|
||||
- 사이트(목 서버 `/mock/latejoin`, 브라우저): 고치기 전 화면은 새 발화 2곳이 "알 수 없음", 고친 화면은 이름이 바로 뜨고 왼쪽 유저 목록에도 추가
|
||||
- 테스트: 앱 63 · 사이트 서버 16 통과, 앱 · 화면 · 서버 타입 검사 · 화면 빌드 통과
|
||||
- 배포: 사이트 서버 다시 배포 (배포된 화면 번들 `index-Cbz_E9Kc.js` 에 모르는 아이디 다시 받기 확인), Windows CI (79d6bb2, full) 7개 모두 PASS · 앱 버전 1.4.2 → Gitea 릴리스 v1.4.2 (v1.4.1 에 새 버전 안내)
|
||||
- 보완 (사이트만): 모르는 아이디를 받기 전에 영구히 기억해서 `/api/users` 가 한 번 실패하면 그 사람은 계속 "알 수 없음"이었다. `site/web/src/lib/unknown-users.ts` 로 빼서, 받는 중에는 또 부르지 않고 실패하면 다음 이벤트에서 다시 받는다 (성공한 아이디만 기억). 테스트 `site/server/test/unknown-users.test.ts` 2개. 목 서버 `/mock/users-fail?n=1` + `/mock/latejoin?again=1`: 고치기 전 화면은 요청 1번에 이름 없음, 고친 화면은 다음 발화에서 다시 받아 이름 표시
|
||||
- 테스트: 앱 63 · 사이트 서버 18 통과, 앱 · 화면 · 서버 타입 검사 · 화면 빌드 통과. 앱 코드는 그대로라 v1.4.2 릴리스는 그대로
|
||||
|
||||
## v1.4.3 — 상대 닉네임을 말로 적던 문제 (2026-10-17)
|
||||
|
||||
- 증상: 사이트 대화에 "QQQWWWQ" 라는 말이 여러 사람 발화로 뜸. 같은 경기 상대 선수 이름이 "QQQWWWQQQ"
|
||||
- 원인: `pipeline.ts` `matchWords` 가 그 경기 10명의 선수 이름을 핫워드 맨 앞에 넣었다. 말을 못 알아들으면 Whisper 가 핫워드를 그대로 적는데, 기존 되풀이 확인(`is_hotword_echo`)은 3단어 이상만 봐서 이름 하나(조각)는 지나갔다
|
||||
- 고침: 선수 이름은 한글이 들어간 것만 핫워드로. 결과가 선수 이름(조각)뿐이면 워커가 이름을 빼고 다시 변환. 예전 발화는 한 번만 다시 변환(파일 없으면 숨김, 고친 발화 제외)
|
||||
- 테스트: 워커 `test_hotword_echo.py` 이름 되풀이 3개, 앱 `name-echo.test.ts` 3개(판정 · 핫워드에 영문 닉네임 빠짐 · 예전 발화 다시 보기 한 번만)
|
||||
- 실제 모델(faster-whisper small, CPU): 실제 말소리 · 키보드 · 잡음 파일에 영문 닉네임 핫워드를 넣어도 정상, 결과 전체를 선수 이름으로 준 경우 되풀이로 잡고 이름 없이 다시 변환해 실제 말을 돌려줌
|
||||
- 배포: Windows CI (010d247, full) 7개 모두 PASS · 앱 버전 1.4.3 → Gitea 릴리스 v1.4.3 (v1.4.2 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
|
||||
|
||||
@@ -427,7 +427,18 @@ export type LiveEvent =
|
||||
| { type: 'recording.state'; data: Overview['recording'] }
|
||||
| { type: 'users.updated'; data: User[] }
|
||||
| { type: 'games.state'; data: LiveGame[] }
|
||||
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } };
|
||||
| { type: 'records.changed'; data: { reason: 'deleted' | 'imported'; ids?: string[] } }
|
||||
/** 사이트 우클릭으로 발화 하나를 지움 (v1.4.0). noise = "잡음이라 삭제" */
|
||||
| { type: 'utterance.deleted'; data: { id: string; noise: boolean } };
|
||||
|
||||
/** "잡음이라 삭제"로 배운 문장 (GET /api/noise-phrases) */
|
||||
export interface NoisePhrase {
|
||||
id: number;
|
||||
text: string;
|
||||
/** 그 뒤로 이 문장을 잡음으로 걸러 낸 횟수 */
|
||||
hits: number;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export interface DeviceStatus {
|
||||
registered: boolean;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { BotBroker, type BotSource } from './bot-broker.js';
|
||||
import { registerCulprit, type ModelCall } from './culprit.js';
|
||||
import type { KnowledgeAuto } from './culprit-prompt.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { registerMaps3d } from './maps3d.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { SiteLog } from './site-log.js';
|
||||
@@ -21,7 +22,7 @@ const RECHECK_MS = 10 * 60000;
|
||||
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
|
||||
export async function buildServer(
|
||||
cfg: Config,
|
||||
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean } = {},
|
||||
opts: { botSource?: BotSource; botRecheckMs?: number; culpritCall?: ModelCall; culpritKnowledge?: KnowledgeAuto; logEcho?: boolean; browserRecheckMs?: number } = {},
|
||||
) {
|
||||
// 사이트 로그: 날짜별 파일(data/logs/site-날짜.log)로 남기고 관리자가 사이트에서 본다. 게임 PC 가 꺼져 있어도 볼 수 있다
|
||||
const siteLog = new SiteLog(path.join(cfg.dataDir, 'logs'), { echo: opts.logEcho ?? true });
|
||||
@@ -50,10 +51,11 @@ export async function buildServer(
|
||||
|
||||
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
|
||||
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
|
||||
// 'wasm-unsafe-eval': 맵 3D 압축 풀기(meshopt, WebAssembly)만 허용. 자바스크립트 eval 은 여전히 막힌다
|
||||
const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws');
|
||||
const csp = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"script-src 'self' 'wasm-unsafe-eval'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob: https://cdn.discordapp.com",
|
||||
"media-src 'self' blob: data:",
|
||||
@@ -71,11 +73,11 @@ export async function buildServer(
|
||||
return payload;
|
||||
});
|
||||
|
||||
/** 사이트에 들어올 수 있는 서버: 게임 PC 앱에서 녹음할 서버로 고른 곳 하나.
|
||||
* 앱이 아직 한 번도 알려 주지 않았을 때만 ALLOWED_GUILD_IDS 를 쓴다 */
|
||||
const allowedGuilds = (): string[] => {
|
||||
const g = new Set(cfg.allowedGuilds);
|
||||
const dg = store.device()?.guildId;
|
||||
if (dg) g.add(dg);
|
||||
return [...g];
|
||||
return dg ? [dg] : cfg.allowedGuilds;
|
||||
};
|
||||
|
||||
/** 세션 확인. 10분마다 서버 멤버인지 다시 확인 (서버에서 나가면 바로 막힘) */
|
||||
@@ -191,11 +193,20 @@ export async function buildServer(
|
||||
}
|
||||
});
|
||||
|
||||
/** 로그인 화면: 들어올 수 있는 서버 이름 (봇과 같은 서버) */
|
||||
app.get('/auth/guild', async () => {
|
||||
const g = allowedGuilds()[0];
|
||||
return { name: g ? await discord.guildName(g) : null };
|
||||
});
|
||||
|
||||
app.post('/auth/logout', async (req, reply) => {
|
||||
const raw = req.cookies[SID];
|
||||
const un = raw ? req.unsignCookie(raw) : null;
|
||||
const s = un?.valid && un.value ? store.session(un.value) : null;
|
||||
if (s) store.deleteSession(s.id);
|
||||
if (s) {
|
||||
store.deleteSession(s.id);
|
||||
hub.closeSession(s.id);
|
||||
}
|
||||
reply.clearCookie(SID, { path: '/' });
|
||||
return { ok: true };
|
||||
});
|
||||
@@ -290,6 +301,9 @@ export async function buildServer(
|
||||
return reply.send(buf);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요)
|
||||
registerMaps3d(app, cfg.dataDir, requireSession);
|
||||
|
||||
app.get('/healthz', async () => 'ok\n');
|
||||
|
||||
// ------------------------------------------------------------------ 사이트 화면
|
||||
@@ -341,7 +355,8 @@ export async function buildServer(
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
return socket.destroy();
|
||||
}
|
||||
hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws));
|
||||
// 연결한 뒤에도 세션 삭제 · 로그아웃 · 서버 탈퇴(getSession 이 10분마다 확인)면 끊는다
|
||||
hub.browserWss.handleUpgrade(req, socket, head, (ws) => hub.attachBrowser(ws, s.id, async () => !!(await getSession(fakeReq)), opts.browserRecheckMs));
|
||||
return;
|
||||
}
|
||||
socket.destroy();
|
||||
|
||||
@@ -52,6 +52,22 @@ export class DiscordApi {
|
||||
const m: any = await r.json();
|
||||
return { nick: m.nick ?? null, avatar: m.avatar ?? null };
|
||||
}
|
||||
|
||||
private guildNames = new Map<string, { name: string | null; at: number }>();
|
||||
/** 서버 이름 (로그인 화면 안내용, 10분 캐시). 모르면 null */
|
||||
async guildName(guildId: string): Promise<string | null> {
|
||||
const c = this.guildNames.get(guildId);
|
||||
if (c && Date.now() - c.at < 600_000) return c.name;
|
||||
let name: string | null = null;
|
||||
try {
|
||||
const r = await fetch(`${this.cfg.discordApi}/guilds/${guildId}`, { headers: { authorization: `Bot ${this.cfg.botToken}` } });
|
||||
if (r.ok) name = ((await r.json()) as { name?: string }).name ?? null;
|
||||
} catch {
|
||||
/* 디스코드 장애면 이름 없이 안내 */
|
||||
}
|
||||
this.guildNames.set(guildId, { name, at: Date.now() });
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
/** 봇 토큰으로 디스코드 계정 조회 (유저 등록 때 이름 확인). 없는 아이디면 null */
|
||||
|
||||
63
site/server/src/maps3d.ts
Normal file
63
site/server/src/maps3d.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
|
||||
/**
|
||||
* 발로란트 맵 3D 모양 (tools/map-extract 가 Riot CDN 에서 뽑아 tools/map-extract/scripts/update.sh 가 올린다).
|
||||
* 게임 파일에서 나온 것이라 로그인한 사람(봇과 같은 서버 멤버)에게만 준다.
|
||||
*
|
||||
* <dataDir>/maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}}
|
||||
* <dataDir>/maps3d/<dir>/<code>.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm)
|
||||
*
|
||||
* GET /site/maps3d → index.json (없으면 {maps:{}})
|
||||
* GET /site/maps3d/:dir/:f → glb (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
|
||||
*/
|
||||
export interface Maps3dIndex {
|
||||
version: string;
|
||||
dir: string;
|
||||
updatedAt: string;
|
||||
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
|
||||
}
|
||||
|
||||
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>) {
|
||||
const root = path.join(dataDir, 'maps3d');
|
||||
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
|
||||
const index = (): Maps3dIndex | null => {
|
||||
const f = path.join(root, 'index.json');
|
||||
let st: fs.Stats;
|
||||
try {
|
||||
st = fs.statSync(f);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (st.mtimeMs !== cache.mtime) {
|
||||
try {
|
||||
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(f, 'utf8')) as Maps3dIndex };
|
||||
} catch {
|
||||
cache = { mtime: st.mtimeMs, data: null };
|
||||
}
|
||||
}
|
||||
return cache.data;
|
||||
};
|
||||
|
||||
app.get('/site/maps3d', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
reply.header('cache-control', 'private, no-cache');
|
||||
return index() ?? { version: null, dir: null, maps: {} };
|
||||
});
|
||||
|
||||
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
const { dir, file } = req.params;
|
||||
if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+\.glb$/.test(file) || dir.includes('..')) return reply.code(404).send({ error: 'not_found' });
|
||||
const gz = path.join(root, dir, file + '.gz');
|
||||
if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' });
|
||||
reply.header('cache-control', 'private, max-age=31536000, immutable').type('model/gltf-binary');
|
||||
if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) {
|
||||
reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size);
|
||||
return reply.send(fs.createReadStream(gz));
|
||||
}
|
||||
return reply.send(fs.createReadStream(gz).pipe(zlib.createGunzip()));
|
||||
});
|
||||
}
|
||||
@@ -30,6 +30,7 @@ export interface RelayResponse {
|
||||
export class RelayHub {
|
||||
private device: { ws: WebSocket; id: string; name: string; version: string | null; lastMsg: number } | null = null;
|
||||
private browsers = new Set<WebSocket>();
|
||||
private browserSessions = new Map<WebSocket, string>();
|
||||
private pending = new Map<string, Pending>();
|
||||
readonly deviceWss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024 });
|
||||
readonly browserWss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
|
||||
@@ -224,17 +225,38 @@ export class RelayHub {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 브라우저
|
||||
attachBrowser(ws: WebSocket): void {
|
||||
/**
|
||||
* sessionId: 로그아웃하면 바로 끊는다 (closeSession).
|
||||
* stillAllowed: 주기적으로(기본 30초) 세션이 살아 있고 봇과 같은 서버 멤버인지 다시 확인해, 아니면 4401 로 끊는다
|
||||
*/
|
||||
attachBrowser(ws: WebSocket, sessionId?: string, stillAllowed?: () => Promise<boolean>, recheckMs = 30000): void {
|
||||
this.browsers.add(ws);
|
||||
if (sessionId) this.browserSessions.set(ws, sessionId);
|
||||
ws.send(JSON.stringify({ type: 'status', data: { device: this.status() } } satisfies BrowserMessage));
|
||||
const ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.ping(), 25000);
|
||||
const recheck = stillAllowed
|
||||
? setInterval(() => {
|
||||
void stillAllowed()
|
||||
.catch(() => true) // 확인 자체가 실패하면(디스코드 장애) 유지
|
||||
.then((ok) => {
|
||||
if (!ok && ws.readyState === WebSocket.OPEN) ws.close(4401, 'unauthorized');
|
||||
});
|
||||
}, recheckMs)
|
||||
: null;
|
||||
ws.on('close', () => {
|
||||
clearInterval(ping);
|
||||
if (recheck) clearInterval(recheck);
|
||||
this.browsers.delete(ws);
|
||||
this.browserSessions.delete(ws);
|
||||
});
|
||||
ws.on('message', () => undefined);
|
||||
}
|
||||
|
||||
/** 로그아웃: 그 세션의 실시간 연결을 끊는다 */
|
||||
closeSession(sessionId: string): void {
|
||||
for (const [ws, sid] of this.browserSessions) if (sid === sessionId) ws.close(4401, 'logged_out');
|
||||
}
|
||||
|
||||
/** 로그아웃·세션 만료 시 해당 브라우저 연결 끊기용 */
|
||||
get browserCount(): number {
|
||||
return this.browsers.size;
|
||||
|
||||
71
site/server/test/login-guild.test.ts
Normal file
71
site/server/test/login-guild.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
// 사이트 로그인: 게임 PC 앱에서 녹음할 서버로 고른 서버의 멤버만 들어온다.
|
||||
// 앱이 서버를 알려 주기 전에만 ALLOWED_GUILD_IDS 를 쓴다.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { buildServer } from '../src/app.ts';
|
||||
import type { Config } from '../src/config.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-guild-'));
|
||||
|
||||
// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버"
|
||||
async function fakeDiscord() {
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url!, 'http://x');
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' }));
|
||||
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
|
||||
if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
|
||||
if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' }));
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
});
|
||||
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
|
||||
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
|
||||
}
|
||||
|
||||
async function stack() {
|
||||
const dc = await fakeDiscord();
|
||||
const cfg: Config = {
|
||||
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
|
||||
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
|
||||
version: 'test', discordApi: dc.url, assetUpstream: {},
|
||||
};
|
||||
const { app, store } = await buildServer(cfg);
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
const login = async () => {
|
||||
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
||||
return cb.headers.get('location');
|
||||
};
|
||||
return { base, store, login, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('로그인: 앱이 서버를 알려 주기 전에는 ALLOWED_GUILD_IDS 멤버가 들어온다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
assert.equal(await s.login(), '/');
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('로그인: 앱에서 고른 서버의 멤버가 아니면 (ALLOWED_GUILD_IDS 멤버라도) 봇과 다른 서버라 막는다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const { code } = s.store.createCode('owner');
|
||||
const dev = s.store.redeem(code, 'PC')!;
|
||||
s.store.touchDevice(dev.deviceId, { guildId: '222' });
|
||||
assert.equal(await s.login(), '/?login=not_member');
|
||||
// 로그인 화면은 그 서버 이름으로 안내한다
|
||||
const g = await (await fetch(s.base + '/auth/guild')).json();
|
||||
assert.deepEqual(g, { name: '앱 서버' });
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
80
site/server/test/maps3d.test.ts
Normal file
80
site/server/test/maps3d.test.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
// 맵 3D (/site/maps3d): 로그인한 사람에게만, gzip 그대로 보낸다
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { buildServer } from '../src/app.ts';
|
||||
import type { Config } from '../src/config.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-maps3d-'));
|
||||
|
||||
// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버"
|
||||
async function fakeDiscord() {
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url!, 'http://x');
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' }));
|
||||
if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null }));
|
||||
if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null }));
|
||||
if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' }));
|
||||
res.statusCode = 404;
|
||||
res.end('{}');
|
||||
});
|
||||
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
|
||||
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
|
||||
}
|
||||
|
||||
async function stack() {
|
||||
const dc = await fakeDiscord();
|
||||
const cfg: Config = {
|
||||
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
|
||||
allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
|
||||
version: 'test', discordApi: dc.url, assetUpstream: {},
|
||||
};
|
||||
// 올려 둔 맵 3D (update.sh 가 만드는 모양)
|
||||
const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test')));
|
||||
fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } }));
|
||||
const { app, store } = await buildServer(cfg);
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
const login = async () => {
|
||||
const start = await fetch(base + '/auth/discord', { redirect: 'manual' });
|
||||
const state = new URL(start.headers.get('location')!).searchParams.get('state')!;
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
||||
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
|
||||
};
|
||||
return { base, store, login, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
assert.equal((await fetch(s.base + '/site/maps3d')).status, 401);
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb')).status, 401);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경로는 404', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const cookie = await s.login();
|
||||
const idx = (await (await fetch(s.base + '/site/maps3d', { headers: { cookie } })).json()) as any;
|
||||
assert.equal(idx.dir, 'V1-1');
|
||||
assert.ok(idx.maps['/Game/Maps/Ascent/Ascent']);
|
||||
const r = await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.headers.get('content-encoding'), 'gzip');
|
||||
assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404);
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
59
site/server/test/replay-sync.test.ts
Normal file
59
site/server/test/replay-sync.test.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// 사이트 3D 리플레이: 리플레이 시간 ↔ 기록 시각 맞추기 · 위치 보간 · 죽음 판정 (site/web/src/lib/replay.ts)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { computeSync, isDead, samplePlayer, type ReplayFile } from '../../web/src/lib/replay.ts';
|
||||
|
||||
const track = (pts: [number, number][]) => ({ t: pts.map((p) => p[0]), x: pts.map((p) => p[1]), y: pts.map(() => 0), z: pts.map(() => 100), yaw: pts.map(() => 350), pitch: pts.map(() => 0) });
|
||||
function replay(): ReplayFile {
|
||||
return {
|
||||
format: 'gvr-replay', v: 1, matchId: 'm1', map: null, build: null, recordedAt: 1_000_000, durationMs: 200_000, sampleMs: 100,
|
||||
players: [
|
||||
{ puuid: 'a', character: null, track: track([[0, 0], [10_000, 1000], [50_000, 1000]]) },
|
||||
{ puuid: 'b', character: null, track: track([[0, 0], [40_000, 500]]) },
|
||||
{ puuid: 'c', character: null, track: track([[0, 0], [90_000, 0]]) },
|
||||
],
|
||||
rounds: [{ num: 1, buy: 0, combat: 30_000, end: 80_000 }, { num: 2, buy: 100_000, combat: 130_000, end: -1 }],
|
||||
phases: [], shots: [], objects: [], objectKinds: [],
|
||||
kills: [[40_000, 0, 1], [60_000, 2, 0], [140_000, 0, 2]],
|
||||
};
|
||||
}
|
||||
const kill = (id: string, ts: number, killer: string, victim: string) => ({ kind: 'event', id, ts, type: 'kill', data: { killer: { puuid: killer, name: killer }, victim: { puuid: victim, name: victim }, assists: [], weapon: null } });
|
||||
|
||||
test('킬 시각 차이의 중앙값으로 맞추고, 킬별 오차를 낸다', () => {
|
||||
const r = replay();
|
||||
// 경기 기록이 리플레이보다 2.5초 늦게 찍혔고, 한 킬은 0.2초 더 늦다
|
||||
const m: any = { startedAt: 0, rounds: [], events: [kill('k1', 1_000_000 + 40_000 + 2500, 'a', 'b'), kill('k2', 1_000_000 + 60_000 + 2500, 'c', 'a'), kill('k3', 1_000_000 + 140_000 + 2700, 'a', 'c')] };
|
||||
const s = computeSync(m, r);
|
||||
assert.equal(s.matched, 3);
|
||||
assert.equal(s.offset, 2500);
|
||||
assert.equal(s.spreadMs, 200);
|
||||
});
|
||||
|
||||
test('킬을 못 맞추면 라운드 교전 시작(앱이 저장한 라운드 시작 + 30초)으로 맞춘다', () => {
|
||||
const r = replay();
|
||||
const m: any = { startedAt: 0, events: [], rounds: [{ num: 1, startedAt: 1_000_000 + 30_000 - 30_000 + 4000 }, { num: 2, startedAt: 1_000_000 + 130_000 - 30_000 + 4000 }] };
|
||||
const s = computeSync(m, r);
|
||||
assert.equal(s.matched, 0);
|
||||
assert.equal(s.offset, 4000);
|
||||
assert.equal(s.spreadMs, null);
|
||||
});
|
||||
|
||||
test('위치는 앞뒤 표본 사이를 보간하고, 방향은 짧은 쪽으로 돈다', () => {
|
||||
const tr = track([[0, 0], [100, 100]]);
|
||||
tr.yaw = [350, 10];
|
||||
const p = samplePlayer(tr, 50, 600)!;
|
||||
assert.equal(p.x, 50);
|
||||
assert.equal(p.yaw, 360);
|
||||
assert.equal(samplePlayer(tr, -1000, 600), null);
|
||||
});
|
||||
|
||||
test('죽음: 이 라운드에서 죽은 뒤 다시 움직이지 않으면 죽은 상태, 다음 라운드엔 살아남', () => {
|
||||
const r = replay();
|
||||
assert.equal(isDead(r, 1, 39_000), false);
|
||||
assert.equal(isDead(r, 1, 45_000), true);
|
||||
// a 는 60초에 죽었지만 기록은 50초까지뿐 → 죽음. 다음 라운드(100초~)에는 다시 산다
|
||||
assert.equal(isDead(r, 0, 70_000), true);
|
||||
assert.equal(isDead(r, 0, 110_000), false);
|
||||
// c 는 60초 킬 뒤에도 90초까지 움직였으므로 140초 킬 전까지 살아 있음
|
||||
assert.equal(isDead(r, 2, 120_000), false);
|
||||
});
|
||||
@@ -26,7 +26,7 @@ async function fakeDiscord() {
|
||||
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
|
||||
}
|
||||
|
||||
async function stack(dataDir = tmp()) {
|
||||
async function stack(dataDir = tmp(), opts: { browserRecheckMs?: number } = {}) {
|
||||
const dc = await fakeDiscord();
|
||||
const cfg: Config = {
|
||||
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
|
||||
@@ -34,7 +34,7 @@ async function stack(dataDir = tmp()) {
|
||||
version: 'test', discordApi: dc.url, assetUpstream: {},
|
||||
};
|
||||
const lines: string[] = [];
|
||||
const { app, store } = await buildServer(cfg);
|
||||
const { app, store } = await buildServer(cfg, opts);
|
||||
// 서버 로그를 모아 둔다 (비밀값이 남는지 본다)
|
||||
const orig = process.stdout.write.bind(process.stdout);
|
||||
(process.stdout as any).write = (chunk: any, ...rest: any[]) => (lines.push(String(chunk)), orig(chunk, ...rest));
|
||||
@@ -62,7 +62,7 @@ test('보안 헤더: CSP 는 이 사이트 스크립트 · 접속만 허용하
|
||||
const r = await fetch(s.base + '/healthz');
|
||||
const csp = r.headers.get('content-security-policy') ?? '';
|
||||
assert.match(csp, /default-src 'self'/);
|
||||
assert.match(csp, /script-src 'self'(;|$)/);
|
||||
assert.match(csp, /script-src 'self' 'wasm-unsafe-eval'(;|$)/); // WebAssembly(맵 3D 압축 풀기)만, eval 은 안 됨
|
||||
assert.match(csp, /connect-src 'self' wss:\/\/gvr\.example/);
|
||||
assert.match(csp, /frame-ancestors 'none'/);
|
||||
assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
|
||||
@@ -89,6 +89,28 @@ test('실시간 WebSocket: 다른 사이트에서 로그인 쿠키로 붙으면
|
||||
}
|
||||
});
|
||||
|
||||
test('실시간 WebSocket: 세션이 지워지거나(서버 탈퇴 등) 로그아웃하면 이미 열린 연결도 끊는다', async () => {
|
||||
const s = await stack(tmp(), { browserRecheckMs: 50 });
|
||||
try {
|
||||
const connect = async (sid: string) => {
|
||||
const ws = new WebSocket(s.base.replace('http', 'ws') + '/ws', { headers: { cookie: sid, origin: 'https://gvr.example' } });
|
||||
await new Promise((r) => ws.on('open', r));
|
||||
return { ws, closed: new Promise<number>((r) => ws.on('close', (code) => r(code))) };
|
||||
};
|
||||
// 1) 세션 삭제 (getSession 의 서버 멤버 재확인이 실패하면 이렇게 지운다) → 다음 확인 때 끊김
|
||||
const a = await connect(await s.login());
|
||||
for (const x of [...(s.store as any).d.sessions]) s.store.deleteSession(x.id);
|
||||
assert.equal(await a.closed, 4401);
|
||||
// 2) 로그아웃 → 바로 끊김
|
||||
const sid = await s.login();
|
||||
const b = await connect(sid);
|
||||
await fetch(s.base + '/auth/logout', { method: 'POST', headers: { cookie: sid } });
|
||||
assert.equal(await b.closed, 4401);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('세션: 서버 파일에는 세션 토큰 대신 해시만 남고, 예전 파일의 세션도 그대로 이어진다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
|
||||
51
site/server/test/unknown-users.test.ts
Normal file
51
site/server/test/unknown-users.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
// 사이트 화면: 처음 보는 유저 아이디가 오면 유저 목록을 다시 받는 규칙 (site/web/src/lib/unknown-users.ts)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { makeUnknownUserCheck } from '../../web/src/lib/unknown-users.ts';
|
||||
|
||||
const tick = () => new Promise((r) => setTimeout(r, 0));
|
||||
|
||||
test('모르는 유저: 받는 중에는 또 부르지 않고, 실패하면 다음 이벤트에서 다시 받는다', async () => {
|
||||
const known = new Set(['a']);
|
||||
let calls = 0;
|
||||
let fail = true;
|
||||
let release!: () => void;
|
||||
const check = makeUnknownUserCheck(() => {
|
||||
calls++;
|
||||
return new Promise<void>((ok, no) => {
|
||||
release = () => (fail ? no(new Error('500')) : (known.add('late'), ok()));
|
||||
});
|
||||
});
|
||||
const has = (id: string) => known.has(id);
|
||||
|
||||
check(['a'], has);
|
||||
assert.equal(calls, 0, '아는 사람은 부르지 않음');
|
||||
check(['late'], has);
|
||||
check(['late'], has);
|
||||
assert.equal(calls, 1, '받는 중에는 한 번만');
|
||||
release(); // 500
|
||||
await tick();
|
||||
check(['late'], has);
|
||||
assert.equal(calls, 2, '실패 뒤 다음 발화에서 다시 받음');
|
||||
fail = false;
|
||||
release();
|
||||
await tick();
|
||||
assert.ok(known.has('late'));
|
||||
check(['late'], has);
|
||||
assert.equal(calls, 2, '받은 뒤에는 부르지 않음');
|
||||
});
|
||||
|
||||
test('모르는 유저: 받았는데도 목록에 없는 아이디는 발화마다 다시 부르지 않는다', async () => {
|
||||
let calls = 0;
|
||||
const check = makeUnknownUserCheck(async () => {
|
||||
calls++;
|
||||
});
|
||||
const has = () => false;
|
||||
check(['ghost'], has);
|
||||
await tick();
|
||||
check(['ghost'], has);
|
||||
check(['ghost', ''], has);
|
||||
assert.equal(calls, 1);
|
||||
check(['other'], has);
|
||||
assert.equal(calls, 2, '다른 새 아이디는 다시 받음');
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
// 롤 1판(19:40 무렵) → 발로란트 바인드(패) → 발로란트 어센트(13:9 승) → 경기 후 잡담.
|
||||
// 이미지 URL 은 실제 사이트 서버 캐시 경로 형식(/game-assets/...)을 흉내 낸 /game-assets/mock/...
|
||||
|
||||
import fs from 'node:fs';
|
||||
|
||||
export const A = (p) => `/game-assets/mock/${p}`;
|
||||
|
||||
function mulberry32(a) {
|
||||
@@ -505,6 +507,79 @@ post.forEach(([u, text, status], i) => {
|
||||
addUtt({ user: u, ts, text, status, time: realLabel(ts) });
|
||||
});
|
||||
|
||||
// ── 3D 리플레이 데모 (선택) ─────────────────────────────
|
||||
// GVR_MOCK_REPLAY=<gvr-replay JSON 경로> (+ GVR_MOCK_REPLAY_MAP_FILE=<어비스 미니맵 png>) 를 주면 그 리플레이로 경기 하나를 만든다 (실제 리플레이는 저장소에 넣지 않는다).
|
||||
// 경기 기록(킬 시각)은 리플레이보다 MOCK_SYNC_OFFSET 만큼 늦게 찍어, 사이트가 그 차이를 맞추는지 본다.
|
||||
export const MOCK_SYNC_OFFSET = 1234;
|
||||
function genReplayDemo(file) {
|
||||
const r = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
const id = 'val-replay-demo';
|
||||
const base = r.recordedAt + MOCK_SYNC_OFFSET;
|
||||
// 팀: 같은 팀끼리는 (거의) 안 죽이므로 킬 관계로 두 편을 나눈다 (실제 사이트는 경기 기록의 팀을 쓴다)
|
||||
const adj = r.players.map(() => new Set());
|
||||
for (const [, k, v] of r.kills) if (k >= 0 && v >= 0 && k !== v) (adj[k].add(v), adj[v].add(k));
|
||||
const side = new Map([[0, 0]]);
|
||||
const stack = [0];
|
||||
while (stack.length) {
|
||||
const x = stack.pop();
|
||||
for (const y of adj[x]) if (!side.has(y)) (side.set(y, 1 - side.get(x)), stack.push(y));
|
||||
}
|
||||
const allyIdx = new Set(r.players.map((_, i) => i).filter((i) => side.get(i) === 0));
|
||||
const AGK = { Wushu_PC_C: AG.jett, Hunter_PC_C: AG.sova, Thorne_PC_C: AG.sage, Wraith_PC_C: AG.omen, Killjoy_PC_C: AG.killjoy, Clay_PC_C: AG.raze, Vampire_PC_C: AG.reyna };
|
||||
let si = 0;
|
||||
let an = 0;
|
||||
let en = 0;
|
||||
const players = r.players.map((p, i) => {
|
||||
const ally = allyIdx.has(i);
|
||||
const user = ally && si < SPEAKERS.length ? SPEAKERS[si++] : null;
|
||||
const name = user ? user.name : ally ? `아군${++an}` : `상대${++en}`;
|
||||
const cls = (p.character ?? '').replace(/_PC_C$/, '');
|
||||
return { puuid: p.puuid, name, tag: 'KR1', team: ally ? 'Blue' : 'Red', ally, character: AGK[p.character] ?? { id: cls, name: cls, icon: null }, userId: user?.id, kills: 0, deaths: 0, assists: 0, score: 0, rank: null };
|
||||
});
|
||||
const ref = (i) => (i >= 0 ? { puuid: players[i].puuid, name: players[i].name, team: players[i].team, character: players[i].character, userId: players[i].userId } : null);
|
||||
const mEvents = [];
|
||||
const mUtts = [];
|
||||
const rounds = [];
|
||||
let score = { ally: 0, enemy: 0 };
|
||||
r.rounds.forEach((rd, k) => {
|
||||
const next = r.rounds[k + 1];
|
||||
const startedAt = base + (rd.combat >= 0 ? rd.combat - 30000 : rd.buy);
|
||||
const endedAt = base + (next ? (next.combat >= 0 ? next.combat - 30000 : next.buy) : r.durationMs);
|
||||
const kills = r.kills.filter(([t]) => t >= rd.buy && (!next || t < next.buy));
|
||||
const allyDead = kills.filter(([, , v]) => allyIdx.has(v)).length;
|
||||
const enemyDead = kills.filter(([, , v]) => !allyIdx.has(v)).length;
|
||||
const win = enemyDead >= allyDead;
|
||||
win ? score.ally++ : score.enemy++;
|
||||
rounds.push({ num: rd.num, startedAt, endedAt, win, result: 'Elimination', score: { ...score }, economy: {}, players: {} });
|
||||
const label = (ts) => {
|
||||
const inRound = ts - startedAt;
|
||||
return { primary: inRound < 30000 ? `R${rd.num} · 구매` : `R${rd.num} · ${fmtClock(inRound - 30000)}`, secondary: fmtClock(ts - base), real: ts };
|
||||
};
|
||||
for (const [t, ki, vi] of kills) {
|
||||
const ts = base + t;
|
||||
if (ki >= 0) players[ki].kills++;
|
||||
if (vi >= 0) players[vi].deaths++;
|
||||
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'kill', round: rd.num, data: { killer: ref(ki), victim: ref(vi), assists: [], weapon: null, location: null, ally: ki >= 0 && allyIdx.has(ki) }, time: label(ts) });
|
||||
}
|
||||
mEvents.push({ kind: 'event', id: nid('ev_'), ts: endedAt - 1, game: 'valorant', matchId: id, type: 'round_end', round: rd.num, data: { round: rd.num, win, result: 'Elimination', score: { ...score } }, time: label(endedAt - 1) });
|
||||
// 대화: 라운드마다 3~5개
|
||||
const n = irange(3, 5);
|
||||
for (let j = 0; j < n; j++) {
|
||||
const ts = startedAt + irange(5, Math.max(6, Math.floor((endedAt - startedAt) / 1000) - 3)) * 1000;
|
||||
mUtts.push(addUtt({ user: pick(SPEAKERS), ts, text: pick(VAL_LINES), game: { type: 'valorant', matchId: id, round: rd.num }, time: label(ts) }));
|
||||
}
|
||||
});
|
||||
const endedAt = base + r.durationMs;
|
||||
events.push(...mEvents);
|
||||
const T = { xMultiplier: 8.1e-5, yMultiplier: -8.1e-5, xScalarToAdd: 0.5, yScalarToAdd: 0.5 };
|
||||
const summary = {
|
||||
id, game: 'valorant', startedAt: base, endedAt, map: { id: '/Game/Maps/Infinity/Infinity', name: '어비스', image: process.env.GVR_MOCK_REPLAY_MAP_FILE ? A('replay-map.png') : null },
|
||||
mode: '경쟁전', win: score.ally > score.enemy, score, status: 'complete', participants: SPEAKERS.map((u) => u.id),
|
||||
};
|
||||
matches.push({ ...summary, players, rounds, events: mEvents, utterances: mUtts, mapTransform: { valorant: T }, replayPath: file });
|
||||
}
|
||||
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
|
||||
|
||||
// ── 내보내기 ─────────────────────────────────────────
|
||||
export const db = {
|
||||
users: USERS,
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
// GET /mock/device?registered=0|1 등록 안 된 상태 흉내
|
||||
// GET /mock/live?on=0|1 주기적 가짜 실시간 발화 켜기/끄기
|
||||
// GET /mock/emit 가짜 실시간 발화 하나 즉시 만들기
|
||||
// GET /mock/latejoin 녹음 중에 새 사람이 들어와 말함 (v1.4.1 이하 앱처럼 users.updated 없이 발화만 보냄). ?again=1 이면 마지막에 들어온 사람이 또 말함
|
||||
// GET /mock/users-fail?n=1 다음 n 번 /api/users 를 500 으로 실패
|
||||
// GET /auth/discord?as=notmember 길드 멤버가 아닌 계정으로 로그인 흉내 (403 not_member)
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
@@ -117,6 +119,9 @@ function userProfile(id) {
|
||||
|
||||
// ── WS ───────────────────────────────────────────────
|
||||
let wss;
|
||||
// "잡음이라 삭제"로 배운 문장 (v1.4.0)
|
||||
const noisePhrases = [{ id: 1, text: '시청해 주셔서 감사합니다 자막 제공', hits: 3, createdAt: Date.now() - 86400000 }];
|
||||
let noiseSeq = 1;
|
||||
const broadcast = (msg) => {
|
||||
const s = JSON.stringify(msg, (k, v) => (k.startsWith('_') ? undefined : v));
|
||||
wss?.clients.forEach((c) => c.readyState === 1 && c.send(s));
|
||||
@@ -163,8 +168,37 @@ async function handle(req, res) {
|
||||
return json(res, 200, { live: state.live });
|
||||
}
|
||||
if (p === '/mock/emit') return json(res, 200, emitLive() ?? { error: 'device_offline' });
|
||||
if (p === '/mock/users-fail') {
|
||||
state.usersFail = Number(q.get('n') ?? 1);
|
||||
return json(res, 200, { usersFail: state.usersFail });
|
||||
}
|
||||
if (p === '/mock/latejoin') {
|
||||
const n = db.users.length;
|
||||
const u = q.get('again') === '1' ? db.users[n - 1] : { id: `41000000000000${String(n).padStart(4, '0')}`, name: `늦게온사람${n}`, color: '#d4537e', avatar: null, excluded: false, riot: [] };
|
||||
if (q.get('again') !== '1') db.users.push(u);
|
||||
const it = db.addLiveUtterance(u, '나 지금 들어왔어');
|
||||
broadcast({ type: 'utterance.created', data: it });
|
||||
return json(res, 200, { user: u, utterance: it.id });
|
||||
}
|
||||
|
||||
// 맵 3D (GVR_MOCK_MAPS3D=<사이트 서버 data/maps3d 와 같은 구조의 폴더>: index.json + <dir>/<code>.glb.gz)
|
||||
if (p === '/site/maps3d' || p.startsWith('/site/maps3d/')) {
|
||||
const root = process.env.GVR_MOCK_MAPS3D;
|
||||
if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' });
|
||||
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
|
||||
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
|
||||
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
|
||||
if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+\.glb$/.test(file ?? '') || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
|
||||
res.writeHead(200, { 'content-type': 'model/gltf-binary', 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size });
|
||||
return fs.createReadStream(f).pipe(res);
|
||||
}
|
||||
|
||||
// 게임 이미지 (목: docs/report/mock/assets)
|
||||
// 3D 리플레이 데모 바닥 미니맵 (GVR_MOCK_REPLAY_MAP_FILE, 데이터 생성은 data.mjs genReplayDemo)
|
||||
if (p === '/game-assets/mock/replay-map.png' && process.env.GVR_MOCK_REPLAY_MAP_FILE) {
|
||||
res.writeHead(200, { 'content-type': 'image/png' });
|
||||
return fs.createReadStream(process.env.GVR_MOCK_REPLAY_MAP_FILE).pipe(res);
|
||||
}
|
||||
if (p.startsWith('/game-assets/mock/')) {
|
||||
const f = path.resolve(ASSET_DIR, decodeURIComponent(p.slice('/game-assets/mock/'.length)));
|
||||
if (!f.startsWith(ASSET_DIR) || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
|
||||
@@ -231,7 +265,13 @@ async function handle(req, res) {
|
||||
version: '1.0.0',
|
||||
});
|
||||
}
|
||||
if (p === '/api/users') return json(res, 200, db.users);
|
||||
if (p === '/api/users') {
|
||||
if (state.usersFail > 0) {
|
||||
state.usersFail--;
|
||||
return json(res, 500, { error: 'mock_fail' });
|
||||
}
|
||||
return json(res, 200, db.users);
|
||||
}
|
||||
let m;
|
||||
if ((m = p.match(/^\/api\/users\/([^/]+)$/))) {
|
||||
const prof = userProfile(decodeURIComponent(m[1]));
|
||||
@@ -247,7 +287,16 @@ async function handle(req, res) {
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
return mt ? json(res, 200, mt) : json(res, 404, { error: 'not_found' });
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
const { replayPath, ...rest } = mt;
|
||||
return json(res, 200, rest);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
if (!mt.replayPath) return json(res, 404, { error: 'replay_not_found' });
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
return fs.createReadStream(mt.replayPath).pipe(res);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/utterances\/([^/]+)$/)) && req.method === 'PATCH') {
|
||||
const it = db.utterances.find((u) => u.id === decodeURIComponent(m[1]));
|
||||
@@ -264,6 +313,35 @@ async function handle(req, res) {
|
||||
broadcast({ type: 'utterance.updated', data: it });
|
||||
return json(res, 200, it);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/utterances\/([^/]+)\/delete$/)) && req.method === 'POST') {
|
||||
const i = db.utterances.findIndex((u) => u.id === decodeURIComponent(m[1]));
|
||||
if (i < 0) return json(res, 404, { error: 'not_found' });
|
||||
const body = JSON.parse((await readBody(req)) || '{}');
|
||||
const [it] = db.utterances.splice(i, 1);
|
||||
let learned = null;
|
||||
if (body.noise && it.text) {
|
||||
learned = it.text;
|
||||
noisePhrases.unshift({ id: ++noiseSeq, text: it.text, hits: 0, createdAt: Date.now() });
|
||||
}
|
||||
broadcast({ type: 'utterance.deleted', data: { id: it.id, noise: !!body.noise } });
|
||||
return json(res, 200, { ok: true, learned });
|
||||
}
|
||||
if (p === '/api/dictionary')
|
||||
return json(res, 200, {
|
||||
labels: { valorant: '발로란트', lol: '롤' },
|
||||
entries: [
|
||||
{ id: 1, word: '로테', from: null, kind: 'hotword', pack: 'site', source: 'site', enabled: true, hits: 12 },
|
||||
{ id: 2, word: '레이즈', from: '레이저', kind: 'correction', pack: 'site', source: 'site', enabled: true, hits: 0 },
|
||||
],
|
||||
packs: [{ key: 'valorant', label: '발로란트', count: 420 }],
|
||||
});
|
||||
if (p === '/api/noise-phrases') return json(res, 200, { phrases: noisePhrases });
|
||||
if ((m = p.match(/^\/api\/noise-phrases\/(\d+)$/)) && req.method === 'DELETE') {
|
||||
const i = noisePhrases.findIndex((x) => x.id === Number(m[1]));
|
||||
if (i < 0) return json(res, 404, { error: 'not_found' });
|
||||
noisePhrases.splice(i, 1);
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
if (p === '/api/bundles') {
|
||||
const out = [];
|
||||
for (const mt of db.matches) {
|
||||
|
||||
64
site/web/package-lock.json
generated
64
site/web/package-lock.json
generated
@@ -12,12 +12,14 @@
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^7.18.4",
|
||||
"three": "^0.180.0",
|
||||
"wavesurfer.js": "^7.12.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
@@ -287,6 +289,12 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -1095,6 +1103,12 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/babel__core": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -1169,6 +1183,33 @@
|
||||
"@types/react": "^19.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": "*",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~0.22.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",
|
||||
@@ -1189,6 +1230,12 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@webgpu/types": {
|
||||
"version": "0.1.74",
|
||||
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
|
||||
"integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.11.28",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.28.tgz",
|
||||
@@ -1368,6 +1415,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/framer-motion": {
|
||||
"version": "12.43.0",
|
||||
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz",
|
||||
@@ -1456,6 +1509,12 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
|
||||
"integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/motion-dom": {
|
||||
"version": "12.43.0",
|
||||
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.43.0.tgz",
|
||||
@@ -1670,6 +1729,11 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^7.18.4",
|
||||
"three": "^0.180.0",
|
||||
"wavesurfer.js": "^7.12.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import { IDiscord } from './Icons';
|
||||
|
||||
@@ -31,6 +32,15 @@ function FakeBackdrop() {
|
||||
}
|
||||
|
||||
export function LoginPage({ notMember = false, error }: { notMember?: boolean; error?: string }) {
|
||||
// 들어올 수 있는 서버 = 게임 PC 앱에서 녹음할 서버로 고른 곳 (겜녹이 봇이 있는 서버)
|
||||
const [guild, setGuild] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
fetch('/auth/guild')
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((d: { name?: string | null } | null) => setGuild(d?.name ?? null))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
const g = guild ? `(${guild})` : '';
|
||||
return (
|
||||
<div className="login">
|
||||
<FakeBackdrop />
|
||||
@@ -43,9 +53,9 @@ export function LoginPage({ notMember = false, error }: { notMember?: boolean; e
|
||||
<div className="in">
|
||||
{notMember ? (
|
||||
<>
|
||||
<div className="t h">들어올 수 없는 계정입니다</div>
|
||||
<div className="nm-warn">M&L 서버 멤버만 들어올 수 있습니다</div>
|
||||
<div className="d">겜녹이 봇이 있는 디스코드 서버(M&L)에 참여한 계정으로 다시 로그인해 주세요.</div>
|
||||
<div className="t h">로그인할 수 없습니다</div>
|
||||
<div className="nm-warn">봇과 다른 서버에 있는 계정입니다</div>
|
||||
<div className="d">겜녹이 봇이 있는 디스코드 서버{g}에 참여한 계정만 들어올 수 있습니다. 그 서버에 참여한 계정으로 다시 로그인해 주세요.</div>
|
||||
<a className="dc" href="/auth/discord">
|
||||
<IDiscord />
|
||||
다른 계정으로 로그인
|
||||
@@ -56,7 +66,7 @@ export function LoginPage({ notMember = false, error }: { notMember?: boolean; e
|
||||
<div className="t h">디스코드 계정으로 로그인</div>
|
||||
{error && <div className="nm-warn">{error}</div>}
|
||||
<div className="d">
|
||||
겜녹이 봇이 있는 디스코드 서버(M&L)의 멤버만 들어올 수 있어요.
|
||||
겜녹이 봇이 있는 디스코드 서버{g}의 멤버만 들어올 수 있어요.
|
||||
<br />
|
||||
로그인하면 녹음된 대화와 경기 기록을 볼 수 있습니다.
|
||||
</div>
|
||||
|
||||
85
site/web/src/components/ReplayPanel.tsx
Normal file
85
site/web/src/components/ReplayPanel.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
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);
|
||||
const [converting, setConverting] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!open || replay) return;
|
||||
let alive = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
setErr(null);
|
||||
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
|
||||
const ask = (tries: number) =>
|
||||
api
|
||||
.replay(m.id)
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
if ('status' in r && r.status === 'converting') {
|
||||
setConverting(true);
|
||||
if (tries >= 100) setErr(new Error('게임 PC 가 리플레이 변환을 끝내지 못했습니다'));
|
||||
else timer = setTimeout(() => ask(tries + 1), 3000);
|
||||
return;
|
||||
}
|
||||
setConverting(false);
|
||||
setReplay(r as ReplayFile);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!alive) return;
|
||||
setConverting(false);
|
||||
setErr(e);
|
||||
});
|
||||
void ask(0);
|
||||
return () => {
|
||||
alive = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [open, m.id, replay]);
|
||||
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
||||
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
|
||||
const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found';
|
||||
const appTooOld = err instanceof ApiError && err.status === 404 && err.code === 'Not Found'; // Fastify 기본 404 (경로 없음)
|
||||
const failed = err instanceof ApiError && err.status === 422 && err.code === 'replay_failed';
|
||||
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>
|
||||
) : appTooOld ? (
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
) : failed ? (
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다 (게임 PC 앱 로그에 이유가 남습니다).</div>
|
||||
) : err ? (
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
) : !replay || !sync ? (
|
||||
<Spinner label={converting ? '게임 PC 가 리플레이를 변환하는 중 (처음 한 번, 10초 안팎)' : '리플레이 불러오는 중'} />
|
||||
) : (
|
||||
<Suspense fallback={<Spinner label="3D 화면 준비 중" />}>
|
||||
<ReplayViewer m={m} replay={replay} sync={sync} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
600
site/web/src/components/ReplayViewer.tsx
Normal file
600
site/web/src/components/ReplayViewer.tsx
Normal file
@@ -0,0 +1,600 @@
|
||||
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';
|
||||
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
|
||||
|
||||
/**
|
||||
* 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON).
|
||||
* 맵은 게임 파일에서 뽑은 3D 모양(tools/map-extract, 사이트 서버 /site/maps3d)을 쓰고, 없으면 미니맵 바닥만 깐다.
|
||||
* 위에서 내려다볼 수 있게 천장 높이 위는 잘라 낸다 (자동: 고른 선수 · 가장 높은 선수 머리 위).
|
||||
* 시계는 플레이어 "현장 모드"(대화를 실제 시각대로 겹쳐 재생)와 같은 값을 쓴다:
|
||||
* 기록 시각 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];
|
||||
/** 자동 천장: 선수(몸 중심) 위로 이만큼(cm) 남기고 자른다 */
|
||||
const CEIL_ABOVE = 380;
|
||||
|
||||
type MapState = { state: 'none' | 'loading' | 'ready' | 'error'; progress?: number };
|
||||
/** 천장 자르기: 자동 · 끔 · 직접(가장 낮은 층에서 cm) */
|
||||
type Ceil = { mode: 'auto' } | { mode: 'off' } | { mode: 'manual'; cm: number };
|
||||
|
||||
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>(() => {});
|
||||
const [map3d, setMap3d] = useState<MapState>({ state: 'none' });
|
||||
const [ceil, setCeil] = useState<Ceil>({ mode: 'auto' });
|
||||
const ceilRef = useRef(ceil);
|
||||
ceilRef.current = ceil;
|
||||
/** 지금 자르는 높이 (가장 낮은 층에서 cm, 화면 표시용) */
|
||||
const [ceilNow, setCeilNow] = useState<number | null>(null);
|
||||
|
||||
// 바닥(미니맵) 높이: 선수 높이의 하위 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 zTop = useMemo(() => {
|
||||
let top = zBase;
|
||||
for (const p of replay.players) for (let i = 0; i < p.track.z.length; i += 20) if (p.track.z[i] > top) top = p.track.z[i];
|
||||
return top;
|
||||
}, [replay, zBase]);
|
||||
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);
|
||||
|
||||
// 맵 3D 모양: 받으면 미니맵 바닥 · 선수 그림자를 숨긴다. 천장 위는 잘라 낸다
|
||||
renderer.localClippingEnabled = true;
|
||||
const hPerCm = Math.abs(T.xMultiplier) * S * VEX;
|
||||
const clip = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1e6);
|
||||
let clipY = 1e6;
|
||||
let mapReady = false;
|
||||
const mapGroup = new THREE.Group();
|
||||
mapGroup.matrixAutoUpdate = false;
|
||||
mapGroup.matrix.copy(worldMatrix(T, S, zBase, VEX));
|
||||
scene.add(mapGroup);
|
||||
let disposed = false;
|
||||
setMap3d({ state: 'loading', progress: 0 });
|
||||
void findMap3d(m.map.id)
|
||||
.then((info) => {
|
||||
if (disposed) return;
|
||||
if (!info) return setMap3d({ state: 'none' });
|
||||
const mat = mapMaterial(clip, { lo: 0, hi: Math.max(8, (zTop - zBase + 600) * hPerCm) });
|
||||
return loadMap3d(info.url, mat, (p) => !disposed && setMap3d({ state: 'loading', progress: p })).then((obj) => {
|
||||
if (disposed) return;
|
||||
mapGroup.add(obj);
|
||||
mapGroup.updateMatrixWorld(true);
|
||||
mapReady = true;
|
||||
floor.visible = false;
|
||||
grid.visible = false;
|
||||
setMap3d({ state: 'ready' });
|
||||
});
|
||||
})
|
||||
.catch(() => !disposed && setMap3d({ state: 'error' }));
|
||||
|
||||
// 선수
|
||||
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 = true;
|
||||
v.drop.visible = v.shadow.visible = !mapReady;
|
||||
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;
|
||||
}
|
||||
// 천장 자르기
|
||||
const cm = ceilRef.current;
|
||||
let want = 1e6;
|
||||
if (mapReady && cm.mode === 'manual') want = cm.cm * hPerCm;
|
||||
else if (mapReady && cm.mode === 'auto') {
|
||||
const sv = selIdx != null ? views[selIdx] : null;
|
||||
let top = -Infinity;
|
||||
if (sv?.group.visible) top = sv.group.position.y;
|
||||
else for (const v of views) if (v.group.visible && !isDead(replay, v.idx, t)) top = Math.max(top, v.group.position.y);
|
||||
if (top > -Infinity) want = top + CEIL_ABOVE * hPerCm;
|
||||
}
|
||||
clipY = clipY > 1e5 || want > 1e5 ? want : clipY + (want - clipY) * 0.12;
|
||||
clip.constant = clipY;
|
||||
// 경로
|
||||
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;
|
||||
setCeilNow((c) => {
|
||||
const v = clipY > 1e5 ? null : Math.round(clipY / hPerCm / 10) * 10;
|
||||
return c === v ? c : v;
|
||||
});
|
||||
setUi((u) => (Math.abs(u.t - t) < 50 && u.playing === (inScene && ps.playing) ? u : { t, playing: inScene && ps.playing }));
|
||||
}
|
||||
};
|
||||
raf = requestAnimationFrame(frame);
|
||||
return () => {
|
||||
disposed = true;
|
||||
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, zTop]);
|
||||
|
||||
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>}
|
||||
{map3d.state === 'loading' && <div className="muted small">맵 3D 불러오는 중 {Math.round((map3d.progress ?? 0) * 100)}%</div>}
|
||||
{map3d.state === 'error' && <div className="muted small">맵 3D 를 불러오지 못해 미니맵으로 보여 줍니다</div>}
|
||||
</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>
|
||||
{map3d.state === 'ready' && (
|
||||
<span className="r3d-ceil" title="위에서 보이게 이 높이 위(지붕 · 위층)는 잘라 냅니다">
|
||||
<button
|
||||
className={`chip${ceil.mode === 'auto' ? ' on' : ''}`}
|
||||
onClick={() => setCeil((c) => (c.mode === 'auto' ? { mode: 'off' } : { mode: 'auto' }))}
|
||||
title="자동: 고른 선수(없으면 가장 높은 선수) 머리 위까지 보이게"
|
||||
>
|
||||
천장 {ceil.mode === 'auto' ? '자동' : ceil.mode === 'off' ? '없음' : `${Math.round(ceil.cm / 100)}m`}
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={Math.round(zTop - zBase + 800)}
|
||||
step={50}
|
||||
value={ceil.mode === 'manual' ? ceil.cm : ceilNow ?? Math.round(zTop - zBase + 800)}
|
||||
onChange={(e) => setCeil({ mode: 'manual', cm: Number(e.target.value) })}
|
||||
aria-label="천장 높이"
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<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;
|
||||
}
|
||||
|
||||
@@ -3,13 +3,16 @@ import type { UtteranceInfo, UtteranceItem } from '@gvr/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { fmtWhen } from '../lib/format';
|
||||
import { player } from '../store/player';
|
||||
import { useData } from '../store/app';
|
||||
import { useAuth, useData, useLive } from '../store/app';
|
||||
import { IClose, IDownload, IPlay } from './Icons';
|
||||
|
||||
/** 발화 우클릭 메뉴 · 자세한 정보 창 (앱에 하나만 띄운다) */
|
||||
type MenuState = { item: UtteranceItem; x: number; y: number } | null;
|
||||
let menu: MenuState = null;
|
||||
let infoFor: UtteranceItem | null = null;
|
||||
let deleteFor: UtteranceItem | null = null;
|
||||
/** 이 화면에서 지운 발화 (다른 사람이 지운 것도 실시간으로). 목록마다 따로 고치지 않고 줄이 스스로 숨는다 */
|
||||
const deleted = new Set<string>();
|
||||
const subs = new Set<() => void>();
|
||||
const notify = () => subs.forEach((f) => f());
|
||||
const subscribe = (f: () => void) => {
|
||||
@@ -36,6 +39,25 @@ function closeInfo(): void {
|
||||
infoFor = null;
|
||||
notify();
|
||||
}
|
||||
function openDelete(item: UtteranceItem): void {
|
||||
menu = null;
|
||||
deleteFor = item;
|
||||
notify();
|
||||
}
|
||||
function closeDelete(): void {
|
||||
deleteFor = null;
|
||||
notify();
|
||||
}
|
||||
function markDeleted(id: string): void {
|
||||
if (deleted.has(id)) return;
|
||||
deleted.add(id);
|
||||
if (player.state.item?.id === id) player.stop();
|
||||
notify();
|
||||
}
|
||||
/** 지운 발화인가 (줄을 숨긴다) */
|
||||
export function useDeleted(id: string): boolean {
|
||||
return useSyncExternalStore(subscribe, () => deleted.has(id));
|
||||
}
|
||||
|
||||
/** 녹음 원본(.ogg)을 내려받는다. 게임 PC → 사이트 서버 중계로 받은 파일을 그대로 저장 */
|
||||
export async function downloadAudio(item: UtteranceItem, fileName?: string | null): Promise<void> {
|
||||
@@ -59,7 +81,16 @@ const copy = (text: string) => navigator.clipboard?.writeText(text).catch(() =>
|
||||
export function UttMenuHost() {
|
||||
const m = useSyncExternalStore(subscribe, () => menu);
|
||||
const info = useSyncExternalStore(subscribe, () => infoFor);
|
||||
const del = useSyncExternalStore(subscribe, () => deleteFor);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [okMsg, setOkMsg] = useState<string | null>(null);
|
||||
const { auth } = useAuth();
|
||||
// 지우기: 관리자나 말한 사람만 (게임 PC 도 한 번 더 확인한다)
|
||||
const canDelete = (it: UtteranceItem) => auth.status === 'ok' && (!!auth.me.canViewLogs || auth.me.user.id === it.userId);
|
||||
|
||||
useLive((e) => {
|
||||
if (e.type === 'utterance.deleted') markDeleted(e.data.id);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!m) return;
|
||||
@@ -82,6 +113,11 @@ export function UttMenuHost() {
|
||||
const t = setTimeout(() => setErr(null), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [err]);
|
||||
useEffect(() => {
|
||||
if (!okMsg) return;
|
||||
const t = setTimeout(() => setOkMsg(null), 4000);
|
||||
return () => clearTimeout(t);
|
||||
}, [okMsg]);
|
||||
|
||||
const act = (fn: () => unknown) => (e: React.PointerEvent | React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
@@ -95,7 +131,7 @@ export function UttMenuHost() {
|
||||
<div
|
||||
className="ctx-menu"
|
||||
role="menu"
|
||||
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 190) }}
|
||||
style={{ left: Math.min(m.x, window.innerWidth - 230), top: Math.min(m.y, window.innerHeight - 240) }}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
@@ -111,10 +147,32 @@ export function UttMenuHost() {
|
||||
<button role="menuitem" disabled={!m.item.text} onClick={act(() => copy(m.item.text ?? ''))}>
|
||||
<span className="ctx-ic">⧉</span> 내용 복사
|
||||
</button>
|
||||
<div className="ctx-sep" />
|
||||
<button
|
||||
role="menuitem"
|
||||
className="danger"
|
||||
disabled={!canDelete(m.item)}
|
||||
title={canDelete(m.item) ? undefined : '관리자나 말한 사람만 지울 수 있습니다'}
|
||||
onClick={act(() => openDelete(m.item))}
|
||||
>
|
||||
<span className="ctx-ic">🗑</span> 삭제…
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{info && <InfoDialog item={info} onError={setErr} />}
|
||||
{del && (
|
||||
<DeleteDialog
|
||||
key={del.id}
|
||||
item={del}
|
||||
onDone={(learned) => {
|
||||
markDeleted(del.id);
|
||||
closeDelete();
|
||||
setOkMsg(learned ? `삭제했습니다. 앞으로 "${learned.length > 40 ? learned.slice(0, 40) + '…' : learned}" 는 잡음으로 거릅니다` : '삭제했습니다');
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{err && <div className="ctx-toast">{err}</div>}
|
||||
{okMsg && !err && <div className="ctx-toast ok">{okMsg}</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -218,3 +276,73 @@ function InfoDialog({ item, onError }: { item: UtteranceItem; onError: (m: strin
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 삭제 확인: 잡음이라 삭제(같은 문장을 다음부터 잡음으로 거름) · 그냥 삭제 · 취소 */
|
||||
function DeleteDialog({ item, onDone }: { item: UtteranceItem; onDone: (learned: string | null) => void }) {
|
||||
const { userById } = useData();
|
||||
const [busy, setBusy] = useState<'noise' | 'plain' | null>(null);
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const text = item.text?.trim() || null;
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !busy && closeDelete();
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [busy]);
|
||||
|
||||
const run = async (noise: boolean) => {
|
||||
setBusy(noise ? 'noise' : 'plain');
|
||||
setFailed(null);
|
||||
try {
|
||||
const r = await api.deleteUtterance(item.id, noise);
|
||||
onDone(r.learned);
|
||||
} catch (e) {
|
||||
setBusy(null);
|
||||
if (e instanceof ApiError && e.status === 404 && e.code === 'not_found') return onDone(null); // 이미 지워짐
|
||||
setFailed(
|
||||
e instanceof ApiError && e.status === 404
|
||||
? '게임 PC 의 겜녹이가 예전 버전입니다. v1.4.0 이상으로 업데이트하면 지울 수 있습니다.'
|
||||
: e instanceof ApiError && e.status === 403
|
||||
? '관리자나 말한 사람만 지울 수 있습니다.'
|
||||
: e instanceof ApiError && e.status === 503
|
||||
? '게임 PC 가 꺼져 있어 지우지 못했습니다.'
|
||||
: '지우지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="ctx-dim" onPointerDown={() => !busy && closeDelete()}>
|
||||
<div className="ctx-dialog del-dialog" role="dialog" aria-label="발화 삭제" onPointerDown={(e) => e.stopPropagation()}>
|
||||
<div className="ctx-head">
|
||||
<b>발화 삭제</b>
|
||||
<button className="icon-btn" onClick={closeDelete} disabled={!!busy} aria-label="닫기">
|
||||
<IClose width={16} height={16} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="del-quote">
|
||||
<span className="dim">{userById(item.userId)?.name ?? '알 수 없음'} · {fmtWhen(item.ts)}</span>
|
||||
<p>{text ?? '(인식된 글 없음)'}</p>
|
||||
</div>
|
||||
<p className="del-help">
|
||||
글과 음성 파일을 게임 PC 에서 지웁니다. 되돌릴 수 없습니다.
|
||||
<br />
|
||||
<b>잡음이라 삭제</b>를 고르면 이 문장을 잡음으로 배워서, 다음에 같은 문장이 인식되면 자동으로 잡음 처리합니다 (띄어쓰기 · 문장부호는 무시하고, 긴 문장은 글자 수가 같고 한두 글자만 바뀐 것까지 같은 문장으로 봅니다. 앞뒤에 다른 말이 붙은 발화는 지우지 않습니다).
|
||||
배운 문장은 사전 화면에서 지울 수 있습니다.
|
||||
</p>
|
||||
{failed && <p className="del-err">{failed}</p>}
|
||||
<div className="ctx-foot">
|
||||
<button className="chip" onClick={closeDelete} disabled={!!busy}>
|
||||
취소
|
||||
</button>
|
||||
<button className="chip danger" onClick={() => void run(false)} disabled={!!busy}>
|
||||
{busy === 'plain' ? '지우는 중…' : '그냥 삭제'}
|
||||
</button>
|
||||
<button className="chip danger on" onClick={() => void run(true)} disabled={!!busy || !text} title={text ? undefined : '인식된 글이 없어 배울 문장이 없습니다'}>
|
||||
{busy === 'noise' ? '지우는 중…' : '잡음이라 삭제'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { sfx } from '../lib/sfx';
|
||||
import { realTip } from '../lib/format';
|
||||
import { Avatar, TimeCell } from './common';
|
||||
import { IEdit } from './Icons';
|
||||
import { openUttMenu } from './UttMenu';
|
||||
import { openUttMenu, useDeleted } from './UttMenu';
|
||||
|
||||
const STATUS: Record<UtteranceItem['status'], [string, string]> = {
|
||||
realtime: ['실시간', 'st-rt'],
|
||||
@@ -147,6 +147,7 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
|
||||
const playing = usePlayer((s) => active && s.playing);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [st, stCls] = STATUS[item.status];
|
||||
const gone = useDeleted(item.id);
|
||||
|
||||
const click = () => {
|
||||
if (editing) return;
|
||||
@@ -183,6 +184,9 @@ export const UtteranceRow = memo(function UtteranceRow({ item, variant = 'full',
|
||||
</button>
|
||||
);
|
||||
|
||||
// 우클릭으로 지운 발화 (경기 화면 · 유저 화면 등 어느 목록이든 줄이 숨는다)
|
||||
if (gone) return null;
|
||||
|
||||
if (variant === 'compact') {
|
||||
return (
|
||||
<div className={`l utt${active ? ' cur' : ''}${item.noise ? ' is-noise' : ''}`} onClick={click} onContextMenu={menu} data-id={item.id}>
|
||||
|
||||
@@ -14,9 +14,11 @@ import type {
|
||||
GameType,
|
||||
BundleInfo,
|
||||
BundleImportResult,
|
||||
NoisePhrase,
|
||||
} from '@gvr/shared';
|
||||
|
||||
import { reportClient } from './report';
|
||||
import type { ReplayFile } from './replay';
|
||||
|
||||
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
|
||||
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
|
||||
@@ -134,6 +136,8 @@ export const api = {
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */
|
||||
replay: (id: string) => request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`),
|
||||
culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request<CulpritMatchItem[]>(`/api/culprit/matches${qs(o)}`),
|
||||
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
|
||||
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
|
||||
@@ -191,6 +195,11 @@ export const api = {
|
||||
utteranceInfo: (id: string) => request<UtteranceInfo>(`/api/utterances/${encodeURIComponent(id)}/info`),
|
||||
correct: (id: string, text: string) =>
|
||||
request<UtteranceItem>(`/api/utterances/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ text }) }),
|
||||
/** 발화 지우기 (v1.4.0). noise = 잡음이라 삭제 (같은 문장을 다음부터 잡음으로) */
|
||||
deleteUtterance: (id: string, noise: boolean) =>
|
||||
request<{ ok: true; learned: string | null }>(`/api/utterances/${encodeURIComponent(id)}/delete`, { method: 'POST', body: JSON.stringify({ noise }) }),
|
||||
noisePhrases: () => request<{ phrases: NoisePhrase[] }>('/api/noise-phrases'),
|
||||
deleteNoisePhrase: (id: number) => request<{ ok: true }>(`/api/noise-phrases/${id}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
export interface DictionaryEntry {
|
||||
|
||||
94
site/web/src/lib/map3d.ts
Normal file
94
site/web/src/lib/map3d.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import * as THREE from 'three';
|
||||
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
|
||||
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
|
||||
|
||||
/**
|
||||
* 발로란트 맵 3D 모양 (사이트 서버 /site/maps3d, 로그인 필요).
|
||||
* glb 의 위치는 UE 월드 좌표(cm) 그대로다. 리플레이 선수 x,y,z 와 같은 좌표라 같은 변환으로 옮기면 겹친다.
|
||||
*/
|
||||
interface Index {
|
||||
dir: string | null;
|
||||
version: string | null;
|
||||
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
|
||||
}
|
||||
|
||||
let indexP: Promise<Index | null> | null = null;
|
||||
function loadIndex(): Promise<Index | null> {
|
||||
indexP ??= fetch('/site/maps3d', { credentials: 'same-origin' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<Index>) : null))
|
||||
.catch(() => null)
|
||||
.then((d) => {
|
||||
if (!d) indexP = null; // 실패하면 다음에 다시
|
||||
return d;
|
||||
});
|
||||
return indexP;
|
||||
}
|
||||
|
||||
export interface Map3dInfo {
|
||||
url: string;
|
||||
bytes: number;
|
||||
triangles: number;
|
||||
version: string | null;
|
||||
}
|
||||
|
||||
/** 경기 맵 경로(/Game/Maps/Ascent/Ascent)의 3D 파일. 없으면 null. 폴더 대소문자는 게임 파일과 다를 수 있어 무시한다 */
|
||||
export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
|
||||
const idx = await loadIndex();
|
||||
if (!idx?.dir || !mapUrl) return null;
|
||||
const key = mapUrl.toLowerCase();
|
||||
const hit = Object.entries(idx.maps).find(([k]) => k.toLowerCase() === key)?.[1];
|
||||
return hit ? { url: `/site/maps3d/${encodeURIComponent(idx.dir)}/${encodeURIComponent(hit.file)}`, bytes: hit.bytes, triangles: hit.triangles, version: idx.version } : null;
|
||||
}
|
||||
|
||||
/** glb 를 받아 메시 하나로. onProgress: 0~1 */
|
||||
export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
|
||||
const loader = new GLTFLoader();
|
||||
loader.setMeshoptDecoder(MeshoptDecoder);
|
||||
return new Promise((resolve, reject) => {
|
||||
loader.load(
|
||||
url,
|
||||
(gltf) => {
|
||||
gltf.scene.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
if (mesh.isMesh) {
|
||||
mesh.material = material;
|
||||
mesh.frustumCulled = false;
|
||||
}
|
||||
});
|
||||
resolve(gltf.scene);
|
||||
},
|
||||
(e) => onProgress?.(e.total ? e.loaded / e.total : 0),
|
||||
reject,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** UE 월드 좌표(cm) → 3D 리플레이 화면 좌표. ReplayViewer 의 toWorld 와 같은 식을 행렬로 */
|
||||
export function worldMatrix(T: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, S: number, zBase: number, vex: number) {
|
||||
const h = Math.abs(T.xMultiplier) * S * vex;
|
||||
return new THREE.Matrix4().set(
|
||||
0, T.xMultiplier * S, 0, (T.xScalarToAdd - 0.5) * S,
|
||||
0, 0, h, -zBase * h,
|
||||
T.yMultiplier * S, 0, 0, (T.yScalarToAdd - 0.5) * S,
|
||||
0, 0, 0, 1,
|
||||
);
|
||||
}
|
||||
|
||||
/** 높이에 따라 색이 바뀌는 맵 재질 (낮은 곳 푸른 회색 → 높은 곳 밝은 베이지). 천장 자르기 평면을 쓴다 */
|
||||
export function mapMaterial(clip: THREE.Plane, yRange: { lo: number; hi: number }) {
|
||||
const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.92, metalness: 0, flatShading: true, side: THREE.DoubleSide, clippingPlanes: [clip], clipShadows: true });
|
||||
mat.onBeforeCompile = (sh) => {
|
||||
sh.uniforms.uLo = { value: yRange.lo };
|
||||
sh.uniforms.uHi = { value: yRange.hi };
|
||||
sh.vertexShader = sh.vertexShader
|
||||
.replace('#include <common>', '#include <common>\nvarying float vH;')
|
||||
.replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvH = (modelMatrix * vec4(transformed, 1.0)).y;');
|
||||
sh.fragmentShader = sh.fragmentShader
|
||||
.replace('#include <common>', '#include <common>\nvarying float vH;\nuniform float uLo;\nuniform float uHi;')
|
||||
.replace(
|
||||
'vec4 diffuseColor = vec4( diffuse, opacity );',
|
||||
'float hN = clamp((vH - uLo) / max(uHi - uLo, 0.001), 0.0, 1.0);\nvec4 diffuseColor = vec4(mix(vec3(0.20, 0.25, 0.32), vec3(0.62, 0.57, 0.48), hN), opacity);',
|
||||
);
|
||||
};
|
||||
return mat;
|
||||
}
|
||||
141
site/web/src/lib/replay.ts
Normal file
141
site/web/src/lib/replay.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import type { KillData, MatchDetail } from '@gvr/shared';
|
||||
|
||||
/** tools/replay-extract (gvr-replay v1) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위 */
|
||||
export interface ReplayFile {
|
||||
format: 'gvr-replay';
|
||||
v: 1;
|
||||
matchId: string | null;
|
||||
map: string | null;
|
||||
build: string | null;
|
||||
/** 리플레이 녹화 시작 (서버 시계, 유닉스 ms) */
|
||||
recordedAt: number;
|
||||
durationMs: number;
|
||||
sampleMs: number;
|
||||
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[] } }[];
|
||||
rounds: { num: number; buy: number; combat: number; end: number }[];
|
||||
phases: [number, number][];
|
||||
/** [t, killer, victim] */
|
||||
kills: [number, number, number][];
|
||||
/** [t, player, x, y, z, yaw, pitch] */
|
||||
shots: [number, number, number, number, number, number, number][];
|
||||
/** [t0, t1, kind, x, y, z, owner] */
|
||||
objects: [number, number, number, number, number, number, number][];
|
||||
objectKinds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리플레이 시간(t) ↔ 기록 시각(ts, 게임 PC 시계) 맞추기.
|
||||
* 기본: ts = recordedAt + t + offset. offset 은 같은 킬(죽인 사람 · 죽은 사람이 같은 것)이
|
||||
* 경기 기록(match-details → 킬 이벤트 ts)과 리플레이에서 각각 언제인지 비교한 차이의 중앙값.
|
||||
* 킬을 못 맞추면 라운드 교전 시작으로 맞춘다 (정확도 낮음).
|
||||
*/
|
||||
export interface ReplaySync {
|
||||
offset: number;
|
||||
/** 맞춘 킬 수 */
|
||||
matched: number;
|
||||
/** 킬별 차이가 중앙값에서 벗어난 정도 (절대값 최대, ms). 이게 작아야 동기화가 정확하다 */
|
||||
spreadMs: number | null;
|
||||
/** 킬별 차이 (ms, 중앙값 기준) */
|
||||
residuals: number[];
|
||||
}
|
||||
|
||||
export function computeSync(m: MatchDetail, r: ReplayFile): ReplaySync {
|
||||
const kills = m.events.filter((e) => e.type === 'kill');
|
||||
const used = new Set<string>();
|
||||
const diffs: number[] = [];
|
||||
for (const [t, ki, vi] of r.kills) {
|
||||
const killer = r.players[ki]?.puuid;
|
||||
const victim = r.players[vi]?.puuid;
|
||||
if (!victim) continue;
|
||||
const at = r.recordedAt + t;
|
||||
let best: { id: string; d: number } | null = null;
|
||||
for (const e of kills) {
|
||||
if (used.has(e.id)) continue;
|
||||
const d = e.data as KillData;
|
||||
if (d.victim?.puuid !== victim) continue;
|
||||
if (killer && d.killer?.puuid && d.killer.puuid !== killer) continue;
|
||||
const diff = e.ts - at;
|
||||
// 1분 넘게 차이 나면 다른 라운드의 킬
|
||||
if (Math.abs(diff - (diffs.length ? median(diffs) : diff)) > 60000) continue;
|
||||
if (!best || Math.abs(diff) < Math.abs(best.d)) best = { id: e.id, d: diff };
|
||||
}
|
||||
if (best) {
|
||||
used.add(best.id);
|
||||
diffs.push(best.d);
|
||||
}
|
||||
}
|
||||
if (diffs.length >= 3) {
|
||||
const off = median(diffs);
|
||||
const residuals = diffs.map((d) => d - off);
|
||||
return { offset: off, matched: diffs.length, spreadMs: Math.max(...residuals.map(Math.abs)), residuals };
|
||||
}
|
||||
// 킬로 못 맞추면 라운드 교전 시작으로 맞춘다. 앱은 라운드 시작을 "교전 시작 - 30초" 로 저장한다 (valorant.ts BUY_MS)
|
||||
const rd: number[] = [];
|
||||
for (const mr of m.rounds ?? []) {
|
||||
const rr = r.rounds.find((x) => x.num === mr.num);
|
||||
if (rr && rr.combat >= 0) rd.push(mr.startedAt + 30000 - (r.recordedAt + rr.combat));
|
||||
}
|
||||
if (rd.length) return { offset: median(rd), matched: 0, spreadMs: null, residuals: [] };
|
||||
return { offset: 0, matched: 0, spreadMs: null, residuals: [] };
|
||||
}
|
||||
|
||||
function median(a: number[]): number {
|
||||
const s = [...a].sort((x, y) => x - y);
|
||||
const n = s.length;
|
||||
return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
|
||||
}
|
||||
|
||||
/** 이동 기록에서 t 시점 위치 (앞뒤 표본 사이 직선 보간). 표본이 sampleMs*5 넘게 끊겼으면 그 사이는 없음 */
|
||||
export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: number, gapMs: number) {
|
||||
const T = tr.t;
|
||||
if (!T.length || t < T[0] - gapMs) return null;
|
||||
let lo = 0;
|
||||
let hi = T.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (T[mid] <= t) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
const i = lo;
|
||||
const j = Math.min(i + 1, T.length - 1);
|
||||
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: tr.pitch[i], stale: true };
|
||||
const span = T[j] - T[i];
|
||||
const k = j === i || span > gapMs || span <= 0 ? 0 : Math.min(1, Math.max(0, (t - T[i]) / span));
|
||||
let dy = tr.yaw[j] - tr.yaw[i];
|
||||
if (dy > 180) dy -= 360;
|
||||
if (dy < -180) dy += 360;
|
||||
return {
|
||||
x: tr.x[i] + (tr.x[j] - tr.x[i]) * k,
|
||||
y: tr.y[i] + (tr.y[j] - tr.y[i]) * k,
|
||||
z: tr.z[i] + (tr.z[j] - tr.z[i]) * k,
|
||||
yaw: tr.yaw[i] + dy * k,
|
||||
pitch: tr.pitch[i] + (tr.pitch[j] - tr.pitch[i]) * k,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** t 가 속한 라운드 (구매 단계 시작 기준) */
|
||||
export function roundAt(r: ReplayFile, t: number) {
|
||||
let cur = r.rounds[0] ?? null;
|
||||
for (const rd of r.rounds) if (rd.buy <= t) cur = rd;
|
||||
return cur;
|
||||
}
|
||||
|
||||
/** 이 라운드에서 t 전에 죽었는지 (다시 움직인 기록이 있으면 부활로 본다) */
|
||||
export function isDead(r: ReplayFile, player: number, t: number) {
|
||||
const rd = roundAt(r, t);
|
||||
if (!rd) return false;
|
||||
let death = -1;
|
||||
for (const [kt, , v] of r.kills) if (v === player && kt >= rd.buy && kt <= t) death = kt;
|
||||
if (death < 0) return false;
|
||||
const T = r.players[player]?.track.t ?? [];
|
||||
// 죽은 뒤 2초 넘어 움직인 표본이 t 전에 있으면 살아난 것
|
||||
let lo = 0;
|
||||
let hi = T.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (T[mid] <= death + 2000) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return !(lo < T.length && T[lo] <= t);
|
||||
}
|
||||
24
site/web/src/lib/unknown-users.ts
Normal file
24
site/web/src/lib/unknown-users.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* 처음 보는 유저 아이디가 오면 유저 목록을 다시 받아 온다 (v1.4.1 이하 앱은 녹음 중에 들어온 사람을 알려 주지 않아 "알 수 없음"으로 뜸).
|
||||
* - 받는 중에는 또 부르지 않는다
|
||||
* - 받기에 성공한 아이디는 다시 묻지 않는다 (목록에 없어도 매 발화마다 부르지 않게)
|
||||
* - 실패하면 기억하지 않아 다음 이벤트에서 다시 받는다
|
||||
*/
|
||||
export function makeUnknownUserCheck(load: () => Promise<unknown>) {
|
||||
const done = new Set<string>();
|
||||
let busy = false;
|
||||
return (ids: string[], known: (id: string) => boolean): void => {
|
||||
if (busy) return;
|
||||
const fresh = ids.filter((id) => id && !known(id) && !done.has(id));
|
||||
if (!fresh.length) return;
|
||||
busy = true;
|
||||
load()
|
||||
.then(
|
||||
() => fresh.forEach((id) => done.add(id)),
|
||||
() => {},
|
||||
)
|
||||
.finally(() => {
|
||||
busy = false;
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { NoisePhrase } from '@gvr/shared';
|
||||
import { api, type DictionaryResponse } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { sfx } from '../lib/sfx';
|
||||
@@ -17,12 +18,18 @@ export function DictionaryPage() {
|
||||
const [from, setFrom] = useState('');
|
||||
const [to, setTo] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
// "잡음이라 삭제"로 배운 문장 (v1.4.0). 예전 앱이면 null → 칸을 숨긴다
|
||||
const [noise, setNoise] = useState<NoisePhrase[] | null>(null);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.dictionary()
|
||||
.then((d) => alive && setData(d))
|
||||
.catch((e) => alive && setErr(e));
|
||||
api
|
||||
.noisePhrases()
|
||||
.then((r) => alive && setNoise(r.phrases))
|
||||
.catch(() => alive && setNoise(null));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
@@ -110,6 +117,34 @@ export function DictionaryPage() {
|
||||
</table>
|
||||
</section>
|
||||
</div>
|
||||
{noise && (
|
||||
<section className="card dict-noise">
|
||||
<h3 className="h">
|
||||
잡음으로 배운 문장 <span className="dim small">{noise.length}</span>
|
||||
</h3>
|
||||
<p className="muted small">타임라인에서 우클릭 → 삭제 → "잡음이라 삭제"로 넣은 문장입니다. 같은 문장이 다시 인식되면 자동으로 잡음 처리합니다 (띄어쓰기 · 문장부호 무시, 8글자 이상이면 글자 수가 같고 한두 글자만 바뀐 것까지. 앞뒤에 다른 말이 붙으면 그대로 둡니다). 실제 말까지 걸러지면 여기서 지워 주세요.</p>
|
||||
<table className="dict-table">
|
||||
<tbody>
|
||||
{noise.length === 0 && (
|
||||
<tr>
|
||||
<td className="dim small">아직 없습니다</td>
|
||||
</tr>
|
||||
)}
|
||||
{noise.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td className="from">{p.text}</td>
|
||||
<td className="dim small">{p.hits ? `${p.hits}번 거름` : ''}</td>
|
||||
<td>
|
||||
<button className="link" disabled={busy} onClick={() => void run(() => api.deleteNoisePhrase(p.id))}>
|
||||
삭제
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -321,6 +321,9 @@ export function TimelinePage() {
|
||||
if (i < 0) return next ? prev : [...prev, it];
|
||||
return [...prev.slice(0, i), it, ...prev.slice(i)];
|
||||
});
|
||||
} else if (e.type === 'utterance.deleted') {
|
||||
// 우클릭으로 지운 발화 (v1.4.0)
|
||||
setItems((prev) => prev.filter((p) => p.id !== e.data.id));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { KillLine, SeparatorRow } from '../components/EventRow';
|
||||
import { IPlay, IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
import { ReplayPanel } from '../components/ReplayPanel';
|
||||
|
||||
const BUY_MS = 30000;
|
||||
/** "R7 · 0:38" → "0:38" */
|
||||
@@ -299,6 +300,7 @@ export function ValorantMatch({ m }: { m: MatchDetail }) {
|
||||
</div>
|
||||
<RoundStrip rounds={rounds} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
<ReplayPanel m={m} />
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use
|
||||
import type { DeviceStatus, LiveEvent, Overview, User } from '@gvr/shared';
|
||||
import { api, onApiSignal, type Me } from '../lib/api';
|
||||
import { live, type LiveConn } from '../lib/live';
|
||||
import { makeUnknownUserCheck } from '../lib/unknown-users';
|
||||
|
||||
// ── 로그인 ───────────────────────────────────────────
|
||||
type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me };
|
||||
@@ -139,21 +140,28 @@ export function DataProvider({ children }: { children: ReactNode }) {
|
||||
alive = false;
|
||||
};
|
||||
}, [epoch, locked]);
|
||||
const fetchUsers = useCallback(() => api.users().then((users) => setOverview((o) => (o ? { ...o, users } : o))), []);
|
||||
const reloadUsers = useCallback(() => void fetchUsers().catch(() => {}), [fetchUsers]);
|
||||
const users = overview?.users ?? [];
|
||||
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
// 처음 보는 사람 아이디가 오면 유저 목록을 다시 받아 온다 (실패하면 다음 이벤트에서 다시)
|
||||
const unknownCheck = useRef(makeUnknownUserCheck(fetchUsers));
|
||||
const checkUnknown = (ids: string[]) => {
|
||||
if (overview) unknownCheck.current(ids, (id) => map.has(id));
|
||||
};
|
||||
useLive((e) => {
|
||||
if (e.type === 'users.updated') {
|
||||
// v1.3.5 이하 앱은 빈 목록을 보낸다: 그대로 쓰면 모든 발화가 "알 수 없음"이 되니 다시 받아 온다
|
||||
if (e.data.length) setOverview((o) => (o ? { ...o, users: e.data } : o));
|
||||
else
|
||||
api
|
||||
.users()
|
||||
.then((users) => setOverview((o) => (o ? { ...o, users } : o)))
|
||||
.catch(() => {});
|
||||
else reloadUsers();
|
||||
}
|
||||
if (e.type === 'recording.state') setOverview((o) => (o ? { ...o, recording: e.data } : o));
|
||||
if (e.type === 'recording.state') {
|
||||
setOverview((o) => (o ? { ...o, recording: e.data } : o));
|
||||
checkUnknown(e.data.participants);
|
||||
}
|
||||
if (e.type === 'utterance.created' || e.type === 'utterance.updated') checkUnknown([e.data.userId]);
|
||||
if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o));
|
||||
});
|
||||
const users = overview?.users ?? [];
|
||||
const map = useMemo(() => new Map(users.map((u) => [u.id, u])), [users]);
|
||||
const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]);
|
||||
return <DataCtx.Provider value={{ overview, users, userById }}>{children}</DataCtx.Provider>;
|
||||
}
|
||||
|
||||
@@ -10,17 +10,21 @@ export interface Settings {
|
||||
normalize: boolean;
|
||||
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
|
||||
playVolume: number;
|
||||
/** 기본값을 바꾼 횟수 (예전에 저장한 설정을 한 번만 새 기본값으로 맞춘다) */
|
||||
defaultsRev?: number;
|
||||
}
|
||||
|
||||
const KEY = 'gvr.settings.v1';
|
||||
const DEFAULTS: Settings = {
|
||||
volume: 0.5,
|
||||
sfx: { click: true, play: true, kill: true, round: true, chime: true },
|
||||
// 새 발화 알림 · 재생 시작 효과음은 기본으로 끈다 (v1.4.0)
|
||||
sfx: { click: true, play: false, kill: true, round: true, chime: false },
|
||||
reduceMotion: false,
|
||||
rate: 1,
|
||||
continuous: true,
|
||||
normalize: true,
|
||||
playVolume: 1,
|
||||
defaultsRev: 1,
|
||||
};
|
||||
|
||||
function load(): Settings {
|
||||
@@ -28,7 +32,18 @@ function load(): Settings {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return DEFAULTS;
|
||||
const v = JSON.parse(raw) as Partial<Settings>;
|
||||
return { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
|
||||
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
|
||||
// 예전 사이트는 설정을 하나만 바꿔도 효과음 켜짐/꺼짐을 전부 저장했다: 새 기본값(두 알림 끄기)을 한 번 적용
|
||||
if ((v.defaultsRev ?? 0) < 1) {
|
||||
out.sfx = { ...out.sfx, play: false, chime: false };
|
||||
out.defaultsRev = 1;
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(out));
|
||||
} catch {
|
||||
/* 사생활 보호 모드 등 */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return DEFAULTS;
|
||||
}
|
||||
|
||||
@@ -3211,6 +3211,9 @@ button.match:hover {
|
||||
@media (max-width: 900px) { .dict-grid { grid-template-columns: 1fr; } }
|
||||
.dict-grid .card { background: #121e29; border: 1px solid #243545; border-radius: 12px; padding: 16px 18px; }
|
||||
.dict-grid h3 { font-size: 15px; margin-bottom: 12px; }
|
||||
.dict-noise { margin-top: 16px; background: #121e29; border: 1px solid #243545; border-radius: 12px; padding: 16px 18px; }
|
||||
.dict-noise h3 { font-size: 15px; margin-bottom: 6px; }
|
||||
.dict-noise p { margin: 0 0 10px; }
|
||||
.dict-form { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }
|
||||
.dict-form input { flex: 1; min-width: 0; background: #0d1720; border: 1px solid #243545; border-radius: 8px; padding: 9px 12px; color: inherit; }
|
||||
.dict-list { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
@@ -3579,6 +3582,53 @@ button.match:hover {
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.ctx-toast.ok {
|
||||
background: #102a1f;
|
||||
border-color: #23573f;
|
||||
color: #a6f0c6;
|
||||
}
|
||||
.ctx-sep {
|
||||
height: 1px;
|
||||
margin: 4px 6px;
|
||||
background: #22323f;
|
||||
}
|
||||
.ctx-menu button.danger:not(:disabled) {
|
||||
color: #ff9aa3;
|
||||
}
|
||||
.ctx-menu button.danger:hover:not(:disabled) {
|
||||
background: rgba(255, 70, 85, 0.14);
|
||||
}
|
||||
.del-dialog {
|
||||
width: min(480px, 100%);
|
||||
}
|
||||
.del-quote {
|
||||
padding: 10px 12px;
|
||||
border-radius: 9px;
|
||||
background: #13202c;
|
||||
border: 1px solid #22323f;
|
||||
font-size: 12px;
|
||||
}
|
||||
.del-quote p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 14px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.del-help {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--muted);
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
.del-err {
|
||||
font-size: 13px;
|
||||
color: #ff9aa3;
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
.chip.danger.on {
|
||||
background: rgba(255, 70, 85, 0.22);
|
||||
border-color: rgba(255, 70, 85, 0.7);
|
||||
color: #ffd0d4;
|
||||
}
|
||||
|
||||
/* ── 사이트 로그 (/logs) ── */
|
||||
.logs-page {
|
||||
@@ -3884,3 +3934,148 @@ button.match:hover {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ── 3D 리플레이 (components/ReplayViewer.tsx) ── */
|
||||
.replay-panel {
|
||||
flex: none;
|
||||
}
|
||||
.match.val:has(.replay-panel.open) {
|
||||
height: auto;
|
||||
}
|
||||
.match.val:has(.replay-panel.open) .mgrid {
|
||||
flex: none;
|
||||
height: 680px;
|
||||
}
|
||||
.r3d {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.r3d-stage {
|
||||
position: relative;
|
||||
height: min(72vh, 760px);
|
||||
min-height: 420px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
background: #0b141c;
|
||||
}
|
||||
.r3d-stage canvas {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: grab;
|
||||
}
|
||||
.r3d-stage canvas:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.r3d-hud {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
padding: 8px 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(8, 14, 20, 0.72);
|
||||
font-size: 14px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-hud.tl {
|
||||
top: 10px;
|
||||
left: 10px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.r3d-hud.tr {
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
align-items: flex-end;
|
||||
}
|
||||
.r3d-hud.bl {
|
||||
left: 10px;
|
||||
bottom: 10px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.r3d-kill {
|
||||
background: rgba(8, 14, 20, 0.78);
|
||||
border-radius: 8px;
|
||||
padding: 4px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.r3d .a {
|
||||
color: #8fd8ff;
|
||||
}
|
||||
.r3d .e {
|
||||
color: #ff9aa5;
|
||||
}
|
||||
.r3d-cap {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
left: 50%;
|
||||
bottom: 14px;
|
||||
transform: translateX(-50%);
|
||||
max-width: min(70%, 760px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-cap > div {
|
||||
background: rgba(8, 14, 20, 0.82);
|
||||
border-radius: 8px;
|
||||
padding: 6px 12px;
|
||||
font-size: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
.r3d-cap b {
|
||||
color: var(--gold);
|
||||
margin-right: 6px;
|
||||
}
|
||||
.r3d-follow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.r3d-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.r3d-play {
|
||||
min-width: 44px;
|
||||
}
|
||||
.r3d-scrub {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.r3d-scrub input {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.r3d-scrub i {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
width: 1px;
|
||||
height: 8px;
|
||||
background: var(--muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-foot {
|
||||
font-size: 12px;
|
||||
}
|
||||
.r3d-ceil {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.r3d-ceil input {
|
||||
width: 90px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
4
tools/map-extract/.gitignore
vendored
Normal file
4
tools/map-extract/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
vendor/
|
||||
bin/
|
||||
obj/
|
||||
out/
|
||||
20
tools/map-extract/MapExtract.csproj
Normal file
20
tools/map-extract/MapExtract.csproj
Normal file
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- 발로란트 맵 3D 모양 추출: Riot CDN 에서 필요한 부분만 읽어(게임 설치 · 전체 다운로드 없음) 맵마다 glb 하나.
|
||||
CUE4Parse 는 fetch-cue4parse.sh 로 vendor/ 에 받는다. 빌드: CUE4PARSE_SKIP_NATIVE=1 dotnet build -c Release -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>gvr-map-extract</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<ServerGarbageCollection>false</ServerGarbageCollection>
|
||||
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="src/**/*.cs" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse/CUE4Parse.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
15
tools/map-extract/fetch-cue4parse.sh
Executable file
15
tools/map-extract/fetch-cue4parse.sh
Executable file
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# CUE4Parse (Apache-2.0, https://github.com/FabianFG/CUE4Parse) 를 고정 커밋으로 받아 vendor/ 에 둔다.
|
||||
# 발로란트 패치로 읽기가 깨지면 CUE4PARSE_COMMIT 을 새 커밋으로 올린다.
|
||||
set -euo pipefail
|
||||
CUE4PARSE_COMMIT="${CUE4PARSE_COMMIT:-605672df7a993a90094bad92d30c388d87ae6c1a}"
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
dst="$here/vendor/CUE4Parse"
|
||||
if [ ! -d "$dst/.git" ]; then
|
||||
git clone --quiet https://github.com/FabianFG/CUE4Parse "$dst"
|
||||
fi
|
||||
if [ "$(git -C "$dst" rev-parse HEAD)" != "$CUE4PARSE_COMMIT" ]; then
|
||||
git -C "$dst" fetch --quiet origin
|
||||
git -C "$dst" checkout --quiet --force "$CUE4PARSE_COMMIT"
|
||||
fi
|
||||
echo "CUE4Parse @ $(git -C "$dst" rev-parse --short HEAD)"
|
||||
62
tools/map-extract/scripts/install.sh
Executable file
62
tools/map-extract/scripts/install.sh
Executable file
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env bash
|
||||
# 맵 3D 자동 갱신을 이 리눅스 서버(.9)에 설치한다. 저장소에서: tools/map-extract/scripts/install.sh
|
||||
# - gvr-map-extract 를 빌드해 $GVR_MAPS_HOME/bin 에 둔다 (저장소 작업 폴더가 바뀌어도 타이머는 그대로 돈다)
|
||||
# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup
|
||||
# 코드를 고쳤으면 다시 실행하면 된다. 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
|
||||
export PATH="$HOME/.dotnet:$PATH" DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DOTNET_CLI_TELEMETRY_OPTOUT=1
|
||||
"$here/fetch-cue4parse.sh"
|
||||
rm -rf "$GVR_MAPS_HOME/bin.new"
|
||||
CUE4PARSE_SKIP_NATIVE=1 dotnet build "$here/MapExtract.csproj" -c Release -o "$GVR_MAPS_HOME/bin.new" -v quiet -nologo -clp:ErrorsOnly
|
||||
rm -rf "$GVR_MAPS_HOME/bin.old"
|
||||
[ -d "$GVR_MAPS_HOME/bin" ] && mv "$GVR_MAPS_HOME/bin" "$GVR_MAPS_HOME/bin.old"
|
||||
mv "$GVR_MAPS_HOME/bin.new" "$GVR_MAPS_HOME/bin"
|
||||
# Oodle 압축 풀기 라이브러리: 처음 실행 때 받는다. 이전 설치에 있으면 옮겨 둔다
|
||||
[ -f "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" ] && cp "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" "$GVR_MAPS_HOME/bin/"
|
||||
rm -rf "$GVR_MAPS_HOME/bin.old"
|
||||
mkdir -p "$GVR_MAPS_HOME/scripts"
|
||||
cp "$here/scripts/update.sh" "$here/scripts/pack.py" "$here/scripts/preview.py" "$GVR_MAPS_HOME/scripts/"
|
||||
chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
|
||||
|
||||
unit="$HOME/.config/systemd/user"
|
||||
mkdir -p "$unit"
|
||||
node_dir="$(dirname "$(command -v node)")"
|
||||
cat > "$unit/gvr-maps-update.service" <<EOF
|
||||
[Unit]
|
||||
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (uedb 매핑 · 라이브 패치 확인 → 추출 → 사이트 반영)
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
Environment=GVR_MAPS_HOME=$GVR_MAPS_HOME
|
||||
Environment=DOTNET_ROOT=$DOTNET_ROOT
|
||||
Environment=PATH=$node_dir:$HOME/.dotnet:/usr/local/bin:/usr/bin:/bin
|
||||
Environment=TMPDIR=$HOME/.tmp
|
||||
Environment=NOTIFY_CHANNEL=${NOTIFY_CHANNEL:-}
|
||||
Environment=NOTIFY_ENV=${NOTIFY_ENV:-}
|
||||
ExecStart=$GVR_MAPS_HOME/scripts/update.sh
|
||||
MemoryMax=6G
|
||||
MemorySwapMax=0
|
||||
CPUQuota=300%
|
||||
CPUWeight=50
|
||||
Nice=10
|
||||
TimeoutStartSec=2h
|
||||
EOF
|
||||
cat > "$unit/gvr-maps-update.timer" <<EOF
|
||||
[Unit]
|
||||
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (30분마다)
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5min
|
||||
OnUnitActiveSec=30min
|
||||
RandomizedDelaySec=2min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now gvr-maps-update.timer
|
||||
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
|
||||
33
tools/map-extract/scripts/pack.py
Executable file
33
tools/map-extract/scripts/pack.py
Executable file
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
|
||||
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
|
||||
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
|
||||
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
|
||||
import datetime, gzip, json, os, re, shutil, subprocess, sys
|
||||
|
||||
src, out, version = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M')
|
||||
d = re.sub(r'[^\w.-]', '_', f'{version}-{stamp}')
|
||||
os.makedirs(os.path.join(out, d), exist_ok=True)
|
||||
maps = {}
|
||||
for name in sorted(os.listdir(src)):
|
||||
if not name.endswith('.json'):
|
||||
continue
|
||||
info = json.load(open(os.path.join(src, name)))
|
||||
code = info['code']
|
||||
glb = os.path.join(src, code + '.glb')
|
||||
if not os.path.exists(glb) or info.get('triangles', 0) == 0:
|
||||
continue
|
||||
packed = os.path.join(out, d, code + '.glb')
|
||||
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc'], check=True, stdout=subprocess.DEVNULL)
|
||||
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
|
||||
shutil.copyfileobj(f, g)
|
||||
os.remove(packed)
|
||||
size = os.path.getsize(packed + '.gz')
|
||||
maps[info['mapUrl']] = {'code': code, 'file': code + '.glb', 'bytes': size, 'triangles': info['triangles']}
|
||||
print(f"{code}: {info['triangles']} 삼각형 → {size / 1e6:.1f}MB")
|
||||
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps}
|
||||
tmp = os.path.join(out, 'index.json.tmp')
|
||||
json.dump(idx, open(tmp, 'w'), ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, os.path.join(out, 'index.json'))
|
||||
print(f'index.json: 맵 {len(maps)}개 · 폴더 {d}')
|
||||
43
tools/map-extract/scripts/preview.py
Executable file
43
tools/map-extract/scripts/preview.py
Executable file
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""추출한 맵 glb 를 위에서 본 그림(PNG)으로 그린다. 확인용.
|
||||
preview.py <맵.glb> <출력.png> [천장 cm (이보다 높은 삼각형 제외)]
|
||||
삼각형마다 무게중심 · 꼭짓점을 찍고 높은 것이 위에 오게 칠한다 (빠른 근사)."""
|
||||
import json, struct, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
zmax = float(sys.argv[3]) if len(sys.argv) > 3 else None
|
||||
b = open(src, 'rb').read()
|
||||
jl = struct.unpack('<I', b[12:16])[0]
|
||||
j = json.loads(b[20:20 + jl])
|
||||
bin_ = b[20 + jl + 8:]
|
||||
pa, ia = j['accessors'][0], j['accessors'][1]
|
||||
pv, iv = j['bufferViews'][pa['bufferView']], j['bufferViews'][ia['bufferView']]
|
||||
P = np.frombuffer(bin_, '<f4', pa['count'] * 3, pv.get('byteOffset', 0)).reshape(-1, 3)
|
||||
I = np.frombuffer(bin_, '<u4', ia['count'], iv.get('byteOffset', 0)).reshape(-1, 3)
|
||||
T = P[I] # (n,3,3)
|
||||
if zmax is not None:
|
||||
T = T[T[:, :, 2].max(1) < zmax]
|
||||
# 면 방향 음영
|
||||
n = np.cross(T[:, 1] - T[:, 0], T[:, 2] - T[:, 0])
|
||||
n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-9
|
||||
lum = 0.35 + 0.65 * np.abs(n @ np.array([0.3, 0.5, 0.81]))
|
||||
pts = np.concatenate([T.mean(1), T[:, 0], T[:, 1], T[:, 2], (T[:, 0] + T[:, 1]) / 2, (T[:, 1] + T[:, 2]) / 2, (T[:, 0] + T[:, 2]) / 2])
|
||||
L = np.tile(lum, 7)
|
||||
lo, hi = np.percentile(pts, 0.5, axis=0), np.percentile(pts, 99.5, axis=0)
|
||||
size = 1400
|
||||
s = (size - 20) / max(hi[0] - lo[0], hi[1] - lo[1])
|
||||
# 미니맵과 같은 방향: 화면 x = 월드 y, 화면 아래 = 월드 x 감소
|
||||
x = ((pts[:, 1] - lo[1]) * s + 10).astype(int)
|
||||
y = ((hi[0] - pts[:, 0]) * s + 10).astype(int)
|
||||
W, H = int((hi[1] - lo[1]) * s + 20), int((hi[0] - lo[0]) * s + 20)
|
||||
ok = (x >= 0) & (x < W) & (y >= 0) & (y < H)
|
||||
x, y, z, L = x[ok], y[ok], pts[ok, 2], L[ok]
|
||||
order = np.argsort(z) # 낮은 것 먼저, 높은 것이 덮는다
|
||||
img = np.zeros((H, W, 3), np.float32) + np.array([18, 20, 26], np.float32) / 255
|
||||
zn = np.clip((z - lo[2]) / (hi[2] - lo[2] + 1e-9), 0, 1)
|
||||
col = np.stack([0.35 + 0.45 * zn, 0.40 + 0.35 * zn, 0.55 - 0.15 * zn], 1) * L[:, None]
|
||||
img[y[order], x[order]] = col[order]
|
||||
Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8)).save(dst)
|
||||
print(dst, W, H, 'triangles', len(T), 'z', lo[2].round(), hi[2].round())
|
||||
52
tools/map-extract/scripts/test-update.sh
Executable file
52
tools/map-extract/scripts/test-update.sh
Executable file
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# update.sh 시험 (네트워크 · 사이트 서버 없이): 가짜 추출기 · 가짜 pack.py · ssh/scp 를 로컬 복사로 바꿔
|
||||
# 성공 → 변경 없음 → 추출 실패(첫 실패만 알림, 대기) → 재시도 간격 2배 → 맵 누락이면 안 올림 → 압축 실패 → 복구 → uedb 장애
|
||||
set -uo pipefail
|
||||
UPD="$(cd "$(dirname "$0")" && pwd)/update.sh"
|
||||
T="$(mktemp -d "${TMPDIR:-/tmp}/gvr-upd-test.XXXXXX")"
|
||||
trap 'rm -rf "$T"' EXIT
|
||||
mkdir -p "$T/home/scripts" "$T/shim" "$T/site"
|
||||
cat > "$T/shim/ssh" <<'E'
|
||||
#!/bin/bash
|
||||
while [[ "$1" == -* ]]; do shift 2; done; shift; exec bash -c "$*"
|
||||
E
|
||||
cat > "$T/shim/scp" <<'E'
|
||||
#!/bin/bash
|
||||
a=(); s=0; for x in "$@"; do [ $s = 1 ] && { s=0; continue; }; [ "$x" = -o ] && { s=1; continue; }; [[ "$x" == -* ]] && continue; a+=("${x#*:}"); done; cp "${a[0]}" "${a[1]}"
|
||||
E
|
||||
cat > "$T/fakebin" <<'E'
|
||||
#!/bin/bash
|
||||
[ "$1" = manifest ] && { echo "https://x/releases/${FAKE_MANIFEST:-AAA}.manifest"; exit 0; }
|
||||
[ "${FAKE_FAIL:-}" = extract ] && exit 1
|
||||
for m in ${FAKE_MAPS:-Ascent Bind}; do echo "{\"code\":\"$m\",\"mapUrl\":\"/Game/Maps/$m/$m\",\"triangles\":10}" > "$2/$m.json"; echo glb > "$2/$m.glb"; done
|
||||
E
|
||||
cat > "$T/home/scripts/pack.py" <<'E'
|
||||
import json, os, sys
|
||||
src, out, ver = sys.argv[1:4]; d = ver + '-' + os.environ.get('FAKE_STAMP', '1'); os.makedirs(f'{out}/{d}', exist_ok=True); maps = {}
|
||||
for n in os.listdir(src):
|
||||
if n.endswith('.json'):
|
||||
i = json.load(open(f'{src}/{n}')); open(f"{out}/{d}/{i['code']}.glb.gz", 'w').write('x'); maps[i['mapUrl']] = {'code': i['code'], 'file': i['code'] + '.glb', 'bytes': 1, 'triangles': 10}
|
||||
json.dump({'version': ver, 'dir': d, 'maps': maps}, open(f'{out}/index.json', 'w'))
|
||||
E
|
||||
chmod +x "$T/shim/"* "$T/fakebin"
|
||||
echo usmap > "$T/m_br.usmap"
|
||||
echo "{\"version\":\"V1\",\"updated\":\"2026-10-17T00:00:00Z\",\"mappings\":{\"Brotli\":\"file://$T/m_br.usmap\"}}" > "$T/uedb.json"
|
||||
run() { PATH="$T/shim:$PATH" GVR_MAPS_HOME="$T/home" SITE_HOST=x SITE_DATA="$T/site" UEDB="file://$T/uedb.json" BIN="$T/fakebin" SECRETS=/nonexistent NOTIFY_CHANNEL= bash "$UPD" "$@" 2>&1; }
|
||||
st() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get(sys.argv[2], ""))' "$T/home/state.json" "$1"; }
|
||||
ready() { python3 -c 'import json,sys; f=sys.argv[1]; d=json.load(open(f)); d["retryAt"]="0"; json.dump(d, open(f, "w"))' "$T/home/state.json"; }
|
||||
maps() { jq -c '.maps | keys' "$T/site/maps3d/index.json"; }
|
||||
fail=0
|
||||
ok() { if eval "$2"; then echo "ok - $1"; else echo "not ok - $1"; fail=1; fi; }
|
||||
|
||||
o="$(run)"; ok "처음: 올리고 알림" '[[ "$o" == *"사이트 반영 완료: 맵 2"* && "$o" == *"알림: 🗺️"* && "$(maps)" == *Bind* ]]'
|
||||
o="$(run)"; ok "같으면 변경 없음" '[[ "$o" == *"변경 없음"* ]]'
|
||||
o="$(FAKE_MANIFEST=BBB FAKE_FAIL=extract run)"; ok "추출 실패: 첫 실패 알림 · 30분 대기" '[[ "$o" == *"알림: ⚠️"* && "$o" == *"30분 뒤"* && "$(st failCount)" == 1 ]]'
|
||||
o="$(FAKE_MANIFEST=BBB run)"; ok "대기 중에는 다시 안 함" '[[ "$o" == *"이후 다시"* ]]'
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_FAIL=extract run)"; ok "재실패: 알림 없이 간격 2배" '[[ "$o" != *"알림:"* && "$o" == *"60분 뒤"* && "$(st failCount)" == 2 ]]'
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS=Ascent FAKE_STAMP=2 run)"; ok "맵이 빠진 결과는 안 올림" '[[ "$o" == *"빠진 맵: /Game/Maps/Bind/Bind"* && "$(maps)" == *Bind* ]]'
|
||||
ready; mv "$T/home/scripts/pack.py" "$T/pack.bak"; o="$(FAKE_MANIFEST=BBB run)"; mv "$T/pack.bak" "$T/home/scripts/pack.py"
|
||||
ok "압축 실패도 같은 실패 처리" '[[ "$o" == *"압축 단계"* ]]'
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS="Ascent Bind Haven" FAKE_STAMP=3 run)"; ok "복구: 새 맵 포함해 올리고 이전 폴더 하나만 남김" '[[ "$o" == *"맵 3 개"* && "$(maps)" == *Haven* && "$(ls "$T/site/maps3d" | tr "\n" " ")" == "V1-1 V1-3 index.json " && "$(st failCount)" == 0 ]]'
|
||||
mv "$T/uedb.json" "$T/uedb.bak"; o="$(FAKE_MANIFEST=CCC run)"; mv "$T/uedb.bak" "$T/uedb.json"; ok "uedb 장애: 확인 실패 횟수만 셈" '[[ "$o" == *"확인 실패 (1 번째"* ]]'
|
||||
o="$(FAKE_MANIFEST=DDD FAKE_MAPS=Ascent FAKE_STAMP=4 run --force)"; ok "--force 면 빠진 맵도 올림" '[[ "$(maps)" == "[\"/Game/Maps/Ascent/Ascent\"]" ]]'
|
||||
exit $fail
|
||||
153
tools/map-extract/scripts/update.sh
Executable file
153
tools/map-extract/scripts/update.sh
Executable file
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env bash
|
||||
# 발로란트 맵 3D 자동 갱신 (systemd 타이머가 30분마다 실행, install.sh 참고)
|
||||
#
|
||||
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝
|
||||
# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/
|
||||
# 3. 모든 맵을 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
|
||||
# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다
|
||||
#
|
||||
# 실패하면(어느 단계든) 사이트는 이전 맵을 그대로 쓰고, 같은 조합은 30분 · 1시간 · 2시간 … 최대 6시간 간격으로 다시 해 본다.
|
||||
# 처음 실패 · 다시 성공했을 때 알린다. 지금 올라가 있는 맵 중 하나라도 새 결과에 없으면 올리지 않는다 (일부 누락 방지).
|
||||
# 강제로 다시(대기 · 누락 검사 무시): update.sh --force
|
||||
set -Eeuo pipefail
|
||||
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
|
||||
SITE_HOST="${SITE_HOST:-root@192.168.10.5}"
|
||||
SITE_DATA="${SITE_DATA:-/root/other/game-voice-recorder/data}"
|
||||
UEDB="${UEDB:-https://uedb.dev/svc/api/v1/valorant/mappings}"
|
||||
SECRETS="${SECRETS:-$HOME/.config/ejclaw/secrets.json}"
|
||||
export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
|
||||
BIN="${BIN:-$GVR_MAPS_HOME/bin/gvr-map-extract}"
|
||||
STATE="$GVR_MAPS_HOME/state.json"
|
||||
mkdir -p "$GVR_MAPS_HOME/mappings" "$GVR_MAPS_HOME/work"
|
||||
exec 9>"$GVR_MAPS_HOME/.lock"
|
||||
flock -n 9 || { echo "이미 실행 중"; exit 0; }
|
||||
log() { echo "[$(date '+%F %T')] $*"; }
|
||||
# 결과 알림 (선택): NOTIFY_CHANNEL=<디스코드 채널 id>, NOTIFY_ENV=<DISCORD_OWNER_BOT_TOKEN 이 든 .env>
|
||||
notify() {
|
||||
log "알림: $1"
|
||||
[ -n "${NOTIFY_CHANNEL:-}" ] && [ -f "${NOTIFY_ENV:-}" ] || return 0
|
||||
local token
|
||||
token="$(grep -E '^DISCORD_OWNER_BOT_TOKEN=' "$NOTIFY_ENV" | head -1 | sed -E 's/^[^=]+=//' | tr -d '"'\''\r')"
|
||||
[ -n "$token" ] || return 0
|
||||
curl -sS -o /dev/null --max-time 20 -X POST "https://discord.com/api/v10/channels/$NOTIFY_CHANNEL/messages" \
|
||||
-H "Authorization: Bot $token" -H 'Content-Type: application/json' \
|
||||
-d "$(jq -nc --arg c "$1" '{content:$c, allowed_mentions:{parse:[]}}')" || true
|
||||
}
|
||||
st() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])) if __import__("os").path.exists(sys.argv[1]) else {}; print(d.get(sys.argv[2],""))' "$STATE" "$1"; }
|
||||
stn() { local v; v="$(st "$1")"; echo "${v:-0}"; }
|
||||
set_state() { python3 - "$STATE" "$@" <<'P'
|
||||
import json, os, sys
|
||||
f = sys.argv[1]
|
||||
d = json.load(open(f)) if os.path.exists(f) else {}
|
||||
for kv in sys.argv[2:]:
|
||||
k, v = kv.split('=', 1)
|
||||
d[k] = v
|
||||
json.dump(d, open(f + '.tmp', 'w'), indent=1)
|
||||
os.replace(f + '.tmp', f)
|
||||
P
|
||||
}
|
||||
|
||||
FORCE=0
|
||||
[ "${1:-}" = "--force" ] && FORCE=1
|
||||
stage="확인"
|
||||
key=""
|
||||
# 어느 단계에서 실패해도: 상태 기록(다음 재시도 시각) · 처음 실패면 알림. 사이트의 이전 맵은 그대로
|
||||
on_fail() {
|
||||
local rc=$?
|
||||
# $(...) 안에서 난 오류는 바깥 셸이 한 번 더 받는다 → 바깥에서만 처리
|
||||
[ "$BASHPID" = "$$" ] || exit "$rc"
|
||||
trap - ERR
|
||||
if [ -z "$key" ]; then
|
||||
# uedb · 매니페스트 확인 단계 (네트워크 문제 등). 3시간(6번) 연속이면 한 번 알림
|
||||
local n=$(( $(stn checkFails) + 1 ))
|
||||
set_state "checkFails=$n"
|
||||
log "확인 실패 ($n 번째 연속)"
|
||||
[ "$n" = 6 ] && notify "⚠️ 발로란트 맵 3D 자동 갱신: uedb · Riot 패치 확인이 3시간째 실패합니다. 로그: journalctl --user -u gvr-maps-update"
|
||||
exit "$rc"
|
||||
fi
|
||||
local n=1
|
||||
[ "$key" = "$(st failed)" ] && n=$(( $(stn failCount) + 1 ))
|
||||
local wait=$(( 1800 * (1 << (n > 5 ? 4 : n - 1)) ))
|
||||
[ "$wait" -gt 21600 ] && wait=21600
|
||||
set_state "failed=$key" "failCount=$n" "failedAt=$(date -Is)" "retryAt=$(( $(date +%s) + wait - 120 ))" "failStage=$stage"
|
||||
log "실패 ($stage 단계, $n 번째) → 사이트는 이전 맵 유지, $(( wait / 60 ))분 뒤 다시"
|
||||
[ "$n" = 1 ] && notify "⚠️ 발로란트 맵 3D 자동 갱신 실패 ($stage 단계 · 매핑 $version · 패치 $(basename "$manifest" .manifest)). 사이트는 이전 맵을 그대로 쓰고, 간격을 늘려 가며 다시 해 봅니다. 로그: journalctl --user -u gvr-maps-update"
|
||||
exit "$rc"
|
||||
}
|
||||
trap on_fail ERR
|
||||
|
||||
# 1. 바뀐 것이 있나
|
||||
meta="$(curl -fsS --max-time 30 "$UEDB")"
|
||||
version="$(jq -r .version <<<"$meta")"
|
||||
updated="$(jq -r .updated <<<"$meta")"
|
||||
usmap_url="$(jq -r '.mappings.Brotli // .mappings.ZStandard' <<<"$meta")"
|
||||
[ -n "$version" ] && [ "$version" != null ] && [ -n "$usmap_url" ] && [ "$usmap_url" != null ] || { log "uedb 응답 이상: $meta"; false; }
|
||||
manifest="$("$BIN" manifest)"
|
||||
set_state "checkFails=0"
|
||||
if [ "$version|$updated|$manifest" = "$(st published)" ] && [ "$FORCE" = 0 ]; then
|
||||
log "변경 없음 ($version, $(basename "$manifest"))"
|
||||
exit 0
|
||||
fi
|
||||
key="$version|$updated|$manifest"
|
||||
if [ "$FORCE" = 0 ] && [ "$key" = "$(st failed)" ] && [ "$(date +%s)" -lt "$(stn retryAt)" ]; then
|
||||
log "지난번 실패($(st failStage) 단계, $(st failCount)번) → $(date -d "@$(st retryAt)" '+%H:%M') 이후 다시"
|
||||
exit 0
|
||||
fi
|
||||
log "새로 뽑기: 매핑 $version ($updated) · 패치 $(basename "$manifest")"
|
||||
stage="매핑 받기"
|
||||
|
||||
# 2. 매핑 받기 · 보관
|
||||
stamp="$(date -u -d "$updated" +%Y%m%d%H%M 2>/dev/null || date -u +%Y%m%d%H%M)"
|
||||
usmap="$GVR_MAPS_HOME/mappings/${version}_${stamp}_$(basename "$usmap_url" | sed 's/^.*_\(br\|zs\)\.usmap$/\1/').usmap"
|
||||
if [ ! -s "$usmap" ]; then
|
||||
curl -fsS --max-time 300 -o "$usmap.part" "$usmap_url"
|
||||
mv "$usmap.part" "$usmap"
|
||||
log "매핑 저장 $usmap ($(stat -c %s "$usmap") 바이트)"
|
||||
# nextcloud 보관 (claude/ 폴더 안만 쓴다, 사용자 규칙)
|
||||
if [ -f "$SECRETS" ]; then
|
||||
read -r nc_host nc_user nc_token < <(python3 -c 'import json,sys; c=json.load(open(sys.argv[1]))["credentials"]["nextcloud.192.168.10.10"]; print(c["host"], c["username"], c["token"])' "$SECRETS") || true
|
||||
if [ -n "${nc_token:-}" ]; then
|
||||
dav="$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant/mappings"
|
||||
curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant" >/dev/null 2>&1 || true
|
||||
curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$dav" >/dev/null 2>&1 || true
|
||||
if curl -fsS -u "$nc_user:$nc_token" -T "$usmap" "$dav/$(basename "$usmap")" >/dev/null; then log "nextcloud 보관 완료"; else log "nextcloud 보관 실패 (계속 진행)"; fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. 뽑기 · 압축
|
||||
stage="추출"
|
||||
raw="$GVR_MAPS_HOME/work/raw"
|
||||
out="$GVR_MAPS_HOME/work/out"
|
||||
rm -rf "$raw" "$out"
|
||||
mkdir -p "$raw" "$out"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"
|
||||
stage="압축"
|
||||
python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version"
|
||||
dir="$(jq -r .dir "$out/index.json")"
|
||||
count="$(jq '.maps | length' "$out/index.json")"
|
||||
|
||||
# 지금 사이트에 있는 맵이 새 결과에 다 있어야 올린다 (일부만 뽑힌 결과로 덮어쓰지 않게)
|
||||
stage="맵 목록 대조"
|
||||
cur="$(ssh -o BatchMode=yes "$SITE_HOST" "cat '$SITE_DATA/maps3d/index.json' 2>/dev/null || echo '{}'")"
|
||||
prev="$(jq -r '.dir // empty' <<<"$cur")"
|
||||
missing="$(jq -rn --argjson a "$cur" --slurpfile b "$out/index.json" '[($a.maps // {}) | keys[] as $k | select(($b[0].maps | has($k)) | not) | $k] | join(", ")')"
|
||||
if [ -n "$missing" ] && [ "$FORCE" = 0 ]; then
|
||||
log "새 결과에 빠진 맵: $missing → 올리지 않음 (게임에서 정말 빠진 맵이면 update.sh --force)"
|
||||
false
|
||||
fi
|
||||
[ "$count" -gt 0 ] || { log "맵 0개 → 올리지 않음"; false; }
|
||||
|
||||
# 4. 사이트 서버에 올리기 (폴더 먼저, index.json 은 마지막에 바꿔 끼움)
|
||||
stage="사이트 올리기"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "mkdir -p '$SITE_DATA/maps3d'"
|
||||
tar -C "$out" -cf - "$dir" | ssh -o BatchMode=yes "$SITE_HOST" "tar -xf - -C '$SITE_DATA/maps3d'"
|
||||
scp -q -o BatchMode=yes "$out/index.json" "$SITE_HOST:$SITE_DATA/maps3d/index.json.tmp"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "mv '$SITE_DATA/maps3d/index.json.tmp' '$SITE_DATA/maps3d/index.json'"
|
||||
# 지금 것과 바로 전 것(이미 열어 둔 화면용)만 남긴다
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "cd '$SITE_DATA/maps3d' && for d in */; do d=\${d%/}; [ \"\$d\" = '$dir' ] || [ \"\$d\" = '$prev' ] || rm -rf -- \"\$d\"; done"
|
||||
trap - ERR
|
||||
set_state "published=$key" "publishedAt=$(date -Is)" "dir=$dir" "failed=" "failCount=0" "retryAt=0"
|
||||
rm -rf "$raw" "$out"
|
||||
log "사이트 반영 완료: 맵 $count 개 · $dir"
|
||||
notify "🗺️ 발로란트 맵 3D 자동 갱신: 매핑 $version · 맵 ${count}개를 사이트에 반영했습니다"
|
||||
220
tools/map-extract/src/Cdn.cs
Normal file
220
tools/map-extract/src/Cdn.cs
Normal file
@@ -0,0 +1,220 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using CUE4Parse.UE4.Readers;
|
||||
using CUE4Parse.UE4.Versions;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>Riot CDN 번들에서 매니페스트 조각을 필요할 때만 받는다 (HTTP Range).
|
||||
/// 받은 조각은 압축을 풀어 메모리에 둔다 (오래 안 쓴 것부터 버림). 디스크는 쓰지 않는다.</summary>
|
||||
public sealed class CdnStore(string bundleBase, long cacheBytes)
|
||||
{
|
||||
private readonly HttpClient _http = new(new SocketsHttpHandler { MaxConnectionsPerServer = 8, AutomaticDecompression = DecompressionMethods.None })
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(90),
|
||||
};
|
||||
private readonly object _lock = new();
|
||||
private readonly Dictionary<(ulong, uint), LinkedListNode<((ulong, uint) key, byte[] data)>> _map = new();
|
||||
private readonly LinkedList<((ulong, uint) key, byte[] data)> _lru = new();
|
||||
private readonly Dictionary<(ulong, uint), Task> _inflight = new();
|
||||
private long _cached;
|
||||
public long DownloadedBytes;
|
||||
public long Requests;
|
||||
|
||||
private bool TryGet((ulong, uint) key, out byte[] data)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
data = node.Value.data;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
data = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Put((ulong, uint) key, byte[] data)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.ContainsKey(key)) return;
|
||||
_map[key] = _lru.AddFirst((key, data));
|
||||
_cached += data.Length;
|
||||
while (_cached > cacheBytes && _lru.Last is { } last)
|
||||
{
|
||||
_lru.RemoveLast();
|
||||
_map.Remove(last.Value.key);
|
||||
_cached -= last.Value.data.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>파일의 i 번째 조각. 없으면 뒤로 이어진 조각(같은 번들 · 연속 위치)까지 한 번에 받는다</summary>
|
||||
public byte[] Get(Rman.RFile f, int i)
|
||||
{
|
||||
var c = f.Chunks[i];
|
||||
var key = (c.BundleId, c.BundleOffset);
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
if (TryGet(key, out var hit)) return hit;
|
||||
Task? wait;
|
||||
TaskCompletionSource? mine = null;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_inflight.TryGetValue(key, out wait))
|
||||
{
|
||||
mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_inflight[key] = mine.Task;
|
||||
}
|
||||
}
|
||||
if (mine == null)
|
||||
{
|
||||
try { wait!.Wait(); } catch { /* 받던 쪽이 실패하면 다시 시도 */ }
|
||||
if (attempt > 4) throw new IOException("조각 받기 실패 (반복)");
|
||||
continue;
|
||||
}
|
||||
// 이어 받을 조각 범위
|
||||
var run = new List<int> { i };
|
||||
long total = c.CompressedSize;
|
||||
for (var j = i + 1; j < f.Chunks.Length && run.Count < 64 && total < 8 << 20; j++)
|
||||
{
|
||||
var n = f.Chunks[j];
|
||||
var prev = f.Chunks[j - 1];
|
||||
if (n.BundleId != c.BundleId || n.BundleOffset != prev.BundleOffset + prev.CompressedSize) break;
|
||||
lock (_lock) if (_map.ContainsKey((n.BundleId, n.BundleOffset)) || _inflight.ContainsKey((n.BundleId, n.BundleOffset))) break;
|
||||
run.Add(j);
|
||||
total += n.CompressedSize;
|
||||
}
|
||||
lock (_lock) foreach (var j in run.Skip(1)) _inflight.TryAdd((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), mine.Task);
|
||||
try
|
||||
{
|
||||
var raw = Fetch(c.BundleId, c.BundleOffset, total);
|
||||
var pos = 0;
|
||||
using var z = new ZstdSharp.Decompressor();
|
||||
foreach (var j in run)
|
||||
{
|
||||
var cj = f.Chunks[j];
|
||||
var outBuf = new byte[cj.UncompressedSize];
|
||||
var n = z.Unwrap(raw.AsSpan(pos, (int)cj.CompressedSize), outBuf);
|
||||
if (n != cj.UncompressedSize) throw new IOException("조각 크기가 다름");
|
||||
pos += (int)cj.CompressedSize;
|
||||
Put((cj.BundleId, cj.BundleOffset), outBuf);
|
||||
}
|
||||
mine.SetResult();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
mine.SetException(e);
|
||||
if (attempt > 4) throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_lock) foreach (var j in run) if (_inflight.TryGetValue((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), out var t) && t == mine.Task) _inflight.Remove((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] Fetch(ulong bundle, uint offset, long length)
|
||||
{
|
||||
var url = $"{bundleBase}/{bundle:X16}.bundle";
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
req.Headers.Range = new RangeHeaderValue(offset, offset + length - 1);
|
||||
using var res = _http.Send(req, HttpCompletionOption.ResponseHeadersRead);
|
||||
if (res.StatusCode != HttpStatusCode.PartialContent) throw new IOException($"{url} {(int)res.StatusCode}");
|
||||
using var s = res.Content.ReadAsStream();
|
||||
var buf = new byte[length];
|
||||
s.ReadExactly(buf);
|
||||
Interlocked.Add(ref DownloadedBytes, length);
|
||||
Interlocked.Increment(ref Requests);
|
||||
return buf;
|
||||
}
|
||||
catch (Exception) when (attempt < 4)
|
||||
{
|
||||
Thread.Sleep(1000 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> GetBytes(string url) => await _http.GetByteArrayAsync(url);
|
||||
}
|
||||
|
||||
/// <summary>매니페스트 파일 하나를 CUE4Parse 가 읽는 파일처럼 보이게 한다 (임의 위치 읽기)</summary>
|
||||
public sealed class CdnArchive : FArchive
|
||||
{
|
||||
private readonly CdnStore _store;
|
||||
private readonly Rman.RFile _file;
|
||||
private readonly long[] _starts;
|
||||
|
||||
public CdnArchive(CdnStore store, Rman.RFile file, VersionContainer? versions) : base(versions)
|
||||
{
|
||||
_store = store;
|
||||
_file = file;
|
||||
_starts = file.Chunks.Select(c => c.FileOffset).ToArray();
|
||||
Name = file.Path;
|
||||
}
|
||||
|
||||
public override string Name { get; }
|
||||
public override bool CanSeek => true;
|
||||
public override long Length => _file.Size;
|
||||
public override long Position { get; set; }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
var n = ReadAt(Position, buffer, offset, count);
|
||||
Position += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
public override int ReadAt(long position, byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (position >= Length) return 0;
|
||||
count = (int)Math.Min(count, Length - position);
|
||||
var done = 0;
|
||||
var i = Array.BinarySearch(_starts, position);
|
||||
if (i < 0) i = ~i - 1;
|
||||
while (done < count)
|
||||
{
|
||||
var c = _file.Chunks[i];
|
||||
var data = _store.Get(_file, i);
|
||||
var inChunk = (int)(position + done - c.FileOffset);
|
||||
var n = Math.Min(count - done, data.Length - inChunk);
|
||||
Buffer.BlockCopy(data, inChunk, buffer, offset + done, n);
|
||||
done += n;
|
||||
i++;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
public override Task<int> ReadAtAsync(long position, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(ReadAt(position, buffer, offset, count));
|
||||
|
||||
public override ValueTask<int> ReadAtAsync(long position, Memory<byte> memory, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tmp = new byte[memory.Length];
|
||||
var n = ReadAt(position, tmp, 0, tmp.Length);
|
||||
tmp.AsSpan(0, n).CopyTo(memory.Span);
|
||||
return ValueTask.FromResult(n);
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
Position = origin switch
|
||||
{
|
||||
SeekOrigin.Begin => offset,
|
||||
SeekOrigin.Current => Position + offset,
|
||||
SeekOrigin.End => Length + offset,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(origin)),
|
||||
};
|
||||
return Position;
|
||||
}
|
||||
|
||||
public override object Clone() => new CdnArchive(_store, _file, Versions) { Position = Position };
|
||||
}
|
||||
225
tools/map-extract/src/MapScene.cs
Normal file
225
tools/map-extract/src/MapScene.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
using System.Text;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <param name="Code">영구 레벨 이름 (Ascent, HURM_Alley …)</param>
|
||||
/// <param name="MapUrl">경기 기록의 맵 경로 (/Game/Maps/Ascent/Ascent)</param>
|
||||
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
|
||||
|
||||
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
|
||||
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</summary>
|
||||
public sealed class MapScene
|
||||
{
|
||||
public int Placements, Meshes, Failed, Skipped;
|
||||
public long Triangles => _idx.Count / 3;
|
||||
private readonly List<float> _pos = new();
|
||||
private readonly List<uint> _idx = new();
|
||||
private readonly List<string> _levels = new();
|
||||
private string _code = "";
|
||||
private string _mapUrl = "";
|
||||
|
||||
/// <summary>맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록의 맵 경로 "/Game/Maps/Ascent/Ascent" 와 같다).
|
||||
/// 연습장 · 튜토리얼 · 메뉴처럼 경기가 없는 곳은 뺀다</summary>
|
||||
public static List<MapInfo> FindMaps(IFileProvider provider, Action<string>? log = null)
|
||||
{
|
||||
var umaps = provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Maps/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".umap", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
var byDir = umaps.GroupBy(k => k[..k.LastIndexOf('/')]).ToDictionary(g => g.Key, g => g.Select(x => Path.GetFileNameWithoutExtension(x)).ToList());
|
||||
var res = new List<MapInfo>();
|
||||
foreach (var k in umaps.OrderBy(x => x))
|
||||
{
|
||||
var dir = k[..k.LastIndexOf('/')];
|
||||
var name = Path.GetFileNameWithoutExtension(k);
|
||||
if (NotPlayable.Any(x => k.Contains(x, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
if (!byDir[dir].Any(o => o.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))) continue;
|
||||
List<(string level, string cls, string props)> subs;
|
||||
try { subs = StreamingLevels(provider, k); } catch (Exception e) { log?.Invoke($"{k}: 레벨 목록 실패 {e.Message}"); continue; }
|
||||
var levels = subs.Where(x => x.cls == "LevelStreamingAlwaysLoaded" && IsVisualLevel(x.level))
|
||||
.Select(x => "ShooterGame/Content" + x.level["/Game".Length..] + ".umap")
|
||||
.Where(provider.Files.ContainsKey).ToList();
|
||||
if (levels.Count == 0) continue;
|
||||
levels.Insert(0, k);
|
||||
res.Add(new MapInfo(name, "/Game" + k["ShooterGame/Content".Length..^".umap".Length], levels));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private static readonly string[] NotPlayable = ["/Poveglia", "/NPE", "/Menu/", "/Init/", "/Pregame", "_Copy/", "/SharedSubLevels/"];
|
||||
// 보이는 모양이 아닌 하위 레벨 (게임 규칙 · 빛 · 소리 · 부피 · 길찾기 · 카메라 · 효과 · 먼 배경 · 이벤트 장식)
|
||||
private static readonly string[] NotVisual = ["Gameplay", "Lighting", "Volume", "NavMesh", "Audio", "Sound", "_BV", "Callout", "VFX", "_FX", "Vista", "Background", "Decal",
|
||||
"Activation", "Birthday", "Snow", "LiveStory", "Sequence", "Camera", "Probe", "Profiling", "Greybox", "Blockout", "Design", "Layout", "Lanes", "Mode_", "Spawns_Proto", "SpawnPoints", "Skybox", "AuxiliaryZones", "KillVol", "Barrier", "Collider"];
|
||||
|
||||
/// <summary>영구 레벨이 불러오는 하위 레벨들 (패키지 경로 · 형 · b 로 시작하는 속성)</summary>
|
||||
public static List<(string level, string cls, string props)> StreamingLevels(IFileProvider provider, string umap)
|
||||
{
|
||||
var res = new List<(string, string, string)>();
|
||||
var pkg = provider.LoadPackage(umap);
|
||||
var world = pkg.GetExports().OfType<CUE4Parse.UE4.Objects.Engine.UWorld>().FirstOrDefault();
|
||||
if (world?.StreamingLevels == null) return res;
|
||||
foreach (var r in world.StreamingLevels)
|
||||
{
|
||||
var ls = r.Load<CUE4Parse.UE4.Objects.Engine.ULevelStreaming>();
|
||||
if (ls?.WorldAsset == null) continue;
|
||||
var pkgName = ls.WorldAsset.Value.AssetPathName.Text.Split('.')[0];
|
||||
var props = string.Join(' ', ls.Properties.Where(p => p.Name.Text.StartsWith('b')).Select(p => $"{p.Name.Text}={p.Tag?.GenericValue}"));
|
||||
res.Add((pkgName, ls.ExportType, props));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static bool IsVisualLevel(string level)
|
||||
{
|
||||
var name = level[(level.LastIndexOf('/') + 1)..];
|
||||
return !NotVisual.Any(x => name.Contains(x, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다
|
||||
private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"];
|
||||
|
||||
public static MapScene Build(IFileProvider provider, MapInfo map)
|
||||
{
|
||||
var s = new MapScene { _code = map.Code, _mapUrl = map.MapUrl };
|
||||
var meshCache = new Dictionary<string, (FVector[] v, uint[] i)?>();
|
||||
foreach (var level in map.Levels)
|
||||
{
|
||||
s._levels.Add(Path.GetFileNameWithoutExtension(level));
|
||||
var pkg = provider.LoadPackage(level);
|
||||
foreach (var lazy in pkg.ExportsLazy)
|
||||
{
|
||||
UObject o;
|
||||
try { o = lazy.Value; } catch { s.Failed++; continue; }
|
||||
if (o is not UStaticMeshComponent c) continue;
|
||||
if (c.GetOrDefault<bool>("bHiddenInGame") || !c.GetOrDefault("bVisible", true)) { s.Skipped++; continue; }
|
||||
UStaticMesh? mesh;
|
||||
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { s.Failed++; continue; }
|
||||
if (mesh == null) continue;
|
||||
var path = mesh.GetPathName();
|
||||
if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; }
|
||||
if (!meshCache.TryGetValue(path, out var geo))
|
||||
{
|
||||
geo = Geometry(mesh);
|
||||
meshCache[path] = geo;
|
||||
if (geo != null) s.Meshes++;
|
||||
}
|
||||
if (geo == null) continue;
|
||||
FTransform w;
|
||||
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
|
||||
if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data)
|
||||
foreach (var d in data) s.Add(geo.Value, d.TransformData * w);
|
||||
else s.Add(geo.Value, w);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
|
||||
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
|
||||
{
|
||||
var lods = mesh.RenderData?.LODs;
|
||||
if (lods == null) return null;
|
||||
for (var l = lods.Length - 1; l >= 0; l--)
|
||||
{
|
||||
var lod = lods[l];
|
||||
if (lod.SkipLod || lod.PositionVertexBuffer?.Verts is not { Length: > 0 } v || lod.IndexBuffer?.Buffer is not { Length: > 0 } ib) continue;
|
||||
var idx = new List<uint>();
|
||||
foreach (var sec in lod.Sections)
|
||||
for (var k = 0; k < sec.NumTriangles * 3; k++) idx.Add(ib[sec.FirstIndex + k]);
|
||||
return (v, idx.ToArray());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Add((FVector[] v, uint[] i) g, FTransform t)
|
||||
{
|
||||
Placements++;
|
||||
var b = (uint)(_pos.Count / 3);
|
||||
foreach (var p in g.v)
|
||||
{
|
||||
var w = t.TransformPosition(p);
|
||||
_pos.Add(w.X);
|
||||
_pos.Add(w.Y);
|
||||
_pos.Add(w.Z);
|
||||
}
|
||||
// 크기가 음수(거울)면 삼각형 방향이 뒤집힌다
|
||||
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z < 0;
|
||||
for (var k = 0; k + 2 < g.i.Length; k += 3)
|
||||
{
|
||||
_idx.Add(b + g.i[k]);
|
||||
_idx.Add(b + g.i[flip ? k + 2 : k + 1]);
|
||||
_idx.Add(b + g.i[flip ? k + 1 : k + 2]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
|
||||
public void WriteGlb(string file)
|
||||
{
|
||||
var pos = _pos.ToArray();
|
||||
var idx = _idx.ToArray();
|
||||
float[] min = [float.MaxValue, float.MaxValue, float.MaxValue], max = [float.MinValue, float.MinValue, float.MinValue];
|
||||
for (var i = 0; i < pos.Length; i++)
|
||||
{
|
||||
min[i % 3] = Math.Min(min[i % 3], pos[i]);
|
||||
max[i % 3] = Math.Max(max[i % 3], pos[i]);
|
||||
}
|
||||
var posBytes = pos.Length * 4;
|
||||
var idxBytes = idx.Length * 4;
|
||||
var gltf = new
|
||||
{
|
||||
asset = new { version = "2.0", generator = "gvr-map-extract" },
|
||||
scene = 0,
|
||||
scenes = new[] { new { nodes = new[] { 0 } } },
|
||||
nodes = new[] { new { mesh = 0, name = _code } },
|
||||
meshes = new[] { new { name = _code, primitives = new[] { new { attributes = new { POSITION = 0 }, indices = 1, mode = 4 } } } },
|
||||
accessors = new object[]
|
||||
{
|
||||
new { bufferView = 0, componentType = 5126, count = pos.Length / 3, type = "VEC3", min, max },
|
||||
new { bufferView = 1, componentType = 5125, count = idx.Length, type = "SCALAR" },
|
||||
},
|
||||
bufferViews = new[]
|
||||
{
|
||||
new { buffer = 0, byteOffset = 0, byteLength = posBytes, target = 34962 },
|
||||
new { buffer = 0, byteOffset = posBytes, byteLength = idxBytes, target = 34963 },
|
||||
},
|
||||
buffers = new[] { new { byteLength = posBytes + idxBytes } },
|
||||
};
|
||||
var json = Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(gltf));
|
||||
var jsonPad = (4 - json.Length % 4) % 4;
|
||||
using var fs = File.Create(file);
|
||||
using var w = new BinaryWriter(fs);
|
||||
var total = 12 + 8 + json.Length + jsonPad + 8 + posBytes + idxBytes;
|
||||
w.Write(0x46546C67u); // glTF
|
||||
w.Write(2u);
|
||||
w.Write((uint)total);
|
||||
w.Write((uint)(json.Length + jsonPad));
|
||||
w.Write(0x4E4F534Au); // JSON
|
||||
w.Write(json);
|
||||
for (var i = 0; i < jsonPad; i++) w.Write((byte)' ');
|
||||
w.Write((uint)(posBytes + idxBytes));
|
||||
w.Write(0x004E4942u); // BIN
|
||||
foreach (var f in pos) w.Write(f);
|
||||
foreach (var i in idx) w.Write(i);
|
||||
}
|
||||
|
||||
public void WriteInfo(string file, string manifest, string? usmap)
|
||||
{
|
||||
var info = new
|
||||
{
|
||||
code = _code,
|
||||
mapUrl = _mapUrl,
|
||||
levels = _levels,
|
||||
placements = Placements,
|
||||
meshes = Meshes,
|
||||
triangles = Triangles,
|
||||
skipped = Skipped,
|
||||
failed = Failed,
|
||||
manifest,
|
||||
usmap = usmap == null ? null : Path.GetFileName(usmap),
|
||||
extractedAt = DateTimeOffset.UtcNow.ToString("o"),
|
||||
};
|
||||
File.WriteAllText(file, System.Text.Json.JsonSerializer.Serialize(info, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
}
|
||||
127
tools/map-extract/src/Program.cs
Normal file
127
tools/map-extract/src/Program.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
using Serilog;
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using CUE4Parse;
|
||||
using CUE4Parse.Compression;
|
||||
using CUE4Parse.Encryption.Aes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.MappingsProvider.Usmap;
|
||||
using CUE4Parse.UE4.Objects.Core.Misc;
|
||||
using CUE4Parse.UE4.Versions;
|
||||
using GvrMapExtract;
|
||||
|
||||
// gvr-map-extract: 발로란트 맵 3D 모양을 Riot CDN 에서 바로 뽑는다 (게임 설치 · 전체 다운로드 없음)
|
||||
//
|
||||
// gvr-map-extract ls <정규식> [개수] 파일 목록
|
||||
// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수)
|
||||
// gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json
|
||||
//
|
||||
// 환경변수
|
||||
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
|
||||
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
|
||||
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
|
||||
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
|
||||
|
||||
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
|
||||
CUE4ParseLog.UseLogger(Serilog.Log.Logger);
|
||||
|
||||
const string AesKey = "0x4BE71AF2459CF83899EC9DC2CB60E22AC4B3047E0211034BBABE9D174C069DD6"; // 발로란트 공개 키 (모든 패치 같음)
|
||||
const string BundleBase = "https://valorant.secure.dyn.riotcdn.net/channels/public/bundles";
|
||||
const string Patchlines = "https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines";
|
||||
|
||||
if (args.Length == 0)
|
||||
{
|
||||
Console.Error.WriteLine("사용법: gvr-map-extract ls <정규식> | maps | extract <출력 폴더> [맵...] | manifest");
|
||||
return 2;
|
||||
}
|
||||
var sw = Stopwatch.StartNew();
|
||||
var store = new CdnStore(BundleBase, long.Parse(Environment.GetEnvironmentVariable("GVR_CACHE_MB") ?? "1500") << 20);
|
||||
var manifestUrl = Environment.GetEnvironmentVariable("GVR_MANIFEST") ?? await LiveManifest(store);
|
||||
if (args[0] == "manifest")
|
||||
{
|
||||
Console.WriteLine(manifestUrl);
|
||||
return 0;
|
||||
}
|
||||
var rman = Rman.Parse(await store.GetBytes(manifestUrl));
|
||||
Console.Error.WriteLine($"매니페스트 {manifestUrl} 파일 {rman.Files.Count}");
|
||||
|
||||
var oodle = Environment.GetEnvironmentVariable("GVR_OODLE") ?? Path.Combine(AppContext.BaseDirectory, OodleHelper.OodleFileName);
|
||||
await OodleHelper.InitializeAsync(oodle);
|
||||
var versions = new VersionContainer(EGame.GAME_Valorant);
|
||||
var provider = new StreamedFileProvider("VALORANT", versions, StringComparer.OrdinalIgnoreCase);
|
||||
provider.Initialize();
|
||||
foreach (var f in rman.Files.Values.Where(f => f.Path.StartsWith("ShooterGame/Content/Paks/", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var ext = Path.GetExtension(f.Path).ToLowerInvariant();
|
||||
if (ext == ".utoc")
|
||||
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, open =>
|
||||
rman.Files.TryGetValue(open, out var c) ? new CdnArchive(store, c, versions) : throw new FileNotFoundException(open));
|
||||
else if (ext == ".pak")
|
||||
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, null);
|
||||
}
|
||||
provider.SubmitKey(new FGuid(), new FAesKey(AesKey));
|
||||
provider.PostMount();
|
||||
var usmap = Environment.GetEnvironmentVariable("GVR_USMAP");
|
||||
if (usmap != null) provider.MappingsContainer = new FileUsmapTypeMappingsProvider(usmap);
|
||||
Console.Error.WriteLine($"파일 {provider.Files.Count} · 묶음 {provider.MountedVfs.Count} (못 연 것 {provider.UnloadedVfs.Count}) · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalSeconds:F0}초");
|
||||
|
||||
switch (args[0])
|
||||
{
|
||||
case "ls":
|
||||
{
|
||||
var re = new Regex(args[1], RegexOptions.IgnoreCase);
|
||||
foreach (var k in provider.Files.Keys.Where(k => re.IsMatch(k)).OrderBy(k => k).Take(args.Length > 2 ? int.Parse(args[2]) : 200)) Console.WriteLine(k);
|
||||
break;
|
||||
}
|
||||
case "levels":
|
||||
foreach (var (lvl, cls, props) in MapScene.StreamingLevels(provider, args[1]))
|
||||
Console.WriteLine($"{lvl}\t{cls}\t{props}");
|
||||
break;
|
||||
case "maps":
|
||||
foreach (var m in MapScene.FindMaps(provider, Console.Error.WriteLine)) Console.WriteLine($"{m.Code}\t{m.MapUrl}\t{m.Levels.Count}\t{string.Join(',', m.Levels.Select(Path.GetFileNameWithoutExtension))}");
|
||||
break;
|
||||
case "extract":
|
||||
{
|
||||
var outDir = args[1];
|
||||
Directory.CreateDirectory(outDir);
|
||||
var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
// 맵 찾기에서 읽지 못한 레벨이 있으면 맵이 빠졌을 수 있다 → 실패로 친다 (빠진 결과로 기존 맵을 덮어쓰지 않게)
|
||||
var findErrors = 0;
|
||||
var maps = MapScene.FindMaps(provider, e => { findErrors++; Console.Error.WriteLine(e); }).Where(m => want.Count == 0 || want.Contains(m.Code)).ToList();
|
||||
var failed = findErrors;
|
||||
foreach (var m in maps)
|
||||
{
|
||||
var t0 = sw.Elapsed;
|
||||
var d0 = store.DownloadedBytes;
|
||||
try
|
||||
{
|
||||
var r = MapScene.Build(provider, m);
|
||||
r.WriteGlb(Path.Combine(outDir, m.Code + ".glb"));
|
||||
r.WriteInfo(Path.Combine(outDir, m.Code + ".json"), manifestUrl, usmap);
|
||||
Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"{m.Code}: 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
if (findErrors > 0) Console.WriteLine($"맵 찾기 실패 {findErrors}개 (위 로그)");
|
||||
Console.WriteLine($"끝: 맵 {maps.Count - (failed - findErrors)}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분");
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
default:
|
||||
Console.Error.WriteLine("모르는 명령 " + args[0]);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
|
||||
static async Task<string> LiveManifest(CdnStore store)
|
||||
{
|
||||
var json = System.Text.Json.JsonDocument.Parse(await store.GetBytes(Patchlines));
|
||||
var live = json.RootElement.GetProperty("keystone.products.valorant.patchlines.live");
|
||||
foreach (var c in live.GetProperty("platforms").GetProperty("win").GetProperty("configurations").EnumerateArray())
|
||||
if (c.TryGetProperty("patch_url", out var u)) return u.GetString()!;
|
||||
throw new InvalidOperationException("라이브 매니페스트를 못 찾음");
|
||||
}
|
||||
119
tools/map-extract/src/Rman.cs
Normal file
119
tools/map-extract/src/Rman.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>Riot 매니페스트(.manifest, RMAN 2.x) 읽기. 본문은 zstd 로 압축된 FlatBuffers.
|
||||
/// 구조는 Morilli/ManifestDownloader rman.c 를 따랐다.</summary>
|
||||
public sealed class Rman
|
||||
{
|
||||
public sealed record Chunk(ulong BundleId, uint BundleOffset, uint CompressedSize, uint UncompressedSize, long FileOffset);
|
||||
public sealed record RFile(string Path, long Size, Chunk[] Chunks);
|
||||
|
||||
public ulong ManifestId { get; private set; }
|
||||
public Dictionary<string, RFile> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static Rman Parse(byte[] data)
|
||||
{
|
||||
if (data.Length < 28 || Encoding.ASCII.GetString(data, 0, 4) != "RMAN") throw new InvalidDataException("RMAN 아님");
|
||||
if (data[4] != 2) throw new InvalidDataException($"모르는 매니페스트 버전 {data[4]}.{data[5]}");
|
||||
var contentOffset = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8));
|
||||
var compressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12));
|
||||
var r = new Rman { ManifestId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) };
|
||||
var uncompressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24));
|
||||
var body = new byte[uncompressedSize];
|
||||
using (var z = new ZstdSharp.Decompressor())
|
||||
{
|
||||
var n = z.Unwrap(data.AsSpan((int)contentOffset, (int)compressedSize), body);
|
||||
if (n != uncompressedSize) throw new InvalidDataException("매니페스트 압축 풀기 실패");
|
||||
}
|
||||
r.ParseBody(new Fb(body));
|
||||
return r;
|
||||
}
|
||||
|
||||
private void ParseBody(Fb b)
|
||||
{
|
||||
var root = b.Root();
|
||||
// 번들 → 조각 (번들 안 위치는 앞 조각 크기의 누적)
|
||||
var chunks = new Dictionary<ulong, (ulong bundle, uint off, uint comp, uint raw)>();
|
||||
foreach (var bt in b.Tables(root, 0))
|
||||
{
|
||||
var bundleId = b.U64(bt, 0);
|
||||
uint off = 0;
|
||||
foreach (var ct in b.Tables(bt, 1))
|
||||
{
|
||||
var comp = b.U32(ct, 1);
|
||||
chunks[b.U64(ct, 0)] = (bundleId, off, comp, b.U32(ct, 2));
|
||||
off += comp;
|
||||
}
|
||||
}
|
||||
// 폴더
|
||||
var dirs = new Dictionary<ulong, (ulong parent, string name)>();
|
||||
foreach (var dt in b.Tables(root, 3)) dirs[b.U64(dt, 0)] = (b.U64(dt, 1), b.Str(dt, 2));
|
||||
// 파일
|
||||
foreach (var ft in b.Tables(root, 2))
|
||||
{
|
||||
var name = b.Str(ft, 3);
|
||||
var dir = b.U64(ft, 1);
|
||||
while (dir != 0 && dirs.TryGetValue(dir, out var d))
|
||||
{
|
||||
if (d.name.Length > 0) name = d.name + "/" + name;
|
||||
dir = d.parent;
|
||||
}
|
||||
var ids = b.U64Vector(ft, 7);
|
||||
var list = new Chunk[ids.Length];
|
||||
long fo = 0;
|
||||
for (var i = 0; i < ids.Length; i++)
|
||||
{
|
||||
var c = chunks[ids[i]];
|
||||
list[i] = new Chunk(c.bundle, c.off, c.comp, c.raw, fo);
|
||||
fo += c.raw;
|
||||
}
|
||||
Files[name] = new RFile(name, (long)b.U64(ft, 2), list);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>아주 작은 FlatBuffers 읽기 (필요한 형만)</summary>
|
||||
private sealed class Fb(byte[] d)
|
||||
{
|
||||
private uint U32At(int p) => BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p));
|
||||
public int Root() => (int)U32At(0);
|
||||
/// <summary>테이블 필드 위치. 없으면 -1</summary>
|
||||
private int Field(int table, int idx)
|
||||
{
|
||||
var vt = table - BinaryPrimitives.ReadInt32LittleEndian(d.AsSpan(table));
|
||||
var vsize = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt));
|
||||
if (4 + idx * 2 >= vsize) return -1;
|
||||
var off = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt + 4 + idx * 2));
|
||||
return off == 0 ? -1 : table + off;
|
||||
}
|
||||
private int Ref(int p) => p + (int)U32At(p);
|
||||
public ulong U64(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(p)); }
|
||||
public uint U32(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : U32At(p); }
|
||||
public string Str(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) return "";
|
||||
var v = Ref(p);
|
||||
return Encoding.UTF8.GetString(d, v + 4, (int)U32At(v));
|
||||
}
|
||||
public ulong[] U64Vector(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) return [];
|
||||
var v = Ref(p);
|
||||
var n = (int)U32At(v);
|
||||
var a = new ulong[n];
|
||||
for (var k = 0; k < n; k++) a[k] = BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(v + 4 + k * 8));
|
||||
return a;
|
||||
}
|
||||
public IEnumerable<int> Tables(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) yield break;
|
||||
var v = Ref(p);
|
||||
var n = (int)U32At(v);
|
||||
for (var k = 0; k < n; k++) yield return Ref(v + 4 + k * 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
4
tools/replay-extract/.gitignore
vendored
Normal file
4
tools/replay-extract/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
vendor/
|
||||
bin/
|
||||
obj/
|
||||
out/
|
||||
20
tools/replay-extract/ReplayExtract.csproj
Normal file
20
tools/replay-extract/ReplayExtract.csproj
Normal file
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- 발로란트 리플레이(.vrf) → 사이트 재생기용 작은 JSON. 파서는 fetch-parser.sh 로 vendor/ 에 받는다 -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>gvr-replay</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="src/**/*.cs" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Encoding/Replay.Encoding.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Models/Replay.Models.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Unreal/Replay.Unreal.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Valorant/Replay.Valorant.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Valorant.Events/Replay.Valorant.Events.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
21
tools/replay-extract/fetch-parser.sh
Executable file
21
tools/replay-extract/fetch-parser.sh
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# ValorantReplayParser (MIT, https://github.com/michel-giehl/ValorantReplayParser) 를 고정 커밋으로 받아 vendor/ 에 둔다.
|
||||
# 발로란트 패치로 리플레이 형식이 바뀌면 PARSER_COMMIT 을 새 커밋으로 올린다.
|
||||
set -euo pipefail
|
||||
PARSER_COMMIT="${PARSER_COMMIT:-28e24af44f5d2e2444fb679f500b6ec04ab60672}"
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
dst="$here/vendor/ValorantReplayParser"
|
||||
if [ ! -d "$dst/.git" ]; then
|
||||
git clone --quiet https://github.com/michel-giehl/ValorantReplayParser "$dst"
|
||||
fi
|
||||
git -C "$dst" fetch --quiet origin
|
||||
git -C "$dst" checkout --quiet --force "$PARSER_COMMIT"
|
||||
# 저장소의 global.json 은 SDK 패치 버전까지 고정한다. 같은 10.0 대 SDK 면 쓰게 풀어 준다
|
||||
python3 - "$dst/global.json" <<'P'
|
||||
import json, sys
|
||||
p = sys.argv[1]
|
||||
d = json.load(open(p))
|
||||
d.setdefault('sdk', {})['rollForward'] = 'latestFeature'
|
||||
json.dump(d, open(p, 'w'), indent=2)
|
||||
P
|
||||
echo "parser @ $(git -C "$dst" rev-parse --short HEAD)"
|
||||
265
tools/replay-extract/src/Collector.cs
Normal file
265
tools/replay-extract/src/Collector.cs
Normal file
@@ -0,0 +1,265 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Replay.Models.Events;
|
||||
using Replay.Models.Unreal;
|
||||
using Replay.Valorant.Combat;
|
||||
using Replay.Valorant.Descriptors;
|
||||
using Replay.Valorant.Descriptors.Agents;
|
||||
using Replay.Valorant.Events.Combat;
|
||||
using Replay.Valorant.Events.Movement;
|
||||
using Replay.Valorant.GameState;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
/// 파서 이벤트 → 필요한 것만 모은다 (선수 이동은 sampleMs 간격으로 줄임)
|
||||
public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
{
|
||||
private string? _matchId;
|
||||
private string? _map;
|
||||
private readonly Dictionary<uint, string> _archetypeByActor = [];
|
||||
private readonly Dictionary<uint, string> _subjectByState = [];
|
||||
private readonly Dictionary<uint, uint> _stateByCharacter = [];
|
||||
// 조종 중인 폰 (드론 · 카메라 · 클로브 사후 몸 등). 요원 몸(*_PC_C)만 선수 이동으로 쓴다
|
||||
private readonly Dictionary<uint, uint> _possessedByState = [];
|
||||
private readonly Dictionary<uint, List<int[]>> _moves = [];
|
||||
private readonly Dictionary<uint, int> _lastMoveT = [];
|
||||
private readonly List<int[]> _phases = [];
|
||||
private readonly List<(int T, int NewRoundIndex)> _roundEnds = [];
|
||||
private readonly List<(int T, uint Killer, uint Victim)> _kills = [];
|
||||
private readonly List<(int T, uint State, int X, int Y, int Z, int Yaw, int Pitch)> _shots = [];
|
||||
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z)> _objects = [];
|
||||
private readonly Dictionary<uint, int> _closedAt = [];
|
||||
private readonly Dictionary<uint, uint> _objectOwner = [];
|
||||
private readonly Dictionary<string, int> _stats = [];
|
||||
|
||||
private static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0);
|
||||
private static int R(double v) => (int)Math.Round(v);
|
||||
|
||||
[GeneratedRegex(@"^/Game/Maps/([^/.]+)/\1$")]
|
||||
private static partial Regex MapPath();
|
||||
|
||||
// 스킬 · 설치물로 보는 액터 클래스 (요원 본체 *_PC_C 와 무기 · 상태는 뺀다)
|
||||
// GameObject_* (연막 · 함정 · 정찰 등), Patch_* (장판), Pawn_* (드론 · 분신), Projectile_* (날아가는 스킬), TimedBomb_C (설치된 스파이크)
|
||||
[GeneratedRegex(@"^Default__(GameObject_|Patch_|Pawn_|Projectile_|TimedBomb_C$)")]
|
||||
private static partial Regex ObjectClass();
|
||||
|
||||
public void Emit(ReplayEvent e)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case NetGuidExported g:
|
||||
if (_map is null && MapPath().IsMatch(g.Path)) _map = g.Path;
|
||||
break;
|
||||
case ActorSpawned s:
|
||||
if (s.ArchetypePath is { } arch)
|
||||
{
|
||||
_archetypeByActor[s.ActorNetGuid] = arch;
|
||||
Count("spawn " + Simplify(arch));
|
||||
if (s.Location is { } loc && ObjectClass().IsMatch(arch) && !arch.EndsWith("_PC_C"))
|
||||
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z)));
|
||||
}
|
||||
break;
|
||||
case ActorClosed c:
|
||||
_closedAt[c.ActorNetGuid] = Ms(c.TimeSeconds);
|
||||
break;
|
||||
case ExportGroupReceived x:
|
||||
OnExport(x);
|
||||
break;
|
||||
case RpcReceived r:
|
||||
OnRpc(r);
|
||||
break;
|
||||
case RemoteCharacterMovementReceived m:
|
||||
OnMove(m);
|
||||
break;
|
||||
case ValorantShotReceived shot:
|
||||
OnShot(shot);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnExport(ExportGroupReceived x)
|
||||
{
|
||||
switch (x.Payload)
|
||||
{
|
||||
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
|
||||
_matchId ??= gs.MatchID;
|
||||
break;
|
||||
case BombPlayerStateDescriptor ps:
|
||||
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.Subject)) && !string.IsNullOrEmpty(ps.Subject))
|
||||
_subjectByState[x.ActorNetGuid] = ps.Subject!;
|
||||
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.SpawnedCharacter)) && ps.SpawnedCharacter.NetGuid != 0)
|
||||
_stateByCharacter[ps.SpawnedCharacter.NetGuid] = x.ActorNetGuid;
|
||||
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.PossessedCharacter)) && ps.PossessedCharacter.NetGuid != 0)
|
||||
_possessedByState[ps.PossessedCharacter.NetGuid] = x.ActorNetGuid;
|
||||
break;
|
||||
case GenericAgentDescriptor agent:
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.PlayerState)) && agent.PlayerState.NetGuid != 0)
|
||||
_stateByCharacter.TryAdd(x.ActorNetGuid, agent.PlayerState.NetGuid);
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Owner)) && agent.Owner.NetGuid != 0)
|
||||
_objectOwner.TryAdd(x.ActorNetGuid, agent.Owner.NetGuid);
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Instigator)) && agent.Instigator.NetGuid != 0)
|
||||
_objectOwner[x.ActorNetGuid] = agent.Instigator.NetGuid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRpc(RpcReceived r)
|
||||
{
|
||||
var t = Ms(r.TimeSeconds);
|
||||
switch (r.Payload)
|
||||
{
|
||||
case ClientGamePhaseBeginParameters p:
|
||||
// 같은 시각에 같은 단계가 여러 컨트롤러로 올 수 있다
|
||||
if (_phases.Count == 0 || _phases[^1][1] != p.NewPhase || _phases[^1][0] != t)
|
||||
_phases.Add([t, p.NewPhase]);
|
||||
break;
|
||||
case MulticastEndRoundParameters er:
|
||||
if (_roundEnds.Count == 0 || _roundEnds[^1].NewRoundIndex != er.NewRoundNumber)
|
||||
_roundEnds.Add((t, er.NewRoundNumber));
|
||||
break;
|
||||
case MulticastNotifyKilledEnemyParameters k:
|
||||
if (!_kills.Any(q => Math.Abs(q.T - t) < 50 && q.Victim == k.KilledCharacter.NetGuid))
|
||||
_kills.Add((t, k.KillerCharacter.NetGuid, k.KilledCharacter.NetGuid));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMove(RemoteCharacterMovementReceived m)
|
||||
{
|
||||
var t = Ms(m.TimeSeconds);
|
||||
var ch = m.ShooterCharacterNetGuidValue;
|
||||
if (_lastMoveT.TryGetValue(ch, out var last) && t - last < sampleMs) return;
|
||||
_lastMoveT[ch] = t;
|
||||
var p = m.Move.Position;
|
||||
if (!_moves.TryGetValue(ch, out var list)) _moves[ch] = list = [];
|
||||
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch)]);
|
||||
}
|
||||
|
||||
private void OnShot(ValorantShotReceived s)
|
||||
{
|
||||
var shot = s.Shot;
|
||||
if (shot.Location is not { } loc) return;
|
||||
var state = shot.FiringPlayerState?.NetGuid ?? 0;
|
||||
double yaw = 0, pitch = 0;
|
||||
if (shot.Rotation is { } rot)
|
||||
{
|
||||
yaw = rot.Yaw;
|
||||
pitch = rot.Pitch;
|
||||
}
|
||||
else if (shot.AttackVectors.Count > 0)
|
||||
{
|
||||
var v = shot.AttackVectors[0];
|
||||
yaw = Math.Atan2(v.Y, v.X) * 180 / Math.PI;
|
||||
pitch = Math.Atan2(v.Z, Math.Sqrt(v.X * v.X + v.Y * v.Y)) * 180 / Math.PI;
|
||||
}
|
||||
_shots.Add((Ms(s.TimeSeconds), state, R(loc.X), R(loc.Y), R(loc.Z), R(yaw), R(pitch)));
|
||||
}
|
||||
|
||||
private static string Simplify(string archetype) => archetype.StartsWith("Default__") ? archetype[9..] : archetype;
|
||||
|
||||
private void Count(string key) => _stats[key] = _stats.GetValueOrDefault(key) + 1;
|
||||
|
||||
public void PrintStats()
|
||||
{
|
||||
Console.WriteLine($"match {_matchId} map {_map} states {_subjectByState.Count} chars {_stateByCharacter.Count} moves {_moves.Count} kills {_kills.Count} shots {_shots.Count} objects {_objects.Count} phases {_phases.Count} roundEnds {_roundEnds.Count}");
|
||||
Console.WriteLine("stateByChar: " + string.Join(",", _stateByCharacter.Select(kv => $"{kv.Key}->{kv.Value}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
|
||||
Console.WriteLine("moves: " + string.Join(",", _moves.OrderByDescending(kv => kv.Value.Count).Take(14).Select(kv => $"{kv.Key}:{kv.Value.Count}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
|
||||
Console.WriteLine("states: " + string.Join(",", _subjectByState.Keys));
|
||||
foreach (var (k, v) in _stats.OrderByDescending(kv => kv.Value).Take(150)) Console.WriteLine($"{v,6} {k}");
|
||||
}
|
||||
|
||||
public ReplayFile Build(string? branch, long recordedAt, int durationMs, int hz)
|
||||
{
|
||||
// 선수 = 계정(subject) 하나. 캐릭터가 여러 번 바뀌어도(부활 등) 같은 선수로 묶는다
|
||||
var players = new List<ReplayPlayer>();
|
||||
var indexBySubject = new Dictionary<string, int>();
|
||||
var indexByCharacter = new Dictionary<uint, int>();
|
||||
int PlayerOfState(uint state)
|
||||
{
|
||||
if (!_subjectByState.TryGetValue(state, out var subject)) return -1;
|
||||
if (!indexBySubject.TryGetValue(subject, out var i))
|
||||
{
|
||||
i = players.Count;
|
||||
indexBySubject[subject] = i;
|
||||
players.Add(new ReplayPlayer { Puuid = subject });
|
||||
}
|
||||
return i;
|
||||
}
|
||||
foreach (var state in _subjectByState.Keys.OrderBy(k => k)) PlayerOfState(state);
|
||||
foreach (var (ch, state) in _possessedByState)
|
||||
if (_archetypeByActor.TryGetValue(ch, out var a) && a.EndsWith("_PC_C")) _stateByCharacter.TryAdd(ch, state);
|
||||
foreach (var (ch, state) in _stateByCharacter)
|
||||
{
|
||||
var i = PlayerOfState(state);
|
||||
if (i < 0) continue;
|
||||
indexByCharacter[ch] = i;
|
||||
if (_archetypeByActor.TryGetValue(ch, out var arch) && arch.EndsWith("_PC_C"))
|
||||
players[i].Character ??= Simplify(arch);
|
||||
}
|
||||
var merged = players.Select(_ => new List<int[]>()).ToList();
|
||||
foreach (var (ch, moves) in _moves)
|
||||
if (indexByCharacter.TryGetValue(ch, out var i)) merged[i].AddRange(moves);
|
||||
for (var i = 0; i < players.Count; i++)
|
||||
{
|
||||
var tr = players[i].Track;
|
||||
var lastT = int.MinValue / 2;
|
||||
foreach (var mv in merged[i].OrderBy(m => m[0]))
|
||||
{
|
||||
if (mv[0] - lastT < sampleMs) continue;
|
||||
lastT = mv[0];
|
||||
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]);
|
||||
}
|
||||
}
|
||||
|
||||
// 라운드: MulticastEndRound(NewRoundNumber=k) 는 라운드 k+1(1부터) 의 시작. 단계 3=구매, 4=교전, 5=라운드 끝
|
||||
var rounds = new List<ReplayRound>();
|
||||
var starts = new List<(int T, int Num)> { (0, 1) };
|
||||
foreach (var (t, idx) in _roundEnds) starts.Add((t, idx + 1));
|
||||
for (var r = 0; r < starts.Count; r++)
|
||||
{
|
||||
var from = starts[r].T;
|
||||
var to = r + 1 < starts.Count ? starts[r + 1].T : int.MaxValue;
|
||||
int Phase(int ph) => _phases.FirstOrDefault(p => p[1] == ph && p[0] >= from && p[0] < to)?[0] ?? -1;
|
||||
var buy = Phase(3);
|
||||
rounds.Add(new ReplayRound { Num = starts[r].Num, Buy = buy >= 0 ? buy : from, Combat = Phase(4), End = Phase(5) });
|
||||
}
|
||||
|
||||
var kinds = new List<string>();
|
||||
var kindIndex = new Dictionary<string, int>();
|
||||
var objects = new List<int[]>();
|
||||
// 맵 자체 연출(예: GameObject_Infinity_Rain_*)은 뺀다
|
||||
var mapName = _map?.Split('/')[^1];
|
||||
foreach (var o in _objects)
|
||||
{
|
||||
if (mapName is not null && o.Kind.Contains("_" + mapName + "_")) continue;
|
||||
if (!kindIndex.TryGetValue(o.Kind, out var k)) { k = kinds.Count; kinds.Add(o.Kind); kindIndex[o.Kind] = k; }
|
||||
var owner = -1;
|
||||
var cur = o.Actor;
|
||||
for (var d = 0; d < 6 && _objectOwner.TryGetValue(cur, out var up); d++)
|
||||
{
|
||||
if (indexByCharacter.TryGetValue(up, out owner)) break;
|
||||
owner = -1;
|
||||
if (_stateByCharacter.ContainsKey(up)) break;
|
||||
if (_subjectByState.ContainsKey(up)) { owner = PlayerOfState(up); break; }
|
||||
cur = up;
|
||||
}
|
||||
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
|
||||
}
|
||||
|
||||
return new ReplayFile
|
||||
{
|
||||
MatchId = _matchId,
|
||||
Map = _map,
|
||||
Build = branch?.Replace("++Ares-Core+", ""),
|
||||
RecordedAt = recordedAt,
|
||||
DurationMs = durationMs,
|
||||
SampleMs = sampleMs,
|
||||
Players = players,
|
||||
Rounds = rounds,
|
||||
Phases = _phases,
|
||||
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1) }).ToList(),
|
||||
Shots = _shots.Select(s => new[] { s.T, PlayerOfState(s.State), s.X, s.Y, s.Z, s.Yaw, s.Pitch }).ToList(),
|
||||
Objects = objects,
|
||||
ObjectKinds = kinds,
|
||||
};
|
||||
}
|
||||
}
|
||||
69
tools/replay-extract/src/Model.cs
Normal file
69
tools/replay-extract/src/Model.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
// 사이트로 가는 형식. 시간은 모두 리플레이 시작부터 ms (t), 좌표는 게임 월드 단위(cm) 정수
|
||||
public sealed class ReplayFile
|
||||
{
|
||||
public string Format { get; set; } = "gvr-replay";
|
||||
public int V { get; set; } = 1;
|
||||
public string? MatchId { get; set; }
|
||||
public string? Map { get; set; }
|
||||
public string? Build { get; set; }
|
||||
/// 리플레이 녹화 시작 시각 (서버 기준 유닉스 ms). t 를 실제 시각으로 바꿀 때 recordedAt + t
|
||||
public long RecordedAt { get; set; }
|
||||
public int DurationMs { get; set; }
|
||||
public int SampleMs { get; set; }
|
||||
public List<ReplayPlayer> Players { get; set; } = [];
|
||||
public List<ReplayRound> Rounds { get; set; } = [];
|
||||
/// [t, phase] 게임 단계 바뀜 (원본 값)
|
||||
public List<int[]> Phases { get; set; } = [];
|
||||
/// [t, killer, victim] (선수 번호, 모르면 -1)
|
||||
public List<int[]> Kills { get; set; } = [];
|
||||
/// [t, player, x, y, z, yaw, pitch] 사격 위치와 방향
|
||||
public List<int[]> Shots { get; set; } = [];
|
||||
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
|
||||
public List<int[]> Objects { get; set; } = [];
|
||||
public List<string> ObjectKinds { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayPlayer
|
||||
{
|
||||
public string? Puuid { get; set; }
|
||||
/// 캐릭터 클래스 (예: Wushu_PC_C). 요원 이름은 사이트가 경기 상세(match-details)로 붙인다
|
||||
public string? Character { get; set; }
|
||||
/// 이동 기록. 열 별 배열 (같은 길이): t, x, y, z, yaw(도), pitch(도)
|
||||
public PlayerTrack Track { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class PlayerTrack
|
||||
{
|
||||
public List<int> T { get; set; } = [];
|
||||
public List<int> X { get; set; } = [];
|
||||
public List<int> Y { get; set; } = [];
|
||||
public List<int> Z { get; set; } = [];
|
||||
public List<int> Yaw { get; set; } = [];
|
||||
public List<int> Pitch { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayRound
|
||||
{
|
||||
/// 1부터
|
||||
public int Num { get; set; }
|
||||
/// 구매 단계 시작
|
||||
public int Buy { get; set; }
|
||||
/// 교전 시작 (구매 단계 끝), 모르면 -1
|
||||
public int Combat { get; set; }
|
||||
/// 라운드 끝 (승패 확정), 모르면 -1
|
||||
public int End { get; set; }
|
||||
}
|
||||
|
||||
public static class ReplayJson
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||
};
|
||||
}
|
||||
76
tools/replay-extract/src/Program.cs
Normal file
76
tools/replay-extract/src/Program.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v1)
|
||||
// gvr-replay <file.vrf> <out.json> [--hz 10]
|
||||
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
|
||||
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Replay.Encoding.Archives;
|
||||
using Replay.Models.Descriptors;
|
||||
using Replay.Valorant;
|
||||
using Replay.Valorant.Events;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
if (args.Length < 2)
|
||||
{
|
||||
Console.Error.WriteLine("사용법: gvr-replay <file.vrf> <out.json> [--hz 10] | gvr-replay <file.vrf> --stats");
|
||||
return 2;
|
||||
}
|
||||
var input = args[0];
|
||||
var stats = args[1] == "--stats";
|
||||
var hz = 10;
|
||||
for (var i = 2; i < args.Length - 1; i++)
|
||||
if (args[i] == "--hz") hz = Math.Clamp(int.Parse(args[i + 1]), 1, 60);
|
||||
try
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var collector = new Collector(1000 / hz);
|
||||
using var file = File.OpenRead(input);
|
||||
using var archive = new FBinaryArchive(file);
|
||||
var enricher = new ValorantEventEnricher(collector);
|
||||
var result = ValorantReplayReader.CreateDefault(null, enricher, ParseProfile.Default).Read(archive);
|
||||
enricher.Complete();
|
||||
var info = result.Metadata.ReplayInfo;
|
||||
if (stats)
|
||||
{
|
||||
collector.PrintStats();
|
||||
return 0;
|
||||
}
|
||||
var replay = collector.Build(
|
||||
result.Metadata.ReplayVersion.Branch,
|
||||
FDateTimeToUnixMs(info.Timestamp),
|
||||
info.LengthInMs,
|
||||
hz);
|
||||
var tmp = args[1] + ".tmp";
|
||||
using (var fs = File.Create(tmp))
|
||||
JsonSerializer.Serialize(fs, replay, ReplayJson.Options);
|
||||
File.Move(tmp, args[1], true);
|
||||
Console.WriteLine(JsonSerializer.Serialize(new
|
||||
{
|
||||
ok = true,
|
||||
matchId = replay.MatchId,
|
||||
map = replay.Map,
|
||||
build = replay.Build,
|
||||
players = replay.Players.Count,
|
||||
rounds = replay.Rounds.Count,
|
||||
kills = replay.Kills.Count,
|
||||
elapsedMs = sw.ElapsedMilliseconds,
|
||||
status = result.Status.ToString(),
|
||||
warnings = result.TotalDiagnosticCount,
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(JsonSerializer.Serialize(new { ok = false, error = e.GetType().Name + ": " + e.Message }));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// UE FDateTime ticks (100ns, 0001-01-01 기준, UTC) → 유닉스 ms
|
||||
public static long FDateTimeToUnixMs(long ticks) => ticks <= 0 ? 0 : (ticks - 621355968000000000L) / 10000L;
|
||||
}
|
||||
@@ -120,6 +120,46 @@ try {
|
||||
}
|
||||
|
||||
if ($Phase -eq 'full') {
|
||||
# 3D 리플레이 변환기 (v1.5.0~): .NET SDK 10 (없으면 받음) → ValorantReplayParser 고정 커밋 → win-x64 단일 exe
|
||||
$r['replay_build'] = Step 'replay_build' {
|
||||
$dn = 'C:\win-ci\dotnet'
|
||||
if (-not (Test-Path (Join-Path $dn 'dotnet.exe'))) {
|
||||
$inst = Get-File 'https://dot.net/v1/dotnet-install.ps1' 'dotnet-install.ps1'
|
||||
& powershell -NoProfile -ExecutionPolicy Bypass -File $inst -Channel 10.0 -InstallDir $dn
|
||||
}
|
||||
$env:DOTNET_ROOT = $dn
|
||||
$env:DOTNET_CLI_TELEMETRY_OPTOUT = '1'
|
||||
$env:DOTNET_NOLOGO = '1'
|
||||
& (Join-Path $dn 'dotnet.exe') --version
|
||||
$tx = Join-Path $Repo 'tools\replay-extract'
|
||||
$vd = Join-Path $tx 'vendor\ValorantReplayParser'
|
||||
$pc = (Select-String -Path (Join-Path $tx 'fetch-parser.sh') -Pattern 'PARSER_COMMIT:-([0-9a-f]{40})').Matches[0].Groups[1].Value
|
||||
if (-not (Test-Path (Join-Path $vd '.git'))) { & git clone -q https://github.com/michel-giehl/ValorantReplayParser $vd }
|
||||
& git -C $vd fetch -q origin
|
||||
& git -C $vd checkout -q --force $pc
|
||||
# global.json 의 SDK 패치 버전 고정을 푼다 (fetch-parser.sh 와 같게)
|
||||
$gj = Join-Path $vd 'global.json'
|
||||
$j = Get-Content $gj -Raw | ConvertFrom-Json
|
||||
$j.sdk | Add-Member -NotePropertyName rollForward -NotePropertyValue 'latestFeature' -Force
|
||||
$j | ConvertTo-Json -Depth 5 | Set-Content $gj -Encoding UTF8
|
||||
"parser @ $(& git -C $vd rev-parse --short HEAD)"
|
||||
Push-Location $tx
|
||||
& (Join-Path $dn 'dotnet.exe') publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none -o out\win
|
||||
$c = $LASTEXITCODE
|
||||
Pop-Location
|
||||
if ($c -ne 0) { throw "dotnet publish exit $c" }
|
||||
$exe = Join-Path $tx 'out\win\gvr-replay.exe'
|
||||
if (-not (Test-Path $exe)) { throw 'gvr-replay.exe 없음' }
|
||||
"gvr-replay.exe $([math]::Round((Get-Item $exe).Length / 1MB, 1)) MB"
|
||||
# 실제 13.08 리플레이 변환 (호스트가 serve/ 에 둔 시험 파일, 없으면 건너뜀)
|
||||
$vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf'
|
||||
try { Invoke-WebRequest -Uri 'http://10.0.2.2:8099/gvr-test.vrf' -OutFile $vrf -UseBasicParsing -TimeoutSec 600 } catch { Remove-Item $vrf -Force -ErrorAction SilentlyContinue; "시험 리플레이 없음: $($_.Exception.Message)" }
|
||||
if (Test-Path $vrf) {
|
||||
$out = & $exe $vrf (Join-Path $OutDir 'replay.json')
|
||||
$out
|
||||
if ($LASTEXITCODE -ne 0) { throw "gvr-replay exit $LASTEXITCODE" }
|
||||
}
|
||||
}
|
||||
$r['app_build'] = Step 'app_build' {
|
||||
Push-Location (Join-Path $Repo 'app')
|
||||
& npm.cmd ci --no-audit --no-fund
|
||||
@@ -134,6 +174,9 @@ try {
|
||||
$exe = Get-ChildItem app\release\win-unpacked\GameVoiceRecorder.exe
|
||||
$data = Join-Path $OutDir 'smoke-data'
|
||||
Remove-Item $data -Recurse -Force -ErrorAction SilentlyContinue
|
||||
# 시험 리플레이가 있으면 앱 안의 변환기로 실제 변환까지 확인한다
|
||||
$vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf'
|
||||
if (Test-Path $vrf) { $env:GVR_SMOKE_VRF = $vrf } else { Remove-Item Env:GVR_SMOKE_VRF -ErrorAction SilentlyContinue }
|
||||
$p = Start-Process $exe.FullName -ArgumentList '--smoke', "--data-dir=$data" -PassThru -Wait
|
||||
Get-Content (Join-Path $data 'smoke.json') -ErrorAction SilentlyContinue
|
||||
if ($p.ExitCode -ne 0) { throw "app smoke exit $($p.ExitCode)" }
|
||||
|
||||
@@ -176,10 +176,17 @@ class SttEngine:
|
||||
segs = run(hotwords)
|
||||
# 핫워드 되풀이 방지: Whisper 가 말을 못 알아들으면 프롬프트(핫워드 목록)를 그대로 읽어 버리는 경우가 있다.
|
||||
# 결과가 핫워드로만 채워져 있으면 핫워드 없이 한 번 더 돌려 그 결과를 쓴다.
|
||||
names = [n for n in (req.get("player_names") or []) if isinstance(n, str) and n.strip()]
|
||||
if hotwords and is_hotword_echo("".join(x.text for x in segs), hotwords):
|
||||
log.info("핫워드 되풀이 감지 → 핫워드 없이 다시 변환")
|
||||
segs = run(None)
|
||||
result["hotword_retry"] = True
|
||||
elif names and is_name_echo("".join(x.text for x in segs), names):
|
||||
# 말을 못 알아들으면 핫워드에 넣은 선수 이름(상대 닉네임 등)을 그대로 적는 경우가 있다 (예: "QQQWWWQ").
|
||||
# 결과가 선수 이름(또는 그 조각)뿐이면 선수 이름을 빼고 다시 변환한다. 정말 이름을 말했으면 다시 해도 그 이름이 나온다.
|
||||
log.info("선수 이름 되풀이 감지 → 선수 이름 없이 다시 변환")
|
||||
segs = run(_without_names(hotwords, names))
|
||||
result["name_retry"] = True
|
||||
|
||||
words: list[dict[str, Any]] = []
|
||||
for seg in segs:
|
||||
@@ -214,6 +221,36 @@ class SttEngine:
|
||||
return done()
|
||||
|
||||
|
||||
def _norm_name(s: str) -> str:
|
||||
"""대소문자 · 띄어쓰기 · 문장부호를 무시한 비교용 글자."""
|
||||
return "".join(ch for ch in s.lower() if ch.isalnum())
|
||||
|
||||
|
||||
def is_name_echo(text: str, names: list[str]) -> bool:
|
||||
"""결과 문장이 선수 이름(또는 이름 조각)만으로 되어 있는지.
|
||||
|
||||
문장 전체(띄어쓰기 무시) 또는 모든 단어가 2글자 이상이면서 어떤 선수 이름 안에 그대로 들어 있어야 한다.
|
||||
예: 이름 "QQQWWWQQQ" → "QQQWWWQ", "QQQWWWQ QQQWWWQ" 는 되풀이, "QQQ 잡았다" 는 아님.
|
||||
"""
|
||||
keys = [k for k in (_norm_name(n) for n in names) if len(k) >= 2]
|
||||
toks = [_norm_name(t) for t in text.split()]
|
||||
toks = [t for t in toks if t]
|
||||
if not keys or not toks:
|
||||
return False
|
||||
whole = "".join(toks)
|
||||
if len(whole) >= 2 and any(whole in k for k in keys):
|
||||
return True
|
||||
return all(len(t) >= 2 and any(t in k for k in keys) for t in toks)
|
||||
|
||||
|
||||
def _without_names(hotwords: str | None, names: list[str]) -> str | None:
|
||||
if not hotwords:
|
||||
return None
|
||||
drop = {w for n in names for w in n.split()}
|
||||
rest = " ".join(h for h in hotwords.split() if h not in drop)
|
||||
return rest or None
|
||||
|
||||
|
||||
def is_hotword_echo(text: str, hotwords: str) -> bool:
|
||||
"""결과 문장이 핫워드 목록을 되풀이한 것인지.
|
||||
|
||||
|
||||
@@ -15,3 +15,33 @@ def test_normal_sentence_with_some_hotwords_is_kept():
|
||||
assert not is_hotword_echo("드래곤 가자 바텀으로 모여", HW)
|
||||
assert not is_hotword_echo("바론 치자 시야 잡아줘", HW)
|
||||
assert not is_hotword_echo("포탑 밀자", HW)
|
||||
|
||||
|
||||
# 선수 이름 되풀이 (v1.4.3): 상대 닉네임 "QQQWWWQQQ" 를 핫워드로 넣었더니 말소리를 "QQQWWWQ" 로 적었다
|
||||
from gvr_worker.stt import _without_names, is_name_echo # noqa: E402
|
||||
|
||||
NAMES = ["QQQWWWQQQ", "노곤노곤탐방가", "하늘 별"]
|
||||
|
||||
|
||||
def test_name_echo_detected_for_name_or_fragment():
|
||||
assert is_name_echo("QQQWWWQ", NAMES)
|
||||
assert is_name_echo(" QQQWWWQ.", NAMES)
|
||||
assert is_name_echo("qqqwwwqqq", NAMES)
|
||||
assert is_name_echo("QQQWWWQ QQQWWWQ", NAMES)
|
||||
assert is_name_echo("노곤노곤탐방가", NAMES)
|
||||
assert is_name_echo("하늘 별", NAMES)
|
||||
|
||||
|
||||
def test_name_echo_not_for_real_speech():
|
||||
assert not is_name_echo("QQQ 잡았다", NAMES)
|
||||
assert not is_name_echo("노곤노곤탐방가 죽였어", NAMES)
|
||||
assert not is_name_echo("아이고, 점프티... 아, 갔다.", NAMES)
|
||||
assert not is_name_echo("Q", NAMES)
|
||||
assert not is_name_echo("", NAMES)
|
||||
assert not is_name_echo("QQQWWWQ", [])
|
||||
|
||||
|
||||
def test_without_names_keeps_other_hotwords():
|
||||
assert _without_names("제트 레이즈 QQQWWWQQQ 하늘 별 로테", NAMES) == "제트 레이즈 로테"
|
||||
assert _without_names("QQQWWWQQQ", NAMES) is None
|
||||
assert _without_names(None, NAMES) is None
|
||||
|
||||
Reference in New Issue
Block a user