Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cd6f1103f | ||
|
|
f82857f476 | ||
|
|
86c42d99ca | ||
|
|
f8f585f230 | ||
|
|
d87f4ade27 | ||
|
|
6d71abaabd | ||
|
|
1ee753bc79 | ||
|
|
b9431c1a15 | ||
|
|
916b35c691 | ||
|
|
84ba2e3e64 |
15
README.md
15
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.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)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.6.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0) (`GameVoiceRecorder-1.6.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.6.0-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,19 @@
|
||||
- 앱은 시작할 때와 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.6.0 바뀐 점
|
||||
|
||||
- **내 정보** (사이트 오른쪽 위 내 이름 누르기, `site/web/src/components/UserEdit.tsx`): 표시 이름 바꾸기 · 되돌리기(디스코드 서버 별명으로), 내 색, 라이엇 ID, 녹음 제외, 내 기록 보기 · 관리 페이지 · 로그아웃
|
||||
- 표시 이름은 사이트 서버에 저장하고(`PUT /site/profile/name`, 1~32자 · 보이지 않는 글자 금지 · 다른 사람 표시 이름과 겹치면 거절 · 10분에 10번) 게임 PC 앱에 바로 보낸다(`PUT /api/internal/names`, 예전 앱은 10분마다 받아 감)
|
||||
- 색 · 라이엇 ID · 녹음 제외는 게임 PC 앱 기록에 저장 (`PATCH /api/users/:id`, 본인 또는 관리자. 다른 사람에게 연결된 라이엇 ID 는 본인이 가져갈 수 없음)
|
||||
- **관리 페이지** `/admin` (관리자 · 최고 관리자, `site/web/src/pages/AdminPage.tsx`): 게임 PC 연결 · 앱 버전 · 새 버전 안내(Gitea 최신 릴리스), 녹음된 사람 + 앱 등록 유저 목록에서 표시 이름 · 색 · 라이엇 ID · 녹음 제외 바꾸기, 앱 등록 · 역할 · 해제(최고 관리자). 서버 `/site/admin/*` 는 앱 관리자 탭 `/app/admin/*` 와 같은 코드 (`site/server/src/app-auth.ts`). 표시 이름은 사이트에서는 관리자도 바꿀 수 있다
|
||||
|
||||
## v1.5.0 바뀐 점
|
||||
|
||||
- **3D 리플레이**: 발로란트 경력 탭에서 경기 리플레이를 내려받아 두면, 사이트 경기 화면 "3D 리플레이"를 열 때 게임 PC 앱이 `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` 를 찾아 변환해 보낸다 (처음 한 번 10초 안팎, 그 뒤로는 `GVR-Data/replays/<경기 ID>.json.gz` 보관본). 선수 10명이 3D 맵 위에서 움직이고 그때 대화가 같이 재생된다
|
||||
- 변환기 `resources/replay/gvr-replay.exe` (`tools/replay-extract`, .NET 단일 파일). 한 번에 하나 · 낮은 우선순위로 돌린다. 실패하면 이유를 사이트에 보여 주고, 같은 파일은 다시 내려받을 때까지 다시 하지 않는다
|
||||
- 앱 `app/src/core/replays.ts`, API `GET /api/matches/:id/replay` (gzip JSON, 변환 중 202) · `GET /api/replays` (찾은 리플레이 목록)
|
||||
|
||||
## v1.4.3 바뀐 점
|
||||
|
||||
- 상대 닉네임을 말로 적던 문제 (예: 말소리가 "QQQWWWQ"로 나옴): 그 경기 선수 이름을 모두 핫워드로 넣어서, 말을 못 알아들으면 Whisper 가 닉네임을 그대로 적었다. 이제
|
||||
|
||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.0",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
@@ -40,6 +40,8 @@ export interface ApiDeps {
|
||||
bundles?: Bundles;
|
||||
/** 발로란트 리플레이 (없으면 /api/replays 없음) */
|
||||
replays?: Replays;
|
||||
/** 사이트 서버가 새 표시 이름을 보내 왔을 때 (녹음 파일 이름 다시 맞추기) */
|
||||
onNamesChanged?: () => void;
|
||||
}
|
||||
|
||||
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
|
||||
@@ -118,6 +120,39 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches };
|
||||
});
|
||||
|
||||
// 유저 설정 (v1.6.0, 사이트 "내 정보" · 관리 화면): 색 · 녹음 제외 · 라이엇 ID. 본인 또는 관리자만
|
||||
app.patch<{ Params: { id: string }; Body: { color?: string; excluded?: boolean; riotIds?: string[] } }>('/api/users/:id', async (req, reply) => {
|
||||
const u = store.getUser(req.params.id);
|
||||
if (!u) return reply.code(404).send({ error: 'not_found', message: '이 PC 기록에 없는 유저입니다 (음성채널에서 한 번 녹음되면 생깁니다)' });
|
||||
const admin = req.headers['x-gvr-role'] === 'admin' || !req.headers['x-gvr-user'];
|
||||
if (!admin && !canDelete(req, u.id)) return reply.code(403).send({ error: 'forbidden', message: '본인 또는 관리자만 바꿀 수 있습니다' });
|
||||
const b = req.body ?? {};
|
||||
if (b.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(b.color))) return reply.code(400).send({ error: 'bad_color', message: '색은 #rrggbb 형식입니다' });
|
||||
if (b.riotIds !== undefined && (!Array.isArray(b.riotIds) || b.riotIds.length > 5 || b.riotIds.some((r) => typeof r !== 'string' || r.length > 45)))
|
||||
return reply.code(400).send({ error: 'bad_riot_ids', message: '라이엇 ID 는 5개까지, 이름#태그 형식입니다' });
|
||||
let taken: string[] = [];
|
||||
store.db.transaction(() => {
|
||||
if (b.color !== undefined) store.setColor(u.id, String(b.color).toLowerCase());
|
||||
if (b.excluded !== undefined) store.setExcluded(u.id, !!b.excluded);
|
||||
if (b.riotIds !== undefined) taken = store.setRiotIds(u.id, b.riotIds, admin).taken;
|
||||
})();
|
||||
log.info(`유저 설정 바뀜 ${u.id}: ${Object.keys(b).join(', ')}${taken.length ? ` (이미 다른 사람에게 연결된 라이엇 ID ${taken.length}개 뺌)` : ''}`);
|
||||
d.bus.live({ type: 'users.updated', data: [] });
|
||||
return { user: toUser(store.getUser(u.id)!, store.listAccounts()), taken };
|
||||
});
|
||||
|
||||
// 표시 이름 (v1.6.0): 사이트에서 이름을 바꾸면 사이트 서버가 바로 보낸다 (예전 앱은 10분마다 받아 감)
|
||||
app.put<{ Body: { names?: Record<string, string> } }>('/api/internal/names', async (req, reply) => {
|
||||
if (req.headers['x-gvr-internal'] !== '1') return reply.code(403).send({ error: 'forbidden' });
|
||||
const names = req.body?.names;
|
||||
if (!names || typeof names !== 'object') return reply.code(400).send({ error: 'bad_names' });
|
||||
store.setDisplayNames(names);
|
||||
timeline.invalidate();
|
||||
d.onNamesChanged?.();
|
||||
d.bus.live({ type: 'users.updated', data: [] });
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.get<{ Querystring: Record<string, string> }>('/api/timeline', async (req) => {
|
||||
const q = req.query;
|
||||
const tq: TimelineQuery = {
|
||||
|
||||
@@ -241,6 +241,10 @@ export class Store {
|
||||
setExcluded(id: string, excluded: boolean): void {
|
||||
this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id);
|
||||
}
|
||||
/** 사이트 · 타임라인에서 쓰는 유저 색 (#rrggbb) */
|
||||
setColor(id: string, color: string): void {
|
||||
this.db.prepare('UPDATE users SET color=?, updated_at=? WHERE id=?').run(color, Date.now(), id);
|
||||
}
|
||||
/** 유저 평소 음량 누적 평균 (최근값에 가중치) */
|
||||
updateGainProfile(id: string, lufs: number): void {
|
||||
const u = this.getUser(id);
|
||||
@@ -252,6 +256,29 @@ export class Store {
|
||||
listAccounts(): { user_id: string; puuid: string; riot_id: string }[] {
|
||||
return this.db.prepare('SELECT * FROM game_accounts').all() as any[];
|
||||
}
|
||||
/**
|
||||
* 라이엇 ID (이름#태그) 목록으로 연결 계정을 바꾼다. 이미 연결된 것은 puuid 를 그대로 두고, 새것은 riotid: 로 두었다가
|
||||
* 경기에서 만나면 실제 puuid 로 바뀐다. 다른 사람에게 연결된 라이엇 ID 는 넣지 않고 돌려준다 (관리자는 allowTaken 으로 같이 연결)
|
||||
*/
|
||||
setRiotIds(userId: string, riotIds: string[], allowTaken = false): { taken: string[] } {
|
||||
const all = this.listAccounts();
|
||||
const cur = all.filter((a) => a.user_id === userId);
|
||||
const taken: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const next: { puuid: string; riot_id: string }[] = [];
|
||||
for (const raw of riotIds) {
|
||||
const r = raw.trim();
|
||||
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(r) || seen.has(r.toLowerCase())) continue;
|
||||
seen.add(r.toLowerCase());
|
||||
if (!allowTaken && all.some((a) => a.user_id !== userId && a.riot_id.toLowerCase() === r.toLowerCase())) {
|
||||
taken.push(r);
|
||||
continue;
|
||||
}
|
||||
next.push(cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
|
||||
}
|
||||
this.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
|
||||
return { taken };
|
||||
}
|
||||
setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void {
|
||||
const tx = this.db.transaction(() => {
|
||||
this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId);
|
||||
|
||||
@@ -106,6 +106,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
trainingDir: () => paths().training,
|
||||
version: opts.version,
|
||||
replays,
|
||||
onNamesChanged: () => audioNames.refreshAll(),
|
||||
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
|
||||
overviewExtra: () => ({
|
||||
guild: bot.state.guild,
|
||||
|
||||
@@ -241,12 +241,8 @@ export function registerIpc(ctx: IpcContext) {
|
||||
return core.store.listUsers().map((u) => toUser(u, acc));
|
||||
},
|
||||
setRiotIds: (userId: string, riotIds: string[]) => {
|
||||
const cur = core.store.listAccounts().filter((a) => a.user_id === userId);
|
||||
const next = riotIds
|
||||
.map((r) => r.trim())
|
||||
.filter((r) => /^.+#.+$/.test(r))
|
||||
.map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
|
||||
core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
|
||||
core.store.setRiotIds(userId, riotIds, true);
|
||||
core.bus.live({ type: 'users.updated', data: [] });
|
||||
},
|
||||
setExcluded: (userId: string, excluded: boolean) => {
|
||||
core.store.setExcluded(userId, excluded);
|
||||
|
||||
82
app/test/user-settings.test.ts
Normal file
82
app/test/user-settings.test.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
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 { 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';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-uset-'));
|
||||
const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role });
|
||||
|
||||
async function setup() {
|
||||
const dir = tmp();
|
||||
const store = new Store(path.join(dir, '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: !!u.excluded, riot: [] }));
|
||||
const live: any[] = [];
|
||||
bus.on('live', (e) => live.push(e));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
|
||||
store.setAccounts('u2', [{ puuid: 'p2', riotId: '민수#KR1' }]);
|
||||
let renamed = 0;
|
||||
const app = await buildApi({
|
||||
store,
|
||||
timeline: new Timeline(store),
|
||||
games: {} as any,
|
||||
dict: {} as any,
|
||||
culprit: {} as any,
|
||||
bus,
|
||||
settings: () => ({}) as any,
|
||||
trainingDir: () => path.join(dir, 'training'),
|
||||
overviewExtra: () => ({ guild: null, recording: {} as any }),
|
||||
version: 'test',
|
||||
onNamesChanged: () => renamed++,
|
||||
});
|
||||
return { store, app, live, renamed: () => renamed };
|
||||
}
|
||||
|
||||
test('유저 설정: 본인은 색 · 녹음 제외 · 라이엇 ID 를 바꾸고, 바뀌면 사이트에 실시간으로 알린다', async () => {
|
||||
const s = await setup();
|
||||
const r = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: '#45D39A', excluded: true, riotIds: ['하늘#KR1', ' 하늘#KR1 ', '별빛#0001'] } });
|
||||
assert.equal(r.statusCode, 200);
|
||||
const u = r.json().user;
|
||||
assert.equal(u.color, '#45d39a');
|
||||
assert.equal(u.excluded, true);
|
||||
assert.deepEqual(u.riot.map((x: any) => x.riotId), ['하늘#KR1', '별빛#0001'], '같은 ID 는 한 번만');
|
||||
assert.equal(s.live.at(-1).type, 'users.updated');
|
||||
assert.ok(s.live.at(-1).data.length >= 2, '실제 유저 목록을 보낸다');
|
||||
// 이미 연결된 puuid 는 그대로 둔다
|
||||
s.store.setAccounts('u1', [{ puuid: 'p1', riotId: '하늘#KR1' }]);
|
||||
await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['하늘#KR1'] } });
|
||||
assert.deepEqual(s.store.listAccounts().filter((a) => a.user_id === 'u1'), [{ user_id: 'u1', puuid: 'p1', riot_id: '하늘#KR1' }]);
|
||||
});
|
||||
|
||||
test('유저 설정: 다른 사람 것은 관리자만, 남의 라이엇 ID 는 본인이 가져갈 수 없다, 형식 검사', async () => {
|
||||
const s = await setup();
|
||||
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1'), payload: { excluded: true } })).statusCode, 403);
|
||||
assert.equal(s.store.getUser('u2')!.excluded, 0);
|
||||
const taken = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['민수#KR1', '하늘#KR1'] } });
|
||||
assert.deepEqual(taken.json().taken, ['민수#KR1']);
|
||||
assert.deepEqual(taken.json().user.riot.map((x: any) => x.riotId), ['하늘#KR1']);
|
||||
// 관리자는 다른 사람 설정도 바꾼다
|
||||
const adm = await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1', 'admin'), payload: { excluded: true, color: '#ff4655' } });
|
||||
assert.equal(adm.statusCode, 200);
|
||||
assert.equal(s.store.getUser('u2')!.excluded, 1);
|
||||
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: 'red' } })).statusCode, 400);
|
||||
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['a#1', 'b#2', 'c#3', 'd#4', 'e#5', 'f#6'] } })).statusCode, 400);
|
||||
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/nobody', headers: as('nobody'), payload: { excluded: true } })).statusCode, 404);
|
||||
});
|
||||
|
||||
test('표시 이름: 사이트 서버(내부 요청)만 보낼 수 있고, 받으면 이름 · 녹음 파일 이름을 맞추고 알린다', async () => {
|
||||
const s = await setup();
|
||||
const bad = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: as('u1', 'admin'), payload: { names: { u1: '해커' } } });
|
||||
assert.equal(bad.statusCode, 403);
|
||||
const ok = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: { ...as('server'), 'x-gvr-internal': '1' }, payload: { names: { u1: '하늘별' } } });
|
||||
assert.equal(ok.statusCode, 200);
|
||||
assert.equal(s.store.getUser('u1')!.name, '하늘별');
|
||||
assert.equal(s.renamed(), 1);
|
||||
assert.equal(s.live.at(-1).type, 'users.updated');
|
||||
});
|
||||
@@ -23,10 +23,22 @@
|
||||
- 천장 자르기: 자동(고른 선수 · 없으면 가장 높은 산 선수 몸 중심 + 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`.
|
||||
|
||||
## 앱 (v1.5.0)
|
||||
- `app/src/core/replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래(깊이 3, Logs · Crashes · Config 제외) `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe <vrf> <tmp.json>` (낮은 우선순위, 한 번에 하나, 3분 제한) → gzip → `GVR-Data/replays/<경기 ID>.json.gz` + `.src`(크기:수정시각:앱 버전). 실패는 메모리에 기억 (파일이 바뀌거나 앱을 다시 켜면 다시)
|
||||
- `GET /api/matches/:id/replay`: 15초 안에 끝나면 200 (content-encoding gzip), 아니면 202 `{status:'converting'}` → 사이트가 3초마다 다시. 중계는 content-encoding 이 있으면 바이너리 조각 (`relay/client.ts`)
|
||||
- 빌드: win-ci `replay_build` 단계 (.NET 10 SDK `C:\win-ci\dotnet`, `dotnet publish -r win-x64` 단일 파일 38MB) → electron-builder extraResources `replay/`. 호스트 `~/win-ci/serve/gvr-test.vrf`(13.08 어비스 경기) 가 있으면 변환기 · 포터블 앱 smoke(`GVR_SMOKE_VRF`) 둘 다 실제 변환
|
||||
- 리눅스 실측(13.08, 73.8MB vrf): 5.5초, 최대 메모리 347MB, gzip 1.4MB
|
||||
|
||||
## 완전 3D (2026-10-17, v1.7.0)
|
||||
- 맵 색: `MapScene` 이 재질마다 primitive 하나 (법선 · UV, 디퓨즈 텍스처 256px JPEG/PNG(알파), `DiffuseColor` 색). 두 층 재질(`BaseEnv_Blend_*`, Diffuse A/B)은 정점 색 R 로 섞는다 (`extras.blend`, 사이트 `map3d.ts` 셰이더). UE 왼손 → glTF 앞면에 맞춰 삼각형을 뒤집는다. 어비스 압축 12MB.
|
||||
- 요원: `gvr-map-extract agents <폴더>` → `agent_<코드>.glb` (요원 블루프린트 `Characters/<코드>/<코드>_PC` 의 3인칭 메시 LOD1, 512px 텍스처, 뼈대 + 공용 애니메이션 `ub_rifle`(Core_Rifle_Idle 위 몸) · `lb_idle/run*/walk*`(아래 몸, Skeleton·Root 는 회전만)). 애니메이션은 ACL 압축이라 CUE4Parse-Natives(ACL 만)를 g++ 로 빌드해 실행 파일 옆에 둔다 (`install.sh`). 30명 46초, 압축 6.4MB.
|
||||
- 무기: `weapon_<이름>.glb` (기본 스킨 몸 + 탄창, 원점 = 손잡이, 총구 +X). 사이트는 손목(R_Hand) 에 붙이고 보는 방향(pitch)으로 돌린다 (공용 애니메이션은 R_WeaponPoint 를 움직이지 않아 손과 떨어져 있다). 22종 1.5MB.
|
||||
- 변환기: `equips` [t, 선수, 종류] / `equipKinds` (총 영어 이름 · Melee · Spike · 스킬 클래스). 사이트 이름표 "🔫 밴달", 킬 피드에 무기. 옛 리플레이 JSON 에는 없다 (앱 v1.7.0 부터).
|
||||
- 재생기: 카메라 위에서 / 1인칭(고른 선수 눈 + 60cm, pitch) / 자유시점(WASD · Q/E · Shift, 끌어서 둘러보기). 요원은 이동 방향 · 속도로 아래 몸 애니메이션을 섞는다. 스킬은 `lib/abilities.ts` 가 클래스 이름으로 연막(요원 색 구) · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크로 나눈다.
|
||||
- 한계: 스킬 효과(파티클) · 벽 스킬 방향 · 앉기 · 점프 자세 · 스킨은 없다. 리플레이 위치는 10Hz 라 빠른 움직임은 보간이다.
|
||||
|
||||
## 남은 일
|
||||
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초)")
|
||||
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
|
||||
|
||||
## 완전 3D (맵 · 캐릭터 · 총 · 효과) 조사 (2026-10-17)
|
||||
- 게임 파일: Riot CDN 에서 바로 받을 수 있다 (게임 PC 불필요). 매니페스트는
|
||||
|
||||
@@ -272,3 +272,17 @@ VOICE E2E PASS
|
||||
- 테스트: 워커 `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 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
|
||||
|
||||
## v1.5.0 — 3D 리플레이: 앱이 리플레이를 찾아 변환 (2026-10-17)
|
||||
|
||||
- 앱 `replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe` 로 변환 → `GVR-Data/replays/<경기 ID>.json.gz`. API `GET /api/matches/:id/replay` (gzip, 변환 중 202, 실패 422) · `GET /api/replays`
|
||||
- 테스트: 앱 73(새 `replays.test.ts` 7개: 찾기 · 변환 후 보관본 · 실패 기억과 다시 내려받으면 다시 · 202 → 200 · 변환기 없음 · 중계 gzip 바이너리 · 실제 리눅스 변환기로 13.08 리플레이) · 사이트 서버 27 통과, 타입 검사 · 화면 빌드 통과
|
||||
- Windows CI (adc1c66, full) 8개 모두 PASS: 새 `replay_build` (.NET 10.0.402, gvr-replay.exe 36.3MB, 13.08 어비스 리플레이 6.8초 변환), `app_smoke` 에서 포터블 앱 안 변환기로 같은 리플레이 9.1초 변환(gzip 1.39MB)
|
||||
- 배포: 사이트 서버 다시 배포 (화면 번들에 '변환하는 중' 확인), 앱 버전 1.5.0 → Gitea 릴리스 v1.5.0 (v1.4.3 에 새 버전 안내)
|
||||
|
||||
## v1.6.0 — 사이트 내 정보 · 관리 페이지 (2026-10-17)
|
||||
|
||||
- 사이트: 머리글 내 이름 → 내 정보 (표시 이름 · 색 · 라이엇 ID · 녹음 제외 · 로그아웃), `/admin` 관리 페이지 (게임 PC · 새 버전 안내 · 유저별 설정 · 앱 등록/역할/해제)
|
||||
- 테스트: 앱 76 (새 `user-settings.test.ts` 3개) · 사이트 서버 30 (새 `profile-admin.test.ts` 3개) 통과, 타입 검사 · 화면 빌드 통과
|
||||
- 화면: 목 서버 + 헤드리스 크롬(playwright-core)으로 내 정보(이름 저장 · 머리글 반영 · 색 · 녹음 제외 · 되돌리기) · 관리 페이지(새 버전 링크 · 이름 바꾸기 · 앱 유저 등록) · 모바일 390px 확인, 콘솔 오류 0
|
||||
- 배포: 사이트 서버 다시 배포 (`/site/admin/overview` · `/site/profile/name` 로그인 없이 401, 컨테이너에서 Gitea 최신 릴리스 조회 확인), Windows CI (b9431c1, full) 8개 모두 PASS · 앱 버전 1.6.0 → Gitea 릴리스 v1.6.0 (v1.5.0 · v1.4.3 에 새 버전 안내)
|
||||
|
||||
@@ -28,7 +28,17 @@ const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
|
||||
|
||||
export function registerAppAuth(
|
||||
app: FastifyInstance,
|
||||
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
|
||||
deps: {
|
||||
cfg: Config;
|
||||
store: ServerStore;
|
||||
discord: DiscordApi;
|
||||
secure: boolean;
|
||||
onRevoke?: (by: { userId?: string; token?: string }) => void;
|
||||
/** 사이트 로그인 세션 (사이트 관리 화면 /site/admin/*). app.ts 가 나중에 넣는다 */
|
||||
siteSession?: (req: FastifyRequest, reply: FastifyReply) => Promise<{ user: { id: string } } | null>;
|
||||
/** 표시 이름이 바뀌었을 때 (게임 PC 앱에 바로 보낸다) */
|
||||
onNamesChanged?: (id: string, name: string | null) => void;
|
||||
},
|
||||
) {
|
||||
const { cfg, store, discord, secure } = deps;
|
||||
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
|
||||
@@ -186,64 +196,109 @@ export function registerAppAuth(
|
||||
if (!(await auth(req, reply))) return;
|
||||
return { names: store.displayNames() };
|
||||
});
|
||||
app.put<{ Body: { id?: string; name?: string | null } }>('/app/admin/names', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
const name = String(req.body?.name ?? '').trim().slice(0, 32);
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
store.setDisplayName(id, name || null);
|
||||
req.log.info({ by: a.id, user: id, set: !!name }, '표시 이름 변경');
|
||||
return { names: store.displayNames() };
|
||||
});
|
||||
|
||||
app.get('/app/admin/users', async (req, reply) => {
|
||||
if (!(await need(req, reply, 'admin'))) return;
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.post<{ Body: { id?: string; role?: string } }>('/app/admin/users', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
const r = role(req.body?.role ?? 'user');
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
|
||||
let du: DiscordUser | null;
|
||||
try {
|
||||
du = await fetchDiscordUser(cfg, id);
|
||||
} catch (e) {
|
||||
req.log.warn(e, '디스코드 계정 조회 실패');
|
||||
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
// 관리 API 는 두 곳에서 부른다: 앱 관리자 탭(/app/admin/*, 앱 토큰) · 사이트 관리 화면(/site/admin/*, 사이트 로그인 v1.6.0~)
|
||||
const siteNeed = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
|
||||
const s = deps.siteSession ? await deps.siteSession(req, reply) : null;
|
||||
if (!s) {
|
||||
if (!reply.sent) reply.code(401).send({ error: 'unauthorized' });
|
||||
return null;
|
||||
}
|
||||
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
|
||||
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
|
||||
store.upsertAppUser({ id, name: du.global_name || du.username, avatar: avatarUrl(du), role: r, addedBy: a.id });
|
||||
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
|
||||
return { users: rows() };
|
||||
});
|
||||
// 쓰기 요청은 같은 사이트에서 온 것만 (CSRF)
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (req.method !== 'GET' && origin && origin !== cfg.publicUrl) {
|
||||
reply.code(403).send({ error: 'bad_origin' });
|
||||
return null;
|
||||
}
|
||||
const r = siteRole(s.user.id);
|
||||
const ok = r && (level === 'superadmin' ? r === 'superadmin' : r !== 'user');
|
||||
if (!ok) {
|
||||
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록 · 역할 바꾸기는 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
|
||||
return null;
|
||||
}
|
||||
return { id: s.user.id, role: r };
|
||||
};
|
||||
for (const [prefix, who] of [
|
||||
['/app/admin', need],
|
||||
['/site/admin', siteNeed],
|
||||
] as const) {
|
||||
// 표시 이름: 앱에서는 최고 관리자만 (v1.2~), 사이트 관리 화면에서는 관리자도 (v1.6.0)
|
||||
app.put<{ Body: { id?: string; name?: string | null } }>(`${prefix}/names`, async (req, reply) => {
|
||||
const a = await who(req, reply, prefix === '/app/admin' ? 'superadmin' : 'admin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
const v = checkName(req.body?.name, id);
|
||||
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
|
||||
store.setDisplayName(id, v.name);
|
||||
req.log.info({ by: a.id, user: id, set: !!v.name }, '표시 이름 변경');
|
||||
deps.onNamesChanged?.(id, v.name);
|
||||
return { names: store.displayNames() };
|
||||
});
|
||||
|
||||
app.patch<{ Params: { id: string }; Body: { role?: string } }>('/app/admin/users/:id', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const r = role(req.body?.role);
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
|
||||
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
|
||||
return { users: rows() };
|
||||
});
|
||||
app.get(`${prefix}/users`, async (req, reply) => {
|
||||
if (!(await who(req, reply, 'admin'))) return;
|
||||
return { users: rows(), names: store.displayNames() };
|
||||
});
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/app/admin/users/:id', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
|
||||
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
revoke({ userId: req.params.id });
|
||||
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
|
||||
return { users: rows() };
|
||||
});
|
||||
app.post<{ Body: { id?: string; role?: string } }>(`${prefix}/users`, async (req, reply) => {
|
||||
const a = await who(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
const r = role(req.body?.role ?? 'user');
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
|
||||
let du: DiscordUser | null;
|
||||
try {
|
||||
du = await fetchDiscordUser(cfg, id);
|
||||
} catch (e) {
|
||||
req.log.warn(e, '디스코드 계정 조회 실패');
|
||||
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
}
|
||||
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
|
||||
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
|
||||
store.upsertAppUser({ id, name: store.nameOf(id, du.global_name || du.username), avatar: avatarUrl(du), role: r, addedBy: a.id });
|
||||
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.patch<{ Params: { id: string }; Body: { role?: string } }>(`${prefix}/users/:id`, async (req, reply) => {
|
||||
const a = await who(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const r = role(req.body?.role);
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
|
||||
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.delete<{ Params: { id: string } }>(`${prefix}/users/:id`, async (req, reply) => {
|
||||
const a = await who(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
|
||||
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
revoke({ userId: req.params.id });
|
||||
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
|
||||
return { users: rows() };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 표시 이름 확인: 빈 값이면 지우기(디스코드 이름으로), 아니면 1~32자 · 제어 문자 없음 · 다른 사람의 표시 이름과 겹치지 않음
|
||||
* (같은 이름이 둘이면 기록 · 범인 분석에서 누가 누군지 알 수 없다)
|
||||
*/
|
||||
function checkName(raw: unknown, id: string): { name: string | null } | { error: string } {
|
||||
if (raw === null || raw === undefined) return { name: null };
|
||||
const name = String(raw).normalize('NFC').replace(/\s+/g, ' ').trim();
|
||||
if (!name) return { name: null };
|
||||
if ([...name].length > 32) return { error: '이름은 32자까지입니다' };
|
||||
if (/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(name)) return { error: '이름에 쓸 수 없는 글자가 있습니다' };
|
||||
const key = name.toLowerCase();
|
||||
for (const [other, n] of Object.entries(store.displayNames())) if (other !== id && n.toLowerCase() === key) return { error: '다른 사람이 이미 쓰는 이름입니다' };
|
||||
return { name };
|
||||
}
|
||||
const siteRole = (id: string): AppRole | null => roleOf(id) ?? (cfg.owners.includes(id) ? 'admin' : null);
|
||||
|
||||
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
|
||||
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
|
||||
@@ -252,7 +307,7 @@ export function registerAppAuth(
|
||||
return s && r ? { userId: s.userId, role: r } : null;
|
||||
};
|
||||
|
||||
return { completeLogin, verifyToken, roleOf };
|
||||
return { completeLogin, verifyToken, roleOf, siteRole, checkName };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
@@ -9,7 +9,7 @@ import { registerAppAuth } from './app-auth.js';
|
||||
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 { avatarUrl, DiscordApi, fetchDiscordUser } from './discord.js';
|
||||
import { registerMaps3d } from './maps3d.js';
|
||||
import { RateLimiter } from './rate-limit.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
@@ -46,7 +46,15 @@ export async function buildServer(
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
let broker: BotBroker | null = null;
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
|
||||
const appAuth = registerAppAuth(app, {
|
||||
cfg,
|
||||
store,
|
||||
discord,
|
||||
secure,
|
||||
onRevoke: (by) => broker?.kick(by),
|
||||
siteSession: (req, reply) => requireSession(req, reply),
|
||||
onNamesChanged: (id, name) => (name ? pushNames() : void restoreName(id).then(pushNames)),
|
||||
});
|
||||
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
|
||||
|
||||
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
|
||||
@@ -214,7 +222,78 @@ export async function buildServer(
|
||||
app.get('/auth/me', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
|
||||
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id), role: appAuth.siteRole(s.user.id) };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 내 정보 · 표시 이름 (v1.6.0)
|
||||
/** 표시 이름을 게임 PC 앱에 바로 보낸다 (v1.6.0 앱. 예전 앱은 10분마다 받아 간다) */
|
||||
function pushNames(): void {
|
||||
if (!hub.status().online) return;
|
||||
hub
|
||||
.request('PUT', '/api/internal/names', { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, JSON.stringify({ names: store.displayNames() }), 10000)
|
||||
.then((r) => r.status >= 400 && app.log.info({ area: 'names', status: r.status }, '게임 PC 앱이 표시 이름을 바로 받지 못함 (예전 앱은 10분 안에 받아 감)'))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
/** 표시 이름을 지우면 디스코드 이름(서버 별명 → 전역 이름 → 아이디)으로 되돌린다 */
|
||||
async function restoreName(id: string): Promise<void> {
|
||||
try {
|
||||
let nick: string | null = null;
|
||||
for (const g of allowedGuilds()) {
|
||||
const m = await discord.memberOf(g, id);
|
||||
if (m?.nick) nick = m.nick;
|
||||
if (m) break;
|
||||
}
|
||||
const u = nick ? null : await fetchDiscordUser(cfg, id);
|
||||
const name = nick || u?.global_name || u?.username;
|
||||
if (name) store.restoreDiscordName(id, name);
|
||||
} catch (e) {
|
||||
app.log.warn({ area: 'names', err: String(e) }, '디스코드 이름 다시 받기 실패');
|
||||
}
|
||||
}
|
||||
// 관리 화면 머리: 게임 PC 상태 + 최신 앱 릴리스 (Gitea, 1시간 보관). 새 버전이 있으면 관리자에게 알린다
|
||||
let latest: { at: number; v: { version: string; url: string; publishedAt: string | null } | null } = { at: 0, v: null };
|
||||
async function latestRelease() {
|
||||
if (!cfg.releasesApi || Date.now() - latest.at < 3600000) return latest.v;
|
||||
latest.at = Date.now();
|
||||
try {
|
||||
const r = await fetch(cfg.releasesApi, { signal: AbortSignal.timeout(5000), headers: { accept: 'application/json' } });
|
||||
if (r.ok) {
|
||||
const j: any = await r.json();
|
||||
if (typeof j.tag_name === 'string') latest.v = { version: j.tag_name.replace(/^v/, ''), url: String(j.html_url ?? ''), publishedAt: j.published_at ?? null };
|
||||
}
|
||||
} catch {
|
||||
/* 다음에 다시 */
|
||||
latest.at = Date.now() - 3300000;
|
||||
}
|
||||
return latest.v;
|
||||
}
|
||||
app.get('/site/admin/overview', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
const r = appAuth.siteRole(s.user.id);
|
||||
if (!r || r === 'user') return reply.code(403).send({ error: 'forbidden', message: '관리자만 볼 수 있습니다' });
|
||||
const dev = store.device();
|
||||
return { device: { ...hub.status(), guildId: dev?.guildId ?? null }, latest: await latestRelease(), role: r, serverVersion: cfg.version };
|
||||
});
|
||||
const nameLimit = new RateLimiter(10, 10 * 60000);
|
||||
app.get('/site/profile', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
return { user: s.user, customName: store.displayNames()[s.user.id] ?? null, role: appAuth.siteRole(s.user.id) };
|
||||
});
|
||||
app.put<{ Body: { name?: string | null } }>('/site/profile/name', async (req, reply) => {
|
||||
const s = await requireSession(req, reply);
|
||||
if (!s) return;
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
|
||||
if (!nameLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited', message: '이름을 너무 자주 바꿨습니다. 10분 뒤 다시 해 주세요' });
|
||||
const v = appAuth.checkName(req.body?.name, s.user.id);
|
||||
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
|
||||
store.setDisplayName(s.user.id, v.name);
|
||||
if (!v.name) await restoreName(s.user.id);
|
||||
req.log.info({ user: s.user.id, set: !!v.name }, '내 표시 이름 변경');
|
||||
pushNames();
|
||||
return { user: s.user, customName: v.name };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 상태 · 관리
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface Config {
|
||||
/** 테스트용: 디스코드 API 주소 바꾸기 */
|
||||
discordApi: string;
|
||||
assetUpstream: Record<string, string>;
|
||||
/** 최신 앱 릴리스 (Gitea API, 관리 화면에서 새 버전 안내) */
|
||||
releasesApi?: string;
|
||||
/** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */
|
||||
culprit?: {
|
||||
apiKey: string | null;
|
||||
@@ -59,6 +61,7 @@ export function loadConfig(env = process.env): Config {
|
||||
webDir: env.WEB_DIR || path.resolve('../web/dist'),
|
||||
version: env.GVR_VERSION || '1.0.0',
|
||||
discordApi: env.DISCORD_API || 'https://discord.com/api/v10',
|
||||
releasesApi: env.RELEASES_API || 'https://git.tkrmagid.kr/api/v1/repos/tkrmagid/game_voice_recorder/releases/latest',
|
||||
assetUpstream: {
|
||||
valmedia: 'https://media.valorant-api.com/',
|
||||
ddragon: 'https://ddragon.leagueoflegends.com/',
|
||||
|
||||
@@ -212,6 +212,15 @@ export class ServerStore {
|
||||
} else delete this.d.displayNames[id];
|
||||
this.save(true);
|
||||
}
|
||||
/** 표시 이름을 지운 뒤 디스코드에서 다시 받은 이름으로 세션 · 앱 유저 이름을 되돌린다 (예전 표시 이름이 남지 않게) */
|
||||
restoreDiscordName(id: string, name: string): void {
|
||||
if (this.d.displayNames[id]) return;
|
||||
for (const s of this.d.sessions) if (s.user.id === id) s.user.name = name;
|
||||
const u = this.appUser(id);
|
||||
if (u) u.name = name;
|
||||
if (this.d.appSeen[id]) this.d.appSeen[id].name = name;
|
||||
this.save(true);
|
||||
}
|
||||
|
||||
// ---- 앱 유저 등록 · 앱 로그인 토큰
|
||||
appUsers(): AppUser[] {
|
||||
|
||||
132
site/server/test/profile-admin.test.ts
Normal file
132
site/server/test/profile-admin.test.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
// 사이트 "내 정보" (표시 이름) · 관리 화면 API (v1.6.0)
|
||||
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 SUPER = '293719842274541579';
|
||||
const ADMIN = '111111111111111111';
|
||||
const MEMBER = '222222222222222222';
|
||||
const OTHER = '333333333333333333';
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-profile-'));
|
||||
const NICK: Record<string, string> = { [SUPER]: '사금향', [ADMIN]: '관리', [MEMBER]: '멤버닉', [OTHER]: '다른' };
|
||||
|
||||
async function fakeDiscord() {
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url!, 'http://x');
|
||||
res.setHeader('content-type', 'application/json');
|
||||
const m = /^\/guilds\/111\/members\/(\d+)$/.exec(u.pathname);
|
||||
if (m && NICK[m[1]!]) return res.end(JSON.stringify({ nick: NICK[m[1]!], avatar: null }));
|
||||
const usr = /^\/users\/(\d+)$/.exec(u.pathname);
|
||||
if (usr && NICK[usr[1]!]) return res.end(JSON.stringify({ id: usr[1], username: 'u' + usr[1], global_name: NICK[usr[1]!], avatar: null }));
|
||||
if (u.pathname === '/releases/latest') return res.end(JSON.stringify({ tag_name: 'v1.6.0', html_url: 'https://git.example/releases/tag/v1.6.0', published_at: '2026-10-17T00:00:00Z' }));
|
||||
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: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
|
||||
version: 'test', discordApi: dc.url, assetUpstream: {}, releasesApi: `${dc.url}/releases/latest`,
|
||||
};
|
||||
const { app, store } = await buildServer(cfg);
|
||||
store.upsertAppUser({ id: ADMIN, name: '관리', avatar: null, role: 'admin', addedBy: SUPER });
|
||||
await app.listen({ host: '127.0.0.1', port: 0 });
|
||||
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
|
||||
const cookieOf = (id: string) => {
|
||||
const s = store.createSession({ id, name: NICK[id]!, avatar: null });
|
||||
return `gvr_sid=${app.signCookie(s.token)}`;
|
||||
};
|
||||
const as = (id: string) => {
|
||||
const cookie = cookieOf(id);
|
||||
const call = async (method: string, p: string, body?: unknown, origin = 'https://gvr.example') => {
|
||||
const r = await fetch(base + p, { method, headers: { cookie, ...(body !== undefined ? { 'content-type': 'application/json', origin } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
return { status: r.status, json: (await r.json().catch(() => null)) as any };
|
||||
};
|
||||
return { get: (p: string) => call('GET', p), put: (p: string, b: unknown, o?: string) => call('PUT', p, b, o), post: (p: string, b: unknown) => call('POST', p, b), patch: (p: string, b: unknown) => call('PATCH', p, b), del: (p: string) => call('DELETE', p, {}) };
|
||||
};
|
||||
return { store, as, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('내 정보: 누구나 자기 표시 이름을 바꾸고, 지우면 디스코드 별명으로 돌아간다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const me = s.as(MEMBER);
|
||||
assert.deepEqual((await me.get('/site/profile')).json, { user: { id: MEMBER, name: '멤버닉', avatar: null }, customName: null, role: null });
|
||||
const r = await me.put('/site/profile/name', { name: ' 하늘 별 ' });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.json.user.name, '하늘 별');
|
||||
assert.equal((await me.get('/auth/me')).json.user.name, '하늘 별');
|
||||
assert.equal(s.store.displayNames()[MEMBER], '하늘 별');
|
||||
// 지우기 → 디스코드 서버 별명
|
||||
const back = await me.put('/site/profile/name', { name: '' });
|
||||
assert.equal(back.status, 200);
|
||||
assert.equal(back.json.customName, null);
|
||||
assert.equal((await me.get('/auth/me')).json.user.name, '멤버닉');
|
||||
assert.equal(s.store.displayNames()[MEMBER], undefined);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('내 정보: 다른 사람 이름 · 너무 긴 이름 · 보이지 않는 글자 · 다른 사이트에서 온 요청은 막는다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
assert.equal((await s.as(OTHER).put('/site/profile/name', { name: '하늘' })).status, 200);
|
||||
const me = s.as(MEMBER);
|
||||
const dup = await me.put('/site/profile/name', { name: '하늘' });
|
||||
assert.equal(dup.status, 400);
|
||||
assert.match(dup.json.message, /이미 쓰는 이름/);
|
||||
assert.equal((await me.put('/site/profile/name', { name: '가'.repeat(33) })).status, 400);
|
||||
assert.equal((await me.put('/site/profile/name', { name: '하늘' })).status, 400);
|
||||
assert.equal((await me.put('/site/profile/name', { name: '별' }, 'https://evil.example')).status, 403);
|
||||
assert.equal(s.store.displayNames()[MEMBER], undefined);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('관리 화면: 관리자는 목록 · 남의 표시 이름, 등록 · 역할 · 해제는 최고 관리자만, 일반 멤버는 못 들어온다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const member = s.as(MEMBER);
|
||||
const admin = s.as(ADMIN);
|
||||
const sup = s.as(SUPER);
|
||||
assert.equal((await member.get('/site/admin/users')).status, 403);
|
||||
assert.equal((await member.get('/site/admin/overview')).status, 403);
|
||||
assert.equal((await member.put('/site/admin/names', { id: OTHER, name: 'x' })).status, 403);
|
||||
|
||||
const list = await admin.get('/site/admin/users');
|
||||
assert.equal(list.status, 200);
|
||||
assert.deepEqual(list.json.users.map((u: any) => [u.id, u.role]), [[SUPER, 'superadmin'], [ADMIN, 'admin']]);
|
||||
const ov = await admin.get('/site/admin/overview');
|
||||
assert.equal(ov.json.role, 'admin');
|
||||
assert.equal(ov.json.latest.version, '1.6.0');
|
||||
assert.equal(ov.json.device.registered, false);
|
||||
|
||||
const named = await admin.put('/site/admin/names', { id: MEMBER, name: '지호' });
|
||||
assert.equal(named.status, 200);
|
||||
assert.equal(named.json.names[MEMBER], '지호');
|
||||
assert.equal((await member.get('/auth/me')).json.user.name, '지호', '로그인해 있는 세션 이름도 바뀐다');
|
||||
|
||||
assert.equal((await admin.post('/site/admin/users', { id: MEMBER, role: 'user' })).status, 403);
|
||||
const added = await sup.post('/site/admin/users', { id: MEMBER, role: 'user' });
|
||||
assert.equal(added.status, 200);
|
||||
assert.equal(added.json.users.find((u: any) => u.id === MEMBER).name, '지호', '등록할 때도 표시 이름으로');
|
||||
assert.equal((await sup.patch(`/site/admin/users/${MEMBER}`, { role: 'admin' })).json.users.find((u: any) => u.id === MEMBER).role, 'admin');
|
||||
assert.equal((await sup.patch(`/site/admin/users/${SUPER}`, { role: 'user' })).status, 400);
|
||||
assert.equal((await sup.del(`/site/admin/users/${MEMBER}`)).status, 200);
|
||||
assert.equal((await member.get('/site/admin/users')).status, 403);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
@@ -21,7 +21,21 @@ const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ASSET_DIR = path.resolve(here, '../../../docs/report/mock/assets');
|
||||
const ME = { id: '310482915522101248', name: '하늘', avatar: null };
|
||||
|
||||
let m0;
|
||||
/** 표시 이름: 목에서는 유저 목록 이름도 같이 바꾼다 (실제로는 게임 PC 앱이 받아서 바꿈) */
|
||||
function setName(id, n) {
|
||||
const u = db.users.find((x) => x.id === id);
|
||||
if (u) u._orig ??= u.name;
|
||||
if (n) state.names[id] = n;
|
||||
else delete state.names[id];
|
||||
if (u) u.name = n || u._orig;
|
||||
broadcast({ type: 'users.updated', data: db.users });
|
||||
}
|
||||
const state = {
|
||||
names: {},
|
||||
regs: [
|
||||
{ id: ME.id, name: ME.name, avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: Date.now() - 3600000, lastVersion: '1.5.0' },
|
||||
],
|
||||
device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' },
|
||||
live: process.env.MOCK_LIVE !== '0',
|
||||
liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000),
|
||||
@@ -241,7 +255,35 @@ async function handle(req, res) {
|
||||
if (p === '/auth/me') {
|
||||
if (!sess) return json(res, 401, { error: 'unauthorized' });
|
||||
if (sess === 'nm') return json(res, 403, { error: 'not_member' });
|
||||
return json(res, 200, { user: ME, isOwner: true, canViewLogs: true });
|
||||
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, isOwner: true, canViewLogs: true, role: 'superadmin' });
|
||||
}
|
||||
// 내 정보 · 관리 화면 (v1.6.0)
|
||||
if (p === '/site/profile') return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null, role: 'superadmin' });
|
||||
if (p === '/site/profile/name' && req.method === 'PUT') {
|
||||
const b = JSON.parse((await readBody(req)) || '{}');
|
||||
const n = String(b.name ?? '').trim();
|
||||
if (n && Object.entries(state.names).some(([id, x]) => id !== ME.id && x === n)) return json(res, 400, { error: 'bad_name', message: '다른 사람이 이미 쓰는 이름입니다' });
|
||||
setName(ME.id, n);
|
||||
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null });
|
||||
}
|
||||
if (p === '/site/admin/overview') return json(res, 200, { device: { ...deviceStatus(), guildId: '1200000000000000000' }, latest: { version: '1.6.0', url: 'https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0', publishedAt: null }, role: 'superadmin', serverVersion: '1.0.0' });
|
||||
if (p === '/site/admin/users' && req.method === 'GET') return json(res, 200, { users: state.regs, names: state.names });
|
||||
if (p === '/site/admin/names' && req.method === 'PUT') {
|
||||
const b = JSON.parse((await readBody(req)) || '{}');
|
||||
setName(String(b.id), String(b.name ?? '').trim());
|
||||
return json(res, 200, { names: state.names });
|
||||
}
|
||||
if (p === '/site/admin/users' && req.method === 'POST') {
|
||||
const b = JSON.parse((await readBody(req)) || '{}');
|
||||
const u = db.users.find((x) => x.id === b.id);
|
||||
state.regs.push({ id: b.id, name: u?.name ?? b.id, avatar: null, role: b.role, fixed: false, addedBy: ME.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
|
||||
return json(res, 200, { users: state.regs });
|
||||
}
|
||||
if ((m0 = p.match(/^\/site\/admin\/users\/(\d+)$/))) {
|
||||
const b = req.method === 'PATCH' ? JSON.parse((await readBody(req)) || '{}') : {};
|
||||
if (req.method === 'PATCH') state.regs = state.regs.map((r) => (r.id === m0[1] ? { ...r, role: b.role } : r));
|
||||
if (req.method === 'DELETE') state.regs = state.regs.filter((r) => r.id !== m0[1]);
|
||||
return json(res, 200, { users: state.regs });
|
||||
}
|
||||
|
||||
if (p.startsWith('/api/')) {
|
||||
@@ -273,6 +315,16 @@ async function handle(req, res) {
|
||||
return json(res, 200, db.users);
|
||||
}
|
||||
let m;
|
||||
if ((m = p.match(/^\/api\/users\/([^/]+)$/)) && req.method === 'PATCH') {
|
||||
const u = db.users.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
if (!u) return json(res, 404, { error: 'not_found', message: '이 PC 기록에 없는 유저입니다' });
|
||||
const b = JSON.parse((await readBody(req)) || '{}');
|
||||
if (b.color) u.color = b.color;
|
||||
if (b.excluded !== undefined) u.excluded = !!b.excluded;
|
||||
if (b.riotIds) u.riot = b.riotIds.map((r) => ({ puuid: `riotid:${r}`, riotId: r }));
|
||||
broadcast({ type: 'users.updated', data: db.users });
|
||||
return json(res, 200, { user: u, taken: [] });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/users\/([^/]+)$/))) {
|
||||
const prof = userProfile(decodeURIComponent(m[1]));
|
||||
return prof ? json(res, 200, prof) : json(res, 404, { error: 'not_found' });
|
||||
|
||||
@@ -18,6 +18,7 @@ import { CulpritPage } from './pages/CulpritPage';
|
||||
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
|
||||
import { LogsPage } from './pages/LogsPage';
|
||||
import { RecordsPage } from './pages/RecordsPage';
|
||||
import { AdminPage } from './pages/AdminPage';
|
||||
import { installErrorReporting } from './lib/report';
|
||||
import { useLocation } from 'react-router';
|
||||
|
||||
@@ -75,6 +76,7 @@ function Shell() {
|
||||
<Route path="/dictionary" element={<DictionaryPage />} />
|
||||
<Route path="/culprit" element={<CulpritPage />} />
|
||||
<Route path="/culprit/:id" element={<CulpritPage />} />
|
||||
<Route path="/admin" element={<AdminPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,8 @@ import { settings, useSettings, type SfxKind } from '../store/settings';
|
||||
import { sfx, SFX_LABEL } from '../lib/sfx';
|
||||
import { resumeAudio } from '../lib/audio';
|
||||
import { Avatar, Brand } from './common';
|
||||
import { IGear, ILogout, ISearch } from './Icons';
|
||||
import { IGear, ISearch } from './Icons';
|
||||
import { ProfilePopover } from './UserEdit';
|
||||
import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared';
|
||||
|
||||
function SettingsPopover({ onClose }: { onClose: () => void }) {
|
||||
@@ -165,10 +166,11 @@ export function SearchBox() {
|
||||
}
|
||||
|
||||
export function Header() {
|
||||
const { auth, logout } = useAuth();
|
||||
const { overview } = useData();
|
||||
const { auth } = useAuth();
|
||||
const { overview, userById } = useData();
|
||||
const { device, locked, conn } = useStatus();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [profile, setProfile] = useState(false);
|
||||
const me = auth.status === 'ok' ? auth.me.user : null;
|
||||
const rec = overview?.recording;
|
||||
const nav = [
|
||||
@@ -178,6 +180,7 @@ export function Header() {
|
||||
['/users', '유저'],
|
||||
['/dictionary', '단어사전'],
|
||||
['/culprit', '🔍 범인찾기'],
|
||||
...(auth.status === 'ok' && auth.me.canViewLogs ? ([['/admin', '🛡️ 관리']] as const) : []),
|
||||
] as const;
|
||||
return (
|
||||
<header className="topbar">
|
||||
@@ -211,14 +214,13 @@ export function Header() {
|
||||
</button>
|
||||
<AnimatePresence>{open && <SettingsPopover onClose={() => setOpen(false)} />}</AnimatePresence>
|
||||
{me && (
|
||||
<div className="me">
|
||||
<Avatar name={me.name} src={me.avatar} color="#5865f2" size={26} />
|
||||
<button className="me me-btn" onClick={() => setProfile((o) => !o)} aria-expanded={profile} title="내 정보 · 표시 이름 · 색 · 로그아웃">
|
||||
<Avatar name={me.name} src={me.avatar} color={userById(me.id)?.color ?? '#5865f2'} size={26} />
|
||||
<span className="me-nm">{me.name}</span>
|
||||
<button className="icon-btn" onClick={logout} title="로그아웃" aria-label="로그아웃">
|
||||
<ILogout width={16} height={16} />
|
||||
</button>
|
||||
</div>
|
||||
<span className="me-caret">▾</span>
|
||||
</button>
|
||||
)}
|
||||
<AnimatePresence>{profile && <ProfilePopover onClose={() => setProfile(false)} />}</AnimatePresence>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ 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 { reportClient } from '../lib/report';
|
||||
import { Panel, Spinner } from './common';
|
||||
|
||||
// three.js 는 크므로 3D 리플레이를 열 때만 받는다
|
||||
@@ -37,6 +38,8 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
if (!alive) return;
|
||||
setConverting(false);
|
||||
setErr(e);
|
||||
// 변환 실패 이유는 게임 PC 에만 남으므로 사이트 로그에도 남긴다
|
||||
if (e instanceof ApiError && e.status === 422) reportClient('warn', `리플레이 변환 실패 ${m.id}: ${e.detail ?? e.code}`);
|
||||
});
|
||||
void ask(0);
|
||||
return () => {
|
||||
@@ -70,7 +73,7 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
) : appTooOld ? (
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
) : failed ? (
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다 (게임 PC 앱 로그에 이유가 남습니다).</div>
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
|
||||
) : err ? (
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
) : !replay || !sync ? (
|
||||
|
||||
@@ -6,8 +6,10 @@ 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 { equipAt, equipLabel, equipTracks, isDead, roundAt, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
|
||||
import { AgentRig, loadAgent, loadWeapon } from '../lib/agents3d';
|
||||
import { abilityLook, type AbilityLook } from '../lib/abilities';
|
||||
|
||||
/**
|
||||
* 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON).
|
||||
@@ -25,6 +27,18 @@ const ENEMY = 0xff4d5e;
|
||||
const RATES = [0.5, 1, 1.5, 2];
|
||||
/** 자동 천장: 선수(몸 중심) 위로 이만큼(cm) 남기고 자른다 */
|
||||
const CEIL_ABOVE = 380;
|
||||
/** 리플레이 선수 위치(캡슐 중심)에서 눈 · 발까지 (cm) */
|
||||
const EYE_CM = 60;
|
||||
const FOOT_CM = 90;
|
||||
/** 1인칭 · 자유시점에서는 선수 표시(이름표 · 원기둥)를 줄이고 머리 위(이 높이, cm)로 올린다 */
|
||||
const REAL_SCALE = 0.2;
|
||||
const REAL_LABEL_CM = 190;
|
||||
/** 위에서 볼 때 요원 몸을 이만큼 키운다 (맵 전체를 볼 때도 보이게) */
|
||||
const TOP_MODEL_SCALE = 1.8;
|
||||
|
||||
/** 카메라: 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */
|
||||
type CamMode = 'top' | 'fp' | 'free';
|
||||
const CAM_LABEL: Record<CamMode, string> = { top: '위에서', fp: '1인칭', free: '자유시점' };
|
||||
|
||||
type MapState = { state: 'none' | 'loading' | 'ready' | 'error'; progress?: number };
|
||||
/** 천장 자르기: 자동 · 끔 · 직접(가장 낮은 층에서 cm) */
|
||||
@@ -39,6 +53,14 @@ interface Props {
|
||||
}
|
||||
|
||||
function labelSprite(text: string, color: string) {
|
||||
const { tex, aspect } = labelTexture(text, color);
|
||||
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false, transparent: true }));
|
||||
sp.scale.set(aspect * 2.2, 2.2, 1);
|
||||
sp.renderOrder = 10;
|
||||
return sp;
|
||||
}
|
||||
|
||||
function labelTexture(text: string, color: string) {
|
||||
const c = document.createElement('canvas');
|
||||
const ctx = c.getContext('2d')!;
|
||||
const font = '600 44px Pretendard, "Noto Sans KR", sans-serif';
|
||||
@@ -56,10 +78,7 @@ function labelSprite(text: string, color: string) {
|
||||
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;
|
||||
return { tex, aspect: w / 68 };
|
||||
}
|
||||
|
||||
interface PlayerView {
|
||||
@@ -71,11 +90,16 @@ interface PlayerView {
|
||||
body: THREE.Mesh;
|
||||
cone: THREE.Mesh;
|
||||
label: THREE.Sprite;
|
||||
/** 들고 있는 것 (총 이름) */
|
||||
weapon: THREE.Sprite;
|
||||
weaponKind: number;
|
||||
voice: THREE.Sprite;
|
||||
ring: THREE.Mesh;
|
||||
/** 바닥(미니맵)까지 내린 선과 그림자 점: 높이가 있어도 평면 위치가 보이게 */
|
||||
drop: THREE.Line;
|
||||
shadow: THREE.Mesh;
|
||||
/** 요원 3D 몸 (게임 파일에서 뽑은 것, 받기 전 · 없으면 null → 원기둥) */
|
||||
rig: AgentRig | null;
|
||||
}
|
||||
|
||||
export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
@@ -88,6 +112,9 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
const [ui, setUi] = useState({ t: firstCombat, playing: false });
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [follow, setFollow] = useState(false);
|
||||
const [cam, setCam] = useState<CamMode>('top');
|
||||
const camRef = useRef(cam);
|
||||
camRef.current = cam;
|
||||
const selRef = useRef(sel);
|
||||
const followRef = useRef(follow);
|
||||
selRef.current = sel;
|
||||
@@ -115,6 +142,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
}, [replay, zBase]);
|
||||
const T = (m.mapTransform && 'valorant' in m.mapTransform ? m.mapTransform.valorant : null) as T4 | null;
|
||||
|
||||
const equipByPlayer = useMemo(() => equipTracks(replay), [replay]);
|
||||
// 리플레이 선수 ↔ 경기 기록 선수 (puuid)
|
||||
const roster = useMemo(
|
||||
() =>
|
||||
@@ -148,6 +176,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
mount.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(45, 1, 0.5, 2000);
|
||||
renderer.domElement.tabIndex = 0; // 자유시점 키보드
|
||||
const controls = new OrbitControls(camera, renderer.domElement);
|
||||
controls.enableDamping = true;
|
||||
controls.maxPolarAngle = Math.PI * 0.49;
|
||||
@@ -159,8 +188,9 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
controls.update();
|
||||
};
|
||||
resetCam.current();
|
||||
scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.6));
|
||||
const sun = new THREE.DirectionalLight(0xffffff, 1.2);
|
||||
// 게임처럼 밝게: 하늘빛 + 해 (맵 텍스처가 어둡게 묻히지 않게)
|
||||
scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.6));
|
||||
const sun = new THREE.DirectionalLight(0xfff4e0, 1.8);
|
||||
sun.position.set(30, 80, 20);
|
||||
scene.add(sun);
|
||||
|
||||
@@ -200,8 +230,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
.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) => {
|
||||
const fallback = () => mapMaterial(clip, { lo: 0, hi: Math.max(8, (zTop - zBase + 600) * hPerCm) });
|
||||
return loadMap3d(info.url, clip, fallback, (p) => !disposed && setMap3d({ state: 'loading', progress: p })).then((obj) => {
|
||||
if (disposed) return;
|
||||
mapGroup.add(obj);
|
||||
mapGroup.updateMatrixWorld(true);
|
||||
@@ -227,6 +257,10 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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 weapon = new THREE.Sprite(new THREE.SpriteMaterial({ depthTest: false, transparent: true }));
|
||||
weapon.position.y = 2.75;
|
||||
weapon.renderOrder = 10;
|
||||
weapon.visible = false;
|
||||
const voice = labelSprite('🔊 말하는 중', '#ffe08a');
|
||||
voice.position.y = 6.6;
|
||||
voice.visible = false;
|
||||
@@ -234,7 +268,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
ring.rotation.x = -Math.PI / 2;
|
||||
ring.position.y = 0.05;
|
||||
ring.visible = false;
|
||||
group.add(body, cone, label, voice, ring);
|
||||
group.add(body, cone, label, weapon, 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 }));
|
||||
@@ -242,9 +276,46 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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 };
|
||||
return { idx: r.idx, info: r.info, name: r.name, ally: r.ally, group, body, cone, label, weapon, weaponKind: -2, voice, ring, drop, shadow, rig: null };
|
||||
});
|
||||
|
||||
// 요원 3D 몸: UE 좌표(cm) 그대로 두고 맵과 같은 행렬로 옮긴다
|
||||
const agentsGroup = new THREE.Group();
|
||||
agentsGroup.matrixAutoUpdate = false;
|
||||
agentsGroup.matrix.copy(worldMatrix(T, S, zBase, VEX));
|
||||
scene.add(agentsGroup);
|
||||
for (const v of views) {
|
||||
const cls = replay.players[v.idx].character;
|
||||
if (!cls) continue;
|
||||
void loadAgent(cls)
|
||||
.then((g) => {
|
||||
if (!g || disposed) return;
|
||||
v.rig = new AgentRig(g);
|
||||
agentsGroup.add(v.rig.root);
|
||||
agentsGroup.updateMatrixWorld(true);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
let prevT = localT.current;
|
||||
|
||||
// 총 이름표 (같은 글자는 텍스처 하나)
|
||||
const weaponTex = new Map<string, { tex: THREE.Texture; aspect: number }>();
|
||||
const setWeapon = (v: PlayerView, kind: number) => {
|
||||
if (v.weaponKind === kind) return;
|
||||
v.weaponKind = kind;
|
||||
const text = equipLabel(replay.equipKinds?.[kind]);
|
||||
if (!text) {
|
||||
v.weapon.visible = false;
|
||||
return;
|
||||
}
|
||||
let lt = weaponTex.get(text);
|
||||
if (!lt) weaponTex.set(text, (lt = labelTexture(`🔫 ${text}`, '#ffe9b0')));
|
||||
v.weapon.material.map = lt.tex;
|
||||
v.weapon.material.needsUpdate = true;
|
||||
v.weapon.scale.set(lt.aspect * 1.6, 1.6, 1);
|
||||
v.weapon.visible = true;
|
||||
};
|
||||
|
||||
// 선택한 선수 이동 경로 (최근 6초)
|
||||
const trailGeo = new THREE.BufferGeometry();
|
||||
trailGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * 80), 3));
|
||||
@@ -277,23 +348,100 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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;
|
||||
// 스킬 · 설치물: 종류별 모양 · 요원 색 (lib/abilities.ts)
|
||||
type ObjView = { look: AbilityLook; obj: THREE.Object3D; mats: THREE.Material[]; t0: number; end: number };
|
||||
const objViews = new Map<number, ObjView>();
|
||||
const softMat = (color: number, opacity: number, extra: Partial<THREE.MeshLambertMaterialParameters> = {}) =>
|
||||
new THREE.MeshLambertMaterial({ color, emissive: color, emissiveIntensity: 0.35, transparent: true, opacity, depthWrite: false, side: THREE.DoubleSide, ...extra });
|
||||
// 연막 가장자리를 흐리게 (보는 방향과 면이 비스듬할수록 투명)
|
||||
const smokeEdge = (m: THREE.MeshLambertMaterial) => {
|
||||
m.onBeforeCompile = (sh) => {
|
||||
sh.fragmentShader = sh.fragmentShader.replace(
|
||||
'#include <dithering_fragment>',
|
||||
'#include <dithering_fragment>\ngl_FragColor.a *= smoothstep(0.0, 0.55, abs(dot(normalize(vNormal), normalize(vViewPosition))));',
|
||||
);
|
||||
};
|
||||
return m;
|
||||
};
|
||||
const objView = (i: number): ObjView => {
|
||||
let ov = objViews.get(i);
|
||||
if (ov) return ov;
|
||||
const [t0, t1, kind, x, y, z] = replay.objects[i];
|
||||
const look = abilityLook(replay.objectKinds[kind] ?? '');
|
||||
const r = look.radiusCm * hPerCm;
|
||||
const obj = new THREE.Group();
|
||||
const mats: THREE.Material[] = [];
|
||||
const add = (geo: THREE.BufferGeometry, mat: THREE.Material) => {
|
||||
mats.push(mat);
|
||||
obj.add(new THREE.Mesh(geo, mat));
|
||||
};
|
||||
switch (look.shape) {
|
||||
case 'smoke': {
|
||||
// 연막: 바깥 · 안쪽 두 겹 구 (안에 들어가면 그 색으로 가려진다)
|
||||
add(new THREE.SphereGeometry(r, 32, 20), smokeEdge(softMat(look.color, 0.7)));
|
||||
add(new THREE.SphereGeometry(r * 0.82, 24, 16), smokeEdge(softMat(look.color, 0.55, { emissiveIntensity: 0.15 })));
|
||||
break;
|
||||
}
|
||||
case 'fire': {
|
||||
const m = softMat(look.color, 0.6, { emissiveIntensity: 0.8 });
|
||||
const disc = new THREE.Mesh(new THREE.CircleGeometry(r, 40), m);
|
||||
disc.rotation.x = -Math.PI / 2;
|
||||
disc.position.y = 0.03;
|
||||
mats.push(m);
|
||||
obj.add(disc);
|
||||
break;
|
||||
}
|
||||
case 'burst':
|
||||
add(new THREE.SphereGeometry(r, 24, 16), softMat(look.color, 0.6, { emissiveIntensity: 1 }));
|
||||
break;
|
||||
case 'pulse': {
|
||||
const m = softMat(look.color, 0.8, { emissiveIntensity: 1 });
|
||||
const ring = new THREE.Mesh(new THREE.RingGeometry(r * 0.96, r, 64), m);
|
||||
ring.rotation.x = -Math.PI / 2;
|
||||
mats.push(m);
|
||||
obj.add(ring);
|
||||
break;
|
||||
}
|
||||
case 'projectile':
|
||||
add(new THREE.SphereGeometry(Math.max(r, 0.05), 12, 8), new THREE.MeshBasicMaterial({ color: look.color, transparent: true }));
|
||||
break;
|
||||
case 'spike': {
|
||||
const m = new THREE.MeshStandardMaterial({ color: look.color, emissive: look.color, emissiveIntensity: 0.6, transparent: true });
|
||||
add(new THREE.OctahedronGeometry(Math.max(r, 0.2)), m);
|
||||
// 스파이크 3D 가 있으면 그것으로 (UE 좌표 그대로 → 요원과 같은 묶음에)
|
||||
void loadWeapon('Spike')
|
||||
.then((g) => {
|
||||
if (!g || disposed) return;
|
||||
const sp = g.scene.clone(true);
|
||||
sp.position.set(x, y, z);
|
||||
sp.userData.objIndex = i;
|
||||
agentsGroup.add(sp);
|
||||
agentsGroup.updateMatrixWorld(true);
|
||||
const cur = objViews.get(i);
|
||||
if (cur) {
|
||||
cur.obj.children.forEach((c) => (c.visible = false)); // 대신 그린 다이아몬드는 숨김
|
||||
cur.obj.userData.model = sp;
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const m = new THREE.MeshStandardMaterial({ color: look.color, emissive: look.color, emissiveIntensity: 0.5, transparent: true });
|
||||
add(new THREE.OctahedronGeometry(Math.max(r, 0.12)), m);
|
||||
}
|
||||
}
|
||||
obj.position.copy(toWorld(x, y, z, zBase));
|
||||
scene.add(obj);
|
||||
ov = { look, obj, mats, t0, end: t1 >= t0 ? t1 : t0 + look.defaultMs };
|
||||
objViews.set(i, ov);
|
||||
return ov;
|
||||
};
|
||||
const setOpacity = (ov: ObjView, k: number) => {
|
||||
for (const m of ov.mats) {
|
||||
const base = (m.userData.baseOpacity ??= m.opacity) as number;
|
||||
m.opacity = base * k;
|
||||
}
|
||||
};
|
||||
|
||||
// 크기
|
||||
@@ -311,31 +459,91 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
// 선수 눌러서 고르기
|
||||
const ray = new THREE.Raycaster();
|
||||
const down = { x: 0, y: 0 };
|
||||
// 자유시점: 끌어서 둘러보기, WASD 이동 · Q/E 아래/위 · Shift 빠르게
|
||||
const free = { yaw: 0, pitch: -0.6, drag: false, lx: 0, ly: 0, keys: new Set<string>() };
|
||||
const onDown = (e: PointerEvent) => {
|
||||
down.x = e.clientX;
|
||||
down.y = e.clientY;
|
||||
if (camRef.current === 'free') {
|
||||
free.drag = true;
|
||||
free.lx = e.clientX;
|
||||
free.ly = e.clientY;
|
||||
renderer.domElement.setPointerCapture(e.pointerId);
|
||||
}
|
||||
renderer.domElement.focus({ preventScroll: true });
|
||||
};
|
||||
const onMove = (e: PointerEvent) => {
|
||||
if (!free.drag || camRef.current !== 'free') return;
|
||||
free.yaw -= (e.clientX - free.lx) * 0.004;
|
||||
free.pitch = Math.max(-1.55, Math.min(1.55, free.pitch - (e.clientY - free.ly) * 0.004));
|
||||
free.lx = e.clientX;
|
||||
free.ly = e.clientY;
|
||||
};
|
||||
const MOVE_KEYS = new Set(['KeyW', 'KeyA', 'KeyS', 'KeyD', 'KeyQ', 'KeyE', 'ShiftLeft', 'ShiftRight', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (camRef.current !== 'free' || !MOVE_KEYS.has(e.code)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (e.type === 'keydown') free.keys.add(e.code);
|
||||
else free.keys.delete(e.code);
|
||||
};
|
||||
const onBlur = () => free.keys.clear();
|
||||
const onUp = (e: PointerEvent) => {
|
||||
free.drag = false;
|
||||
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);
|
||||
// 1인칭에서는 빈 곳을 눌러도 보던 선수를 놓지 않는다
|
||||
if (hit) setSel(hit.object.userData.idx as number);
|
||||
else if (camRef.current !== 'fp') setSel(null);
|
||||
};
|
||||
renderer.domElement.addEventListener('pointerdown', onDown);
|
||||
renderer.domElement.addEventListener('pointerup', onUp);
|
||||
renderer.domElement.addEventListener('pointermove', onMove);
|
||||
renderer.domElement.addEventListener('keydown', onKey);
|
||||
renderer.domElement.addEventListener('keyup', onKey);
|
||||
renderer.domElement.addEventListener('blur', onBlur);
|
||||
|
||||
// 개발 확인용 (목 서버 스크린샷 스크립트가 카메라를 옮긴다)
|
||||
if (import.meta.env.DEV) (window as unknown as { __r3d: unknown }).__r3d = { camera, controls, views, scene, free, toWorld: (x: number, y: number, z: number) => toWorld(x, y, z, zBase) };
|
||||
let raf = 0;
|
||||
let lastUi = 0;
|
||||
let lastNow = 0;
|
||||
let lastMode: CamMode = 'top';
|
||||
const tmp = new THREE.Vector3();
|
||||
const euler = new THREE.Euler(0, 0, 0, 'YXZ');
|
||||
const frame = (now: number) => {
|
||||
raf = requestAnimationFrame(frame);
|
||||
const dt = lastNow ? Math.min(0.1, (now - lastNow) / 1000) : 0;
|
||||
lastNow = now;
|
||||
const mode = camRef.current;
|
||||
if (mode !== lastMode) {
|
||||
controls.enabled = mode === 'top';
|
||||
camera.near = mode === 'top' ? 0.5 : 0.01;
|
||||
camera.far = mode === 'top' ? 2000 : 600;
|
||||
camera.fov = mode === 'fp' ? 70 : 45;
|
||||
camera.updateProjectionMatrix();
|
||||
if (mode === 'top') resetCam.current();
|
||||
if (mode === 'free') {
|
||||
// 지금 보던 방향에서 시작
|
||||
euler.setFromQuaternion(camera.quaternion);
|
||||
free.yaw = euler.y;
|
||||
free.pitch = euler.x;
|
||||
}
|
||||
free.keys.clear();
|
||||
lastMode = mode;
|
||||
}
|
||||
const real = mode !== 'top';
|
||||
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;
|
||||
// 리플레이 시간 흐름 (애니메이션용, 시간을 크게 옮기면 0)
|
||||
const dtR = t - prevT >= 0 && t - prevT < 1000 ? (t - prevT) / 1000 : 0;
|
||||
prevT = t;
|
||||
// 지금 말하는 사람
|
||||
const speaking = new Set<number>();
|
||||
for (const u of m.utterances) if (u.ts <= ts && ts <= u.endTs && !u.noise) {
|
||||
@@ -350,9 +558,11 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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));
|
||||
// 1인칭으로 보는 선수 자신은 숨긴다
|
||||
v.group.visible = !(mode === 'fp' && v.idx === selRef.current);
|
||||
v.drop.visible = v.shadow.visible = !mapReady && !real;
|
||||
v.group.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400) + (real ? REAL_LABEL_CM - FOOT_CM : 0), zBase));
|
||||
v.group.scale.setScalar(real ? REAL_SCALE : 1);
|
||||
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);
|
||||
@@ -367,13 +577,38 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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;
|
||||
const kind = dead ? -1 : equipAt(equipByPlayer[v.idx], t);
|
||||
setWeapon(v, kind);
|
||||
v.weapon.material.opacity = v.label.material.opacity;
|
||||
if (v.rig) {
|
||||
// 몸이 있으면 원기둥 대신. 죽으면 몸을 숨긴다 (죽은 자리는 X 표시)
|
||||
v.body.visible = v.cone.visible = false;
|
||||
const rr = v.rig.root;
|
||||
rr.visible = v.group.visible && !dead;
|
||||
rr.position.set(p.x, p.y, Math.max(p.z, zBase - 400) - FOOT_CM);
|
||||
rr.rotation.set(0, 0, (p.yaw * Math.PI) / 180);
|
||||
rr.scale.setScalar(real ? 1 : TOP_MODEL_SCALE);
|
||||
if (rr.visible) {
|
||||
const q = samplePlayer(tr, t - 150, replay.sampleMs * 6);
|
||||
const vx = q ? ((p.x - q.x) * 1000) / 150 : 0;
|
||||
const vy = q ? ((p.y - q.y) * 1000) / 150 : 0;
|
||||
const a = (p.yaw * Math.PI) / 180;
|
||||
const ek = replay.equipKinds?.[kind];
|
||||
v.rig.setWeapon(ek && !/^Ability_|Unarmed|Bomb_Defuser/.test(ek) ? ek : null);
|
||||
v.rig.update(dtR, vx * Math.cos(a) + vy * Math.sin(a), -vx * Math.sin(a) + vy * Math.cos(a), p.pitch);
|
||||
}
|
||||
} else {
|
||||
v.body.visible = true;
|
||||
v.cone.visible = true;
|
||||
}
|
||||
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') {
|
||||
if (mode === 'fp') want = 1e6;
|
||||
else if (mapReady && cm.mode === 'manual') want = cm.cm * hPerCm;
|
||||
else if (mapReady && cm.mode === 'auto' && mode === 'top') {
|
||||
const sv = selIdx != null ? views[selIdx] : null;
|
||||
let top = -Infinity;
|
||||
if (sv?.group.visible) top = sv.group.position.y;
|
||||
@@ -396,7 +631,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
trailGeo.setDrawRange(0, n);
|
||||
pos.needsUpdate = true;
|
||||
trail.visible = n > 1;
|
||||
if (followRef.current && views[selIdx].group.visible) {
|
||||
if (mode === 'top' && 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));
|
||||
@@ -426,21 +661,77 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
if (on) {
|
||||
const age = t - k.t;
|
||||
const s = age < 600 ? 1 + (600 - age) / 300 : 1;
|
||||
k.mk.scale.setScalar(s);
|
||||
k.mk.scale.setScalar(s * (real ? 0.25 : 1));
|
||||
}
|
||||
}
|
||||
// 스킬 · 설치물: 생긴 뒤 사라질 때까지 (사라진 시각을 모르면 12초)
|
||||
// 스킬 · 설치물: 생긴 뒤 사라질 때까지 (모르면 종류별 기본 시간). 날아가는 것은 던진 자리에 잠깐만
|
||||
for (let i = 0; i < replay.objects.length; i++) {
|
||||
const [t0, t1] = replay.objects[i];
|
||||
const end = t1 >= 0 ? t1 : t0 + 12000;
|
||||
const [t0, t1, kind] = replay.objects[i];
|
||||
const ov0 = objViews.get(i);
|
||||
const end = ov0 ? ov0.end : t1 >= t0 ? t1 : t0 + abilityLook(replay.objectKinds[kind] ?? '').defaultMs;
|
||||
const on = t >= t0 && t <= end;
|
||||
if (on) objMesh(i).visible = true;
|
||||
else {
|
||||
const mesh = objMeshes.get(i);
|
||||
if (mesh) mesh.visible = false;
|
||||
if (!on) {
|
||||
if (ov0) {
|
||||
ov0.obj.visible = false;
|
||||
if (ov0.obj.userData.model) (ov0.obj.userData.model as THREE.Object3D).visible = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const ov = objView(i);
|
||||
const age = t - t0;
|
||||
const left = ov.end - t;
|
||||
ov.obj.visible = true;
|
||||
const model = ov.obj.userData.model as THREE.Object3D | undefined;
|
||||
if (model) model.visible = true;
|
||||
const big = mode === 'top' ? 3 : 1; // 위에서 볼 때 작은 것은 키운다
|
||||
switch (ov.look.shape) {
|
||||
case 'smoke':
|
||||
ov.obj.scale.setScalar(Math.min(1, 0.25 + age / 800));
|
||||
setOpacity(ov, Math.min(1, left / 1000));
|
||||
break;
|
||||
case 'fire':
|
||||
ov.obj.scale.setScalar(Math.min(1, 0.3 + age / 500));
|
||||
setOpacity(ov, Math.min(1, left / 600) * (0.8 + 0.2 * Math.sin(now / 120)));
|
||||
break;
|
||||
case 'burst': {
|
||||
const k = Math.min(1, age / Math.max(300, ov.end - ov.t0));
|
||||
ov.obj.scale.setScalar(0.2 + 0.8 * Math.sqrt(k));
|
||||
setOpacity(ov, 1 - k);
|
||||
break;
|
||||
}
|
||||
case 'pulse': {
|
||||
const k = (age % 1500) / 1500;
|
||||
ov.obj.scale.setScalar(0.05 + 0.95 * k);
|
||||
setOpacity(ov, (1 - k) * Math.min(1, left / 500));
|
||||
break;
|
||||
}
|
||||
case 'projectile':
|
||||
ov.obj.visible = age < 400;
|
||||
ov.obj.scale.setScalar(big);
|
||||
break;
|
||||
default:
|
||||
ov.obj.scale.setScalar(big);
|
||||
ov.obj.rotation.y = now / 900;
|
||||
}
|
||||
}
|
||||
controls.update();
|
||||
if (mode === 'fp' && selIdx != null) {
|
||||
// 고른 선수 눈 위치에서 보는 방향 (yaw · pitch) 으로
|
||||
const p = samplePlayer(replay.players[selIdx].track, t, replay.sampleMs * 6);
|
||||
if (p) {
|
||||
const eye = toWorld(p.x, p.y, p.z + EYE_CM, zBase);
|
||||
const d = dirOf(p.yaw);
|
||||
const pr = (Math.max(-89, Math.min(89, p.pitch)) * Math.PI) / 180;
|
||||
camera.position.copy(eye);
|
||||
camera.lookAt(eye.x + d.x * Math.cos(pr), eye.y + Math.sin(pr), eye.z + d.z * Math.cos(pr));
|
||||
}
|
||||
} else if (mode === 'free') {
|
||||
euler.set(free.pitch, free.yaw, 0, 'YXZ');
|
||||
camera.quaternion.setFromEuler(euler);
|
||||
const k = free.keys;
|
||||
const speed = (k.has('ShiftLeft') || k.has('ShiftRight') ? 40 : 12) * dt;
|
||||
tmp.set((k.has('KeyD') || k.has('ArrowRight') ? 1 : 0) - (k.has('KeyA') || k.has('ArrowLeft') ? 1 : 0), (k.has('KeyE') ? 1 : 0) - (k.has('KeyQ') ? 1 : 0), (k.has('KeyS') || k.has('ArrowDown') ? 1 : 0) - (k.has('KeyW') || k.has('ArrowUp') ? 1 : 0));
|
||||
if (tmp.lengthSq() > 0) camera.position.add(tmp.normalize().multiplyScalar(speed).applyQuaternion(camera.quaternion));
|
||||
} else controls.update();
|
||||
renderer.render(scene, camera);
|
||||
if (now - lastUi > 100) {
|
||||
lastUi = now;
|
||||
@@ -458,7 +749,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
ro.disconnect();
|
||||
renderer.domElement.removeEventListener('pointerdown', onDown);
|
||||
renderer.domElement.removeEventListener('pointerup', onUp);
|
||||
renderer.domElement.removeEventListener('pointermove', onMove);
|
||||
renderer.domElement.removeEventListener('keydown', onKey);
|
||||
renderer.domElement.removeEventListener('keyup', onKey);
|
||||
renderer.domElement.removeEventListener('blur', onBlur);
|
||||
controls.dispose();
|
||||
for (const v of views) v.rig?.dispose();
|
||||
scene.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
mesh.geometry?.dispose?.();
|
||||
@@ -472,7 +768,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
renderer.domElement.remove();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [m, replay, base, roster, playerByUser, zBase, zTop]);
|
||||
}, [m, replay, base, roster, playerByUser, zBase, zTop, equipByPlayer]);
|
||||
|
||||
const inScene = () => player.state.mode === 'scene' && player.state.scene?.label === REPLAY_SCENE_LABEL;
|
||||
const seek = (t: number) => {
|
||||
@@ -497,6 +793,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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 selEquip = sel != null ? equipLabel(replay.equipKinds?.[equipAt(equipByPlayer[sel], ui.t)]) : 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;
|
||||
@@ -504,6 +801,15 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
if (to) seek(to.combat >= 0 ? to.combat - 3000 : to.buy);
|
||||
};
|
||||
|
||||
const chooseCam = (c: CamMode) => {
|
||||
// 1인칭은 고른 선수가 있어야 한다: 없으면 지금 살아 있는 첫 아군
|
||||
if (c === 'fp' && sel == null) {
|
||||
const alive = roster.find((r) => r.ally && samplePlayer(replay.players[r.idx].track, ui.t, replay.sampleMs * 6) && !isDead(replay, r.idx, ui.t)) ?? roster[0];
|
||||
if (alive) setSel(alive.idx);
|
||||
}
|
||||
setCam(c);
|
||||
};
|
||||
|
||||
if (!T) return <div className="map-missing">이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다</div>;
|
||||
return (
|
||||
<div className="r3d">
|
||||
@@ -517,7 +823,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
<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>
|
||||
<span className={roster[ki]?.ally ? 'a' : 'e'}>{roster[ki]?.name ?? '?'}</span>
|
||||
{(() => {
|
||||
const w = ki >= 0 ? equipLabel(replay.equipKinds?.[equipAt(equipByPlayer[ki], kt)]) : null;
|
||||
return w ? <span className="muted"> [{w}]</span> : null;
|
||||
})()}{' '}
|
||||
✕ <span className={roster[vi]?.ally ? 'a' : 'e'}>{roster[vi]?.name ?? '?'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -530,14 +841,29 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{selInfo && (
|
||||
{cam === 'fp' && <div className="r3d-cross" />}
|
||||
{cam === 'free' && <div className="r3d-hud bl muted small">끌기: 둘러보기 · W A S D: 이동 · Q / E: 아래 / 위 · Shift: 빠르게 (화면을 한 번 누른 뒤)</div>}
|
||||
{selInfo && cam !== 'free' && (
|
||||
<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>}
|
||||
{selEquip && <div>🔫 {selEquip}</div>}
|
||||
{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>
|
||||
{cam === 'top' && (
|
||||
<label className="r3d-follow">
|
||||
<input type="checkbox" checked={follow} onChange={(e) => setFollow(e.target.checked)} /> 따라가기
|
||||
</label>
|
||||
)}
|
||||
{cam === 'fp' && (
|
||||
<select className="r3d-pick" value={sel ?? ''} onChange={(e) => setSel(Number(e.target.value))} aria-label="1인칭으로 볼 선수">
|
||||
{roster.map((r) => (
|
||||
<option key={r.idx} value={r.idx}>
|
||||
{r.ally ? '아군' : '상대'} · {r.name}
|
||||
{r.info?.character?.name ? ` (${r.info.character.name})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -575,10 +901,21 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<button className="chip" onClick={() => resetCam.current()} title="카메라 처음 위치로">전체 보기</button>
|
||||
<span className="r3d-cams" role="group" aria-label="카메라">
|
||||
{(['top', 'fp', 'free'] as CamMode[]).map((c) => (
|
||||
<button key={c} className={`chip${cam === c ? ' on' : ''}`} onClick={() => chooseCam(c)} aria-pressed={cam === c}>
|
||||
{CAM_LABEL[c]}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
{cam === 'top' && (
|
||||
<button className="chip" onClick={() => resetCam.current()} title="카메라 처음 위치로">
|
||||
전체 보기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="r3d-foot muted">
|
||||
마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택 ·{' '}
|
||||
{cam === 'top' ? '마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택' : cam === 'fp' ? '1인칭: 고른 선수 눈높이 · 다른 선수를 누르면 그 선수로' : '자유시점: 끌어서 둘러보기 · WASD 이동'} ·{' '}
|
||||
{sync.matched >= 3
|
||||
? `대화 동기화: 킬 ${sync.matched}개로 맞춤 (최대 오차 ${((sync.spreadMs ?? 0) / 1000).toFixed(2)}초)`
|
||||
: '대화 동기화: 라운드 시작으로 대략 맞춤'}
|
||||
|
||||
234
site/web/src/components/UserEdit.tsx
Normal file
234
site/web/src/components/UserEdit.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
// 유저 설정 고치기 (v1.6.0): 머리글 "내 정보" 와 관리 화면이 같이 쓴다
|
||||
// - 표시 이름: 사이트 서버에 저장 (디스코드 이름 대신 보일 이름, 게임 PC 앱에 바로 전달)
|
||||
// - 색 · 녹음 제외 · 라이엇 ID: 게임 PC 앱 기록에 저장 (앱 v1.6.0~)
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { motion } from 'framer-motion';
|
||||
import type { User } from '@gvr/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { useAuth, useData } from '../store/app';
|
||||
import { Avatar } from './common';
|
||||
import { ILogout } from './Icons';
|
||||
|
||||
/** 타임라인에서 잘 보이는 색들 (어두운 배경) */
|
||||
export const USER_COLORS = ['#ff4655', '#ff8a3d', '#f2b23a', '#c8e04a', '#45d39a', '#14c1b7', '#3db8ff', '#5b8cff', '#9a7bff', '#d46bff', '#ff6fb1', '#c9d1dc'];
|
||||
|
||||
/** 오류를 사람이 읽을 말로 */
|
||||
export function errText(e: unknown): string {
|
||||
if (e instanceof ApiError) {
|
||||
if (e.status === 404 && e.code === 'Not Found') return '게임 PC 앱이 아직 이 기능을 모릅니다. 앱을 v1.6.0 이상으로 업데이트해 주세요';
|
||||
if (e.status === 503 && e.code === 'device_offline') return '게임 PC 가 꺼져 있어 저장하지 못했습니다';
|
||||
if (e.status === 504) return '게임 PC 가 답하지 않습니다. 잠시 뒤 다시 해 주세요';
|
||||
if (e.detail) return e.detail;
|
||||
if (e.status === 0) return '서버에 연결하지 못했습니다';
|
||||
return `저장하지 못했습니다 (${e.status} ${e.code})`;
|
||||
}
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** 표시 이름 입력: 저장 · 디스코드 이름으로 되돌리기 */
|
||||
export function NameEditor({ value, custom, onSave, placeholder }: { value: string; custom: boolean; onSave: (name: string) => Promise<void>; placeholder?: string }) {
|
||||
const [v, setV] = useState(value);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
useEffect(() => setV(value), [value]);
|
||||
const save = async (name: string) => {
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
await onSave(name);
|
||||
setMsg({ ok: true, text: name ? '저장했습니다' : '디스코드 이름으로 되돌렸습니다' });
|
||||
sfx('click');
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errText(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="ue-block">
|
||||
<form
|
||||
className="ue-row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (v.trim() && v.trim() !== value) void save(v.trim());
|
||||
}}
|
||||
>
|
||||
<input className="ue-input" value={v} maxLength={32} placeholder={placeholder ?? '표시 이름'} onChange={(e) => setV(e.target.value)} aria-label="표시 이름" />
|
||||
<button className="btn sm primary" disabled={busy || !v.trim() || v.trim() === value}>
|
||||
저장
|
||||
</button>
|
||||
{custom && (
|
||||
<button type="button" className="btn sm" disabled={busy} onClick={() => void save('')} title="표시 이름을 지우고 디스코드 서버 별명으로 보이게">
|
||||
되돌리기
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱에 저장) */
|
||||
export function AppUserEditor({ user, self }: { user: User; self: boolean }) {
|
||||
const { reloadUsers } = useData();
|
||||
const [riot, setRiot] = useState(user.riot.map((r) => r.riotId).join(', '));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const riotNow = user.riot.map((r) => r.riotId).join(', ');
|
||||
useEffect(() => setRiot(riotNow), [riotNow]);
|
||||
const colorRef = useRef<HTMLInputElement>(null);
|
||||
const patch = async (p: { color?: string; excluded?: boolean; riotIds?: string[] }, okText: string) => {
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
const r = await api.updateUser(user.id, p);
|
||||
reloadUsers();
|
||||
setMsg(r.taken.length ? { ok: false, text: `다른 사람에게 연결된 라이엇 ID 는 빼고 저장했습니다: ${r.taken.join(', ')}` } : { ok: true, text: okText });
|
||||
sfx('click');
|
||||
} catch (e) {
|
||||
setMsg({ ok: false, text: errText(e) });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const riotIds = riot
|
||||
.split(/[,\n]/)
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean);
|
||||
const riotBad = riotIds.filter((r) => !/^[^#]{1,32}#[^#]{1,8}$/.test(r));
|
||||
return (
|
||||
<div className="ue-block">
|
||||
<div className="ue-label">색</div>
|
||||
<div className="ue-colors" role="radiogroup" aria-label="유저 색">
|
||||
{USER_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
className={`ue-sw${user.color.toLowerCase() === c ? ' on' : ''}`}
|
||||
style={{ background: c }}
|
||||
role="radio"
|
||||
aria-checked={user.color.toLowerCase() === c}
|
||||
aria-label={c}
|
||||
disabled={busy}
|
||||
onClick={() => void patch({ color: c }, '색을 바꿨습니다')}
|
||||
/>
|
||||
))}
|
||||
<button className="ue-sw custom" title="다른 색 고르기" aria-label="다른 색 고르기" disabled={busy} onClick={() => colorRef.current?.click()}>
|
||||
+
|
||||
</button>
|
||||
<input ref={colorRef} type="color" className="ue-hidden" defaultValue={user.color} onChange={(e) => void patch({ color: e.target.value }, '색을 바꿨습니다')} />
|
||||
</div>
|
||||
|
||||
<div className="ue-label">라이엇 ID</div>
|
||||
<form
|
||||
className="ue-row"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!riotBad.length) void patch({ riotIds }, '라이엇 ID 를 저장했습니다');
|
||||
}}
|
||||
>
|
||||
<input className="ue-input" value={riot} placeholder="이름#태그 (여러 개는 쉼표로)" onChange={(e) => setRiot(e.target.value)} aria-label="라이엇 ID" />
|
||||
<button className="btn sm" disabled={busy || riot.trim() === riotNow || riotBad.length > 0 || riotIds.length > 5}>
|
||||
저장
|
||||
</button>
|
||||
</form>
|
||||
{riotBad.length > 0 && <div className="ue-msg bad">이름#태그 형식이 아닙니다: {riotBad.join(', ')}</div>}
|
||||
<div className="ue-hint">경기 기록의 선수와 연결됩니다. 새로 넣은 ID 는 다음 경기에서 확인됩니다.</div>
|
||||
|
||||
<label className="ue-check">
|
||||
<input type="checkbox" checked={user.excluded} disabled={busy} onChange={(e) => void patch({ excluded: e.target.checked }, e.target.checked ? '앞으로 녹음하지 않습니다' : '다시 녹음합니다')} />
|
||||
<span>
|
||||
<b>녹음 제외</b>
|
||||
<span className="ue-hint">{self ? '켜면 앞으로 내 목소리를 녹음하지 않습니다 (이미 녹음된 기록은 그대로).' : '켜면 앞으로 이 사람 목소리를 녹음하지 않습니다.'}</span>
|
||||
</span>
|
||||
</label>
|
||||
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 머리글 오른쪽 위 내 이름을 누르면 나오는 "내 정보" */
|
||||
export function ProfilePopover({ onClose }: { onClose: () => void }) {
|
||||
const { auth, logout, refreshMe } = useAuth();
|
||||
const { userById } = useData();
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [custom, setCustom] = useState<boolean | null>(null);
|
||||
useEffect(() => {
|
||||
const down = (e: PointerEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.me-btn')) onClose();
|
||||
};
|
||||
const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
|
||||
document.addEventListener('pointerdown', down);
|
||||
document.addEventListener('keydown', key);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', down);
|
||||
document.removeEventListener('keydown', key);
|
||||
};
|
||||
}, [onClose]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
fetch('/site/profile', { credentials: 'include' })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((p) => alive && p && setCustom(!!p.customName))
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, []);
|
||||
if (auth.status !== 'ok') return null;
|
||||
const me = auth.me.user;
|
||||
const u = userById(me.id);
|
||||
const admin = auth.me.canViewLogs;
|
||||
const roleLabel = auth.me.role === 'superadmin' ? '최고 관리자' : auth.me.role === 'admin' ? '관리자' : auth.me.role === 'user' ? '앱 유저' : admin ? '관리자' : '서버 멤버';
|
||||
return (
|
||||
<motion.div
|
||||
ref={ref}
|
||||
className="popover profile-pop"
|
||||
initial={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -6, scale: 0.98 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
role="dialog"
|
||||
aria-label="내 정보"
|
||||
>
|
||||
<div className="pp-head">
|
||||
<Avatar name={me.name} src={me.avatar} color={u?.color ?? '#5865f2'} size={40} />
|
||||
<div>
|
||||
<b style={u ? { color: u.color } : undefined}>{me.name}</b>
|
||||
<div className="dim small">
|
||||
{roleLabel} · <span className="mono">{me.id}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<h5>표시 이름</h5>
|
||||
<NameEditor
|
||||
value={me.name}
|
||||
custom={!!custom}
|
||||
onSave={async (name) => {
|
||||
const r = await api.setMyName(name);
|
||||
setCustom(!!r.customName);
|
||||
await refreshMe();
|
||||
}}
|
||||
/>
|
||||
<div className="ue-hint">사이트 · 게임 PC 기록 · 범인 분석에서 디스코드 이름 대신 보입니다.</div>
|
||||
<h5>녹음 기록 설정</h5>
|
||||
{u ? <AppUserEditor user={u} self /> : <div className="ue-hint">아직 녹음된 적이 없습니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>}
|
||||
<div className="pp-links">
|
||||
{u && (
|
||||
<Link to={`/users/${me.id}`} className="mini-btn" onClick={onClose}>
|
||||
내 기록 보기
|
||||
</Link>
|
||||
)}
|
||||
{admin && (
|
||||
<Link to="/admin" className="mini-btn" onClick={onClose}>
|
||||
🛡️ 관리 페이지
|
||||
</Link>
|
||||
)}
|
||||
<button className="mini-btn" onClick={logout}>
|
||||
<ILogout width={13} height={13} /> 로그아웃
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
75
site/web/src/lib/abilities.ts
Normal file
75
site/web/src/lib/abilities.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 리플레이 스킬 · 설치물 (변환기 objectKinds: GameObject_Sarge_4_Smoke_… 같은 게임 클래스 이름) → 3D 모양 · 색.
|
||||
* 게임의 효과(파티클)는 그대로 옮길 수 없어서 종류별로 비슷한 모양을 그린다:
|
||||
* smoke 연막(요원 색 구), fire 장판(바닥 원), burst 폭발 · 섬광(커지며 사라지는 구), pulse 정찰 · 소리(퍼지는 고리),
|
||||
* projectile 날아가는 것(작은 빛 구), device 설치물 · 함정 · 드론(작은 다이아몬드), spike 스파이크(총 모델 대신 스파이크 3D)
|
||||
*/
|
||||
export type AbilityShape = 'smoke' | 'fire' | 'burst' | 'pulse' | 'projectile' | 'device' | 'spike';
|
||||
|
||||
export interface AbilityLook {
|
||||
shape: AbilityShape;
|
||||
/** 0xRRGGBB */
|
||||
color: number;
|
||||
/** 게임 단위(cm) 반지름 */
|
||||
radiusCm: number;
|
||||
/** 사라진 시각을 모를 때 보여 줄 시간 (ms) */
|
||||
defaultMs: number;
|
||||
/** 요원 코드 (Sarge 등), 모르면 null */
|
||||
agent: string | null;
|
||||
}
|
||||
|
||||
/** 요원 코드(게임 내부 이름) → 대표 색. 연막 · 장판은 게임에서 보이는 색에 가깝게 */
|
||||
const AGENT_COLOR: Record<string, number> = {
|
||||
Sarge: 0xd9a066, // 브림스톤: 주황빛 연막
|
||||
Wraith: 0x5a3f8f, // 오멘: 짙은 보라
|
||||
Rift: 0x9a5fd6, // 아스트라: 보라
|
||||
Smonk: 0xe48ac6, // 클로브: 분홍
|
||||
Wushu: 0xe9f2ff, // 제트: 흰 바람
|
||||
Mage: 0x2fa9c9, // 하버: 물
|
||||
Pandemic: 0x41c25a, // 바이퍼: 초록 독
|
||||
Phoenix: 0xff7a2f, // 피닉스: 불
|
||||
Hunter: 0x4fb3ff, // 소바: 정찰
|
||||
Deadeye: 0xd9b25a, // 체임버: 금색
|
||||
Killjoy: 0xffd23f, // 킬조이: 노랑
|
||||
Gumshoe: 0xd7dde6, // 사이퍼: 흰 철사
|
||||
Thorne: 0x4fe0c9, // 세이지: 청록
|
||||
Clay: 0xff8a3d, // 레이즈
|
||||
Breach: 0xff9a3d, // 브리치
|
||||
Vampire: 0xc23fd6, // 레이나
|
||||
Stealth: 0x4f6fff, // 요루: 파랑
|
||||
Guide: 0x7ad65a, // 스카이
|
||||
BountyHunter: 0x6b3f8f, // 페이드
|
||||
Grenadier: 0x7fd6ff, // 케이오
|
||||
AggroBot: 0xb6f04a, // 게코
|
||||
Sprinter: 0x3fd0ff, // 네온
|
||||
Cable: 0x9fe8ff, // 데드록
|
||||
Sequoia: 0xb07cff, // 아이소
|
||||
Nox: 0x7d8cff, // 바이스
|
||||
Cashew: 0xffb347, // 테호
|
||||
Terra: 0xff6fa8, // 웨이레이
|
||||
Pine: 0x9ad4ff,
|
||||
Iris: 0xffc0f0,
|
||||
};
|
||||
const DEFAULT_COLOR = 0x9fffe0;
|
||||
|
||||
/** 클래스 이름에서 요원 코드: GameObject_<요원>_… / Projectile_<요원>_… / Ability_Q_<요원>_… */
|
||||
export function abilityAgent(kind: string): string | null {
|
||||
const parts = kind.split('_');
|
||||
for (const p of parts.slice(1, 4)) if (AGENT_COLOR[p] != null) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function abilityLook(kind: string): AbilityLook {
|
||||
const agent = abilityAgent(kind);
|
||||
const color = agent ? AGENT_COLOR[agent] : DEFAULT_COLOR;
|
||||
const k = kind.toLowerCase();
|
||||
const base = { color, agent };
|
||||
if (kind === 'TimedBomb_C') return { ...base, shape: 'spike', color: 0xff2d3d, radiusCm: 40, defaultMs: 45000 };
|
||||
if (/^projectile_/.test(k)) return { ...base, shape: 'projectile', radiusCm: /flash/.test(k) ? 25 : 18, defaultMs: 3000 };
|
||||
// 연막: 관리자 · 생성기는 실제 연막이 아니다
|
||||
if (/smoke|cloud|nebula|dome/.test(k) && !/manager|spawner|projectile/.test(k)) return { ...base, shape: 'smoke', radiusCm: 450, defaultMs: 15000 };
|
||||
if (/^patch_|molotov|fire|acid|slow|snakebite|nanoswarm|paint/.test(k)) return { ...base, shape: 'fire', radiusCm: /slow/.test(k) ? 550 : 450, defaultMs: 7000 };
|
||||
if (/explosion|explode|blast|flash|stun|concuss|beam|strike|decay/.test(k)) return { ...base, shape: 'burst', radiusCm: /strike|beam/.test(k) ? 700 : 400, defaultMs: 1200 };
|
||||
if (/sonar|ping|reveal|recon|scan|pulse|alarm/.test(k)) return { ...base, shape: 'pulse', radiusCm: 1500, defaultMs: 2500 };
|
||||
return { ...base, shape: 'device', radiusCm: 30, defaultMs: 12000 };
|
||||
}
|
||||
147
site/web/src/lib/agents3d.ts
Normal file
147
site/web/src/lib/agents3d.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import * as THREE from 'three';
|
||||
import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js';
|
||||
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
|
||||
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
|
||||
import { loadIndex } from './map3d';
|
||||
|
||||
/**
|
||||
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
|
||||
* 좌표는 게임(UE) 그대로: cm, 발 = 원점 근처, 앞 = +X (애니메이션의 Root 회전 포함).
|
||||
* 몸 애니메이션은 위(ub_rifle, 총 든 자세)와 아래(lb_idle · lb_run* · lb_walk*)를 따로 섞는다.
|
||||
*/
|
||||
const cache = new Map<string, Promise<GLTF>>();
|
||||
|
||||
function load(url: string): Promise<GLTF> {
|
||||
let p = cache.get(url);
|
||||
if (!p) {
|
||||
const loader = new GLTFLoader();
|
||||
loader.setMeshoptDecoder(MeshoptDecoder);
|
||||
p = loader.loadAsync(url);
|
||||
p.catch(() => cache.delete(url)); // 실패하면 다음에 다시
|
||||
cache.set(url, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
function url(dir: string, file: string) {
|
||||
return `/site/maps3d/${encodeURIComponent(dir)}/${encodeURIComponent(file)}`;
|
||||
}
|
||||
|
||||
/** 리플레이 캐릭터 클래스(Wushu_PC_C)의 몸. 없으면 null */
|
||||
export async function loadAgent(characterClass: string): Promise<GLTF | null> {
|
||||
const idx = await loadIndex();
|
||||
const a = idx?.dir ? idx.agents?.[characterClass] : undefined;
|
||||
return a && idx?.dir ? load(url(idx.dir, a.file)) : null;
|
||||
}
|
||||
|
||||
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 없으면 null */
|
||||
export async function loadWeapon(name: string): Promise<GLTF | null> {
|
||||
const idx = await loadIndex();
|
||||
const w = idx?.dir ? idx.weapons?.[name] : undefined;
|
||||
return w && idx?.dir ? load(url(idx.dir, w.file)) : null;
|
||||
}
|
||||
|
||||
const LOWER = ['lb_idle', 'lb_runN', 'lb_runS', 'lb_runE', 'lb_runW', 'lb_walkN', 'lb_walkS', 'lb_walkE', 'lb_walkW'] as const;
|
||||
type Lower = (typeof LOWER)[number];
|
||||
/** 애니메이션이 만든 속도 (cm/s): 이보다 빠르면 빨리 돌린다 */
|
||||
const RUN_CM_S = 540;
|
||||
const WALK_CM_S = 300;
|
||||
|
||||
/** 선수 한 명의 몸 (복제본) · 애니메이션 · 손에 든 총 */
|
||||
export class AgentRig {
|
||||
/** UE 좌표(cm) 공간의 선수 자리. 뷰어가 위치 · yaw 를 넣는다 */
|
||||
readonly root = new THREE.Group();
|
||||
private readonly model: THREE.Object3D;
|
||||
private readonly mixer: THREE.AnimationMixer;
|
||||
private readonly lower = new Map<Lower, THREE.AnimationAction>();
|
||||
private readonly hand: THREE.Object3D | null;
|
||||
private readonly gunSlot = new THREE.Group();
|
||||
private gunName: string | null = null;
|
||||
private gunReq = 0;
|
||||
private readonly tmp = new THREE.Vector3();
|
||||
|
||||
constructor(gltf: GLTF) {
|
||||
this.model = cloneSkinned(gltf.scene);
|
||||
this.model.traverse((o) => {
|
||||
const m = o as THREE.Mesh;
|
||||
if (m.isMesh) m.frustumCulled = false;
|
||||
});
|
||||
this.root.add(this.model);
|
||||
this.root.add(this.gunSlot);
|
||||
this.mixer = new THREE.AnimationMixer(this.model);
|
||||
const clip = (n: string) => gltf.animations.find((a) => a.name === n);
|
||||
const ub = clip('ub_rifle');
|
||||
if (ub) this.mixer.clipAction(ub).play();
|
||||
for (const n of LOWER) {
|
||||
const c = clip(n);
|
||||
if (!c) continue;
|
||||
const a = this.mixer.clipAction(c);
|
||||
a.play();
|
||||
a.setEffectiveWeight(n === 'lb_idle' ? 1 : 0);
|
||||
this.lower.set(n, a);
|
||||
}
|
||||
// R_WeaponPoint 는 공용 애니메이션이 움직이지 않아 손에서 떨어져 있다 → 손목(R_Hand) 기준
|
||||
this.hand = this.model.getObjectByName('R_Hand') ?? null;
|
||||
}
|
||||
|
||||
/** 들고 있는 총 바꾸기 (이름 없으면 맨손) */
|
||||
setWeapon(name: string | null) {
|
||||
if (name === this.gunName) return;
|
||||
this.gunName = name;
|
||||
const req = ++this.gunReq;
|
||||
this.gunSlot.clear();
|
||||
if (!name) return;
|
||||
void loadWeapon(name)
|
||||
.then((g) => {
|
||||
if (!g || req !== this.gunReq) return;
|
||||
const gun = g.scene.clone(true);
|
||||
gun.traverse((o) => {
|
||||
const m = o as THREE.Mesh;
|
||||
if (m.isMesh) m.frustumCulled = false;
|
||||
});
|
||||
gun.position.x = 7; // 손목 → 손바닥 (총 원점 = 손잡이)
|
||||
if (name === 'Melee') gun.rotation.y = Math.PI / 2; // 칼은 날이 +Z → 앞(+X)으로
|
||||
this.gunSlot.add(gun);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* 애니메이션 진행. dt: 리플레이 시간(초), fwd · right: 몸 기준 이동 속도(cm/s, UE: 앞 +X · 오른쪽 +Y), pitch: 위아래 보는 각(도)
|
||||
*/
|
||||
update(dt: number, fwd: number, right: number, pitch: number) {
|
||||
const speed = Math.hypot(fwd, right);
|
||||
const moving = THREE.MathUtils.smoothstep(speed, 40, 140);
|
||||
const run = speed > 400;
|
||||
const sum = Math.abs(fwd) + Math.abs(right) || 1;
|
||||
const w: Record<Lower, number> = {
|
||||
lb_idle: 1 - moving,
|
||||
lb_runN: 0, lb_runS: 0, lb_runE: 0, lb_runW: 0,
|
||||
lb_walkN: 0, lb_walkS: 0, lb_walkE: 0, lb_walkW: 0,
|
||||
};
|
||||
const g = run ? 'lb_run' : 'lb_walk';
|
||||
w[`${g}N` as Lower] = (moving * Math.max(0, fwd)) / sum;
|
||||
w[`${g}S` as Lower] = (moving * Math.max(0, -fwd)) / sum;
|
||||
w[`${g}E` as Lower] = (moving * Math.max(0, right)) / sum;
|
||||
w[`${g}W` as Lower] = (moving * Math.max(0, -right)) / sum;
|
||||
const scale = THREE.MathUtils.clamp(speed / (run ? RUN_CM_S : WALK_CM_S), 0.6, 1.5);
|
||||
for (const [n, a] of this.lower) {
|
||||
a.setEffectiveWeight(w[n]);
|
||||
a.setEffectiveTimeScale(n === 'lb_idle' ? 1 : scale);
|
||||
}
|
||||
this.mixer.update(dt);
|
||||
// 총: 오른손 자리에, 몸 앞(+X)을 보는 방향 + 위아래 각
|
||||
if (this.hand && this.gunSlot.children.length) {
|
||||
this.root.updateWorldMatrix(true, true);
|
||||
this.hand.getWorldPosition(this.tmp);
|
||||
this.root.worldToLocal(this.tmp);
|
||||
this.gunSlot.position.copy(this.tmp);
|
||||
this.gunSlot.rotation.set(0, (-THREE.MathUtils.clamp(pitch, -80, 80) * Math.PI) / 180, 0);
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.mixer.stopAllAction();
|
||||
this.gunSlot.clear();
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import type {
|
||||
BundleInfo,
|
||||
BundleImportResult,
|
||||
NoisePhrase,
|
||||
AppRole,
|
||||
AppUserRow,
|
||||
} from '@gvr/shared';
|
||||
|
||||
import { reportClient } from './report';
|
||||
@@ -33,6 +35,8 @@ export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public code: string,
|
||||
/** 서버가 함께 보낸 설명 (있으면) */
|
||||
public detail?: string,
|
||||
) {
|
||||
super(`${status} ${code}`);
|
||||
}
|
||||
@@ -54,8 +58,11 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
let code = 'error';
|
||||
let detail: string | undefined;
|
||||
try {
|
||||
code = ((await res.json()) as { error?: string }).error ?? code;
|
||||
const b = (await res.json()) as { error?: string; message?: string };
|
||||
code = b.error ?? code;
|
||||
if (typeof b.message === 'string') detail = b.message;
|
||||
} catch {
|
||||
/* 본문 없음 */
|
||||
}
|
||||
@@ -64,7 +71,7 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
|
||||
// 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김)
|
||||
else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`);
|
||||
throw new ApiError(res.status, code);
|
||||
throw new ApiError(res.status, code, detail);
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
@@ -72,6 +79,16 @@ export interface Me {
|
||||
isOwner: boolean;
|
||||
/** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */
|
||||
canViewLogs?: boolean;
|
||||
/** 앱 역할 (등록 안 된 멤버는 null, v1.6.0~) */
|
||||
role?: AppRole | null;
|
||||
}
|
||||
|
||||
/** 관리 화면 머리 (v1.6.0) */
|
||||
export interface AdminOverview {
|
||||
device: DeviceStatus & { guildId: string | null };
|
||||
latest: { version: string; url: string; publishedAt: string | null } | null;
|
||||
role: AppRole;
|
||||
serverVersion: string;
|
||||
}
|
||||
export interface StatusResponse {
|
||||
device: DeviceStatus;
|
||||
@@ -114,6 +131,17 @@ export const api = {
|
||||
/** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */
|
||||
registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }),
|
||||
status: () => request<StatusResponse>('/api/status'),
|
||||
// 내 정보 · 관리 화면 (v1.6.0)
|
||||
setMyName: (name: string) => request<{ user: Me['user']; customName: string | null }>('/site/profile/name', { method: 'PUT', body: JSON.stringify({ name }) }),
|
||||
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱 v1.6.0~, 본인 또는 관리자) */
|
||||
updateUser: (id: string, patch: { color?: string; excluded?: boolean; riotIds?: string[] }) =>
|
||||
request<{ user: User; taken: string[] }>(`/api/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }),
|
||||
adminOverview: () => request<AdminOverview>('/site/admin/overview'),
|
||||
adminUsers: () => request<{ users: AppUserRow[]; names: Record<string, string> }>('/site/admin/users'),
|
||||
adminSetName: (id: string, name: string) => request<{ names: Record<string, string> }>('/site/admin/names', { method: 'PUT', body: JSON.stringify({ id, name }) }),
|
||||
adminAddUser: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>('/site/admin/users', { method: 'POST', body: JSON.stringify({ id, role }) }),
|
||||
adminSetRole: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ role }) }),
|
||||
adminRemoveUser: (id: string) => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }),
|
||||
overview: () => request<Overview>('/api/overview'),
|
||||
users: () => request<User[]>('/api/users'),
|
||||
user: (id: string) => request<UserProfile>(`/api/users/${encodeURIComponent(id)}`),
|
||||
|
||||
@@ -10,10 +10,13 @@ interface Index {
|
||||
dir: string | null;
|
||||
version: string | null;
|
||||
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
|
||||
/** 요원 몸 (리플레이 캐릭터 클래스 → glb), 무기 (equipKinds 이름 → glb). 옛 index 에는 없다 */
|
||||
agents?: Record<string, { code: string; file: string; bytes: number }>;
|
||||
weapons?: Record<string, { file: string; bytes: number }>;
|
||||
}
|
||||
|
||||
let indexP: Promise<Index | null> | null = null;
|
||||
function loadIndex(): Promise<Index | null> {
|
||||
export function loadIndex(): Promise<Index | null> {
|
||||
indexP ??= fetch('/site/maps3d', { credentials: 'same-origin' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<Index>) : null))
|
||||
.catch(() => null)
|
||||
@@ -40,22 +43,57 @@ export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
|
||||
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> {
|
||||
/**
|
||||
* glb 를 받아 장면 하나로. onProgress: 0~1
|
||||
* 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다.
|
||||
* 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다.
|
||||
*/
|
||||
export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => 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) => {
|
||||
const hasMats = !!gltf.parser.json.materials?.length;
|
||||
const fb = hasMats ? null : fallback();
|
||||
const pending: Promise<unknown>[] = [];
|
||||
const done = new Map<THREE.Material, THREE.Material>();
|
||||
gltf.scene.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
if (mesh.isMesh) {
|
||||
mesh.material = material;
|
||||
mesh.frustumCulled = false;
|
||||
if (!mesh.isMesh) return;
|
||||
mesh.frustumCulled = false;
|
||||
if (fb) {
|
||||
mesh.material = fb;
|
||||
return;
|
||||
}
|
||||
const src = mesh.material as THREE.MeshStandardMaterial;
|
||||
const blend = src.userData?.blend as { texture?: number; tint?: number[] } | undefined;
|
||||
// 정점 색은 색칠이 아니라 두 층 섞는 비율이다
|
||||
const col = mesh.geometry.getAttribute('color');
|
||||
if (col) {
|
||||
mesh.geometry.setAttribute('blendCol', col);
|
||||
mesh.geometry.deleteAttribute('color');
|
||||
}
|
||||
let mat = done.get(src);
|
||||
if (!mat) {
|
||||
const m = src.clone() as THREE.MeshStandardMaterial;
|
||||
m.vertexColors = false;
|
||||
// 게임(UE) 좌표를 그대로 쓰고 행렬로 옮기므로 면 방향이 뒤집혀 보일 수 있다 → 양면
|
||||
m.side = THREE.DoubleSide;
|
||||
m.clippingPlanes = [clip];
|
||||
m.clipShadows = true;
|
||||
m.roughness = 1;
|
||||
m.metalness = 0;
|
||||
if (m.map) m.map.anisotropy = 4;
|
||||
if (m.transparent) m.depthWrite = false;
|
||||
if (blend) pending.push(blendLayer(gltf.parser, m, blend));
|
||||
done.set(src, m);
|
||||
mat = m;
|
||||
}
|
||||
mesh.material = mat;
|
||||
});
|
||||
resolve(gltf.scene);
|
||||
void Promise.all(pending).then(() => resolve(gltf.scene), reject);
|
||||
},
|
||||
(e) => onProgress?.(e.total ? e.loaded / e.total : 0),
|
||||
reject,
|
||||
@@ -63,6 +101,39 @@ export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p
|
||||
});
|
||||
}
|
||||
|
||||
/** B 층 텍스처 · 색을 붙이고 셰이더에서 정점 색 R 로 섞는다 */
|
||||
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, m: THREE.MeshStandardMaterial, b: { texture?: number; tint?: number[] }) {
|
||||
let texB: THREE.Texture | null = null;
|
||||
if (b.texture != null) {
|
||||
texB = (await parser.getDependency('texture', b.texture)) as THREE.Texture;
|
||||
texB.colorSpace = THREE.SRGBColorSpace;
|
||||
texB.anisotropy = 4;
|
||||
}
|
||||
const tintB = new THREE.Color().setRGB(b.tint?.[0] ?? 1, b.tint?.[1] ?? 1, b.tint?.[2] ?? 1, THREE.SRGBColorSpace);
|
||||
const md = m as unknown as { defines?: Record<string, string> };
|
||||
md.defines = { ...(md.defines ?? {}), GVR_BLEND: '', ...(texB ? { GVR_BLEND_MAP: '' } : {}) };
|
||||
m.onBeforeCompile = (sh) => {
|
||||
sh.uniforms.mapB = { value: texB };
|
||||
sh.uniforms.tintB = { value: tintB };
|
||||
sh.vertexShader = sh.vertexShader
|
||||
.replace('#include <common>', '#include <common>\nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;')
|
||||
.replace('#include <uv_vertex>', '#include <uv_vertex>\nvBlend = blendCol.r;\nvUvB = uv;');
|
||||
sh.fragmentShader = sh.fragmentShader
|
||||
.replace('#include <common>', '#include <common>\nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;')
|
||||
.replace(
|
||||
'#include <map_fragment>',
|
||||
`#include <map_fragment>
|
||||
#ifdef GVR_BLEND_MAP
|
||||
vec3 layerB = texture2D(mapB, vUvB).rgb * tintB;
|
||||
#else
|
||||
vec3 layerB = tintB;
|
||||
#endif
|
||||
diffuseColor.rgb = mix(layerB, diffuseColor.rgb, vBlend);`,
|
||||
);
|
||||
};
|
||||
m.needsUpdate = true;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
|
||||
@@ -21,6 +21,45 @@ export interface ReplayFile {
|
||||
/** [t0, t1, kind, x, y, z, owner] */
|
||||
objects: [number, number, number, number, number, number, number][];
|
||||
objectKinds: string[];
|
||||
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
|
||||
equips?: [number, number, number][];
|
||||
equipKinds?: string[];
|
||||
}
|
||||
|
||||
const WEAPON_KO: Record<string, string> = {
|
||||
Classic: '클래식', Shorty: '쇼티', Frenzy: '프렌지', Ghost: '고스트', Sheriff: '셰리프', 'Compact Pistol': '밴딧',
|
||||
Stinger: '스팅어', Spectre: '스펙터', Bucky: '버키', Judge: '저지', Bulldog: '불독', Guardian: '가디언', Phantom: '팬텀', Vandal: '밴달',
|
||||
Marshal: '마셜', Outlaw: '아웃로', Operator: '오퍼레이터', Ares: '아레스', Odin: '오딘',
|
||||
Melee: '칼', Spike: '스파이크', Unarmed: '맨손', Headhunter: '헤드헌터', 'Tour de Force': '투르 드 포스', Bomb_Defuser_C: '스파이크 해체',
|
||||
};
|
||||
|
||||
/** 들고 있는 것 이름 (한국어). 스킬은 "스킬", 모르면 null */
|
||||
export function equipLabel(kind: string | undefined): string | null {
|
||||
if (!kind) return null;
|
||||
if (WEAPON_KO[kind]) return WEAPON_KO[kind];
|
||||
if (/^Ability_/.test(kind)) return '스킬';
|
||||
if (/Unarmed/.test(kind)) return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 선수별 [t, kind] 목록 (시간 순) */
|
||||
export function equipTracks(r: ReplayFile): [number, number][][] {
|
||||
const out: [number, number][][] = r.players.map(() => []);
|
||||
for (const [t, p, k] of r.equips ?? []) out[p]?.push([t, k]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** t 시점에 들고 있던 것 (kind 번호, 없으면 -1) */
|
||||
export function equipAt(track: [number, number][] | undefined, t: number): number {
|
||||
if (!track?.length || t < track[0][0]) return -1;
|
||||
let lo = 0;
|
||||
let hi = track.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (track[mid][0] <= t) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return track[lo][1];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,7 +137,7 @@ export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: numb
|
||||
}
|
||||
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 };
|
||||
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: signedDeg(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];
|
||||
@@ -109,11 +148,17 @@ export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: numb
|
||||
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,
|
||||
pitch: signedDeg(tr.pitch[i]) + (signedDeg(tr.pitch[j]) - signedDeg(tr.pitch[i])) * k,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** 게임 각도(0~360) → -180~180 (아래를 보면 음수) */
|
||||
function signedDeg(a: number) {
|
||||
const v = ((a % 360) + 360) % 360;
|
||||
return v > 180 ? v - 360 : v;
|
||||
}
|
||||
|
||||
/** t 가 속한 라운드 (구매 단계 시작 기준) */
|
||||
export function roundAt(r: ReplayFile, t: number) {
|
||||
let cur = r.rounds[0] ?? null;
|
||||
|
||||
299
site/web/src/pages/AdminPage.tsx
Normal file
299
site/web/src/pages/AdminPage.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
// 관리 페이지 (v1.6.0, 관리자 · 최고 관리자)
|
||||
// - 게임 PC: 연결 · 앱 버전 · 새 버전 안내
|
||||
// - 유저: 표시 이름 · 색 · 녹음 제외 · 라이엇 ID (녹음된 사람), 앱 등록 · 역할 · 해제 (최고 관리자)
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import type { AppUserRow, User } from '@gvr/shared';
|
||||
import { api, type AdminOverview } from '../lib/api';
|
||||
import { fmtDay } from '../lib/format';
|
||||
import { useAuth, useData } from '../store/app';
|
||||
import { Avatar, ErrorBox, Panel, Spinner } from '../components/common';
|
||||
import { AppUserEditor, errText, NameEditor } from '../components/UserEdit';
|
||||
|
||||
const ROLE: Record<string, string> = { superadmin: '최고 관리자', admin: '관리자', user: '앱 유저' };
|
||||
|
||||
/** "1.4.1" < "1.5.0" */
|
||||
export function olderVersion(a: string | null | undefined, b: string | null | undefined): boolean {
|
||||
if (!a || !b) return false;
|
||||
const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
|
||||
const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
const when = (t: number | null) => (t ? `${fmtDay(t)} ${new Date(t).toLocaleTimeString('ko-KR', { hour12: false, hour: '2-digit', minute: '2-digit' })}` : '—');
|
||||
|
||||
interface Row {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string | null;
|
||||
/** 녹음 기록에 있는 사람 (게임 PC 앱) */
|
||||
user: User | null;
|
||||
/** 앱 등록 (사이트 서버) */
|
||||
reg: AppUserRow | null;
|
||||
}
|
||||
|
||||
export function AdminPage() {
|
||||
const { auth } = useAuth();
|
||||
const { users } = useData();
|
||||
const [ov, setOv] = useState<AdminOverview | null>(null);
|
||||
const [regs, setRegs] = useState<AppUserRow[] | null>(null);
|
||||
const [names, setNames] = useState<Record<string, string>>({});
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const [q, setQ] = useState('');
|
||||
const load = useCallback(() => {
|
||||
setErr(null);
|
||||
Promise.all([api.adminOverview(), api.adminUsers()])
|
||||
.then(([o, u]) => {
|
||||
setOv(o);
|
||||
setRegs(u.users);
|
||||
setNames(u.names ?? {});
|
||||
})
|
||||
.catch(setErr);
|
||||
}, []);
|
||||
useEffect(load, [load]);
|
||||
const sup = ov?.role === 'superadmin';
|
||||
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
const m = new Map<string, Row>();
|
||||
for (const u of users) m.set(u.id, { id: u.id, name: u.name, avatar: u.avatar, user: u, reg: null });
|
||||
for (const r of regs ?? []) {
|
||||
const cur = m.get(r.id);
|
||||
if (cur) cur.reg = r;
|
||||
else m.set(r.id, { id: r.id, name: r.name, avatar: r.avatar, user: null, reg: r });
|
||||
}
|
||||
const order = (r: Row) => (r.reg?.role === 'superadmin' ? 0 : r.reg?.role === 'admin' ? 1 : r.reg ? 2 : 3);
|
||||
const k = q.trim().toLowerCase();
|
||||
return [...m.values()]
|
||||
.filter((r) => !k || r.name.toLowerCase().includes(k) || r.id.includes(k) || r.user?.riot.some((x) => x.riotId.toLowerCase().includes(k)))
|
||||
.sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name, 'ko'));
|
||||
}, [users, regs, q]);
|
||||
|
||||
if (auth.status !== 'ok' || !auth.me.canViewLogs)
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<h2 className="page-h h">관리</h2>
|
||||
<div className="dim">관리자만 볼 수 있습니다.</div>
|
||||
</main>
|
||||
);
|
||||
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={load} /></main>;
|
||||
if (!ov || !regs) return <main className="page-pad"><Spinner /></main>;
|
||||
|
||||
const dev = ov.device;
|
||||
const outdated = olderVersion(dev.version, ov.latest?.version);
|
||||
return (
|
||||
<main className="page-pad admin-page">
|
||||
<div className="page-h-row">
|
||||
<h2 className="page-h h">🛡️ 관리</h2>
|
||||
<div className="chips-wrap">
|
||||
<a className="mini-btn" href="/logs">
|
||||
📄 사이트 로그
|
||||
</a>
|
||||
<button className="mini-btn" onClick={load}>
|
||||
새로고침
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Panel title="게임 PC">
|
||||
<div className="adm-dev">
|
||||
<div>
|
||||
<span className={`dot-st ${dev.online ? 'on' : 'off'}`} /> <b>{dev.name ?? '등록된 PC 없음'}</b>
|
||||
<span className="dim small"> · {dev.online ? '연결됨' : dev.lastSeen ? `마지막 연결 ${when(dev.lastSeen)}` : '연결 안 됨'}</span>
|
||||
</div>
|
||||
<div>
|
||||
앱 <b className="mono">{dev.version ?? '?'}</b>
|
||||
{ov.latest && (
|
||||
<span className="dim small">
|
||||
{' '}
|
||||
· 최신 <span className="mono">{ov.latest.version}</span>
|
||||
</span>
|
||||
)}
|
||||
{outdated && ov.latest && (
|
||||
<a className="adm-update" href={ov.latest.url} target="_blank" rel="noreferrer">
|
||||
새 버전 v{ov.latest.version} 받기 →
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
{outdated && <div className="ue-hint">게임 PC 앱이 최신이 아닙니다. 색 · 녹음 제외 · 라이엇 ID 바꾸기와 3D 리플레이는 최신 앱에서 됩니다.</div>}
|
||||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
title={`유저 ${rows.length}명`}
|
||||
right={<input className="ue-input adm-search" value={q} placeholder="이름 · 아이디 · 라이엇 ID 찾기" onChange={(e) => setQ(e.target.value)} aria-label="유저 찾기" />}
|
||||
>
|
||||
<div className="ue-hint adm-note">
|
||||
표시 이름은 디스코드 이름 대신 사이트 · 게임 PC 기록 · 범인 분석에 보입니다 (관리자). 앱 등록 · 역할 바꾸기 · 등록 해제는 최고 관리자만 할 수 있습니다.
|
||||
</div>
|
||||
<div className="adm-list">
|
||||
{rows.map((r) => (
|
||||
<AdminUserRow
|
||||
key={r.id}
|
||||
r={r}
|
||||
custom={!!names[r.id]}
|
||||
sup={sup}
|
||||
open={open === r.id}
|
||||
onToggle={() => setOpen((o) => (o === r.id ? null : r.id))}
|
||||
onNames={setNames}
|
||||
onRegs={setRegs}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{sup && <AddUser onRegs={setRegs} />}
|
||||
</Panel>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function AdminUserRow({
|
||||
r,
|
||||
custom,
|
||||
sup,
|
||||
open,
|
||||
onToggle,
|
||||
onNames,
|
||||
onRegs,
|
||||
}: {
|
||||
r: Row;
|
||||
custom: boolean;
|
||||
sup: boolean;
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
onNames: (n: Record<string, string>) => void;
|
||||
onRegs: (u: AppUserRow[]) => void;
|
||||
}) {
|
||||
const { reloadUsers } = useData();
|
||||
const { auth, refreshMe } = useAuth();
|
||||
const [msg, setMsg] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const act = async (fn: () => Promise<{ users: AppUserRow[] }>) => {
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
try {
|
||||
onRegs((await fn()).users);
|
||||
} catch (e) {
|
||||
setMsg(errText(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const role = r.reg?.role ?? null;
|
||||
return (
|
||||
<div className={`adm-row${open ? ' open' : ''}`}>
|
||||
<button className="adm-sum" onClick={onToggle} aria-expanded={open}>
|
||||
<Avatar user={r.user} name={r.name} src={r.avatar} size={30} />
|
||||
<span className="adm-nm">
|
||||
<b style={r.user ? { color: r.user.color } : undefined}>{r.name}</b>
|
||||
{custom && <span className="badge b-name">표시 이름</span>}
|
||||
{r.user?.excluded && <span className="badge b-excl">녹음 제외</span>}
|
||||
<span className="dim small mono">{r.id}</span>
|
||||
</span>
|
||||
<span className="adm-role">{role ? <span className={`badge b-role ${role}`}>{ROLE[role]}</span> : <span className="dim small">앱 미등록</span>}</span>
|
||||
<span className="adm-seen dim small">{r.reg?.lastSeenAt ? `앱 ${when(r.reg.lastSeenAt)}${r.reg.lastVersion ? ` · v${r.reg.lastVersion}` : ''}` : r.user ? '녹음 기록 있음' : ''}</span>
|
||||
<span className="adm-caret">{open ? '▴' : '▾'}</span>
|
||||
</button>
|
||||
{open && (
|
||||
<div className="adm-body">
|
||||
<div className="ue-label">표시 이름</div>
|
||||
<NameEditor
|
||||
value={r.name}
|
||||
custom={custom}
|
||||
onSave={async (name) => {
|
||||
const res = await api.adminSetName(r.id, name);
|
||||
onNames(res.names);
|
||||
// 게임 PC 앱이 이름을 받아 유저 목록을 다시 보낸다. 조금 기다렸다가 다시 받는다
|
||||
window.setTimeout(reloadUsers, 1500);
|
||||
if (auth.status === 'ok' && auth.me.user.id === r.id) await refreshMe();
|
||||
const regs = await api.adminUsers().catch(() => null);
|
||||
if (regs) onRegs(regs.users);
|
||||
}}
|
||||
/>
|
||||
{r.user ? (
|
||||
<AppUserEditor user={r.user} self={false} />
|
||||
) : (
|
||||
<div className="ue-hint">이 PC 녹음 기록에 없는 사람입니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>
|
||||
)}
|
||||
{r.user && (
|
||||
<Link className="mini-btn" to={`/users/${r.id}`}>
|
||||
기록 보기
|
||||
</Link>
|
||||
)}
|
||||
{sup && role !== 'superadmin' && (
|
||||
<div className="adm-acts">
|
||||
<div className="ue-label">앱 사용 (게임 PC 앱 로그인)</div>
|
||||
{role ? (
|
||||
<>
|
||||
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminSetRole(r.id, role === 'admin' ? 'user' : 'admin'))}>
|
||||
{role === 'admin' ? '관리자 → 앱 유저로' : '앱 유저 → 관리자로'}
|
||||
</button>
|
||||
<button
|
||||
className="btn sm danger"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (window.confirm(`${r.name} 님의 앱 등록을 해제할까요? 그 사람의 겜녹이 앱이 바로 잠깁니다.`)) void act(() => api.adminRemoveUser(r.id));
|
||||
}}
|
||||
>
|
||||
등록 해제
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'user'))}>
|
||||
앱 유저로 등록
|
||||
</button>
|
||||
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'admin'))}>
|
||||
관리자로 등록
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{msg && <div className="ue-msg bad">{msg}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddUser({ onRegs }: { onRegs: (u: AppUserRow[]) => void }) {
|
||||
const [id, setId] = useState('');
|
||||
const [role, setRole] = useState<'user' | 'admin'>('user');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const ok = /^\d{17,20}$/.test(id.trim());
|
||||
return (
|
||||
<form
|
||||
className="adm-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!ok) return;
|
||||
setBusy(true);
|
||||
setMsg(null);
|
||||
api
|
||||
.adminAddUser(id.trim(), role)
|
||||
.then((r) => {
|
||||
onRegs(r.users);
|
||||
setMsg({ ok: true, text: '등록했습니다. 그 사람은 이제 겜녹이 앱에 로그인할 수 있습니다' });
|
||||
setId('');
|
||||
})
|
||||
.catch((e) => setMsg({ ok: false, text: errText(e) }))
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
>
|
||||
<div className="ue-label">디스코드 아이디로 앱 유저 등록</div>
|
||||
<div className="ue-row">
|
||||
<input className="ue-input mono" value={id} inputMode="numeric" placeholder="디스코드 아이디 (17~20자리 숫자)" onChange={(e) => setId(e.target.value)} aria-label="디스코드 아이디" />
|
||||
<select className="ue-input adm-sel" value={role} onChange={(e) => setRole(e.target.value as 'user' | 'admin')} aria-label="역할">
|
||||
<option value="user">앱 유저</option>
|
||||
<option value="admin">관리자</option>
|
||||
</select>
|
||||
<button className="btn sm primary" disabled={busy || !ok}>
|
||||
등록
|
||||
</button>
|
||||
</div>
|
||||
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { makeUnknownUserCheck } from '../lib/unknown-users';
|
||||
|
||||
// ── 로그인 ───────────────────────────────────────────
|
||||
type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me };
|
||||
const AuthCtx = createContext<{ auth: AuthState; logout: () => void }>({ auth: { status: 'loading' }, logout: () => {} });
|
||||
const AuthCtx = createContext<{ auth: AuthState; logout: () => void; refreshMe: () => Promise<void> }>({ auth: { status: 'loading' }, logout: () => {}, refreshMe: async () => {} });
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [auth, setAuth] = useState<AuthState>({ status: 'loading' });
|
||||
@@ -28,7 +28,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const logout = useCallback(() => {
|
||||
void api.logout().finally(() => setAuth({ status: 'anon' }));
|
||||
}, []);
|
||||
return <AuthCtx.Provider value={{ auth, logout }}>{children}</AuthCtx.Provider>;
|
||||
// 내 표시 이름을 바꾼 뒤 머리글 이름을 다시 받는다
|
||||
const refreshMe = useCallback(async () => {
|
||||
const r = await api.me().catch(() => null);
|
||||
if (r?.ok) setAuth({ status: 'ok', me: r.me });
|
||||
}, []);
|
||||
return <AuthCtx.Provider value={{ auth, logout, refreshMe }}>{children}</AuthCtx.Provider>;
|
||||
}
|
||||
export const useAuth = () => useContext(AuthCtx);
|
||||
|
||||
@@ -123,8 +128,10 @@ interface DataValue {
|
||||
overview: Overview | null;
|
||||
users: User[];
|
||||
userById: (id: string | undefined | null) => User | undefined;
|
||||
/** 유저 목록 다시 받기 (유저 설정을 바꾼 뒤) */
|
||||
reloadUsers: () => void;
|
||||
}
|
||||
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined });
|
||||
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined, reloadUsers: () => {} });
|
||||
|
||||
export function DataProvider({ children }: { children: ReactNode }) {
|
||||
const { epoch, locked } = useStatus();
|
||||
@@ -163,6 +170,6 @@ export function DataProvider({ children }: { children: ReactNode }) {
|
||||
if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o));
|
||||
});
|
||||
const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]);
|
||||
return <DataCtx.Provider value={{ overview, users, userById }}>{children}</DataCtx.Provider>;
|
||||
return <DataCtx.Provider value={{ overview, users, userById, reloadUsers }}>{children}</DataCtx.Provider>;
|
||||
}
|
||||
export const useData = () => useContext(DataCtx);
|
||||
|
||||
@@ -4070,6 +4070,36 @@ button.match:hover {
|
||||
.r3d-foot {
|
||||
font-size: 12px;
|
||||
}
|
||||
.r3d-cams {
|
||||
display: inline-flex;
|
||||
gap: 4px;
|
||||
}
|
||||
.r3d-pick {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
max-width: 260px;
|
||||
background: rgba(8, 14, 20, 0.85);
|
||||
color: inherit;
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
padding: 3px 6px;
|
||||
}
|
||||
.r3d-cross {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
margin: -3px 0 0 -3px;
|
||||
border-radius: 50%;
|
||||
background: #7dffb0;
|
||||
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6);
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
}
|
||||
.r3d-stage canvas:focus {
|
||||
outline: none;
|
||||
}
|
||||
.r3d-ceil {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -4079,3 +4109,273 @@ button.match:hover {
|
||||
width: 90px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
/* ── 내 정보 · 관리 페이지 (v1.6.0) ───────────────── */
|
||||
.me-btn {
|
||||
padding: 4px 8px 4px 4px;
|
||||
border-radius: 20px;
|
||||
border: 1px solid transparent;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
}
|
||||
.me-btn:hover,
|
||||
.me-btn[aria-expanded='true'] {
|
||||
border-color: var(--line);
|
||||
background: #15222f;
|
||||
}
|
||||
.me-caret {
|
||||
font-size: 10px;
|
||||
color: var(--dim);
|
||||
}
|
||||
.popover.profile-pop {
|
||||
right: 0;
|
||||
width: 360px;
|
||||
max-height: calc(100vh - var(--header-h) - 24px);
|
||||
overflow: auto;
|
||||
}
|
||||
.pp-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.pp-head b {
|
||||
font-size: 15px;
|
||||
}
|
||||
.pp-links {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 14px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.ue-block {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.ue-row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.ue-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
background: #0b141c;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
padding: 6px 9px;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
}
|
||||
.ue-input:focus {
|
||||
outline: none;
|
||||
border-color: #3a5670;
|
||||
}
|
||||
.ue-label {
|
||||
font-size: 11.5px;
|
||||
color: var(--muted);
|
||||
margin-top: 6px;
|
||||
}
|
||||
.ue-hint {
|
||||
font-size: 11.5px;
|
||||
color: var(--dim);
|
||||
line-height: 1.5;
|
||||
display: block;
|
||||
}
|
||||
.ue-msg {
|
||||
font-size: 12px;
|
||||
}
|
||||
.ue-msg.ok {
|
||||
color: var(--good);
|
||||
}
|
||||
.ue-msg.bad {
|
||||
color: #ff8a8a;
|
||||
}
|
||||
.ue-colors {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.ue-sw {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid transparent;
|
||||
box-shadow: 0 0 0 1px #2c3f52;
|
||||
}
|
||||
.ue-sw.on {
|
||||
border-color: #fff;
|
||||
}
|
||||
.ue-sw.custom {
|
||||
background: var(--panel2);
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
}
|
||||
.ue-hidden {
|
||||
position: absolute;
|
||||
width: 0;
|
||||
height: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.ue-check {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
font-size: 13px;
|
||||
margin-top: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ue-check input {
|
||||
margin-top: 3px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.ue-check > span {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.admin-page .panel {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.adm-dev {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.dot-st {
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #4a5866;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.dot-st.on {
|
||||
background: var(--good);
|
||||
}
|
||||
.adm-update {
|
||||
margin-left: 10px;
|
||||
color: var(--gold);
|
||||
font-weight: 700;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.adm-search {
|
||||
max-width: 240px;
|
||||
}
|
||||
.adm-note {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.adm-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.adm-row {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: #0f1923;
|
||||
}
|
||||
.adm-row.open {
|
||||
border-color: #34506a;
|
||||
}
|
||||
.adm-sum {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 12px;
|
||||
text-align: left;
|
||||
}
|
||||
.adm-nm {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.adm-role {
|
||||
width: 96px;
|
||||
}
|
||||
.adm-seen {
|
||||
width: 200px;
|
||||
text-align: right;
|
||||
}
|
||||
.adm-caret {
|
||||
color: var(--dim);
|
||||
font-size: 11px;
|
||||
}
|
||||
.adm-body {
|
||||
padding: 4px 14px 14px 52px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.adm-body > .ue-block {
|
||||
width: min(520px, 100%);
|
||||
}
|
||||
.adm-acts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.adm-acts .ue-label {
|
||||
width: 100%;
|
||||
}
|
||||
.adm-add {
|
||||
margin-top: 14px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
max-width: 560px;
|
||||
}
|
||||
.adm-sel {
|
||||
flex: none;
|
||||
width: auto;
|
||||
}
|
||||
.b-name {
|
||||
background: #13283a;
|
||||
color: #8fc6ff;
|
||||
border: 1px solid #23415c;
|
||||
}
|
||||
.b-role.superadmin {
|
||||
background: #3a1820;
|
||||
color: #ff8a95;
|
||||
}
|
||||
.b-role.admin {
|
||||
background: #2b2412;
|
||||
color: var(--gold);
|
||||
}
|
||||
.b-role.user {
|
||||
background: #18303a;
|
||||
color: var(--mint);
|
||||
}
|
||||
.btn.danger {
|
||||
border-color: #5a2029;
|
||||
color: #ff8a8a;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.adm-seen,
|
||||
.adm-role {
|
||||
display: none;
|
||||
}
|
||||
.adm-body {
|
||||
padding-left: 14px;
|
||||
}
|
||||
.popover.profile-pop {
|
||||
position: fixed;
|
||||
top: calc(var(--header-h) + 6px);
|
||||
left: 8px;
|
||||
right: 8px;
|
||||
width: auto;
|
||||
max-height: calc(100vh - var(--header-h) - 16px);
|
||||
}
|
||||
}
|
||||
|
||||
1
tools/map-extract/.gitignore
vendored
1
tools/map-extract/.gitignore
vendored
@@ -2,3 +2,4 @@ vendor/
|
||||
bin/
|
||||
obj/
|
||||
out/
|
||||
__pycache__/
|
||||
|
||||
@@ -16,5 +16,6 @@
|
||||
<Compile Include="src/**/*.cs" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse/CUE4Parse.csproj" />
|
||||
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse-Conversion/CUE4Parse-Conversion.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -12,4 +12,6 @@ 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
|
||||
# 애니메이션(ACL 압축) 풀기에 쓰는 네이티브 라이브러리 소스 (헤더만)
|
||||
git -C "$dst" submodule update --quiet --init --recursive CUE4Parse-Natives/ACL/external/acl
|
||||
echo "CUE4Parse @ $(git -C "$dst" rev-parse --short HEAD)"
|
||||
|
||||
@@ -10,6 +10,10 @@ export PATH="$HOME/.dotnet:$PATH" DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DO
|
||||
"$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
|
||||
# CUE4Parse-Natives (ACL 애니메이션 풀기만, cmake 없이 g++): 요원 애니메이션 추출에 필요
|
||||
nat="$here/vendor/CUE4Parse/CUE4Parse-Natives"
|
||||
g++ -shared -fPIC -O2 -std=c++17 -DWITH_ACL -I"$nat/ACL/external/acl/includes" -I"$nat/ACL/external/acl/external/rtm/includes" -I"$nat/common" -I"$nat/ACL/includes" \
|
||||
"$nat/ACL/ACL.cpp" "$nat/Features.cpp" -o "$GVR_MAPS_HOME/bin.new/CUE4Parse-Natives.so"
|
||||
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"
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
|
||||
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
|
||||
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons)
|
||||
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
|
||||
-ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게
|
||||
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
|
||||
import datetime, gzip, json, os, re, shutil, subprocess, sys
|
||||
|
||||
@@ -11,7 +13,7 @@ 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'):
|
||||
if not name.endswith('.json') or name == 'agents.json':
|
||||
continue
|
||||
info = json.load(open(os.path.join(src, name)))
|
||||
code = info['code']
|
||||
@@ -19,14 +21,38 @@ for name in sorted(os.listdir(src)):
|
||||
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)
|
||||
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-ke', '-vt', '14'], 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}
|
||||
# 요원 · 무기 (agents 명령 결과 agents.json 이 있으면): 뼈대 · 애니메이션 · 노드 이름을 지킨다 (-kn)
|
||||
agents, weapons = {}, {}
|
||||
aj = os.path.join(src, 'agents.json')
|
||||
if os.path.exists(aj):
|
||||
a = json.load(open(aj))
|
||||
def pack_one(file):
|
||||
glb = os.path.join(src, file)
|
||||
if not os.path.exists(glb):
|
||||
return None
|
||||
packed = os.path.join(out, d, file)
|
||||
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-kn', '-ke'], 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)
|
||||
return os.path.getsize(packed + '.gz')
|
||||
for cls, v in a.get('agents', {}).items():
|
||||
size = pack_one(v['file'])
|
||||
if size:
|
||||
agents[cls] = {'code': v['code'], 'file': v['file'], 'bytes': size}
|
||||
for name, v in a.get('weapons', {}).items():
|
||||
size = pack_one(v['file'])
|
||||
if size:
|
||||
weapons[name] = {'file': v['file'], 'bytes': size, 'points': v.get('points') or {}}
|
||||
print(f'요원 {len(agents)} · 무기 {len(weapons)}')
|
||||
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons}
|
||||
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'))
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#
|
||||
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝
|
||||
# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/
|
||||
# 3. 모든 맵을 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
|
||||
# 3. 모든 맵 · 요원 · 무기를 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
|
||||
# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다
|
||||
#
|
||||
# 실패하면(어느 단계든) 사이트는 이전 맵을 그대로 쓰고, 같은 조합은 30분 · 1시간 · 2시간 … 최대 6시간 간격으로 다시 해 본다.
|
||||
@@ -122,6 +122,9 @@ out="$GVR_MAPS_HOME/work/out"
|
||||
rm -rf "$raw" "$out"
|
||||
mkdir -p "$raw" "$out"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"
|
||||
# 요원 3D 몸 · 애니메이션 · 무기 (실패해도 맵은 올린다. 일부만 실패하면 뽑힌 것만 쓴다)
|
||||
stage="요원 추출"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" agents "$raw" || log "요원 · 무기 추출 일부 실패 (뽑힌 것만 올림)"
|
||||
stage="압축"
|
||||
python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version"
|
||||
dir="$(jq -r .dir "$out/index.json")"
|
||||
|
||||
345
tools/map-extract/src/Agents.cs
Normal file
345
tools/map-extract/src/Agents.cs
Normal file
@@ -0,0 +1,345 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports.Animation;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
using CUE4Parse_Conversion.Animations;
|
||||
using CUE4Parse_Conversion.Dto;
|
||||
using CUE4Parse_Conversion.Options;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>
|
||||
/// 요원 3인칭 몸 (뼈대 · 피부 · 텍스처) + 공용 애니메이션을 요원마다 glb 하나로.
|
||||
/// 좌표는 게임(UE) 그대로: cm, 메시 공간(발이 z=0 근처, 앞이 +Y). 사이트가 리플레이 좌표 · yaw 로 옮긴다.
|
||||
/// 애니메이션은 위 · 아래 몸을 나눠 넣는다 (사이트가 위 = 총 든 자세, 아래 = 서기/걷기/달리기 방향을 따로 섞는다):
|
||||
/// ub_rifle Spine1 아래 (총 든 서 있는 자세, Core_Rifle_Idle)
|
||||
/// lb_idle Splitter · Pelvis 아래 (Core_Rifle_Idle 다리)
|
||||
/// lb_run{N,S,E,W} TP_Core_Run*_LB, lb_walk{N,S,E,W} TP_Core_Walk*_LB
|
||||
/// Skeleton · Root 뼈는 회전만 넣는다 (애니메이션 이동은 리플레이 위치가 대신한다).
|
||||
/// </summary>
|
||||
public static class Agents
|
||||
{
|
||||
private const string Anims = "/Game/Characters/_Core/3P/Anims/";
|
||||
private static readonly (string Name, string Path, bool Upper)[] Clips =
|
||||
[
|
||||
("ub_rifle", Anims + "Rifle/Core_Rifle_Idle", true),
|
||||
("lb_idle", Anims + "Rifle/Core_Rifle_Idle", false),
|
||||
("lb_runN", Anims + "TP_Core_RunN_LB", false),
|
||||
("lb_runS", Anims + "TP_Core_RunS_LB", false),
|
||||
("lb_runE", Anims + "TP_Core_RunE_LB", false),
|
||||
("lb_runW", Anims + "TP_Core_RunW_LB", false),
|
||||
("lb_walkN", Anims + "TP_Core_WalkN_LB", false),
|
||||
("lb_walkS", Anims + "TP_Core_WalkS_LB", false),
|
||||
("lb_walkE", Anims + "TP_Core_WalkE_LB", false),
|
||||
("lb_walkW", Anims + "TP_Core_WalkW_LB", false),
|
||||
];
|
||||
|
||||
/// <summary>요원 = Characters/<코드>/<코드>_PC 블루프린트. 리플레이 선수 캐릭터 이름(Wushu_PC_C)과 같다</summary>
|
||||
public static List<(string Code, string Blueprint)> Find(IFileProvider provider)
|
||||
{
|
||||
var res = new List<(string, string)>();
|
||||
foreach (var k in provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Characters/", StringComparison.OrdinalIgnoreCase) && k.EndsWith("_PC.uasset", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k))
|
||||
{
|
||||
var parts = k.Split('/');
|
||||
if (parts.Length != 5) continue; // Characters/<코드>/<코드>_PC.uasset 만
|
||||
var code = parts[3];
|
||||
if (!parts[4].Equals(code + "_PC.uasset", StringComparison.OrdinalIgnoreCase) || code.StartsWith('_')) continue;
|
||||
res.Add((code, k));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/// <summary>블루프린트의 3인칭 몸 (SkeletalMeshComponent 중 /3P/ 의 요원 전용 메시)</summary>
|
||||
public static USkeletalMesh? BodyMesh(IFileProvider provider, string blueprint)
|
||||
{
|
||||
var pkg = provider.LoadPackage(blueprint);
|
||||
foreach (var e in pkg.GetExports().OfType<USkeletalMeshComponent>())
|
||||
{
|
||||
var idx = e.GetOrDefault<CUE4Parse.UE4.Objects.UObject.FPackageIndex?>("SkeletalMesh") ?? e.GetOrDefault<CUE4Parse.UE4.Objects.UObject.FPackageIndex?>("SkinnedAsset");
|
||||
var path = idx?.ResolvedObject?.GetPathName() ?? "";
|
||||
if (!path.Contains("/3P/") || path.Contains("/_Core/")) continue;
|
||||
try { return idx!.Load<USkeletalMesh>(); } catch { }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public sealed record Result(int Triangles, int Bones, int Clips, int Textures, long TextureBytes);
|
||||
|
||||
public static Result Export(IFileProvider provider, USkeletalMesh mesh, string file, int maxTex, int lodWant)
|
||||
{
|
||||
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
|
||||
var lod = dto.LODs[Math.Min(lodWant, dto.LODs.Count - 1)];
|
||||
var bones = dto.Bones;
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
|
||||
// 뼈 노드 (참조 자세 TRS), 부모-자식
|
||||
var boneNode = new int[bones.Length];
|
||||
for (var i = 0; i < bones.Length; i++)
|
||||
{
|
||||
var t = bones[i].Transform;
|
||||
glb.Nodes.Add(new JsonObject
|
||||
{
|
||||
["name"] = bones[i].Name,
|
||||
["translation"] = Arr(t.Translation.X, t.Translation.Y, t.Translation.Z),
|
||||
["rotation"] = Arr(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
|
||||
["scale"] = Arr(t.Scale3D.X, t.Scale3D.Y, t.Scale3D.Z),
|
||||
});
|
||||
boneNode[i] = glb.Nodes.Count - 1;
|
||||
}
|
||||
for (var i = 0; i < bones.Length; i++)
|
||||
{
|
||||
var p = bones[i].ParentIndex;
|
||||
if (p < 0) { glb.Roots.Add(boneNode[i]); continue; }
|
||||
var parent = glb.Nodes[boneNode[p]]!.AsObject();
|
||||
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
|
||||
ch.Add(boneNode[i]);
|
||||
}
|
||||
// 역바인드 행렬 = (참조 자세 전역 행렬)^-1
|
||||
var global = new Mat4[bones.Length];
|
||||
for (var i = 0; i < bones.Length; i++)
|
||||
{
|
||||
var local = Mat4.Trs(bones[i].Transform);
|
||||
global[i] = bones[i].ParentIndex >= 0 ? global[bones[i].ParentIndex] * local : local;
|
||||
}
|
||||
var ibm = new float[bones.Length * 16];
|
||||
for (var i = 0; i < bones.Length; i++) global[i].Inverse().CopyTo(ibm, i * 16);
|
||||
var skin = new JsonObject
|
||||
{
|
||||
["joints"] = new JsonArray(boneNode.Select(x => (JsonNode)x).ToArray()),
|
||||
["inverseBindMatrices"] = glb.Raw(ibm, "MAT4"),
|
||||
["skeleton"] = boneNode[0],
|
||||
};
|
||||
|
||||
// 정점 (모든 구간 공유) + 재질별 primitive
|
||||
var vs = lod.Vertices;
|
||||
var pos = new float[vs.Length * 3];
|
||||
var nrm = new float[vs.Length * 3];
|
||||
var uv = new float[vs.Length * 2];
|
||||
var joints = new ushort[vs.Length * 4];
|
||||
var weights = new float[vs.Length * 4];
|
||||
for (var i = 0; i < vs.Length; i++)
|
||||
{
|
||||
var v = vs[i];
|
||||
pos[i * 3] = v.Position.X; pos[i * 3 + 1] = v.Position.Y; pos[i * 3 + 2] = v.Position.Z;
|
||||
var n = new FVector(v.Normal.X, v.Normal.Y, v.Normal.Z);
|
||||
var len = n.Size();
|
||||
if (len > 1e-6f) n /= len;
|
||||
nrm[i * 3] = n.X; nrm[i * 3 + 1] = n.Y; nrm[i * 3 + 2] = n.Z;
|
||||
uv[i * 2] = v.Uv.U; uv[i * 2 + 1] = v.Uv.V;
|
||||
var inf = v.Influences.OrderByDescending(x => x.Weight).Take(4).ToArray();
|
||||
var sum = inf.Sum(x => x.Weight);
|
||||
for (var k = 0; k < inf.Length; k++)
|
||||
{
|
||||
joints[i * 4 + k] = inf[k].Bone;
|
||||
weights[i * 4 + k] = sum > 0 ? inf[k].Weight / sum : (k == 0 ? 1 : 0);
|
||||
}
|
||||
if (inf.Length == 0) weights[i * 4] = 1;
|
||||
}
|
||||
var aPos = glb.Floats(pos, 3, bounds: true);
|
||||
var aNrm = glb.Floats(nrm, 3);
|
||||
var aUv = glb.Floats(uv, 2);
|
||||
var aJ = glb.Ushorts(joints, 4);
|
||||
var aW = glb.Floats(weights, 4);
|
||||
var prims = new JsonArray();
|
||||
var tris = 0;
|
||||
foreach (var sec in lod.Sections)
|
||||
{
|
||||
if (!sec.IsValid || sec.NumFaces <= 0) continue;
|
||||
UMaterialInterface? m = null;
|
||||
try { m = dto.Materials.ElementAtOrDefault(sec.MaterialIndex).Material?.Load<UMaterialInterface>(); } catch { }
|
||||
var mp = m != null ? MatParams.Resolve(m) : null;
|
||||
// 반투명(눈 덧칠 · 유리 · 빛나는 껍데기) · 숨김 재질은 뺀다
|
||||
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate" || m!.Name.Contains("Hidden", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("GVR_DEBUG") != null) Console.Error.WriteLine($" 뺀 재질 {m?.Name} {mp.BlendMode} {mp.Base} 삼각형 {sec.NumFaces}");
|
||||
continue;
|
||||
}
|
||||
var texPath = mp == null ? null : new[] { "Diffuse", "DF", "Albedo", "Base Color", "BaseColor", "Diffuse Map" }.Select(n => mp.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
|
||||
?? mp.Textures.FirstOrDefault(kv => kv.Value.EndsWith("_DF", StringComparison.OrdinalIgnoreCase) || kv.Value.Contains("_DF.", StringComparison.OrdinalIgnoreCase)).Value;
|
||||
var t = tex.Get(texPath);
|
||||
var pbr = new JsonObject { ["metallicFactor"] = 0, ["roughnessFactor"] = 0.8 };
|
||||
if (t is { } tt) pbr["baseColorTexture"] = new JsonObject { ["index"] = tt.tex };
|
||||
else pbr["baseColorFactor"] = Arr(0.55f, 0.55f, 0.6f, 1);
|
||||
var mat = new JsonObject { ["name"] = m?.Name ?? "none", ["pbrMetallicRoughness"] = pbr };
|
||||
if (mp?.BlendMode == "BLEND_Masked" && t is { alpha: true })
|
||||
{
|
||||
mat["alphaMode"] = "MASK";
|
||||
mat["alphaCutoff"] = 0.333;
|
||||
mat["doubleSided"] = true;
|
||||
}
|
||||
glb.Materials.Add(mat);
|
||||
// UE 왼손 좌표 → glTF 앞면 방향으로 삼각형을 뒤집는다 (맵과 같음)
|
||||
var idx = new uint[sec.NumFaces * 3];
|
||||
for (var f = 0; f < sec.NumFaces; f++)
|
||||
{
|
||||
idx[f * 3] = lod.Indices[sec.FirstIndex + f * 3];
|
||||
idx[f * 3 + 1] = lod.Indices[sec.FirstIndex + f * 3 + 2];
|
||||
idx[f * 3 + 2] = lod.Indices[sec.FirstIndex + f * 3 + 1];
|
||||
}
|
||||
tris += sec.NumFaces;
|
||||
prims.Add(new JsonObject
|
||||
{
|
||||
["attributes"] = new JsonObject { ["POSITION"] = aPos, ["NORMAL"] = aNrm, ["TEXCOORD_0"] = aUv, ["JOINTS_0"] = aJ, ["WEIGHTS_0"] = aW },
|
||||
["indices"] = glb.Indices(idx),
|
||||
["material"] = glb.Materials.Count - 1,
|
||||
});
|
||||
}
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = 0, ["skin"] = 0 });
|
||||
glb.Roots.Add(glb.Nodes.Count - 1);
|
||||
|
||||
// 애니메이션
|
||||
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
|
||||
var upperSet = Subtree(bones, "Spine1");
|
||||
upperSet.UnionWith(Subtree(bones, "MasterWeaponAim")); // 총 붙는 뼈 (R_WeaponMaster) 도 위 몸 자세를 따른다
|
||||
var lowerSet = Subtree(bones, "Pelvis");
|
||||
if (nameToBone.TryGetValue("Splitter", out var spl)) lowerSet.Add(spl);
|
||||
// Skeleton · Root 는 회전만 (애니메이션에 따라 몸 방향을 여기서 보정한다). 이동(루트 모션)은 뺀다
|
||||
var rootOnlyRot = new HashSet<int>();
|
||||
foreach (var n in new[] { "Skeleton", "Root" })
|
||||
if (nameToBone.TryGetValue(n, out var ri)) { lowerSet.Add(ri); rootOnlyRot.Add(ri); }
|
||||
var animations = new JsonArray();
|
||||
foreach (var (name, path, upper) in Clips)
|
||||
{
|
||||
try
|
||||
{
|
||||
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
|
||||
var set = a.ConvertAnims();
|
||||
var seq = set.Sequences[0];
|
||||
seq.RetargetTracks(mesh.ReferenceSkeleton);
|
||||
var anim = Clip(glb, seq, set.Skeleton, nameToBone, upper ? upperSet : lowerSet, boneNode, bones, name, rootOnlyRot);
|
||||
if (anim != null) animations.Add(anim);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
}
|
||||
glb.Write(file, new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = animations });
|
||||
return new Result(tris, bones.Length, animations.Count, tex.Count, tex.Bytes);
|
||||
}
|
||||
|
||||
private static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)
|
||||
{
|
||||
var set = new HashSet<int>();
|
||||
var root = Array.FindIndex(bones, b => b.Name.Equals(rootName, StringComparison.OrdinalIgnoreCase));
|
||||
if (root < 0) return set;
|
||||
set.Add(root);
|
||||
for (var i = root + 1; i < bones.Length; i++)
|
||||
if (bones[i].ParentIndex >= 0 && set.Contains(bones[i].ParentIndex)) set.Add(i);
|
||||
return set;
|
||||
}
|
||||
|
||||
/// <summary>한 애니메이션을 glTF 애니메이션으로: 고른 뼈만, 프레임마다 회전(+움직이면 이동)</summary>
|
||||
private static JsonObject? Clip(Glb glb, CUE4Parse_Conversion.Writers.ActorX.Structs.Animations.CAnimSequence seq, USkeleton skel, Dictionary<string, int> nameToBone, HashSet<int> only, int[] boneNode, MeshBoneDto[] bones, string name, HashSet<int> noTranslate)
|
||||
{
|
||||
var frames = Math.Max(1, seq.NumFrames);
|
||||
var fps = seq.FramesPerSecond > 0 ? seq.FramesPerSecond : 30;
|
||||
var times = Enumerable.Range(0, frames).Select(f => f / fps).ToArray();
|
||||
var tAcc = glb.Floats(times, 1, bounds: true);
|
||||
var samplers = new JsonArray();
|
||||
var channels = new JsonArray();
|
||||
var info = skel.ReferenceSkeleton.FinalRefBoneInfo;
|
||||
for (var si = 0; si < seq.Tracks.Count && si < info.Length; si++)
|
||||
{
|
||||
var track = seq.Tracks[si];
|
||||
if (!track.HasKeys() || !nameToBone.TryGetValue(info[si].Name.Text, out var bi) || !only.Contains(bi)) continue;
|
||||
var rot = new float[frames * 4];
|
||||
var tr = new float[frames * 3];
|
||||
var movesT = false;
|
||||
var refT = bones[bi].Transform.Translation;
|
||||
for (var f = 0; f < frames; f++)
|
||||
{
|
||||
FQuat q = bones[bi].Transform.Rotation;
|
||||
FVector p = refT, s = FVector.OneVector;
|
||||
track.GetBoneTransform(f, frames, ref q, ref p, ref s);
|
||||
q.Normalize();
|
||||
// 이웃 프레임과 같은 반구 (보간이 반대로 돌지 않게)
|
||||
if (f > 0 && q.X * rot[(f - 1) * 4] + q.Y * rot[(f - 1) * 4 + 1] + q.Z * rot[(f - 1) * 4 + 2] + q.W * rot[(f - 1) * 4 + 3] < 0) q = new FQuat(-q.X, -q.Y, -q.Z, -q.W);
|
||||
rot[f * 4] = q.X; rot[f * 4 + 1] = q.Y; rot[f * 4 + 2] = q.Z; rot[f * 4 + 3] = q.W;
|
||||
tr[f * 3] = p.X; tr[f * 3 + 1] = p.Y; tr[f * 3 + 2] = p.Z;
|
||||
if ((p - refT).Size() > 0.05f) movesT = true;
|
||||
}
|
||||
samplers.Add(new JsonObject { ["input"] = tAcc, ["output"] = glb.Floats(rot, 4), ["interpolation"] = "LINEAR" });
|
||||
channels.Add(new JsonObject { ["sampler"] = samplers.Count - 1, ["target"] = new JsonObject { ["node"] = boneNode[bi], ["path"] = "rotation" } });
|
||||
if (movesT && !noTranslate.Contains(bi))
|
||||
{
|
||||
samplers.Add(new JsonObject { ["input"] = tAcc, ["output"] = glb.Floats(tr, 3), ["interpolation"] = "LINEAR" });
|
||||
channels.Add(new JsonObject { ["sampler"] = samplers.Count - 1, ["target"] = new JsonObject { ["node"] = boneNode[bi], ["path"] = "translation" } });
|
||||
}
|
||||
}
|
||||
if (channels.Count == 0) return null;
|
||||
return new JsonObject { ["name"] = name, ["samplers"] = samplers, ["channels"] = channels };
|
||||
}
|
||||
|
||||
private static JsonArray Arr(params float[] v) => new(v.Select(x => (JsonNode)x).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>열 우선 4x4 행렬 (glTF 와 같은 배치)</summary>
|
||||
public readonly struct Mat4
|
||||
{
|
||||
private readonly double[] _m; // column-major
|
||||
|
||||
private Mat4(double[] m) => _m = m;
|
||||
|
||||
public static Mat4 Trs(FTransform t)
|
||||
{
|
||||
double x = t.Rotation.X, y = t.Rotation.Y, z = t.Rotation.Z, w = t.Rotation.W;
|
||||
double sx = t.Scale3D.X, sy = t.Scale3D.Y, sz = t.Scale3D.Z;
|
||||
var m = new double[16];
|
||||
m[0] = (1 - 2 * (y * y + z * z)) * sx; m[1] = 2 * (x * y + z * w) * sx; m[2] = 2 * (x * z - y * w) * sx;
|
||||
m[4] = 2 * (x * y - z * w) * sy; m[5] = (1 - 2 * (x * x + z * z)) * sy; m[6] = 2 * (y * z + x * w) * sy;
|
||||
m[8] = 2 * (x * z + y * w) * sz; m[9] = 2 * (y * z - x * w) * sz; m[10] = (1 - 2 * (x * x + y * y)) * sz;
|
||||
m[12] = t.Translation.X; m[13] = t.Translation.Y; m[14] = t.Translation.Z; m[15] = 1;
|
||||
return new Mat4(m);
|
||||
}
|
||||
|
||||
public static Mat4 operator *(Mat4 a, Mat4 b)
|
||||
{
|
||||
var r = new double[16];
|
||||
for (var c = 0; c < 4; c++)
|
||||
for (var rr = 0; rr < 4; rr++)
|
||||
{
|
||||
double s = 0;
|
||||
for (var k = 0; k < 4; k++) s += a._m[k * 4 + rr] * b._m[c * 4 + k];
|
||||
r[c * 4 + rr] = s;
|
||||
}
|
||||
return new Mat4(r);
|
||||
}
|
||||
|
||||
public Mat4 Inverse()
|
||||
{
|
||||
var m = _m;
|
||||
var inv = new double[16];
|
||||
inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
|
||||
inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
|
||||
inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
|
||||
inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
|
||||
inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
|
||||
inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
|
||||
inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
|
||||
inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
|
||||
inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
|
||||
inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
|
||||
inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
|
||||
inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
|
||||
inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
|
||||
inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
|
||||
inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
|
||||
inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];
|
||||
var det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
|
||||
if (Math.Abs(det) < 1e-12) det = 1e-12;
|
||||
for (var i = 0; i < 16; i++) inv[i] /= det;
|
||||
return new Mat4(inv);
|
||||
}
|
||||
|
||||
public void CopyTo(float[] dst, int offset)
|
||||
{
|
||||
for (var i = 0; i < 16; i++) dst[offset + i] = (float)_m[i];
|
||||
}
|
||||
}
|
||||
129
tools/map-extract/src/Glb.cs
Normal file
129
tools/map-extract/src/Glb.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>작은 glTF 2.0 바이너리(glb) 작성기: 버퍼 하나에 accessor · 이미지를 차례로 붙인다</summary>
|
||||
public sealed class Glb
|
||||
{
|
||||
private readonly MemoryStream _bin = new();
|
||||
public readonly JsonArray BufferViews = new(), Accessors = new(), Images = new(), Textures = new(), Materials = new(), Meshes = new(), Nodes = new(), Samplers = new();
|
||||
public JsonObject? Extras;
|
||||
/// <summary>장면의 최상위 노드 (비면 모든 노드)</summary>
|
||||
public readonly List<int> Roots = new();
|
||||
|
||||
private int View(ReadOnlySpan<byte> data, int? target)
|
||||
{
|
||||
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
|
||||
var v = new JsonObject { ["buffer"] = 0, ["byteOffset"] = _bin.Length, ["byteLength"] = data.Length };
|
||||
if (target is { } t) v["target"] = t;
|
||||
_bin.Write(data);
|
||||
BufferViews.Add(v);
|
||||
return BufferViews.Count - 1;
|
||||
}
|
||||
|
||||
private int Accessor(int view, int componentType, int count, string type, bool normalized = false, float[]? min = null, float[]? max = null)
|
||||
{
|
||||
var a = new JsonObject { ["bufferView"] = view, ["componentType"] = componentType, ["count"] = count, ["type"] = type };
|
||||
if (normalized) a["normalized"] = true;
|
||||
if (min != null) a["min"] = new JsonArray(min.Select(x => (JsonNode)x).ToArray());
|
||||
if (max != null) a["max"] = new JsonArray(max.Select(x => (JsonNode)x).ToArray());
|
||||
Accessors.Add(a);
|
||||
return Accessors.Count - 1;
|
||||
}
|
||||
|
||||
public int Floats(float[] data, int comps, bool bounds = false)
|
||||
{
|
||||
float[]? min = null, max = null;
|
||||
if (bounds)
|
||||
{
|
||||
min = Enumerable.Repeat(float.MaxValue, comps).ToArray();
|
||||
max = Enumerable.Repeat(float.MinValue, comps).ToArray();
|
||||
for (var i = 0; i < data.Length; i++)
|
||||
{
|
||||
min[i % comps] = Math.Min(min[i % comps], data[i]);
|
||||
max[i % comps] = Math.Max(max[i % comps], data[i]);
|
||||
}
|
||||
}
|
||||
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
|
||||
return Accessor(v, 5126, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, false, min, max);
|
||||
}
|
||||
|
||||
/// <summary>정규화된 unsigned byte (색 · 가중치)</summary>
|
||||
public int Bytes(byte[] data, int comps, bool normalized = true)
|
||||
{
|
||||
var v = View(data, 34962);
|
||||
return Accessor(v, 5121, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, normalized);
|
||||
}
|
||||
|
||||
public int Ushorts(ushort[] data, int comps)
|
||||
{
|
||||
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
|
||||
return Accessor(v, 5123, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" });
|
||||
}
|
||||
|
||||
public int Indices(uint[] data)
|
||||
{
|
||||
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34963);
|
||||
return Accessor(v, 5125, data.Length, "SCALAR");
|
||||
}
|
||||
|
||||
/// <summary>행렬 같은 비정점 데이터 (target 없음)</summary>
|
||||
public int Raw(float[] data, string type)
|
||||
{
|
||||
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), null);
|
||||
var comps = type switch { "MAT4" => 16, "VEC4" => 4, "VEC3" => 3, _ => 1 };
|
||||
return Accessor(v, 5126, data.Length / comps, type);
|
||||
}
|
||||
|
||||
/// <summary>텍스처 (반복 샘플러) 번호</summary>
|
||||
public int Texture(byte[] image, string mime)
|
||||
{
|
||||
if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 });
|
||||
Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime });
|
||||
Textures.Add(new JsonObject { ["sampler"] = 0, ["source"] = Images.Count - 1 });
|
||||
return Textures.Count - 1;
|
||||
}
|
||||
|
||||
public void Write(string file, JsonObject? extra = null)
|
||||
{
|
||||
var gltf = new JsonObject
|
||||
{
|
||||
["asset"] = new JsonObject { ["version"] = "2.0", ["generator"] = "gvr-map-extract" },
|
||||
["scene"] = 0,
|
||||
["scenes"] = new JsonArray(new JsonObject { ["nodes"] = new JsonArray((Roots.Count > 0 ? Roots : Enumerable.Range(0, Nodes.Count)).Select(i => (JsonNode)i).ToArray()) }),
|
||||
["nodes"] = Nodes,
|
||||
["meshes"] = Meshes,
|
||||
["accessors"] = Accessors,
|
||||
["bufferViews"] = BufferViews,
|
||||
["buffers"] = new JsonArray(new JsonObject { ["byteLength"] = _bin.Length }),
|
||||
};
|
||||
if (Materials.Count > 0) gltf["materials"] = Materials;
|
||||
if (Textures.Count > 0)
|
||||
{
|
||||
gltf["textures"] = Textures;
|
||||
gltf["images"] = Images;
|
||||
gltf["samplers"] = Samplers;
|
||||
}
|
||||
if (extra != null)
|
||||
foreach (var (k, v) in extra) gltf[k] = v?.DeepClone();
|
||||
if (Extras != null) gltf["extras"] = Extras;
|
||||
var json = Encoding.UTF8.GetBytes(gltf.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
|
||||
var jsonPad = (4 - json.Length % 4) % 4;
|
||||
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
|
||||
using var fs = File.Create(file);
|
||||
using var w = new BinaryWriter(fs);
|
||||
w.Write(0x46546C67u); // glTF
|
||||
w.Write(2u);
|
||||
w.Write((uint)(12 + 8 + json.Length + jsonPad + 8 + _bin.Length));
|
||||
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)_bin.Length);
|
||||
w.Write(0x004E4942u); // BIN
|
||||
_bin.Position = 0;
|
||||
_bin.CopyTo(fs);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
using CUE4Parse.UE4.Objects.UObject;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
@@ -12,13 +14,10 @@ namespace GvrMapExtract;
|
||||
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
|
||||
|
||||
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
|
||||
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</summary>
|
||||
/// 재질마다 텍스처(디퓨즈, 작게 줄임) · 색을 붙인다.</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 = "";
|
||||
@@ -80,10 +79,53 @@ public sealed class MapScene
|
||||
// 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다
|
||||
private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"];
|
||||
|
||||
private sealed record Sec(int First, int Tris, int Mat);
|
||||
/// <summary>메시 한 LOD: 위치 · 법선 · UV · 정점 색 · 삼각형 · 재질 구간</summary>
|
||||
private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod);
|
||||
|
||||
/// <summary>재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다</summary>
|
||||
private sealed class Bucket
|
||||
{
|
||||
public readonly List<float> Pos = new(), Nrm = new(), Uv = new();
|
||||
public readonly List<byte> Col = new();
|
||||
public readonly List<uint> Idx = new();
|
||||
}
|
||||
|
||||
/// <summary>사이트에 쓸 재질 요약. Blend = 정점 색(R)으로 두 층(A · B) 섞기</summary>
|
||||
private sealed record Mat(string Key, string Name, string? TexA, string? TexB, float[] TintA, float[] TintB, bool Masked, bool Translucent, bool Blend);
|
||||
|
||||
private readonly Dictionary<string, Mat?> _mats = new();
|
||||
private readonly Dictionary<string, Bucket> _buckets = new();
|
||||
private long _verts, _tris;
|
||||
|
||||
private Mat? MaterialOf(UMaterialInterface? m)
|
||||
{
|
||||
var key = m?.GetPathName() ?? "";
|
||||
if (_mats.TryGetValue(key, out var r)) return r;
|
||||
if (m == null) return _mats[key] = new Mat("", "(없음)", null, null, [0.6f, 0.6f, 0.6f], [1, 1, 1], false, false, false);
|
||||
var p = MatParams.Resolve(m);
|
||||
if (p.BlendMode is "BLEND_Additive" or "BLEND_Modulate" || p.Base.Contains("/VFX/Materials/")) return _mats[key] = null;
|
||||
string? Tex(params string[] names) => names.Select(n => p.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
|
||||
?? (names.Length > 0 && names[0] == "Diffuse" ? p.Textures.FirstOrDefault(kv => kv.Key.Contains("Diffuse", StringComparison.OrdinalIgnoreCase) && !kv.Key.Contains("Low") && !kv.Key.EndsWith(" B")).Value : null);
|
||||
float[] Tint(params string[] names)
|
||||
{
|
||||
foreach (var n in names)
|
||||
if (p.Vectors.TryGetValue(n, out var c)) return [c.R, c.G, c.B];
|
||||
return [1, 1, 1];
|
||||
}
|
||||
var blend = p.Base.Contains("Blend", StringComparison.OrdinalIgnoreCase) && p.Textures.ContainsKey("Diffuse B");
|
||||
var texA = blend ? Tex("Diffuse A", "Diffuse") : Tex("Diffuse", "Diffuse A", "Albedo", "Base Color", "Texture");
|
||||
var tintA = blend ? Tint("Layer A Tint") : Tint("DiffuseColor", "Diffuse Tint", "Layer A Tint", "Tree Base Color");
|
||||
// 텍스처가 없으면 색만 (없으면 회색)
|
||||
if (texA == null && !p.Vectors.Keys.Any(k => k is "DiffuseColor" or "Diffuse Tint" or "Layer A Tint" or "Tree Base Color")) tintA = [0.6f, 0.6f, 0.6f];
|
||||
return _mats[key] = new Mat(key, m.Name, texA, blend ? p.Textures["Diffuse B"] : null, tintA, Tint("Layer B Tint"),
|
||||
p.BlendMode == "BLEND_Masked", p.BlendMode == "BLEND_Translucent", blend);
|
||||
}
|
||||
|
||||
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)?>();
|
||||
var meshCache = new Dictionary<string, Geo?>();
|
||||
foreach (var level in map.Levels)
|
||||
{
|
||||
s._levels.Add(Path.GetFileNameWithoutExtension(level));
|
||||
@@ -101,23 +143,37 @@ public sealed class MapScene
|
||||
if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; }
|
||||
if (!meshCache.TryGetValue(path, out var geo))
|
||||
{
|
||||
geo = Geometry(mesh);
|
||||
try { geo = Geometry(mesh); } catch { geo = null; s.Failed++; }
|
||||
meshCache[path] = geo;
|
||||
if (geo != null) s.Meshes++;
|
||||
}
|
||||
if (geo == null) continue;
|
||||
FTransform w;
|
||||
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
|
||||
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
|
||||
var over = c.GetOrDefault<FPackageIndex[]>("OverrideMaterials", []);
|
||||
var mats = new Mat?[geo.Secs.Length];
|
||||
for (var k = 0; k < geo.Secs.Length; k++)
|
||||
{
|
||||
var mi = geo.Secs[k].Mat;
|
||||
var idx = mi < over.Length && over[mi] is { IsNull: false } ov ? ov : mi < mesh.StaticMaterials.Length ? mesh.StaticMaterials[mi].MaterialInterface : null;
|
||||
UMaterialInterface? mat = null;
|
||||
try { mat = idx?.Load<UMaterialInterface>(); } catch { }
|
||||
mats[k] = s.MaterialOf(mat);
|
||||
}
|
||||
// 칠한 정점 색 (두 층 섞기에 쓴다): 컴포넌트 값이 정점 수와 맞을 때만
|
||||
var col = geo.Col;
|
||||
if (c is { LODData: { } lodData } && geo.Lod < lodData.Length && lodData[geo.Lod].OverrideVertexColors is { Data: { } oc } && oc.Length == geo.V.Length) col = oc;
|
||||
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);
|
||||
foreach (var d in data) s.Add(geo, mats, col, d.TransformData * w);
|
||||
else s.Add(geo, mats, col, w);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
|
||||
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
|
||||
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다)</summary>
|
||||
private static Geo? Geometry(UStaticMesh mesh)
|
||||
{
|
||||
var lods = mesh.RenderData?.LODs;
|
||||
if (lods == null) return null;
|
||||
@@ -125,85 +181,137 @@ public sealed class MapScene
|
||||
{
|
||||
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());
|
||||
var uvItems = lod.VertexBuffer?.UV;
|
||||
var n = new FVector[v.Length];
|
||||
var uv = new float[v.Length * 2];
|
||||
if (uvItems != null && uvItems.Length == v.Length)
|
||||
for (var i = 0; i < v.Length; i++)
|
||||
{
|
||||
var it = uvItems[i];
|
||||
if (it.Normal is { Length: >= 3 }) n[i] = (FVector)it.Normal[2];
|
||||
if (it.UV is { Length: > 0 })
|
||||
{
|
||||
uv[i * 2] = it.UV[0].U;
|
||||
uv[i * 2 + 1] = it.UV[0].V;
|
||||
}
|
||||
}
|
||||
var col = lod.ColorVertexBuffer?.Data is { } cd && cd.Length == v.Length ? cd : null;
|
||||
var secs = lod.Sections.Select(x => new Sec(x.FirstIndex, x.NumTriangles, x.MaterialIndex)).ToArray();
|
||||
return new Geo(v, n, uv, col, ib.Select(x => (uint)x).ToArray(), secs, l);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Add((FVector[] v, uint[] i) g, FTransform t)
|
||||
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t)
|
||||
{
|
||||
Placements++;
|
||||
var b = (uint)(_pos.Count / 3);
|
||||
foreach (var p in g.v)
|
||||
// UE 는 왼손 좌표계라 glTF(오른손, 반시계 앞면) 로 그대로 옮기면 앞뒤가 바뀐다 → 기본으로 뒤집는다.
|
||||
// 크기가 음수(거울)면 한 번 더 뒤집힌다
|
||||
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z >= 0;
|
||||
var inv = new FVector(1 / NonZero(t.Scale3D.X), 1 / NonZero(t.Scale3D.Y), 1 / NonZero(t.Scale3D.Z));
|
||||
for (var k = 0; k < g.Secs.Length; k++)
|
||||
{
|
||||
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]);
|
||||
var m = mats[k];
|
||||
if (m == null) continue;
|
||||
var sec = g.Secs[k];
|
||||
if (!_buckets.TryGetValue(m.Key, out var b)) _buckets[m.Key] = b = new Bucket();
|
||||
// 이 구간이 쓰는 정점만 옮긴다
|
||||
var map = new Dictionary<uint, uint>();
|
||||
uint Vert(uint i)
|
||||
{
|
||||
if (map.TryGetValue(i, out var o)) return o;
|
||||
o = (uint)(b.Pos.Count / 3);
|
||||
var p = t.TransformPosition(g.V[i]);
|
||||
b.Pos.Add(p.X); b.Pos.Add(p.Y); b.Pos.Add(p.Z);
|
||||
var nn = t.Rotation.RotateVector(g.N[i] * inv);
|
||||
var len = nn.Size();
|
||||
if (len > 1e-6f) nn /= len;
|
||||
b.Nrm.Add(nn.X); b.Nrm.Add(nn.Y); b.Nrm.Add(nn.Z);
|
||||
b.Uv.Add(g.Uv[i * 2]); b.Uv.Add(g.Uv[i * 2 + 1]);
|
||||
if (m.Blend)
|
||||
{
|
||||
var c = col != null ? col[i] : new FColor(255, 255, 255, 255);
|
||||
b.Col.Add(c.R); b.Col.Add(c.G); b.Col.Add(c.B); b.Col.Add(c.A);
|
||||
}
|
||||
map[i] = o;
|
||||
_verts++;
|
||||
return o;
|
||||
}
|
||||
for (var j = 0; j < sec.Tris; j++)
|
||||
{
|
||||
var i0 = g.Ib[sec.First + j * 3];
|
||||
var i1 = g.Ib[sec.First + j * 3 + 1];
|
||||
var i2 = g.Ib[sec.First + j * 3 + 2];
|
||||
b.Idx.Add(Vert(i0));
|
||||
b.Idx.Add(Vert(flip ? i2 : i1));
|
||||
b.Idx.Add(Vert(flip ? i1 : i2));
|
||||
_tris++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
|
||||
public void WriteGlb(string file)
|
||||
private static float NonZero(float v) => Math.Abs(v) < 1e-6f ? 1e-6f : v;
|
||||
|
||||
public long Triangles => _tris;
|
||||
public int Materials => _buckets.Count;
|
||||
public int TextureCount, TextureFailed;
|
||||
public long TextureBytes;
|
||||
|
||||
/// <summary>glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색).
|
||||
/// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다)</summary>
|
||||
public void WriteGlb(IFileProvider provider, string file, int maxTex)
|
||||
{
|
||||
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++)
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var prims = new System.Text.Json.Nodes.JsonArray();
|
||||
var byKey = _mats.Values.Where(x => x != null).ToDictionary(x => x!.Key, x => x!);
|
||||
foreach (var (key, b) in _buckets.OrderBy(x => x.Key, StringComparer.Ordinal))
|
||||
{
|
||||
min[i % 3] = Math.Min(min[i % 3], pos[i]);
|
||||
max[i % 3] = Math.Max(max[i % 3], pos[i]);
|
||||
if (b.Idx.Count == 0) continue;
|
||||
var m = byKey[key];
|
||||
var a = tex.Get(m.TexA);
|
||||
var bt = m.Blend ? tex.Get(m.TexB) : null;
|
||||
var pbr = new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
["baseColorFactor"] = new System.Text.Json.Nodes.JsonArray(Clamp(m.TintA[0]), Clamp(m.TintA[1]), Clamp(m.TintA[2]), m.Translucent ? 0.45f : 1f),
|
||||
["metallicFactor"] = 0,
|
||||
["roughnessFactor"] = 0.9,
|
||||
};
|
||||
if (a is { } at) pbr["baseColorTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = at.tex };
|
||||
var mat = new System.Text.Json.Nodes.JsonObject { ["name"] = m.Name, ["pbrMetallicRoughness"] = pbr };
|
||||
if (m.Translucent) mat["alphaMode"] = "BLEND";
|
||||
else if (m.Masked && a is { alpha: true })
|
||||
{
|
||||
mat["alphaMode"] = "MASK";
|
||||
mat["alphaCutoff"] = 0.333;
|
||||
mat["doubleSided"] = true;
|
||||
}
|
||||
if (m.Blend)
|
||||
{
|
||||
var ex = new System.Text.Json.Nodes.JsonObject { ["tint"] = new System.Text.Json.Nodes.JsonArray(Clamp(m.TintB[0]), Clamp(m.TintB[1]), Clamp(m.TintB[2])) };
|
||||
if (bt is { } btt) ex["texture"] = btt.tex;
|
||||
mat["extras"] = new System.Text.Json.Nodes.JsonObject { ["blend"] = ex };
|
||||
}
|
||||
glb.Materials.Add(mat);
|
||||
var attrs = new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
["POSITION"] = glb.Floats(b.Pos.ToArray(), 3, bounds: true),
|
||||
["NORMAL"] = glb.Floats(b.Nrm.ToArray(), 3),
|
||||
["TEXCOORD_0"] = glb.Floats(b.Uv.ToArray(), 2),
|
||||
};
|
||||
if (m.Blend) attrs["COLOR_0"] = glb.Bytes(b.Col.ToArray(), 4);
|
||||
prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 });
|
||||
}
|
||||
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);
|
||||
glb.Meshes.Add(new System.Text.Json.Nodes.JsonObject { ["name"] = _code, ["primitives"] = prims });
|
||||
glb.Nodes.Add(new System.Text.Json.Nodes.JsonObject { ["mesh"] = 0, ["name"] = _code });
|
||||
glb.Write(file);
|
||||
TextureCount = tex.Count;
|
||||
TextureFailed = tex.Failed;
|
||||
TextureBytes = tex.Bytes;
|
||||
}
|
||||
|
||||
private static float Clamp(float v) => Math.Clamp(v, 0f, 1f);
|
||||
|
||||
public void WriteInfo(string file, string manifest, string? usmap)
|
||||
{
|
||||
var info = new
|
||||
@@ -214,6 +322,11 @@ public sealed class MapScene
|
||||
placements = Placements,
|
||||
meshes = Meshes,
|
||||
triangles = Triangles,
|
||||
vertices = _verts,
|
||||
materials = Materials,
|
||||
textures = TextureCount,
|
||||
texturesFailed = TextureFailed,
|
||||
textureBytes = TextureBytes,
|
||||
skipped = Skipped,
|
||||
failed = Failed,
|
||||
manifest,
|
||||
|
||||
46
tools/map-extract/src/Materials.cs
Normal file
46
tools/map-extract/src/Materials.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>재질 인스턴스 사슬을 따라 올라가며 텍스처 · 색 매개변수를 모은다 (자식 값이 먼저)</summary>
|
||||
public sealed class MatParams
|
||||
{
|
||||
public string Path = "";
|
||||
public string Base = "";
|
||||
public readonly Dictionary<string, string> Textures = new(StringComparer.OrdinalIgnoreCase);
|
||||
public readonly Dictionary<string, FLinearColor> Vectors = new(StringComparer.OrdinalIgnoreCase);
|
||||
public readonly Dictionary<string, float> Scalars = new(StringComparer.OrdinalIgnoreCase);
|
||||
public string? BlendMode;
|
||||
|
||||
public static MatParams Resolve(UMaterialInterface mat)
|
||||
{
|
||||
var r = new MatParams { Path = mat.GetPathName() };
|
||||
UMaterialInterface? cur = mat;
|
||||
for (var d = 0; d < 12 && cur != null; d++)
|
||||
{
|
||||
if (cur is UMaterialInstanceConstant mi)
|
||||
{
|
||||
foreach (var t in mi.TextureParameterValues)
|
||||
if (t.ParameterValue is { IsNull: false } tv && !r.Textures.ContainsKey(t.Name))
|
||||
r.Textures[t.Name] = tv.ResolvedObject?.GetPathName() ?? "";
|
||||
foreach (var v in mi.VectorParameterValues)
|
||||
if (v.ParameterValue is { } c && !r.Vectors.ContainsKey(v.Name)) r.Vectors[v.Name] = c;
|
||||
foreach (var s in mi.ScalarParameterValues)
|
||||
if (!r.Scalars.ContainsKey(s.Name)) r.Scalars[s.Name] = s.ParameterValue;
|
||||
if (r.BlendMode == null && mi.TryGetValue(out CUE4Parse.UE4.Assets.Objects.FStructFallback bpo, "BasePropertyOverrides") && bpo.TryGetValue(out bool ov, "bOverride_BlendMode") && ov)
|
||||
r.BlendMode = bpo.GetOrDefault<EBlendMode>("BlendMode").ToString();
|
||||
UMaterialInterface? parent = null;
|
||||
try { parent = mi.Parent?.Load<UMaterialInterface>(); } catch { }
|
||||
cur = parent;
|
||||
}
|
||||
else
|
||||
{
|
||||
r.Base = cur.GetPathName();
|
||||
if (r.BlendMode == null && cur is UMaterial m) r.BlendMode = m.BlendMode.ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
}
|
||||
84
tools/map-extract/src/Probe.cs
Normal file
84
tools/map-extract/src/Probe.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Objects.UObject;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>조사용: 맵이 쓰는 재질 매개변수 통계</summary>
|
||||
public static class Probe
|
||||
{
|
||||
public static void Mats(IFileProvider provider, MapInfo map)
|
||||
{
|
||||
var tris = new Dictionary<string, long>();
|
||||
var mats = new Dictionary<string, UMaterialInterface>();
|
||||
foreach (var level in map.Levels)
|
||||
{
|
||||
var pkg = provider.LoadPackage(level);
|
||||
foreach (var lazy in pkg.ExportsLazy)
|
||||
{
|
||||
UObject o;
|
||||
try { o = lazy.Value; } catch { continue; }
|
||||
if (o is not UStaticMeshComponent c) continue;
|
||||
UStaticMesh? mesh;
|
||||
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { continue; }
|
||||
var lod = mesh?.RenderData?.LODs?.LastOrDefault(l => !l.SkipLod);
|
||||
if (mesh == null || lod == null) continue;
|
||||
var over = c.GetOrDefault<FPackageIndex[]>("OverrideMaterials", []);
|
||||
var inst = c is UInstancedStaticMeshComponent ism ? Math.Max(1, ism.PerInstanceSMData?.Length ?? 1) : 1;
|
||||
foreach (var sec in lod.Sections)
|
||||
{
|
||||
var mi = sec.MaterialIndex;
|
||||
var idx = mi < over.Length && !over[mi].IsNull ? over[mi] : mi < mesh.StaticMaterials.Length ? mesh.StaticMaterials[mi].MaterialInterface : null;
|
||||
UMaterialInterface? m = null;
|
||||
try { m = idx?.Load<UMaterialInterface>(); } catch { }
|
||||
var key = m?.GetPathName() ?? "(none)";
|
||||
if (m != null) mats[key] = m;
|
||||
tris[key] = tris.GetValueOrDefault(key) + sec.NumTriangles * (long)inst;
|
||||
}
|
||||
}
|
||||
}
|
||||
var texNames = new Dictionary<string, (int n, long t)>();
|
||||
var vecNames = new Dictionary<string, (int n, long t)>();
|
||||
var bases = new Dictionary<string, (int n, long t)>();
|
||||
long noDiffuse = 0, total = tris.Values.Sum();
|
||||
void Add(Dictionary<string, (int n, long t)> d, string k, long t) { var v = d.GetValueOrDefault(k); d[k] = (v.n + 1, v.t + t); }
|
||||
foreach (var (k, m) in mats)
|
||||
{
|
||||
var p = MatParams.Resolve(m);
|
||||
var t = tris[k];
|
||||
foreach (var n in p.Textures.Keys) Add(texNames, n, t);
|
||||
foreach (var n in p.Vectors.Keys) Add(vecNames, n, t);
|
||||
Add(bases, p.Base + " " + p.BlendMode, t);
|
||||
if (!p.Textures.Keys.Any(x => x.Contains("Diffuse", StringComparison.OrdinalIgnoreCase) || x.Contains("Albedo", StringComparison.OrdinalIgnoreCase) || x.Contains("Base Color", StringComparison.OrdinalIgnoreCase)))
|
||||
noDiffuse += t;
|
||||
}
|
||||
Console.WriteLine($"재질 {mats.Count} · 삼각형 {total} · 디퓨즈 없음 {noDiffuse * 100.0 / total:F1}% · 없음 {tris.GetValueOrDefault("(none)")}");
|
||||
Console.WriteLine("== 기본 재질"); foreach (var (k, v) in bases.OrderByDescending(x => x.Value.t).Take(40)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
|
||||
Console.WriteLine("== 텍스처"); foreach (var (k, v) in texNames.OrderByDescending(x => x.Value.t).Take(50)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
|
||||
Console.WriteLine("== 색"); foreach (var (k, v) in vecNames.OrderByDescending(x => x.Value.t).Take(50)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProbeAnim
|
||||
{
|
||||
public static void Anim(CUE4Parse.FileProvider.IFileProvider provider, string path)
|
||||
{
|
||||
var a = provider.LoadPackageObject<CUE4Parse.UE4.Assets.Exports.Animation.UAnimSequence>(path);
|
||||
var set = CUE4Parse_Conversion.Animations.AnimConverter.ConvertAnims(a);
|
||||
var seq = set.Sequences[0];
|
||||
var bones = set.Skeleton.ReferenceSkeleton.FinalRefBoneInfo;
|
||||
var keyed = seq.Tracks.Select((t, i) => (t, i)).Where(x => x.t.HasKeys() && (x.t.KeyQuat.Length > 1 || x.t.KeyPos.Length > 1)).Select(x => bones[x.i].Name.Text).ToList();
|
||||
Console.WriteLine($"{a.Name}: skeleton {set.Skeleton.Name} bones {bones.Length} frames {seq.NumFrames} fps {seq.FramesPerSecond:F1} len {a.SequenceLength:F2}s additive {seq.IsAdditive} animated {keyed.Count}: {string.Join(',', keyed.Take(80))}");
|
||||
}
|
||||
|
||||
public static void Skel(CUE4Parse.FileProvider.IFileProvider provider, string path)
|
||||
{
|
||||
var m = provider.LoadPackageObject<CUE4Parse.UE4.Assets.Exports.SkeletalMesh.USkeletalMesh>(path);
|
||||
var rs = m.ReferenceSkeleton;
|
||||
Console.WriteLine($"{m.Name}: bones {rs.FinalRefBoneInfo.Length} lods {m.LODModels?.Length} tris {string.Join('/', m.LODModels?.Select(l => l.Sections.Sum(s => s.NumTriangles)) ?? [])} mats {string.Join(',', m.SkeletalMaterials.Select(x => x.MaterialInterface?.Name))}");
|
||||
Console.WriteLine(string.Join(' ', rs.FinalRefBoneInfo.Select((b, i) => $"{i}:{b.Name.Text}<{b.ParentIndex}")));
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ using GvrMapExtract;
|
||||
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
|
||||
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
|
||||
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
|
||||
// GVR_TEX 텍스처 최대 크기 (기본 256)
|
||||
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
|
||||
|
||||
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
|
||||
@@ -96,9 +97,9 @@ switch (args[0])
|
||||
try
|
||||
{
|
||||
var r = MapScene.Build(provider, m);
|
||||
r.WriteGlb(Path.Combine(outDir, m.Code + ".glb"));
|
||||
r.WriteGlb(provider, Path.Combine(outDir, m.Code + ".glb"), int.Parse(Environment.GetEnvironmentVariable("GVR_TEX") ?? "256"));
|
||||
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}초");
|
||||
Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 재질 {r.Materials} · 텍스처 {r.TextureCount}({r.TextureBytes >> 20}MB, 실패 {r.TextureFailed}) · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -111,6 +112,73 @@ switch (args[0])
|
||||
Console.WriteLine($"끝: 맵 {maps.Count - (failed - findErrors)}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분");
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
case "mats":
|
||||
foreach (var m in MapScene.FindMaps(provider).Where(m => args.Skip(1).Contains(m.Code, StringComparer.OrdinalIgnoreCase))) Probe.Mats(provider, m);
|
||||
break;
|
||||
case "agents":
|
||||
{
|
||||
// 요원마다 agent_<코드>.glb + agents.json {캐릭터 클래스(Wushu_PC_C): {code, file, triangles}}
|
||||
var outDir = args[1];
|
||||
Directory.CreateDirectory(outDir);
|
||||
var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var maxTex = int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512");
|
||||
var lodWant = int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_LOD") ?? "1");
|
||||
var list = new SortedDictionary<string, object>();
|
||||
var failedAgents = 0;
|
||||
foreach (var (code, bp) in Agents.Find(provider).Where(a => want.Count == 0 || want.Contains(a.Code)))
|
||||
{
|
||||
var t0 = sw.Elapsed;
|
||||
try
|
||||
{
|
||||
var mesh = Agents.BodyMesh(provider, bp);
|
||||
if (mesh == null) { Console.WriteLine($"{code}: 3인칭 몸 없음 (건너뜀)"); continue; }
|
||||
var file = $"agent_{code}.glb";
|
||||
var r = Agents.Export(provider, mesh, Path.Combine(outDir, file), maxTex, lodWant);
|
||||
list[code + "_PC_C"] = new { code, file, mesh = mesh.Name, triangles = r.Triangles };
|
||||
Console.WriteLine($"{code}: {mesh.Name} 삼각형 {r.Triangles} · 뼈 {r.Bones} · 애니메이션 {r.Clips} · 텍스처 {r.Textures}({r.TextureBytes >> 10}KB) · {(sw.Elapsed - t0).TotalSeconds:F0}초");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failedAgents++;
|
||||
Console.WriteLine($"{code}: 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
// 무기 (기본 스킨): weapon_<이름>.glb
|
||||
var weapons = new SortedDictionary<string, object>();
|
||||
if (want.Count == 0 || want.Contains("weapons"))
|
||||
foreach (var (name, bp) in Weapons.List)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (wm, mag) = Weapons.Find(provider, bp);
|
||||
if (wm == null) { Console.WriteLine($"무기 {name}: 메시 없음"); continue; }
|
||||
var file = Weapons.FileName(name);
|
||||
var tris = Weapons.Export(provider, wm, mag, Path.Combine(outDir, file), maxTex);
|
||||
weapons[name] = new { file, mesh = wm.Name, triangles = tris, points = Weapons.Points };
|
||||
Console.WriteLine($"무기 {name}: {wm.Name}{(mag != null ? " + " + mag.Name : "")} 삼각형 {tris} {Weapons.Points?.ToJsonString()}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failedAgents++;
|
||||
Console.WriteLine($"무기 {name}: 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
}
|
||||
File.WriteAllText(Path.Combine(outDir, "agents.json"), System.Text.Json.JsonSerializer.Serialize(new { agents = list, weapons }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"끝: 요원 {list.Count} · 무기 {weapons.Count} · 실패 {failedAgents} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
|
||||
return failedAgents == 0 ? 0 : 1;
|
||||
}
|
||||
case "anim":
|
||||
foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a);
|
||||
break;
|
||||
case "skel":
|
||||
foreach (var a in args.Skip(1)) ProbeAnim.Skel(provider, a);
|
||||
break;
|
||||
case "json":
|
||||
// 패키지 내용 (조사용)
|
||||
foreach (var path in args.Skip(1))
|
||||
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(provider.LoadPackage(path).GetExports(), Newtonsoft.Json.Formatting.Indented));
|
||||
break;
|
||||
default:
|
||||
Console.Error.WriteLine("모르는 명령 " + args[0]);
|
||||
return 2;
|
||||
|
||||
80
tools/map-extract/src/TexStore.cs
Normal file
80
tools/map-extract/src/TexStore.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports.Texture;
|
||||
using CUE4Parse_Conversion.Textures;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.Formats.Png;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>게임 텍스처 → 작게 줄여 glb 이미지로 (같은 텍스처는 한 번만). 알파가 있으면 PNG, 없으면 JPEG</summary>
|
||||
public sealed class TexStore(IFileProvider provider, Glb glb, int maxSize)
|
||||
{
|
||||
private readonly Dictionary<string, (int tex, bool alpha)?> _done = new(StringComparer.OrdinalIgnoreCase);
|
||||
public int Count, Failed;
|
||||
public long Bytes;
|
||||
|
||||
public (int tex, bool alpha)? Get(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path)) return null;
|
||||
if (_done.TryGetValue(path, out var r)) return r;
|
||||
r = null;
|
||||
try
|
||||
{
|
||||
var t = provider.LoadPackageObject<UTexture>(path);
|
||||
var c = t.Decode(maxSize);
|
||||
using var img = c == null ? null : ToImage(c);
|
||||
if (img != null)
|
||||
{
|
||||
if (img.Width > maxSize || img.Height > maxSize)
|
||||
img.Mutate(x => x.Resize(new ResizeOptions { Size = new Size(maxSize, maxSize), Mode = ResizeMode.Max }));
|
||||
var alpha = HasAlpha(img);
|
||||
using var ms = new MemoryStream();
|
||||
if (alpha) img.SaveAsPng(ms, new PngEncoder { CompressionLevel = PngCompressionLevel.BestCompression });
|
||||
else img.SaveAsJpeg(ms, new JpegEncoder { Quality = 82 });
|
||||
r = (glb.Texture(ms.ToArray(), alpha ? "image/png" : "image/jpeg"), alpha);
|
||||
Count++;
|
||||
Bytes += ms.Length;
|
||||
}
|
||||
else Failed++;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Failed++;
|
||||
if (Failed <= 5) Console.Error.WriteLine($"텍스처 실패 {path}: {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
_done[path] = r;
|
||||
return r;
|
||||
}
|
||||
|
||||
private static Image<Rgba32>? ToImage(CTexture c)
|
||||
{
|
||||
var d = c.Data;
|
||||
var n = c.Width * c.Height;
|
||||
switch (c.PixelFormat)
|
||||
{
|
||||
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_R8G8B8A8:
|
||||
return d.Length >= n * 4 ? Image.LoadPixelData<Rgba32>(d.AsSpan(0, n * 4), c.Width, c.Height) : null;
|
||||
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_B8G8R8A8:
|
||||
return d.Length >= n * 4 ? Image.LoadPixelData<Bgra32>(d.AsSpan(0, n * 4), c.Width, c.Height).CloneAs<Rgba32>() : null;
|
||||
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_G8:
|
||||
return d.Length >= n ? Image.LoadPixelData<L8>(d.AsSpan(0, n), c.Width, c.Height).CloneAs<Rgba32>() : null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasAlpha(Image<Rgba32> img)
|
||||
{
|
||||
var any = false;
|
||||
img.ProcessPixelRows(a =>
|
||||
{
|
||||
for (var y = 0; y < a.Height && !any; y++)
|
||||
foreach (var p in a.GetRowSpan(y))
|
||||
if (p.A < 250) { any = true; break; }
|
||||
});
|
||||
return any;
|
||||
}
|
||||
}
|
||||
177
tools/map-extract/src/Weapons.cs
Normal file
177
tools/map-extract/src/Weapons.cs
Normal file
@@ -0,0 +1,177 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
using CUE4Parse.UE4.Objects.UObject;
|
||||
using CUE4Parse_Conversion.Dto;
|
||||
using CUE4Parse_Conversion.Options;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>
|
||||
/// 무기(기본 스킨) 3D: 총 몸(참조 자세) + 탄창을 정적 메시 glb 하나로. 원점 = 총 뿌리(요원 R_WeaponPoint 뼈에 붙인다).
|
||||
/// 이름은 리플레이 변환기 equipKinds 와 같다 (ValorantEquippableResolver 이름).
|
||||
/// </summary>
|
||||
public static class Weapons
|
||||
{
|
||||
public static readonly (string Name, string Blueprint)[] List =
|
||||
[
|
||||
("Classic", "/Game/Equippables/Guns/Sidearms/BasePistol/BasePistol"),
|
||||
("Shorty", "/Game/Equippables/Guns/Sidearms/Slim/SawedOffShotgun"),
|
||||
("Frenzy", "/Game/Equippables/Guns/Sidearms/AutoPistol/AutomaticPistol"),
|
||||
("Ghost", "/Game/Equippables/Guns/Sidearms/Luger/LugerPistol"),
|
||||
("Compact Pistol", "/Game/Equippables/Guns/Sidearms/Compact/CompactPistol"),
|
||||
("Sheriff", "/Game/Equippables/Guns/Sidearms/Revolver/RevolverPistol"),
|
||||
("Stinger", "/Game/Equippables/Guns/SubMachineGuns/Vector/Vector"),
|
||||
("Spectre", "/Game/Equippables/Guns/SubMachineGuns/MP5/SubMachineGun_MP5"),
|
||||
("Bucky", "/Game/Equippables/Guns/Shotguns/PumpShotgun/PumpShotgun"),
|
||||
("Judge", "/Game/Equippables/Guns/Shotguns/AutoShotgun/AutomaticShotgun"),
|
||||
("Bulldog", "/Game/Equippables/Guns/Rifles/Burst/AssaultRifle_Burst"),
|
||||
("Warden", "/Game/Equippables/Guns/Rifles/BattleRifle/BattleRifle"),
|
||||
("Guardian", "/Game/Equippables/Guns/SniperRifles/Dmr/DMR"),
|
||||
("Phantom", "/Game/Equippables/Guns/Rifles/Carbine/AssaultRifle_ACR"),
|
||||
("Vandal", "/Game/Equippables/Guns/Rifles/AK/AssaultRifle_AK"),
|
||||
("Marshal", "/Game/Equippables/Guns/SniperRifles/Leversniper/LeverSniperRifle"),
|
||||
("Operator", "/Game/Equippables/Guns/SniperRifles/Boltsniper/BoltSniper"),
|
||||
("Outlaw", "/Game/Equippables/Guns/SniperRifles/Doublesniper/DS_Gun"),
|
||||
("Ares", "/Game/Equippables/Guns/HvyMachineGuns/LMG/LightMachineGun"),
|
||||
("Odin", "/Game/Equippables/Guns/HvyMachineGuns/HMG/HeavyMachineGun"),
|
||||
("Melee", "/Game/Equippables/Melee/Ability_Melee_Base"),
|
||||
("Spike", "/Game/Equippables/Bomb/BombEquippable"),
|
||||
];
|
||||
|
||||
/// <summary>마지막으로 내보낸 무기의 맞출 점 (weapons 목록에 같이 쓴다)</summary>
|
||||
public static JsonObject? Points;
|
||||
|
||||
public static string FileName(string name) => "weapon_" + name.Replace(' ', '_') + ".glb";
|
||||
|
||||
/// <summary>블루프린트의 3인칭(없으면 아무) 스켈레탈 메시와 탄창(이름에 Magazine, 보조 탄창 제외)</summary>
|
||||
public static (USkeletalMesh? Mesh, UStaticMesh? Magazine) Find(IFileProvider provider, string blueprint)
|
||||
{
|
||||
var pkg = provider.LoadPackage(blueprint);
|
||||
USkeletalMesh? mesh = null;
|
||||
UStaticMesh? mag = null;
|
||||
foreach (var c in pkg.GetExports().OfType<USkeletalMeshComponent>().OrderByDescending(c => c.Name.Contains("3P")))
|
||||
{
|
||||
var idx = c.GetOrDefault<FPackageIndex?>("SkeletalMesh") ?? c.GetOrDefault<FPackageIndex?>("SkinnedAsset");
|
||||
if (idx is null || idx.IsNull) continue;
|
||||
try { mesh = idx.Load<USkeletalMesh>(); } catch { }
|
||||
if (mesh != null) break;
|
||||
}
|
||||
// 블루프린트에 메시가 없으면(스킨 데이터로 정하는 총) 기본 스킨 폴더의 GN_<이름>_S0_Skelmesh
|
||||
if (mesh == null)
|
||||
{
|
||||
var dir = "ShooterGame/Content" + blueprint["/Game".Length..blueprint.LastIndexOf('/')] + "/S0/1P/Models/";
|
||||
var re = new System.Text.RegularExpressions.Regex(@"/GN_[A-Za-z0-9]+_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var f = provider.Files.Keys.FirstOrDefault(k => k.StartsWith(dir, StringComparison.OrdinalIgnoreCase) && re.IsMatch(k));
|
||||
if (f != null)
|
||||
try { mesh = provider.LoadPackageObject<USkeletalMesh>("/Game" + f["ShooterGame/Content".Length..^".uasset".Length] + "." + Path.GetFileNameWithoutExtension(f)); } catch { }
|
||||
}
|
||||
foreach (var c in pkg.GetExports().OfType<UStaticMeshComponent>())
|
||||
{
|
||||
if (!c.Name.Contains("Magazine", StringComparison.OrdinalIgnoreCase) || c.Name.Contains("Secondary", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
try { mag = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { }
|
||||
if (mag != null) break;
|
||||
}
|
||||
return (mesh, mag);
|
||||
}
|
||||
|
||||
public static int Export(IFileProvider provider, USkeletalMesh mesh, UStaticMesh? magazine, string file, int maxTex)
|
||||
{
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var prims = new JsonArray();
|
||||
var tris = 0;
|
||||
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
|
||||
var lod = dto.LODs[0];
|
||||
var pos = new List<float>();
|
||||
var nrm = new List<float>();
|
||||
var uv = new List<float>();
|
||||
foreach (var v in lod.Vertices)
|
||||
{
|
||||
pos.AddRange([v.Position.X, v.Position.Y, v.Position.Z]);
|
||||
var n = new FVector(v.Normal.X, v.Normal.Y, v.Normal.Z);
|
||||
if (n.Size() > 1e-6f) n /= n.Size();
|
||||
nrm.AddRange([n.X, n.Y, n.Z]);
|
||||
uv.AddRange([v.Uv.U, v.Uv.V]);
|
||||
}
|
||||
var secs = lod.Sections.Where(s => s.IsValid && s.NumFaces > 0).Select(s => (s.FirstIndex, s.NumFaces, Mat: dto.Materials.ElementAtOrDefault(s.MaterialIndex).Material)).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, lod.Indices, secs);
|
||||
|
||||
// 탄창: 총 뼈 Magazine_Main 위치에
|
||||
if (magazine?.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is { } ml && ml.PositionVertexBuffer?.Verts is { Length: > 0 } mv && ml.IndexBuffer?.Buffer is { } mib)
|
||||
{
|
||||
var bi = Array.FindIndex(dto.Bones, b => b.Name.Equals("Magazine_Main", StringComparison.OrdinalIgnoreCase));
|
||||
var g = FTransform.Identity;
|
||||
for (var i = bi; i >= 0; i = dto.Bones[i].ParentIndex) g = g * dto.Bones[i].Transform;
|
||||
pos = []; nrm = []; uv = [];
|
||||
for (var i = 0; i < mv.Length; i++)
|
||||
{
|
||||
var p = g.TransformPosition(mv[i]);
|
||||
pos.AddRange([p.X, p.Y, p.Z]);
|
||||
var it = ml.VertexBuffer?.UV is { } u && i < u.Length ? u[i] : null;
|
||||
var n = it?.Normal is { Length: >= 3 } nn ? g.Rotation.RotateVector((FVector)nn[2]) : new FVector(0, 0, 1);
|
||||
nrm.AddRange([n.X, n.Y, n.Z]);
|
||||
uv.AddRange([it?.UV is { Length: > 0 } uu ? uu[0].U : 0, it?.UV is { Length: > 0 } uv2 ? uv2[0].V : 0]);
|
||||
}
|
||||
var msecs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < magazine.StaticMaterials.Length ? magazine.StaticMaterials[s.MaterialIndex].MaterialInterface : null))).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), msecs);
|
||||
}
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
|
||||
// 손에 쥘 때 맞출 점 (총 공간 cm): 총구 · 왼손 자리 (사이트가 오른손 = 원점, 왼손 = Left_Hand_Target 이 되게 놓는다)
|
||||
var extras = new JsonObject();
|
||||
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target"), ("root", "Root") })
|
||||
{
|
||||
var bi = Array.FindIndex(dto.Bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0) continue;
|
||||
var g = FTransform.Identity;
|
||||
for (var i = bi; i >= 0; i = dto.Bones[i].ParentIndex) g = g * dto.Bones[i].Transform;
|
||||
extras[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
|
||||
}
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = 0, ["extras"] = extras });
|
||||
Points = extras;
|
||||
glb.Write(file);
|
||||
return tris;
|
||||
}
|
||||
|
||||
private static int AddPrims(IFileProvider provider, Glb glb, TexStore tex, JsonArray prims, List<float> pos, List<float> nrm, List<float> uv, uint[] indices, List<(int First, int Faces, FPackageIndex? Mat)> secs)
|
||||
{
|
||||
var aPos = glb.Floats(pos.ToArray(), 3, bounds: true);
|
||||
var aNrm = glb.Floats(nrm.ToArray(), 3);
|
||||
var aUv = glb.Floats(uv.ToArray(), 2);
|
||||
var tris = 0;
|
||||
foreach (var (first, faces, matIdx) in secs)
|
||||
{
|
||||
UMaterialInterface? m = null;
|
||||
try { m = matIdx?.Load<UMaterialInterface>(); } catch { }
|
||||
var mp = m != null ? MatParams.Resolve(m) : null;
|
||||
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate")) continue;
|
||||
var texPath = mp == null ? null : new[] { "Diffuse", "DF", "Albedo", "Base Color", "BaseColor" }.Select(n => mp.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
|
||||
?? mp.Textures.FirstOrDefault(kv => kv.Value.Contains("_DF", StringComparison.OrdinalIgnoreCase)).Value;
|
||||
var t = tex.Get(texPath);
|
||||
var pbr = new JsonObject { ["metallicFactor"] = 0.2, ["roughnessFactor"] = 0.6 };
|
||||
if (t is { } tt) pbr["baseColorTexture"] = new JsonObject { ["index"] = tt.tex };
|
||||
else pbr["baseColorFactor"] = new JsonArray(0.3, 0.3, 0.32, 1);
|
||||
glb.Materials.Add(new JsonObject { ["name"] = m?.Name ?? "none", ["pbrMetallicRoughness"] = pbr });
|
||||
var idx = new uint[faces * 3];
|
||||
for (var f = 0; f < faces; f++)
|
||||
{
|
||||
idx[f * 3] = indices[first + f * 3];
|
||||
idx[f * 3 + 1] = indices[first + f * 3 + 2];
|
||||
idx[f * 3 + 2] = indices[first + f * 3 + 1];
|
||||
}
|
||||
tris += faces;
|
||||
prims.Add(new JsonObject
|
||||
{
|
||||
["attributes"] = new JsonObject { ["POSITION"] = aPos, ["NORMAL"] = aNrm, ["TEXCOORD_0"] = aUv },
|
||||
["indices"] = glb.Indices(idx),
|
||||
["material"] = glb.Materials.Count - 1,
|
||||
});
|
||||
}
|
||||
return tris;
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
private readonly Dictionary<uint, int> _closedAt = [];
|
||||
private readonly Dictionary<uint, uint> _objectOwner = [];
|
||||
private readonly Dictionary<string, int> _stats = [];
|
||||
// 들고 있는 것: 장비 액터 → 이름 (총은 파서 목록 이름, 나머지는 클래스 이름), 캐릭터별 바뀐 시각
|
||||
private readonly Dictionary<uint, string> _equipName = [];
|
||||
private readonly List<(int T, uint Character, uint Equip)> _equips = [];
|
||||
private readonly List<(int T, uint State, string Name)> _shotEquips = [];
|
||||
|
||||
private static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0);
|
||||
private static int R(double v) => (int)Math.Round(v);
|
||||
@@ -53,6 +57,8 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
if (s.ArchetypePath is { } arch)
|
||||
{
|
||||
_archetypeByActor[s.ActorNetGuid] = arch;
|
||||
if (ValorantEquippableResolver.TryResolve(s.ActorNetGuid, [s.ReplicationClassPath, s.ArchetypePath, s.ActorPath], out var eq) && eq.Name is { } en)
|
||||
_equipName[s.ActorNetGuid] = en;
|
||||
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)));
|
||||
@@ -83,6 +89,15 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
|
||||
_matchId ??= gs.MatchID;
|
||||
break;
|
||||
case AresInventoryDescriptor inv:
|
||||
{
|
||||
var ch = inv.HasDecoded(nameof(AresInventoryDescriptor.Character)) && inv.Character.NetGuid != 0 ? inv.Character.NetGuid : x.ActorNetGuid;
|
||||
uint eq = 0;
|
||||
if (inv.HasDecoded(nameof(AresInventoryDescriptor.CurrentEquippable))) eq = inv.CurrentEquippable.NetGuid;
|
||||
else if (inv.HasDecoded(nameof(AresInventoryDescriptor.NewCurrentEquippable))) eq = inv.NewCurrentEquippable.NetGuid;
|
||||
if (eq != 0) _equips.Add((Ms(x.TimeSeconds), ch, eq));
|
||||
break;
|
||||
}
|
||||
case BombPlayerStateDescriptor ps:
|
||||
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.Subject)) && !string.IsNullOrEmpty(ps.Subject))
|
||||
_subjectByState[x.ActorNetGuid] = ps.Subject!;
|
||||
@@ -105,6 +120,8 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
private void OnRpc(RpcReceived r)
|
||||
{
|
||||
var t = Ms(r.TimeSeconds);
|
||||
if (ValorantEquippableResolver.TryResolveClassNetCachePath(r.ClassPath, r.ActorNetGuid, out var eq) && eq.Name is { } en)
|
||||
_equipName.TryAdd(r.ActorNetGuid, en);
|
||||
switch (r.Payload)
|
||||
{
|
||||
case ClientGamePhaseBeginParameters p:
|
||||
@@ -152,6 +169,11 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
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)));
|
||||
if (shot.Equippable is { Name: { } en })
|
||||
{
|
||||
_shotEquips.Add((Ms(s.TimeSeconds), state, en));
|
||||
if (shot.Equippable.NetGuid != 0) _equipName.TryAdd(shot.Equippable.NetGuid, en);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Simplify(string archetype) => archetype.StartsWith("Default__") ? archetype[9..] : archetype;
|
||||
@@ -245,8 +267,41 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
|
||||
}
|
||||
|
||||
// 들고 있는 것: [t, 선수, 종류]. 같은 선수가 같은 것을 다시 들면 뺀다
|
||||
var equipKinds = new List<string>();
|
||||
var equipKindIndex = new Dictionary<string, int>();
|
||||
int EquipKind(string name)
|
||||
{
|
||||
if (!equipKindIndex.TryGetValue(name, out var k)) { k = equipKinds.Count; equipKinds.Add(name); equipKindIndex[name] = k; }
|
||||
return k;
|
||||
}
|
||||
var equipRows = new List<(int T, int P, string Name)>();
|
||||
foreach (var (t, ch, eq) in _equips)
|
||||
{
|
||||
if (!indexByCharacter.TryGetValue(ch, out var pi)) continue;
|
||||
var name = _equipName.TryGetValue(eq, out var n) ? n : _archetypeByActor.TryGetValue(eq, out var a) ? Simplify(a) : null;
|
||||
if (name != null) equipRows.Add((t, pi, name));
|
||||
}
|
||||
// 인벤토리 기록이 없는 선수는 사격 무기로 채운다
|
||||
var hasInv = equipRows.Select(e => e.P).ToHashSet();
|
||||
foreach (var (t, st, name) in _shotEquips)
|
||||
{
|
||||
var pi = PlayerOfState(st);
|
||||
if (pi >= 0 && !hasInv.Contains(pi)) equipRows.Add((t, pi, name));
|
||||
}
|
||||
var equips = new List<int[]>();
|
||||
var lastByPlayer = new Dictionary<int, string>();
|
||||
foreach (var e in equipRows.OrderBy(e => e.T))
|
||||
{
|
||||
if (lastByPlayer.TryGetValue(e.P, out var last) && last == e.Name) continue;
|
||||
lastByPlayer[e.P] = e.Name;
|
||||
equips.Add([e.T, e.P, EquipKind(e.Name)]);
|
||||
}
|
||||
|
||||
return new ReplayFile
|
||||
{
|
||||
Equips = equips,
|
||||
EquipKinds = equipKinds,
|
||||
MatchId = _matchId,
|
||||
Map = _map,
|
||||
Build = branch?.Replace("++Ares-Core+", ""),
|
||||
|
||||
@@ -26,6 +26,9 @@ public sealed class ReplayFile
|
||||
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
|
||||
public List<int[]> Objects { get; set; } = [];
|
||||
public List<string> ObjectKinds { get; set; } = [];
|
||||
/// 들고 있는 것이 바뀐 시각 [t, player, kind 번호]. 총은 영어 이름(Vandal 등), 칼은 Melee, 스파이크는 Spike, 스킬은 클래스 이름
|
||||
public List<int[]> Equips { get; set; } = [];
|
||||
public List<string> EquipKinds { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayPlayer
|
||||
|
||||
Reference in New Issue
Block a user