From 0c1e7261680ad073ec0c8863e8ab040ce2ca71e3 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sat, 17 Oct 2026 14:01:22 +0900 Subject: [PATCH] =?UTF-8?q?=EB=B0=9C=EB=A1=9C=EB=9E=80=ED=8A=B8=20?= =?UTF-8?q?=EB=A7=B5=203D:=20=EB=AA=A8=EB=93=A0=20=EB=A7=B5=EC=9D=84=20Rio?= =?UTF-8?q?t=20CDN=20=EC=97=90=EC=84=9C=20=EB=B0=94=EB=A1=9C=20=EC=B6=94?= =?UTF-8?q?=EC=B6=9C=ED=95=B4=203D=20=EB=A6=AC=ED=94=8C=EB=A0=88=EC=9D=B4?= =?UTF-8?q?=EC=97=90=20=EB=B6=99=EC=9E=84=20=C2=B7=20=EB=A7=A4=ED=95=91=20?= =?UTF-8?q?=EC=97=85=EB=8D=B0=EC=9D=B4=ED=8A=B8=20=EC=9E=90=EB=8F=99=20?= =?UTF-8?q?=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tools/map-extract (C#, CUE4Parse 고정 커밋): 게임 파일을 받지 않고 매니페스트 조각만 HTTP Range 로 읽어 맵 22개(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트)를 월드 좌표 glb 로. 3.1분 · 587MB 받음 - scripts/pack.py (gltfpack -cc + gzip, 맵당 0.5~4.6MB) · update.sh (uedb 매핑 · 라이브 패치 확인 → 매핑 보관 → 추출 → .5 data/maps3d 반영) · install.sh (systemd 사용자 타이머 30분, 메모리 6GB 상한) - 사이트 서버: GET /site/maps3d* (로그인 필요, gzip 그대로). CSP 에 'wasm-unsafe-eval' (meshopt 압축 풀기만) - 3D 재생기: 맵 3D 위에 선수 표시, 천장 자르기(자동 · 없음 · 직접), 높이 색칠. 맵이 없거나 실패하면 미니맵 - 리플레이 칸: 리플레이를 아직 안 보내는 앱 버전이면 그렇게 안내 - 테스트: maps3d.test.ts 2개, CSP 테스트 갱신 Co-Authored-By: Claude Opus 5.5 --- docs/dev/ARCHITECTURE.md | 4 +- docs/dev/replay-3d.md | 12 +- site/server/src/app.ts | 7 +- site/server/src/maps3d.ts | 63 +++++++ site/server/test/maps3d.test.ts | 80 ++++++++ site/server/test/security.test.ts | 2 +- site/web/mock/data.mjs | 2 +- site/web/mock/server.mjs | 12 ++ site/web/src/components/ReplayPanel.tsx | 6 +- site/web/src/components/ReplayViewer.tsx | 96 +++++++++- site/web/src/lib/map3d.ts | 94 ++++++++++ site/web/src/styles.css | 9 + tools/map-extract/.gitignore | 4 + tools/map-extract/MapExtract.csproj | 20 ++ tools/map-extract/fetch-cue4parse.sh | 15 ++ tools/map-extract/scripts/install.sh | 62 +++++++ tools/map-extract/scripts/pack.py | 33 ++++ tools/map-extract/scripts/preview.py | 43 +++++ tools/map-extract/scripts/update.sh | 107 +++++++++++ tools/map-extract/src/Cdn.cs | 220 ++++++++++++++++++++++ tools/map-extract/src/MapScene.cs | 225 +++++++++++++++++++++++ tools/map-extract/src/Program.cs | 124 +++++++++++++ tools/map-extract/src/Rman.cs | 119 ++++++++++++ 23 files changed, 1350 insertions(+), 9 deletions(-) create mode 100644 site/server/src/maps3d.ts create mode 100644 site/server/test/maps3d.test.ts create mode 100644 site/web/src/lib/map3d.ts create mode 100644 tools/map-extract/.gitignore create mode 100644 tools/map-extract/MapExtract.csproj create mode 100755 tools/map-extract/fetch-cue4parse.sh create mode 100755 tools/map-extract/scripts/install.sh create mode 100755 tools/map-extract/scripts/pack.py create mode 100755 tools/map-extract/scripts/preview.py create mode 100755 tools/map-extract/scripts/update.sh create mode 100644 tools/map-extract/src/Cdn.cs create mode 100644 tools/map-extract/src/MapScene.cs create mode 100644 tools/map-extract/src/Program.cs create mode 100644 tools/map-extract/src/Rman.cs diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index df9de89..995b583 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -200,7 +200,7 @@ type TimelineItem = | Path | 설명 | |---|---| | `GET /auth/discord` | OAuth2 시작 (`identify guilds`) | -| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키 | +| `GET /auth/discord/callback` | 코드 교환 → 봇 토큰으로 `GET /guilds/{GUILD_ID}/members/{uid}` 확인 → 세션 쿠키. GUILD_ID = 게임 PC 앱에서 녹음할 서버로 고른 서버 (앱이 hello 로 알려 줌, 그 전에는 ALLOWED_GUILD_IDS). 아니면 `/?login=not_member` ("봇과 다른 서버") | | `POST /auth/logout` | | | `GET /auth/me` | `{user:{id,name,avatar}, isOwner}` 또는 401 | | `GET /api/status` | `{device:{registered, online, name, lastSeen, version}, server:{version}}` (로그인 필요) | @@ -216,6 +216,8 @@ type TimelineItem = | `GET /app/admin/users` | 관리자 이상 → `{users: AppUserRow[]}` (최고 관리자 고정 행 포함) | | `POST /app/admin/users` · `PATCH`/`DELETE /app/admin/users/:id` | 최고 관리자만: 등록(`{id, role:'admin'|'user'}`, 디스코드에서 계정 확인) · 역할 변경 · 등록 해제 | | `GET /game-assets//` | valorant-api.com · ddragon · cdragon 이미지 캐시 프록시 | +| `GET /auth/guild` | 로그인 화면 안내용 `{name}`: 들어올 수 있는 서버 이름 | +| `GET /site/maps3d` · `GET /site/maps3d/:dir/:code.glb` | 로그인 필요. 발로란트 맵 3D (data/maps3d, `tools/map-extract`). glb 는 gzip 그대로 보낸다 | ## 8. 겜녹이 봇 중계 (v1.2.1~) diff --git a/docs/dev/replay-3d.md b/docs/dev/replay-3d.md index 0e074d5..05be379 100644 --- a/docs/dev/replay-3d.md +++ b/docs/dev/replay-3d.md @@ -10,9 +10,19 @@ - 13.08 실제 경기(73.8MB): 6초, JSON 5.3MB / gzip 1.4MB, 진단 0 - 사이트 `site/web/src/lib/replay.ts` (동기화 · 보간 · 죽음 판정), `components/ReplayViewer.tsx` (three.js, 지연 로드), `ReplayPanel.tsx` - 동기화: `ts = recordedAt + t + offset`, offset = 같은 킬(죽인/죽은 puuid)의 경기 기록 ts − 리플레이 시각의 중앙값. 킬이 3개 미만이면 라운드 교전 시작으로. - - 3D: 바닥은 미니맵, 선수는 실제 높이. 맵 벽 · 지형 3D 모델은 없음 (게임 파일 추출 필요 · 저작권 문제로 보류) + - 3D: 맵 3D 모양(아래 "맵 3D") 위에 선수를 실제 높이로. 맵 3D 가 없으면 미니맵 바닥 - 목 서버: `GVR_MOCK_REPLAY= GVR_MOCK_REPLAY_MAP_FILE=<어비스 png> npm run dev` → `/matches/val-replay-demo` (경기 기록 킬을 1234ms 늦게 찍어 동기화 확인) +## 맵 3D (2026-10-17, 모든 맵) +- `tools/map-extract/` (C#, CUE4Parse 고정 커밋 `fetch-cue4parse.sh`): **게임 파일을 받지 않고** Riot CDN 번들에서 필요한 조각만 HTTP Range 로 읽는다 (매니페스트 RMAN 파싱 `src/Rman.cs`, 원격 임의 읽기 `src/Cdn.cs`, 메모리 캐시 1.5GB, 디스크 안 씀). + - 맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록 맵 경로 `/Game/Maps/Ascent/Ascent` 와 같다). 하위 레벨 중 `LevelStreamingAlwaysLoaded` 이고 이름이 빛 · 소리 · 게임 규칙 · 부피 · 먼 배경 · 이벤트 장식이 아닌 것만 (`MapScene.NotVisual`). + - StaticMesh(+인스턴스) 가장 낮은 LOD 를 월드 좌표(cm)로 구워 맵마다 glb 하나 (위치 + 삼각형만, 재질 없음). 사이트가 높이로 색칠. + - 13.08 실측: 22개 맵(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트 1) 3.1분, 받은 양 587MB, 최대 메모리 약 1.9GB. `scripts/pack.py` → gltfpack `-cc` + gzip 으로 맵당 0.5~4.6MB (합계 52MB). +- 사이트: 서버 `data/maps3d/index.json` + `/.glb.gz`, `GET /site/maps3d*` (로그인 필요). 재생기 `lib/map3d.ts` 가 meshopt 로 풀어 리플레이와 같은 좌표 변환 행렬로 놓는다. 맵이 있으면 미니맵 바닥 · 선수 그림자는 숨긴다. + - meshopt 는 WebAssembly 라 CSP `script-src` 에 `'wasm-unsafe-eval'` 가 필요하다 (없으면 미니맵으로 대체됨, 헤드리스 크롬으로 둘 다 확인). + - 천장 자르기: 자동(고른 선수 · 없으면 가장 높은 산 선수 몸 중심 + 380cm 위를 자름) · 없음 · 직접(슬라이더). +- 자동 갱신: `scripts/install.sh` 가 `~/gvr-maps` 에 설치, `gvr-maps-update.timer` 30분마다 `update.sh`: uedb 매핑(버전 · 갱신 시각) 또는 라이브 매니페스트가 바뀌면 매핑을 받아 `~/gvr-maps/mappings/` + nextcloud `claude/game-voice-recorder/valorant/mappings/` 에 보관 → 전체 추출 → .5 `data/maps3d` 에 올리고 index.json 교체 (이전 폴더 1개만 남김). 실패하면 이전 맵 유지, 같은 조합은 다음 변경까지 다시 안 함. 결과는 이 방 채널에 한 줄 알림. 강제: `~/gvr-maps/scripts/update.sh --force`. + ## 남은 일 1. 앱: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `.vrf` 찾기 → `gvr-replay.exe` 실행 → `GVR-Data/replays/.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/` diff --git a/site/server/src/app.ts b/site/server/src/app.ts index 536aaf4..625f24d 100644 --- a/site/server/src/app.ts +++ b/site/server/src/app.ts @@ -10,6 +10,7 @@ import { BotBroker, type BotSource } from './bot-broker.js'; import { registerCulprit, type ModelCall } from './culprit.js'; import type { KnowledgeAuto } from './culprit-prompt.js'; import { avatarUrl, DiscordApi } from './discord.js'; +import { registerMaps3d } from './maps3d.js'; import { RateLimiter } from './rate-limit.js'; import { RelayHub } from './relay.js'; import { SiteLog } from './site-log.js'; @@ -50,10 +51,11 @@ export async function buildServer( // 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시) // CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게) + // 'wasm-unsafe-eval': 맵 3D 압축 풀기(meshopt, WebAssembly)만 허용. 자바스크립트 eval 은 여전히 막힌다 const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws'); const csp = [ "default-src 'self'", - "script-src 'self'", + "script-src 'self' 'wasm-unsafe-eval'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https://cdn.discordapp.com", "media-src 'self' blob: data:", @@ -296,6 +298,9 @@ export async function buildServer( return reply.send(buf); }); + // ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요) + registerMaps3d(app, cfg.dataDir, requireSession); + app.get('/healthz', async () => 'ok\n'); // ------------------------------------------------------------------ 사이트 화면 diff --git a/site/server/src/maps3d.ts b/site/server/src/maps3d.ts new file mode 100644 index 0000000..7f16b18 --- /dev/null +++ b/site/server/src/maps3d.ts @@ -0,0 +1,63 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; + +/** + * 발로란트 맵 3D 모양 (tools/map-extract 가 Riot CDN 에서 뽑아 tools/map-extract/scripts/update.sh 가 올린다). + * 게임 파일에서 나온 것이라 로그인한 사람(봇과 같은 서버 멤버)에게만 준다. + * + * /maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}} + * /maps3d//.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm) + * + * GET /site/maps3d → index.json (없으면 {maps:{}}) + * GET /site/maps3d/:dir/:f → glb (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다 + */ +export interface Maps3dIndex { + version: string; + dir: string; + updatedAt: string; + maps: Record; +} + +export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise) { + const root = path.join(dataDir, 'maps3d'); + let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null }; + const index = (): Maps3dIndex | null => { + const f = path.join(root, 'index.json'); + let st: fs.Stats; + try { + st = fs.statSync(f); + } catch { + return null; + } + if (st.mtimeMs !== cache.mtime) { + try { + cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(f, 'utf8')) as Maps3dIndex }; + } catch { + cache = { mtime: st.mtimeMs, data: null }; + } + } + return cache.data; + }; + + app.get('/site/maps3d', async (req, reply) => { + if (!(await requireSession(req, reply))) return; + reply.header('cache-control', 'private, no-cache'); + return index() ?? { version: null, dir: null, maps: {} }; + }); + + app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => { + if (!(await requireSession(req, reply))) return; + const { dir, file } = req.params; + if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+\.glb$/.test(file) || dir.includes('..')) return reply.code(404).send({ error: 'not_found' }); + const gz = path.join(root, dir, file + '.gz'); + if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' }); + reply.header('cache-control', 'private, max-age=31536000, immutable').type('model/gltf-binary'); + if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) { + reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size); + return reply.send(fs.createReadStream(gz)); + } + return reply.send(fs.createReadStream(gz).pipe(zlib.createGunzip())); + }); +} diff --git a/site/server/test/maps3d.test.ts b/site/server/test/maps3d.test.ts new file mode 100644 index 0000000..249523b --- /dev/null +++ b/site/server/test/maps3d.test.ts @@ -0,0 +1,80 @@ +// 맵 3D (/site/maps3d): 로그인한 사람에게만, gzip 그대로 보낸다 +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import { buildServer } from '../src/app.ts'; +import type { Config } from '../src/config.ts'; + +const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-maps3d-')); + +// member1 은 111 서버에만 있다. 222 서버 이름은 "앱 서버" +async function fakeDiscord() { + const srv = http.createServer((req, res) => { + const u = new URL(req.url!, 'http://x'); + res.setHeader('content-type', 'application/json'); + if (u.pathname === '/oauth2/token') return res.end(JSON.stringify({ access_token: 'at' })); + if (u.pathname === '/users/@me') return res.end(JSON.stringify({ id: 'member1', username: 'm', global_name: '멤버', avatar: null })); + if (u.pathname === '/guilds/111/members/member1') return res.end(JSON.stringify({ nick: '멤버', avatar: null })); + if (u.pathname === '/guilds/222') return res.end(JSON.stringify({ id: '222', name: '앱 서버' })); + res.statusCode = 404; + res.end('{}'); + }); + await new Promise((r) => srv.listen(0, '127.0.0.1', () => r())); + return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() }; +} + +async function stack() { + const dc = await fakeDiscord(); + const cfg: Config = { + port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot', + allowedGuilds: ['111'], owners: [], superAdmins: [], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent', + version: 'test', discordApi: dc.url, assetUpstream: {}, + }; + // 올려 둔 맵 3D (update.sh 가 만드는 모양) + const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test'))); + fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } })); + const { app, store } = await buildServer(cfg); + await app.listen({ host: '127.0.0.1', port: 0 }); + const base = `http://127.0.0.1:${(app.server.address() as any).port}`; + const login = async () => { + const start = await fetch(base + '/auth/discord', { redirect: 'manual' }); + const state = new URL(start.headers.get('location')!).searchParams.get('state')!; + const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' }); + return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!; + }; + return { base, store, login, close: async () => (await app.close(), dc.close()) }; +} + +test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => { + const s = await stack(); + try { + assert.equal((await fetch(s.base + '/site/maps3d')).status, 401); + assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb')).status, 401); + } finally { + await s.close(); + } +}); + +test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경로는 404', async () => { + const s = await stack(); + try { + const cookie = await s.login(); + const idx = await (await fetch(s.base + '/site/maps3d', { headers: { cookie } })).json(); + assert.equal(idx.dir, 'V1-1'); + assert.ok(idx.maps['/Game/Maps/Ascent/Ascent']); + const r = await fetch(s.base + '/site/maps3d/V1-1/Ascent.glb', { headers: { cookie, 'accept-encoding': 'gzip' } }); + assert.equal(r.status, 200); + assert.equal(r.headers.get('content-encoding'), 'gzip'); + assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다 + assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404); + assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404); + } finally { + await s.close(); + } +}); diff --git a/site/server/test/security.test.ts b/site/server/test/security.test.ts index 4505778..25cf45a 100644 --- a/site/server/test/security.test.ts +++ b/site/server/test/security.test.ts @@ -62,7 +62,7 @@ test('보안 헤더: CSP 는 이 사이트 스크립트 · 접속만 허용하 const r = await fetch(s.base + '/healthz'); const csp = r.headers.get('content-security-policy') ?? ''; assert.match(csp, /default-src 'self'/); - assert.match(csp, /script-src 'self'(;|$)/); + assert.match(csp, /script-src 'self' 'wasm-unsafe-eval'(;|$)/); // WebAssembly(맵 3D 압축 풀기)만, eval 은 안 됨 assert.match(csp, /connect-src 'self' wss:\/\/gvr\.example/); assert.match(csp, /frame-ancestors 'none'/); assert.equal(r.headers.get('x-content-type-options'), 'nosniff'); diff --git a/site/web/mock/data.mjs b/site/web/mock/data.mjs index c190c90..1697a70 100644 --- a/site/web/mock/data.mjs +++ b/site/web/mock/data.mjs @@ -573,7 +573,7 @@ function genReplayDemo(file) { events.push(...mEvents); const T = { xMultiplier: 8.1e-5, yMultiplier: -8.1e-5, xScalarToAdd: 0.5, yScalarToAdd: 0.5 }; const summary = { - id, game: 'valorant', startedAt: base, endedAt, map: { id: '224b0a95-48b9-f703-1bd8-67aca101a61f', name: '어비스', image: process.env.GVR_MOCK_REPLAY_MAP_FILE ? A('replay-map.png') : null }, + id, game: 'valorant', startedAt: base, endedAt, map: { id: '/Game/Maps/Infinity/Infinity', name: '어비스', image: process.env.GVR_MOCK_REPLAY_MAP_FILE ? A('replay-map.png') : null }, mode: '경쟁전', win: score.ally > score.enemy, score, status: 'complete', participants: SPEAKERS.map((u) => u.id), }; matches.push({ ...summary, players, rounds, events: mEvents, utterances: mUtts, mapTransform: { valorant: T }, replayPath: file }); diff --git a/site/web/mock/server.mjs b/site/web/mock/server.mjs index 3194f18..e8f67d8 100644 --- a/site/web/mock/server.mjs +++ b/site/web/mock/server.mjs @@ -181,6 +181,18 @@ async function handle(req, res) { return json(res, 200, { user: u, utterance: it.id }); } + // 맵 3D (GVR_MOCK_MAPS3D=<사이트 서버 data/maps3d 와 같은 구조의 폴더>: index.json + /.glb.gz) + if (p === '/site/maps3d' || p.startsWith('/site/maps3d/')) { + const root = process.env.GVR_MOCK_MAPS3D; + if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' }); + if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8'))); + const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent); + const f = path.join(root, dir ?? '', (file ?? '') + '.gz'); + if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+\.glb$/.test(file ?? '') || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' }); + res.writeHead(200, { 'content-type': 'model/gltf-binary', 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size }); + return fs.createReadStream(f).pipe(res); + } + // 게임 이미지 (목: docs/report/mock/assets) // 3D 리플레이 데모 바닥 미니맵 (GVR_MOCK_REPLAY_MAP_FILE, 데이터 생성은 data.mjs genReplayDemo) if (p === '/game-assets/mock/replay-map.png' && process.env.GVR_MOCK_REPLAY_MAP_FILE) { diff --git a/site/web/src/components/ReplayPanel.tsx b/site/web/src/components/ReplayPanel.tsx index f36849e..a5c7c8f 100644 --- a/site/web/src/components/ReplayPanel.tsx +++ b/site/web/src/components/ReplayPanel.tsx @@ -25,7 +25,9 @@ export function ReplayPanel({ m }: { m: MatchDetail }) { }; }, [open, m.id, replay]); const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]); - const missing = err instanceof ApiError && err.status === 404; + // replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음 + const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found'; + const appTooOld = err instanceof ApiError && err.status === 404 && err.code === 'Not Found'; // Fastify 기본 404 (경로 없음) return ( 이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림). + ) : appTooOld ? ( +
지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.
) : err ? (
리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}
) : !replay || !sync ? ( diff --git a/site/web/src/components/ReplayViewer.tsx b/site/web/src/components/ReplayViewer.tsx index 8878796..6bcb817 100644 --- a/site/web/src/components/ReplayViewer.tsx +++ b/site/web/src/components/ReplayViewer.tsx @@ -7,10 +7,12 @@ import { settings, useSettings } from '../store/settings'; import { useData } from '../store/app'; import { fmtClock } from '../lib/format'; import { isDead, roundAt, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay'; +import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d'; /** * 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON). - * 바닥은 미니맵, 선수는 실제 높이(z)에 세운다. 맵 벽 · 지형 3D 모델은 없다. + * 맵은 게임 파일에서 뽑은 3D 모양(tools/map-extract, 사이트 서버 /site/maps3d)을 쓰고, 없으면 미니맵 바닥만 깐다. + * 위에서 내려다볼 수 있게 천장 높이 위는 잘라 낸다 (자동: 고른 선수 · 가장 높은 선수 머리 위). * 시계는 플레이어 "현장 모드"(대화를 실제 시각대로 겹쳐 재생)와 같은 값을 쓴다: * 기록 시각 ts = recordedAt + t + sync.offset * 그래서 재생 · 멈춤 · 시간 옮기기 · 배속이 대화와 같이 움직인다. @@ -21,6 +23,12 @@ const VEX = 1; // 높이 배율 (1 = 실제 비율) const ALLY = 0x3fb6ff; const ENEMY = 0xff4d5e; const RATES = [0.5, 1, 1.5, 2]; +/** 자동 천장: 선수(몸 중심) 위로 이만큼(cm) 남기고 자른다 */ +const CEIL_ABOVE = 380; + +type MapState = { state: 'none' | 'loading' | 'ready' | 'error'; progress?: number }; +/** 천장 자르기: 자동 · 끔 · 직접(가장 낮은 층에서 cm) */ +type Ceil = { mode: 'auto' } | { mode: 'off' } | { mode: 'manual'; cm: number }; type T4 = { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }; @@ -85,6 +93,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) { selRef.current = sel; followRef.current = follow; const resetCam = useRef<() => void>(() => {}); + const [map3d, setMap3d] = useState({ state: 'none' }); + const [ceil, setCeil] = useState({ mode: 'auto' }); + const ceilRef = useRef(ceil); + ceilRef.current = ceil; + /** 지금 자르는 높이 (가장 낮은 층에서 cm, 화면 표시용) */ + const [ceilNow, setCeilNow] = useState(null); // 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다) const zBase = useMemo(() => { @@ -93,6 +107,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) { zs.sort((a, b) => a - b); return zs.length ? zs[Math.floor(zs.length * 0.05)] : 0; }, [replay]); + // 선수가 간 가장 높은 곳 (천장 직접 조절 범위) + const zTop = useMemo(() => { + let top = zBase; + for (const p of replay.players) for (let i = 0; i < p.track.z.length; i += 20) if (p.track.z[i] > top) top = p.track.z[i]; + return top; + }, [replay, zBase]); const T = (m.mapTransform && 'valorant' in m.mapTransform ? m.mapTransform.valorant : null) as T4 | null; // 리플레이 선수 ↔ 경기 기록 선수 (puuid) @@ -164,6 +184,35 @@ export default function ReplayViewer({ m, replay, sync }: Props) { grid.position.y = -0.05; scene.add(grid); + // 맵 3D 모양: 받으면 미니맵 바닥 · 선수 그림자를 숨긴다. 천장 위는 잘라 낸다 + renderer.localClippingEnabled = true; + const hPerCm = Math.abs(T.xMultiplier) * S * VEX; + const clip = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1e6); + let clipY = 1e6; + let mapReady = false; + const mapGroup = new THREE.Group(); + mapGroup.matrixAutoUpdate = false; + mapGroup.matrix.copy(worldMatrix(T, S, zBase, VEX)); + scene.add(mapGroup); + let disposed = false; + setMap3d({ state: 'loading', progress: 0 }); + void findMap3d(m.map.id) + .then((info) => { + if (disposed) return; + if (!info) return setMap3d({ state: 'none' }); + const mat = mapMaterial(clip, { lo: 0, hi: Math.max(8, (zTop - zBase + 600) * hPerCm) }); + return loadMap3d(info.url, mat, (p) => !disposed && setMap3d({ state: 'loading', progress: p })).then((obj) => { + if (disposed) return; + mapGroup.add(obj); + mapGroup.updateMatrixWorld(true); + mapReady = true; + floor.visible = false; + grid.visible = false; + setMap3d({ state: 'ready' }); + }); + }) + .catch(() => !disposed && setMap3d({ state: 'error' })); + // 선수 const views: PlayerView[] = roster.map((r) => { const color = r.ally ? ALLY : ENEMY; @@ -301,7 +350,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) { v.group.visible = v.drop.visible = v.shadow.visible = false; continue; } - v.group.visible = v.drop.visible = v.shadow.visible = true; + v.group.visible = true; + v.drop.visible = v.shadow.visible = !mapReady; v.group.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400), zBase)); v.shadow.position.set(v.group.position.x, 0.04, v.group.position.z); const dp = v.drop.geometry.getAttribute('position') as THREE.BufferAttribute; @@ -319,6 +369,19 @@ export default function ReplayViewer({ m, replay, sync }: Props) { v.voice.visible = speaking.has(v.idx) && !dead; v.ring.visible = v.idx === selIdx; } + // 천장 자르기 + const cm = ceilRef.current; + let want = 1e6; + if (mapReady && cm.mode === 'manual') want = cm.cm * hPerCm; + else if (mapReady && cm.mode === 'auto') { + const sv = selIdx != null ? views[selIdx] : null; + let top = -Infinity; + if (sv?.group.visible) top = sv.group.position.y; + else for (const v of views) if (v.group.visible && !isDead(replay, v.idx, t)) top = Math.max(top, v.group.position.y); + if (top > -Infinity) want = top + CEIL_ABOVE * hPerCm; + } + clipY = clipY > 1e5 || want > 1e5 ? want : clipY + (want - clipY) * 0.12; + clip.constant = clipY; // 경로 if (selIdx != null) { const tr = replay.players[selIdx].track; @@ -381,11 +444,16 @@ export default function ReplayViewer({ m, replay, sync }: Props) { renderer.render(scene, camera); if (now - lastUi > 100) { lastUi = now; + setCeilNow((c) => { + const v = clipY > 1e5 ? null : Math.round(clipY / hPerCm / 10) * 10; + return c === v ? c : v; + }); setUi((u) => (Math.abs(u.t - t) < 50 && u.playing === (inScene && ps.playing) ? u : { t, playing: inScene && ps.playing })); } }; raf = requestAnimationFrame(frame); return () => { + disposed = true; cancelAnimationFrame(raf); ro.disconnect(); renderer.domElement.removeEventListener('pointerdown', onDown); @@ -404,7 +472,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]); + }, [m, replay, base, roster, playerByUser, zBase, zTop]); const inScene = () => player.state.mode === 'scene' && player.state.scene?.label === REPLAY_SCENE_LABEL; const seek = (t: number) => { @@ -443,6 +511,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
{rd ? `R${rd.num}` : ''} {clock} {mr && · {mr.score.ally}:{mr.score.enemy} 후 {mr.win ? '승리' : '패배'}} + {map3d.state === 'loading' &&
맵 3D 불러오는 중 {Math.round((map3d.progress ?? 0) * 100)}%
} + {map3d.state === 'error' &&
맵 3D 를 불러오지 못해 미니맵으로 보여 줍니다
}
{feed.map(([kt, ki, vi]) => ( @@ -485,6 +555,26 @@ export default function ReplayViewer({ m, replay, sync }: Props) { + {map3d.state === 'ready' && ( + + + setCeil({ mode: 'manual', cm: Number(e.target.value) })} + aria-label="천장 높이" + /> + + )}
diff --git a/site/web/src/lib/map3d.ts b/site/web/src/lib/map3d.ts new file mode 100644 index 0000000..7e43d48 --- /dev/null +++ b/site/web/src/lib/map3d.ts @@ -0,0 +1,94 @@ +import * as THREE from 'three'; +import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; +import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js'; + +/** + * 발로란트 맵 3D 모양 (사이트 서버 /site/maps3d, 로그인 필요). + * glb 의 위치는 UE 월드 좌표(cm) 그대로다. 리플레이 선수 x,y,z 와 같은 좌표라 같은 변환으로 옮기면 겹친다. + */ +interface Index { + dir: string | null; + version: string | null; + maps: Record; +} + +let indexP: Promise | null = null; +function loadIndex(): Promise { + indexP ??= fetch('/site/maps3d', { credentials: 'same-origin' }) + .then((r) => (r.ok ? (r.json() as Promise) : null)) + .catch(() => null) + .then((d) => { + if (!d) indexP = null; // 실패하면 다음에 다시 + return d; + }); + return indexP; +} + +export interface Map3dInfo { + url: string; + bytes: number; + triangles: number; + version: string | null; +} + +/** 경기 맵 경로(/Game/Maps/Ascent/Ascent)의 3D 파일. 없으면 null. 폴더 대소문자는 게임 파일과 다를 수 있어 무시한다 */ +export async function findMap3d(mapUrl: string): Promise { + const idx = await loadIndex(); + if (!idx?.dir || !mapUrl) return null; + const key = mapUrl.toLowerCase(); + const hit = Object.entries(idx.maps).find(([k]) => k.toLowerCase() === key)?.[1]; + return hit ? { url: `/site/maps3d/${encodeURIComponent(idx.dir)}/${encodeURIComponent(hit.file)}`, bytes: hit.bytes, triangles: hit.triangles, version: idx.version } : null; +} + +/** glb 를 받아 메시 하나로. onProgress: 0~1 */ +export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p: number) => void): Promise { + const loader = new GLTFLoader(); + loader.setMeshoptDecoder(MeshoptDecoder); + return new Promise((resolve, reject) => { + loader.load( + url, + (gltf) => { + gltf.scene.traverse((o) => { + const mesh = o as THREE.Mesh; + if (mesh.isMesh) { + mesh.material = material; + mesh.frustumCulled = false; + } + }); + resolve(gltf.scene); + }, + (e) => onProgress?.(e.total ? e.loaded / e.total : 0), + reject, + ); + }); +} + +/** UE 월드 좌표(cm) → 3D 리플레이 화면 좌표. ReplayViewer 의 toWorld 와 같은 식을 행렬로 */ +export function worldMatrix(T: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, S: number, zBase: number, vex: number) { + const h = Math.abs(T.xMultiplier) * S * vex; + return new THREE.Matrix4().set( + 0, T.xMultiplier * S, 0, (T.xScalarToAdd - 0.5) * S, + 0, 0, h, -zBase * h, + T.yMultiplier * S, 0, 0, (T.yScalarToAdd - 0.5) * S, + 0, 0, 0, 1, + ); +} + +/** 높이에 따라 색이 바뀌는 맵 재질 (낮은 곳 푸른 회색 → 높은 곳 밝은 베이지). 천장 자르기 평면을 쓴다 */ +export function mapMaterial(clip: THREE.Plane, yRange: { lo: number; hi: number }) { + const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.92, metalness: 0, flatShading: true, side: THREE.DoubleSide, clippingPlanes: [clip], clipShadows: true }); + mat.onBeforeCompile = (sh) => { + sh.uniforms.uLo = { value: yRange.lo }; + sh.uniforms.uHi = { value: yRange.hi }; + sh.vertexShader = sh.vertexShader + .replace('#include ', '#include \nvarying float vH;') + .replace('#include ', '#include \nvH = (modelMatrix * vec4(transformed, 1.0)).y;'); + sh.fragmentShader = sh.fragmentShader + .replace('#include ', '#include \nvarying float vH;\nuniform float uLo;\nuniform float uHi;') + .replace( + 'vec4 diffuseColor = vec4( diffuse, opacity );', + 'float hN = clamp((vH - uLo) / max(uHi - uLo, 0.001), 0.0, 1.0);\nvec4 diffuseColor = vec4(mix(vec3(0.20, 0.25, 0.32), vec3(0.62, 0.57, 0.48), hN), opacity);', + ); + }; + return mat; +} diff --git a/site/web/src/styles.css b/site/web/src/styles.css index 3928420..f64618c 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -4070,3 +4070,12 @@ button.match:hover { .r3d-foot { font-size: 12px; } +.r3d-ceil { + display: inline-flex; + align-items: center; + gap: 6px; +} +.r3d-ceil input { + width: 90px; + accent-color: var(--accent); +} diff --git a/tools/map-extract/.gitignore b/tools/map-extract/.gitignore new file mode 100644 index 0000000..1fa5540 --- /dev/null +++ b/tools/map-extract/.gitignore @@ -0,0 +1,4 @@ +vendor/ +bin/ +obj/ +out/ diff --git a/tools/map-extract/MapExtract.csproj b/tools/map-extract/MapExtract.csproj new file mode 100644 index 0000000..e3b2878 --- /dev/null +++ b/tools/map-extract/MapExtract.csproj @@ -0,0 +1,20 @@ + + + + Exe + net10.0 + enable + enable + gvr-map-extract + true + false + false + false + + + + + + + diff --git a/tools/map-extract/fetch-cue4parse.sh b/tools/map-extract/fetch-cue4parse.sh new file mode 100755 index 0000000..d8884d2 --- /dev/null +++ b/tools/map-extract/fetch-cue4parse.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# CUE4Parse (Apache-2.0, https://github.com/FabianFG/CUE4Parse) 를 고정 커밋으로 받아 vendor/ 에 둔다. +# 발로란트 패치로 읽기가 깨지면 CUE4PARSE_COMMIT 을 새 커밋으로 올린다. +set -euo pipefail +CUE4PARSE_COMMIT="${CUE4PARSE_COMMIT:-605672df7a993a90094bad92d30c388d87ae6c1a}" +here="$(cd "$(dirname "$0")" && pwd)" +dst="$here/vendor/CUE4Parse" +if [ ! -d "$dst/.git" ]; then + git clone --quiet https://github.com/FabianFG/CUE4Parse "$dst" +fi +if [ "$(git -C "$dst" rev-parse HEAD)" != "$CUE4PARSE_COMMIT" ]; then + git -C "$dst" fetch --quiet origin + git -C "$dst" checkout --quiet --force "$CUE4PARSE_COMMIT" +fi +echo "CUE4Parse @ $(git -C "$dst" rev-parse --short HEAD)" diff --git a/tools/map-extract/scripts/install.sh b/tools/map-extract/scripts/install.sh new file mode 100755 index 0000000..4c38190 --- /dev/null +++ b/tools/map-extract/scripts/install.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# 맵 3D 자동 갱신을 이 리눅스 서버(.9)에 설치한다. 저장소에서: tools/map-extract/scripts/install.sh +# - gvr-map-extract 를 빌드해 $GVR_MAPS_HOME/bin 에 둔다 (저장소 작업 폴더가 바뀌어도 타이머는 그대로 돈다) +# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup +# 코드를 고쳤으면 다시 실행하면 된다. 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update +set -euo pipefail +here="$(cd "$(dirname "$0")/.." && pwd)" +GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}" +export PATH="$HOME/.dotnet:$PATH" DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DOTNET_CLI_TELEMETRY_OPTOUT=1 +"$here/fetch-cue4parse.sh" +rm -rf "$GVR_MAPS_HOME/bin.new" +CUE4PARSE_SKIP_NATIVE=1 dotnet build "$here/MapExtract.csproj" -c Release -o "$GVR_MAPS_HOME/bin.new" -v quiet -nologo -clp:ErrorsOnly +rm -rf "$GVR_MAPS_HOME/bin.old" +[ -d "$GVR_MAPS_HOME/bin" ] && mv "$GVR_MAPS_HOME/bin" "$GVR_MAPS_HOME/bin.old" +mv "$GVR_MAPS_HOME/bin.new" "$GVR_MAPS_HOME/bin" +# Oodle 압축 풀기 라이브러리: 처음 실행 때 받는다. 이전 설치에 있으면 옮겨 둔다 +[ -f "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" ] && cp "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" "$GVR_MAPS_HOME/bin/" +rm -rf "$GVR_MAPS_HOME/bin.old" +mkdir -p "$GVR_MAPS_HOME/scripts" +cp "$here/scripts/update.sh" "$here/scripts/pack.py" "$here/scripts/preview.py" "$GVR_MAPS_HOME/scripts/" +chmod +x "$GVR_MAPS_HOME/scripts/update.sh" + +unit="$HOME/.config/systemd/user" +mkdir -p "$unit" +node_dir="$(dirname "$(command -v node)")" +cat > "$unit/gvr-maps-update.service" < "$unit/gvr-maps-update.timer" <.glb + <코드>.json)를 사이트용으로 압축한다. + pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)> + 출력: <출력>//<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json + 사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts).""" +import datetime, gzip, json, os, re, shutil, subprocess, sys + +src, out, version = sys.argv[1], sys.argv[2], sys.argv[3] +stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M') +d = re.sub(r'[^\w.-]', '_', f'{version}-{stamp}') +os.makedirs(os.path.join(out, d), exist_ok=True) +maps = {} +for name in sorted(os.listdir(src)): + if not name.endswith('.json'): + continue + info = json.load(open(os.path.join(src, name))) + code = info['code'] + glb = os.path.join(src, code + '.glb') + if not os.path.exists(glb) or info.get('triangles', 0) == 0: + continue + packed = os.path.join(out, d, code + '.glb') + subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc'], check=True, stdout=subprocess.DEVNULL) + with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g: + shutil.copyfileobj(f, g) + os.remove(packed) + size = os.path.getsize(packed + '.gz') + maps[info['mapUrl']] = {'code': code, 'file': code + '.glb', 'bytes': size, 'triangles': info['triangles']} + print(f"{code}: {info['triangles']} 삼각형 → {size / 1e6:.1f}MB") +idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps} +tmp = os.path.join(out, 'index.json.tmp') +json.dump(idx, open(tmp, 'w'), ensure_ascii=False, indent=1) +os.replace(tmp, os.path.join(out, 'index.json')) +print(f'index.json: 맵 {len(maps)}개 · 폴더 {d}') diff --git a/tools/map-extract/scripts/preview.py b/tools/map-extract/scripts/preview.py new file mode 100755 index 0000000..83328b2 --- /dev/null +++ b/tools/map-extract/scripts/preview.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""추출한 맵 glb 를 위에서 본 그림(PNG)으로 그린다. 확인용. + preview.py <맵.glb> <출력.png> [천장 cm (이보다 높은 삼각형 제외)] + 삼각형마다 무게중심 · 꼭짓점을 찍고 높은 것이 위에 오게 칠한다 (빠른 근사).""" +import json, struct, sys +import numpy as np +from PIL import Image + +src, dst = sys.argv[1], sys.argv[2] +zmax = float(sys.argv[3]) if len(sys.argv) > 3 else None +b = open(src, 'rb').read() +jl = struct.unpack('= 0) & (x < W) & (y >= 0) & (y < H) +x, y, z, L = x[ok], y[ok], pts[ok, 2], L[ok] +order = np.argsort(z) # 낮은 것 먼저, 높은 것이 덮는다 +img = np.zeros((H, W, 3), np.float32) + np.array([18, 20, 26], np.float32) / 255 +zn = np.clip((z - lo[2]) / (hi[2] - lo[2] + 1e-9), 0, 1) +col = np.stack([0.35 + 0.45 * zn, 0.40 + 0.35 * zn, 0.55 - 0.15 * zn], 1) * L[:, None] +img[y[order], x[order]] = col[order] +Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8)).save(dst) +print(dst, W, H, 'triangles', len(T), 'z', lo[2].round(), hi[2].round()) diff --git a/tools/map-extract/scripts/update.sh b/tools/map-extract/scripts/update.sh new file mode 100755 index 0000000..fc719a0 --- /dev/null +++ b/tools/map-extract/scripts/update.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# 발로란트 맵 3D 자동 갱신 (systemd 타이머가 30분마다 실행, install.sh 참고) +# +# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝 +# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/ +# 3. 모든 맵을 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py) +# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다 +# +# 실패하면 사이트는 이전 맵을 그대로 쓴다. 같은 (매핑, 패치) 조합은 한 번 실패하면 다음 변경 때까지 다시 하지 않는다. +# 강제로 다시: update.sh --force +set -euo pipefail +GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}" +SITE_HOST="${SITE_HOST:-root@192.168.10.5}" +SITE_DATA="${SITE_DATA:-/root/other/game-voice-recorder/data}" +UEDB="https://uedb.dev/svc/api/v1/valorant/mappings" +SECRETS="${SECRETS:-$HOME/.config/ejclaw/secrets.json}" +export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" +BIN="$GVR_MAPS_HOME/bin/gvr-map-extract" +STATE="$GVR_MAPS_HOME/state.json" +mkdir -p "$GVR_MAPS_HOME/mappings" "$GVR_MAPS_HOME/work" +exec 9>"$GVR_MAPS_HOME/.lock" +flock -n 9 || { echo "이미 실행 중"; exit 0; } +log() { echo "[$(date '+%F %T')] $*"; } +# 결과 알림 (선택): NOTIFY_CHANNEL=<디스코드 채널 id>, NOTIFY_ENV= +notify() { + [ -n "${NOTIFY_CHANNEL:-}" ] && [ -f "${NOTIFY_ENV:-}" ] || return 0 + local token + token="$(grep -E '^DISCORD_OWNER_BOT_TOKEN=' "$NOTIFY_ENV" | head -1 | sed -E 's/^[^=]+=//' | tr -d '"'\''\r')" + [ -n "$token" ] || return 0 + curl -sS -o /dev/null --max-time 20 -X POST "https://discord.com/api/v10/channels/$NOTIFY_CHANNEL/messages" \ + -H "Authorization: Bot $token" -H 'Content-Type: application/json' \ + -d "$(jq -nc --arg c "$1" '{content:$c, allowed_mentions:{parse:[]}}')" || true +} +st() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])) if __import__("os").path.exists(sys.argv[1]) else {}; print(d.get(sys.argv[2],""))' "$STATE" "$1"; } +set_state() { python3 - "$STATE" "$@" <<'P' +import json, os, sys +f = sys.argv[1] +d = json.load(open(f)) if os.path.exists(f) else {} +for kv in sys.argv[2:]: + k, v = kv.split('=', 1) + d[k] = v +json.dump(d, open(f + '.tmp', 'w'), indent=1) +os.replace(f + '.tmp', f) +P +} + +# 1. 바뀐 것이 있나 +meta="$(curl -fsS --max-time 30 "$UEDB")" +version="$(jq -r .version <<<"$meta")" +updated="$(jq -r .updated <<<"$meta")" +usmap_url="$(jq -r '.mappings.Brotli // .mappings.ZStandard' <<<"$meta")" +[ -n "$version" ] && [ "$version" != null ] && [ -n "$usmap_url" ] && [ "$usmap_url" != null ] || { log "uedb 응답 이상: $meta"; exit 1; } +manifest="$("$BIN" manifest)" +key="$version|$updated|$manifest" +if [ "${1:-}" != "--force" ]; then + [ "$key" = "$(st published)" ] && { log "변경 없음 ($version, $(basename "$manifest"))"; exit 0; } + [ "$key" = "$(st failed)" ] && { log "이 조합은 이미 실패함, 다음 변경까지 대기 ($version, $(basename "$manifest"))"; exit 0; } +fi +log "새로 뽑기: 매핑 $version ($updated) · 패치 $(basename "$manifest")" + +# 2. 매핑 받기 · 보관 +stamp="$(date -u -d "$updated" +%Y%m%d%H%M 2>/dev/null || date -u +%Y%m%d%H%M)" +usmap="$GVR_MAPS_HOME/mappings/${version}_${stamp}_$(basename "$usmap_url" | sed 's/^.*_\(br\|zs\)\.usmap$/\1/').usmap" +if [ ! -s "$usmap" ]; then + curl -fsS --max-time 300 -o "$usmap.part" "$usmap_url" + mv "$usmap.part" "$usmap" + log "매핑 저장 $usmap ($(stat -c %s "$usmap") 바이트)" + # nextcloud 보관 (claude/ 폴더 안만 쓴다, 사용자 규칙) + if [ -f "$SECRETS" ]; then + read -r nc_host nc_user nc_token < <(python3 -c 'import json,sys; c=json.load(open(sys.argv[1]))["credentials"]["nextcloud.192.168.10.10"]; print(c["host"], c["username"], c["token"])' "$SECRETS") || true + if [ -n "${nc_token:-}" ]; then + dav="$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant/mappings" + curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant" >/dev/null 2>&1 || true + curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$dav" >/dev/null 2>&1 || true + if curl -fsS -u "$nc_user:$nc_token" -T "$usmap" "$dav/$(basename "$usmap")" >/dev/null; then log "nextcloud 보관 완료"; else log "nextcloud 보관 실패 (계속 진행)"; fi + fi + fi +fi + +# 3. 뽑기 · 압축 +raw="$GVR_MAPS_HOME/work/raw" +out="$GVR_MAPS_HOME/work/out" +rm -rf "$raw" "$out" +mkdir -p "$raw" "$out" +if ! GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"; then + set_state "failed=$key" "failedAt=$(date -Is)" + log "추출 실패 → 사이트는 이전 맵 유지" + notify "⚠️ 발로란트 맵 3D 자동 갱신 실패 (매핑 $version · 패치 $(basename "$manifest" .manifest)). 사이트는 이전 맵을 그대로 씁니다. 로그: journalctl --user -u gvr-maps-update" + exit 1 +fi +python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version" +dir="$(jq -r .dir "$out/index.json")" +count="$(jq '.maps | length' "$out/index.json")" +[ "$count" -gt 0 ] || { set_state "failed=$key"; log "맵 0개 → 올리지 않음"; exit 1; } + +# 4. 사이트 서버에 올리기 (폴더 먼저, index.json 은 마지막에 바꿔 끼움) +ssh -o BatchMode=yes "$SITE_HOST" "mkdir -p '$SITE_DATA/maps3d'" +tar -C "$out" -cf - "$dir" | ssh -o BatchMode=yes "$SITE_HOST" "tar -xf - -C '$SITE_DATA/maps3d'" +scp -q -o BatchMode=yes "$out/index.json" "$SITE_HOST:$SITE_DATA/maps3d/index.json.tmp" +prev="$(ssh -o BatchMode=yes "$SITE_HOST" "cat '$SITE_DATA/maps3d/index.json' 2>/dev/null" | jq -r '.dir // empty' 2>/dev/null || true)" +ssh -o BatchMode=yes "$SITE_HOST" "mv '$SITE_DATA/maps3d/index.json.tmp' '$SITE_DATA/maps3d/index.json'" +# 지금 것과 바로 전 것(이미 열어 둔 화면용)만 남긴다 +ssh -o BatchMode=yes "$SITE_HOST" "cd '$SITE_DATA/maps3d' && for d in */; do d=\${d%/}; [ \"\$d\" = '$dir' ] || [ \"\$d\" = '$prev' ] || rm -rf -- \"\$d\"; done" +set_state "published=$key" "publishedAt=$(date -Is)" "dir=$dir" "failed=" +rm -rf "$raw" "$out" +log "사이트 반영 완료: 맵 $count 개 · $dir" +notify "🗺️ 발로란트 맵 3D 자동 갱신: 매핑 $version · 맵 ${count}개를 사이트에 반영했습니다" diff --git a/tools/map-extract/src/Cdn.cs b/tools/map-extract/src/Cdn.cs new file mode 100644 index 0000000..5074242 --- /dev/null +++ b/tools/map-extract/src/Cdn.cs @@ -0,0 +1,220 @@ +using System.Net; +using System.Net.Http.Headers; +using CUE4Parse.UE4.Readers; +using CUE4Parse.UE4.Versions; + +namespace GvrMapExtract; + +/// Riot CDN 번들에서 매니페스트 조각을 필요할 때만 받는다 (HTTP Range). +/// 받은 조각은 압축을 풀어 메모리에 둔다 (오래 안 쓴 것부터 버림). 디스크는 쓰지 않는다. +public sealed class CdnStore(string bundleBase, long cacheBytes) +{ + private readonly HttpClient _http = new(new SocketsHttpHandler { MaxConnectionsPerServer = 8, AutomaticDecompression = DecompressionMethods.None }) + { + Timeout = TimeSpan.FromSeconds(90), + }; + private readonly object _lock = new(); + private readonly Dictionary<(ulong, uint), LinkedListNode<((ulong, uint) key, byte[] data)>> _map = new(); + private readonly LinkedList<((ulong, uint) key, byte[] data)> _lru = new(); + private readonly Dictionary<(ulong, uint), Task> _inflight = new(); + private long _cached; + public long DownloadedBytes; + public long Requests; + + private bool TryGet((ulong, uint) key, out byte[] data) + { + lock (_lock) + { + if (_map.TryGetValue(key, out var node)) + { + _lru.Remove(node); + _lru.AddFirst(node); + data = node.Value.data; + return true; + } + } + data = []; + return false; + } + + private void Put((ulong, uint) key, byte[] data) + { + lock (_lock) + { + if (_map.ContainsKey(key)) return; + _map[key] = _lru.AddFirst((key, data)); + _cached += data.Length; + while (_cached > cacheBytes && _lru.Last is { } last) + { + _lru.RemoveLast(); + _map.Remove(last.Value.key); + _cached -= last.Value.data.Length; + } + } + } + + /// 파일의 i 번째 조각. 없으면 뒤로 이어진 조각(같은 번들 · 연속 위치)까지 한 번에 받는다 + public byte[] Get(Rman.RFile f, int i) + { + var c = f.Chunks[i]; + var key = (c.BundleId, c.BundleOffset); + for (var attempt = 0; ; attempt++) + { + if (TryGet(key, out var hit)) return hit; + Task? wait; + TaskCompletionSource? mine = null; + lock (_lock) + { + if (!_inflight.TryGetValue(key, out wait)) + { + mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _inflight[key] = mine.Task; + } + } + if (mine == null) + { + try { wait!.Wait(); } catch { /* 받던 쪽이 실패하면 다시 시도 */ } + if (attempt > 4) throw new IOException("조각 받기 실패 (반복)"); + continue; + } + // 이어 받을 조각 범위 + var run = new List { i }; + long total = c.CompressedSize; + for (var j = i + 1; j < f.Chunks.Length && run.Count < 64 && total < 8 << 20; j++) + { + var n = f.Chunks[j]; + var prev = f.Chunks[j - 1]; + if (n.BundleId != c.BundleId || n.BundleOffset != prev.BundleOffset + prev.CompressedSize) break; + lock (_lock) if (_map.ContainsKey((n.BundleId, n.BundleOffset)) || _inflight.ContainsKey((n.BundleId, n.BundleOffset))) break; + run.Add(j); + total += n.CompressedSize; + } + lock (_lock) foreach (var j in run.Skip(1)) _inflight.TryAdd((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), mine.Task); + try + { + var raw = Fetch(c.BundleId, c.BundleOffset, total); + var pos = 0; + using var z = new ZstdSharp.Decompressor(); + foreach (var j in run) + { + var cj = f.Chunks[j]; + var outBuf = new byte[cj.UncompressedSize]; + var n = z.Unwrap(raw.AsSpan(pos, (int)cj.CompressedSize), outBuf); + if (n != cj.UncompressedSize) throw new IOException("조각 크기가 다름"); + pos += (int)cj.CompressedSize; + Put((cj.BundleId, cj.BundleOffset), outBuf); + } + mine.SetResult(); + } + catch (Exception e) + { + mine.SetException(e); + if (attempt > 4) throw; + } + finally + { + lock (_lock) foreach (var j in run) if (_inflight.TryGetValue((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), out var t) && t == mine.Task) _inflight.Remove((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset)); + } + } + } + + private byte[] Fetch(ulong bundle, uint offset, long length) + { + var url = $"{bundleBase}/{bundle:X16}.bundle"; + for (var attempt = 0; ; attempt++) + { + try + { + using var req = new HttpRequestMessage(HttpMethod.Get, url); + req.Headers.Range = new RangeHeaderValue(offset, offset + length - 1); + using var res = _http.Send(req, HttpCompletionOption.ResponseHeadersRead); + if (res.StatusCode != HttpStatusCode.PartialContent) throw new IOException($"{url} {(int)res.StatusCode}"); + using var s = res.Content.ReadAsStream(); + var buf = new byte[length]; + s.ReadExactly(buf); + Interlocked.Add(ref DownloadedBytes, length); + Interlocked.Increment(ref Requests); + return buf; + } + catch (Exception) when (attempt < 4) + { + Thread.Sleep(1000 * (attempt + 1)); + } + } + } + + public async Task GetBytes(string url) => await _http.GetByteArrayAsync(url); +} + +/// 매니페스트 파일 하나를 CUE4Parse 가 읽는 파일처럼 보이게 한다 (임의 위치 읽기) +public sealed class CdnArchive : FArchive +{ + private readonly CdnStore _store; + private readonly Rman.RFile _file; + private readonly long[] _starts; + + public CdnArchive(CdnStore store, Rman.RFile file, VersionContainer? versions) : base(versions) + { + _store = store; + _file = file; + _starts = file.Chunks.Select(c => c.FileOffset).ToArray(); + Name = file.Path; + } + + public override string Name { get; } + public override bool CanSeek => true; + public override long Length => _file.Size; + public override long Position { get; set; } + + public override int Read(byte[] buffer, int offset, int count) + { + var n = ReadAt(Position, buffer, offset, count); + Position += n; + return n; + } + + public override int ReadAt(long position, byte[] buffer, int offset, int count) + { + if (position >= Length) return 0; + count = (int)Math.Min(count, Length - position); + var done = 0; + var i = Array.BinarySearch(_starts, position); + if (i < 0) i = ~i - 1; + while (done < count) + { + var c = _file.Chunks[i]; + var data = _store.Get(_file, i); + var inChunk = (int)(position + done - c.FileOffset); + var n = Math.Min(count - done, data.Length - inChunk); + Buffer.BlockCopy(data, inChunk, buffer, offset + done, n); + done += n; + i++; + } + return done; + } + + public override Task ReadAtAsync(long position, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) + => Task.FromResult(ReadAt(position, buffer, offset, count)); + + public override ValueTask ReadAtAsync(long position, Memory memory, CancellationToken cancellationToken = default) + { + var tmp = new byte[memory.Length]; + var n = ReadAt(position, tmp, 0, tmp.Length); + tmp.AsSpan(0, n).CopyTo(memory.Span); + return ValueTask.FromResult(n); + } + + public override long Seek(long offset, SeekOrigin origin) + { + Position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => Position + offset, + SeekOrigin.End => Length + offset, + _ => throw new ArgumentOutOfRangeException(nameof(origin)), + }; + return Position; + } + + public override object Clone() => new CdnArchive(_store, _file, Versions) { Position = Position }; +} diff --git a/tools/map-extract/src/MapScene.cs b/tools/map-extract/src/MapScene.cs new file mode 100644 index 0000000..2a88aed --- /dev/null +++ b/tools/map-extract/src/MapScene.cs @@ -0,0 +1,225 @@ +using System.Text; +using CUE4Parse.FileProvider; +using CUE4Parse.UE4.Assets.Exports; +using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh; +using CUE4Parse.UE4.Assets.Exports.StaticMesh; +using CUE4Parse.UE4.Objects.Core.Math; + +namespace GvrMapExtract; + +/// 영구 레벨 이름 (Ascent, HURM_Alley …) +/// 경기 기록의 맵 경로 (/Game/Maps/Ascent/Ascent) +public sealed record MapInfo(string Code, string MapUrl, List Levels); + +/// 맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다. +/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다). +public sealed class MapScene +{ + public int Placements, Meshes, Failed, Skipped; + public long Triangles => _idx.Count / 3; + private readonly List _pos = new(); + private readonly List _idx = new(); + private readonly List _levels = new(); + private string _code = ""; + private string _mapUrl = ""; + + /// 맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록의 맵 경로 "/Game/Maps/Ascent/Ascent" 와 같다). + /// 연습장 · 튜토리얼 · 메뉴처럼 경기가 없는 곳은 뺀다 + public static List FindMaps(IFileProvider provider, Action? log = null) + { + var umaps = provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Maps/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".umap", StringComparison.OrdinalIgnoreCase)).ToList(); + var byDir = umaps.GroupBy(k => k[..k.LastIndexOf('/')]).ToDictionary(g => g.Key, g => g.Select(x => Path.GetFileNameWithoutExtension(x)).ToList()); + var res = new List(); + foreach (var k in umaps.OrderBy(x => x)) + { + var dir = k[..k.LastIndexOf('/')]; + var name = Path.GetFileNameWithoutExtension(k); + if (NotPlayable.Any(x => k.Contains(x, StringComparison.OrdinalIgnoreCase))) continue; + if (!byDir[dir].Any(o => o.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))) continue; + List<(string level, string cls, string props)> subs; + try { subs = StreamingLevels(provider, k); } catch (Exception e) { log?.Invoke($"{k}: 레벨 목록 실패 {e.Message}"); continue; } + var levels = subs.Where(x => x.cls == "LevelStreamingAlwaysLoaded" && IsVisualLevel(x.level)) + .Select(x => "ShooterGame/Content" + x.level["/Game".Length..] + ".umap") + .Where(provider.Files.ContainsKey).ToList(); + if (levels.Count == 0) continue; + levels.Insert(0, k); + res.Add(new MapInfo(name, "/Game" + k["ShooterGame/Content".Length..^".umap".Length], levels)); + } + return res; + } + + private static readonly string[] NotPlayable = ["/Poveglia", "/NPE", "/Menu/", "/Init/", "/Pregame", "_Copy/", "/SharedSubLevels/"]; + // 보이는 모양이 아닌 하위 레벨 (게임 규칙 · 빛 · 소리 · 부피 · 길찾기 · 카메라 · 효과 · 먼 배경 · 이벤트 장식) + private static readonly string[] NotVisual = ["Gameplay", "Lighting", "Volume", "NavMesh", "Audio", "Sound", "_BV", "Callout", "VFX", "_FX", "Vista", "Background", "Decal", + "Activation", "Birthday", "Snow", "LiveStory", "Sequence", "Camera", "Probe", "Profiling", "Greybox", "Blockout", "Design", "Layout", "Lanes", "Mode_", "Spawns_Proto", "SpawnPoints", "Skybox", "AuxiliaryZones", "KillVol", "Barrier", "Collider"]; + + /// 영구 레벨이 불러오는 하위 레벨들 (패키지 경로 · 형 · b 로 시작하는 속성) + public static List<(string level, string cls, string props)> StreamingLevels(IFileProvider provider, string umap) + { + var res = new List<(string, string, string)>(); + var pkg = provider.LoadPackage(umap); + var world = pkg.GetExports().OfType().FirstOrDefault(); + if (world?.StreamingLevels == null) return res; + foreach (var r in world.StreamingLevels) + { + var ls = r.Load(); + if (ls?.WorldAsset == null) continue; + var pkgName = ls.WorldAsset.Value.AssetPathName.Text.Split('.')[0]; + var props = string.Join(' ', ls.Properties.Where(p => p.Name.Text.StartsWith('b')).Select(p => $"{p.Name.Text}={p.Tag?.GenericValue}")); + res.Add((pkgName, ls.ExportType, props)); + } + return res; + } + + public static bool IsVisualLevel(string level) + { + var name = level[(level.LastIndexOf('/') + 1)..]; + return !NotVisual.Any(x => name.Contains(x, StringComparison.OrdinalIgnoreCase)); + } + + // 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다 + private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"]; + + public static MapScene Build(IFileProvider provider, MapInfo map) + { + var s = new MapScene { _code = map.Code, _mapUrl = map.MapUrl }; + var meshCache = new Dictionary(); + foreach (var level in map.Levels) + { + s._levels.Add(Path.GetFileNameWithoutExtension(level)); + var pkg = provider.LoadPackage(level); + foreach (var lazy in pkg.ExportsLazy) + { + UObject o; + try { o = lazy.Value; } catch { s.Failed++; continue; } + if (o is not UStaticMeshComponent c) continue; + if (c.GetOrDefault("bHiddenInGame") || !c.GetOrDefault("bVisible", true)) { s.Skipped++; continue; } + UStaticMesh? mesh; + try { mesh = c.GetStaticMesh()?.Load(); } catch { s.Failed++; continue; } + if (mesh == null) continue; + var path = mesh.GetPathName(); + if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; } + if (!meshCache.TryGetValue(path, out var geo)) + { + geo = Geometry(mesh); + meshCache[path] = geo; + if (geo != null) s.Meshes++; + } + if (geo == null) continue; + FTransform w; + try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; } + if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data) + foreach (var d in data) s.Add(geo.Value, d.TransformData * w); + else s.Add(geo.Value, w); + } + } + return s; + } + + /// 가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다) + private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh) + { + var lods = mesh.RenderData?.LODs; + if (lods == null) return null; + for (var l = lods.Length - 1; l >= 0; l--) + { + var lod = lods[l]; + if (lod.SkipLod || lod.PositionVertexBuffer?.Verts is not { Length: > 0 } v || lod.IndexBuffer?.Buffer is not { Length: > 0 } ib) continue; + var idx = new List(); + foreach (var sec in lod.Sections) + for (var k = 0; k < sec.NumTriangles * 3; k++) idx.Add(ib[sec.FirstIndex + k]); + return (v, idx.ToArray()); + } + return null; + } + + private void Add((FVector[] v, uint[] i) g, FTransform t) + { + Placements++; + var b = (uint)(_pos.Count / 3); + foreach (var p in g.v) + { + var w = t.TransformPosition(p); + _pos.Add(w.X); + _pos.Add(w.Y); + _pos.Add(w.Z); + } + // 크기가 음수(거울)면 삼각형 방향이 뒤집힌다 + var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z < 0; + for (var k = 0; k + 2 < g.i.Length; k += 3) + { + _idx.Add(b + g.i[k]); + _idx.Add(b + g.i[flip ? k + 2 : k + 1]); + _idx.Add(b + g.i[flip ? k + 1 : k + 2]); + } + } + + /// glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다 + public void WriteGlb(string file) + { + var pos = _pos.ToArray(); + var idx = _idx.ToArray(); + float[] min = [float.MaxValue, float.MaxValue, float.MaxValue], max = [float.MinValue, float.MinValue, float.MinValue]; + for (var i = 0; i < pos.Length; i++) + { + min[i % 3] = Math.Min(min[i % 3], pos[i]); + max[i % 3] = Math.Max(max[i % 3], pos[i]); + } + var posBytes = pos.Length * 4; + var idxBytes = idx.Length * 4; + var gltf = new + { + asset = new { version = "2.0", generator = "gvr-map-extract" }, + scene = 0, + scenes = new[] { new { nodes = new[] { 0 } } }, + nodes = new[] { new { mesh = 0, name = _code } }, + meshes = new[] { new { name = _code, primitives = new[] { new { attributes = new { POSITION = 0 }, indices = 1, mode = 4 } } } }, + accessors = new object[] + { + new { bufferView = 0, componentType = 5126, count = pos.Length / 3, type = "VEC3", min, max }, + new { bufferView = 1, componentType = 5125, count = idx.Length, type = "SCALAR" }, + }, + bufferViews = new[] + { + new { buffer = 0, byteOffset = 0, byteLength = posBytes, target = 34962 }, + new { buffer = 0, byteOffset = posBytes, byteLength = idxBytes, target = 34963 }, + }, + buffers = new[] { new { byteLength = posBytes + idxBytes } }, + }; + var json = Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(gltf)); + var jsonPad = (4 - json.Length % 4) % 4; + using var fs = File.Create(file); + using var w = new BinaryWriter(fs); + var total = 12 + 8 + json.Length + jsonPad + 8 + posBytes + idxBytes; + w.Write(0x46546C67u); // glTF + w.Write(2u); + w.Write((uint)total); + w.Write((uint)(json.Length + jsonPad)); + w.Write(0x4E4F534Au); // JSON + w.Write(json); + for (var i = 0; i < jsonPad; i++) w.Write((byte)' '); + w.Write((uint)(posBytes + idxBytes)); + w.Write(0x004E4942u); // BIN + foreach (var f in pos) w.Write(f); + foreach (var i in idx) w.Write(i); + } + + public void WriteInfo(string file, string manifest, string? usmap) + { + var info = new + { + code = _code, + mapUrl = _mapUrl, + levels = _levels, + placements = Placements, + meshes = Meshes, + triangles = Triangles, + skipped = Skipped, + failed = Failed, + manifest, + usmap = usmap == null ? null : Path.GetFileName(usmap), + extractedAt = DateTimeOffset.UtcNow.ToString("o"), + }; + File.WriteAllText(file, System.Text.Json.JsonSerializer.Serialize(info, new System.Text.Json.JsonSerializerOptions { WriteIndented = true })); + } +} diff --git a/tools/map-extract/src/Program.cs b/tools/map-extract/src/Program.cs new file mode 100644 index 0000000..488270e --- /dev/null +++ b/tools/map-extract/src/Program.cs @@ -0,0 +1,124 @@ +using Serilog; +using System.Diagnostics; +using System.Text.RegularExpressions; +using CUE4Parse; +using CUE4Parse.Compression; +using CUE4Parse.Encryption.Aes; +using CUE4Parse.FileProvider; +using CUE4Parse.MappingsProvider.Usmap; +using CUE4Parse.UE4.Objects.Core.Misc; +using CUE4Parse.UE4.Versions; +using GvrMapExtract; + +// gvr-map-extract: 발로란트 맵 3D 모양을 Riot CDN 에서 바로 뽑는다 (게임 설치 · 전체 다운로드 없음) +// +// gvr-map-extract ls <정규식> [개수] 파일 목록 +// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수) +// gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json +// +// 환경변수 +// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다 +// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다) +// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500) +// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다) + +Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger(); +CUE4ParseLog.UseLogger(Serilog.Log.Logger); + +const string AesKey = "0x4BE71AF2459CF83899EC9DC2CB60E22AC4B3047E0211034BBABE9D174C069DD6"; // 발로란트 공개 키 (모든 패치 같음) +const string BundleBase = "https://valorant.secure.dyn.riotcdn.net/channels/public/bundles"; +const string Patchlines = "https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines"; + +if (args.Length == 0) +{ + Console.Error.WriteLine("사용법: gvr-map-extract ls <정규식> | maps | extract <출력 폴더> [맵...] | manifest"); + return 2; +} +var sw = Stopwatch.StartNew(); +var store = new CdnStore(BundleBase, long.Parse(Environment.GetEnvironmentVariable("GVR_CACHE_MB") ?? "1500") << 20); +var manifestUrl = Environment.GetEnvironmentVariable("GVR_MANIFEST") ?? await LiveManifest(store); +if (args[0] == "manifest") +{ + Console.WriteLine(manifestUrl); + return 0; +} +var rman = Rman.Parse(await store.GetBytes(manifestUrl)); +Console.Error.WriteLine($"매니페스트 {manifestUrl} 파일 {rman.Files.Count}"); + +var oodle = Environment.GetEnvironmentVariable("GVR_OODLE") ?? Path.Combine(AppContext.BaseDirectory, OodleHelper.OodleFileName); +await OodleHelper.InitializeAsync(oodle); +var versions = new VersionContainer(EGame.GAME_Valorant); +var provider = new StreamedFileProvider("VALORANT", versions, StringComparer.OrdinalIgnoreCase); +provider.Initialize(); +foreach (var f in rman.Files.Values.Where(f => f.Path.StartsWith("ShooterGame/Content/Paks/", StringComparison.OrdinalIgnoreCase))) +{ + var ext = Path.GetExtension(f.Path).ToLowerInvariant(); + if (ext == ".utoc") + provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, open => + rman.Files.TryGetValue(open, out var c) ? new CdnArchive(store, c, versions) : throw new FileNotFoundException(open)); + else if (ext == ".pak") + provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, null); +} +provider.SubmitKey(new FGuid(), new FAesKey(AesKey)); +provider.PostMount(); +var usmap = Environment.GetEnvironmentVariable("GVR_USMAP"); +if (usmap != null) provider.MappingsContainer = new FileUsmapTypeMappingsProvider(usmap); +Console.Error.WriteLine($"파일 {provider.Files.Count} · 묶음 {provider.MountedVfs.Count} (못 연 것 {provider.UnloadedVfs.Count}) · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalSeconds:F0}초"); + +switch (args[0]) +{ + case "ls": + { + var re = new Regex(args[1], RegexOptions.IgnoreCase); + foreach (var k in provider.Files.Keys.Where(k => re.IsMatch(k)).OrderBy(k => k).Take(args.Length > 2 ? int.Parse(args[2]) : 200)) Console.WriteLine(k); + break; + } + case "levels": + foreach (var (lvl, cls, props) in MapScene.StreamingLevels(provider, args[1])) + Console.WriteLine($"{lvl}\t{cls}\t{props}"); + break; + case "maps": + foreach (var m in MapScene.FindMaps(provider, Console.Error.WriteLine)) Console.WriteLine($"{m.Code}\t{m.MapUrl}\t{m.Levels.Count}\t{string.Join(',', m.Levels.Select(Path.GetFileNameWithoutExtension))}"); + break; + case "extract": + { + var outDir = args[1]; + Directory.CreateDirectory(outDir); + var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase); + var maps = MapScene.FindMaps(provider, Console.Error.WriteLine).Where(m => want.Count == 0 || want.Contains(m.Code)).ToList(); + var failed = 0; + foreach (var m in maps) + { + var t0 = sw.Elapsed; + var d0 = store.DownloadedBytes; + try + { + var r = MapScene.Build(provider, m); + r.WriteGlb(Path.Combine(outDir, m.Code + ".glb")); + r.WriteInfo(Path.Combine(outDir, m.Code + ".json"), manifestUrl, usmap); + Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초"); + } + catch (Exception e) + { + failed++; + Console.WriteLine($"{m.Code}: 실패 {e.GetType().Name} {e.Message}"); + } + GC.Collect(); + } + Console.WriteLine($"끝: 맵 {maps.Count - failed}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분"); + return failed == 0 ? 0 : 1; + } + default: + Console.Error.WriteLine("모르는 명령 " + args[0]); + return 2; +} +return 0; + +static async Task LiveManifest(CdnStore store) +{ + var json = System.Text.Json.JsonDocument.Parse(await store.GetBytes(Patchlines)); + var live = json.RootElement.GetProperty("keystone.products.valorant.patchlines.live"); + foreach (var c in live.GetProperty("platforms").GetProperty("win").GetProperty("configurations").EnumerateArray()) + if (c.TryGetProperty("patch_url", out var u)) return u.GetString()!; + throw new InvalidOperationException("라이브 매니페스트를 못 찾음"); +} diff --git a/tools/map-extract/src/Rman.cs b/tools/map-extract/src/Rman.cs new file mode 100644 index 0000000..e3b971a --- /dev/null +++ b/tools/map-extract/src/Rman.cs @@ -0,0 +1,119 @@ +using System.Buffers.Binary; +using System.Text; + +namespace GvrMapExtract; + +/// Riot 매니페스트(.manifest, RMAN 2.x) 읽기. 본문은 zstd 로 압축된 FlatBuffers. +/// 구조는 Morilli/ManifestDownloader rman.c 를 따랐다. +public sealed class Rman +{ + public sealed record Chunk(ulong BundleId, uint BundleOffset, uint CompressedSize, uint UncompressedSize, long FileOffset); + public sealed record RFile(string Path, long Size, Chunk[] Chunks); + + public ulong ManifestId { get; private set; } + public Dictionary Files { get; } = new(StringComparer.OrdinalIgnoreCase); + + public static Rman Parse(byte[] data) + { + if (data.Length < 28 || Encoding.ASCII.GetString(data, 0, 4) != "RMAN") throw new InvalidDataException("RMAN 아님"); + if (data[4] != 2) throw new InvalidDataException($"모르는 매니페스트 버전 {data[4]}.{data[5]}"); + var contentOffset = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8)); + var compressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12)); + var r = new Rman { ManifestId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) }; + var uncompressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24)); + var body = new byte[uncompressedSize]; + using (var z = new ZstdSharp.Decompressor()) + { + var n = z.Unwrap(data.AsSpan((int)contentOffset, (int)compressedSize), body); + if (n != uncompressedSize) throw new InvalidDataException("매니페스트 압축 풀기 실패"); + } + r.ParseBody(new Fb(body)); + return r; + } + + private void ParseBody(Fb b) + { + var root = b.Root(); + // 번들 → 조각 (번들 안 위치는 앞 조각 크기의 누적) + var chunks = new Dictionary(); + foreach (var bt in b.Tables(root, 0)) + { + var bundleId = b.U64(bt, 0); + uint off = 0; + foreach (var ct in b.Tables(bt, 1)) + { + var comp = b.U32(ct, 1); + chunks[b.U64(ct, 0)] = (bundleId, off, comp, b.U32(ct, 2)); + off += comp; + } + } + // 폴더 + var dirs = new Dictionary(); + foreach (var dt in b.Tables(root, 3)) dirs[b.U64(dt, 0)] = (b.U64(dt, 1), b.Str(dt, 2)); + // 파일 + foreach (var ft in b.Tables(root, 2)) + { + var name = b.Str(ft, 3); + var dir = b.U64(ft, 1); + while (dir != 0 && dirs.TryGetValue(dir, out var d)) + { + if (d.name.Length > 0) name = d.name + "/" + name; + dir = d.parent; + } + var ids = b.U64Vector(ft, 7); + var list = new Chunk[ids.Length]; + long fo = 0; + for (var i = 0; i < ids.Length; i++) + { + var c = chunks[ids[i]]; + list[i] = new Chunk(c.bundle, c.off, c.comp, c.raw, fo); + fo += c.raw; + } + Files[name] = new RFile(name, (long)b.U64(ft, 2), list); + } + } + + /// 아주 작은 FlatBuffers 읽기 (필요한 형만) + private sealed class Fb(byte[] d) + { + private uint U32At(int p) => BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p)); + public int Root() => (int)U32At(0); + /// 테이블 필드 위치. 없으면 -1 + private int Field(int table, int idx) + { + var vt = table - BinaryPrimitives.ReadInt32LittleEndian(d.AsSpan(table)); + var vsize = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt)); + if (4 + idx * 2 >= vsize) return -1; + var off = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt + 4 + idx * 2)); + return off == 0 ? -1 : table + off; + } + private int Ref(int p) => p + (int)U32At(p); + public ulong U64(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(p)); } + public uint U32(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : U32At(p); } + public string Str(int t, int i) + { + var p = Field(t, i); + if (p < 0) return ""; + var v = Ref(p); + return Encoding.UTF8.GetString(d, v + 4, (int)U32At(v)); + } + public ulong[] U64Vector(int t, int i) + { + var p = Field(t, i); + if (p < 0) return []; + var v = Ref(p); + var n = (int)U32At(v); + var a = new ulong[n]; + for (var k = 0; k < n; k++) a[k] = BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(v + 4 + k * 8)); + return a; + } + public IEnumerable Tables(int t, int i) + { + var p = Field(t, i); + if (p < 0) yield break; + var v = Ref(p); + var n = (int)U32At(v); + for (var k = 0; k < n; k++) yield return Ref(v + 4 + k * 4); + } + } +}