Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96fb41748b | ||
|
|
309974087b | ||
|
|
1fb8821663 | ||
|
|
88e043da28 | ||
|
|
626878e1d8 | ||
|
|
a69ed57a0f | ||
|
|
33e83256ed | ||
|
|
185e8c17bd | ||
|
|
37c898cd73 | ||
|
|
cd4b7cb16f | ||
|
|
dc36d094e9 | ||
|
|
a6cf73dee7 | ||
|
|
ac70f7ce1f |
@@ -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.7.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.7.0) (`GameVoiceRecorder-1.7.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.7.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)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.8.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.8.1) (`GameVoiceRecorder-1.8.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.8.1-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~)
|
||||
|
||||
|
||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.0",
|
||||
"version": "1.8.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.0",
|
||||
"version": "1.8.2",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.8.0",
|
||||
"version": "1.8.2",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
@@ -189,6 +189,7 @@ export async function startCore(opts: CoreOptions) {
|
||||
relay.stop();
|
||||
retention.stop();
|
||||
games.stop();
|
||||
stt.stop();
|
||||
await bot.stop();
|
||||
await worker.stop();
|
||||
await api.close();
|
||||
|
||||
@@ -81,6 +81,8 @@ export class SttPipeline {
|
||||
private queued = new Set<string>();
|
||||
private busy = false;
|
||||
private processing: string | null = null;
|
||||
/** 앱 종료 중: 새 작업을 꺼내지 않고, 워커가 끊겨 실패한 작업은 DB(곧 닫힘)에 기록하지 않는다. 남은 발화는 다음 시작 때 다시 처리 */
|
||||
private stopped = false;
|
||||
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
|
||||
onDone: ((id: string) => void) | null = null;
|
||||
/** 예전 녹음 고치기가 끝났을 때 */
|
||||
@@ -238,8 +240,13 @@ export class SttPipeline {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 종료 시작 (워커 · DB 를 닫기 전에 부른다) */
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
if (this.busy || !this.worker.ready) return;
|
||||
if (this.stopped || this.busy || !this.worker.ready) return;
|
||||
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
|
||||
if (idx < 0) return;
|
||||
const job = this.queue.splice(idx, 1)[0];
|
||||
@@ -254,6 +261,7 @@ export class SttPipeline {
|
||||
this.busy = false;
|
||||
this.processing = null;
|
||||
this.status.processing = null;
|
||||
if (this.stopped) return;
|
||||
try {
|
||||
if (!this.isBusy(job.id)) this.onDone?.(job.id);
|
||||
} catch (e) {
|
||||
@@ -320,6 +328,7 @@ export class SttPipeline {
|
||||
5 * 60000,
|
||||
);
|
||||
} catch (e: any) {
|
||||
if (this.stopped) return;
|
||||
const attempts = this.store.bumpAttempt(u.id);
|
||||
this.status.lastError = e.message;
|
||||
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);
|
||||
@@ -331,6 +340,8 @@ export class SttPipeline {
|
||||
} else this.enqueue(u.id, job.slot, job.prio + 2);
|
||||
return;
|
||||
}
|
||||
// 종료 중에 결과가 왔으면 버린다 (DB 가 이미 닫혔을 수 있다. 발화는 다음 시작 때 다시 처리)
|
||||
if (this.stopped) return;
|
||||
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
|
||||
if (!this.store.getUtterance(u.id)) return;
|
||||
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Finetuner } from './finetune.js';
|
||||
import type { AuthView } from './api-types.js';
|
||||
import { buildState, registerIpc } from './ipc.js';
|
||||
import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
|
||||
import { TrayShell } from './tray-shell.js';
|
||||
|
||||
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
|
||||
hardenTlsEnv();
|
||||
@@ -33,7 +34,7 @@ let ft: Finetuner | null = null;
|
||||
let settings: SettingsStore | null = null;
|
||||
let auth: AppAuth | null = null;
|
||||
let win: BrowserWindow | null = null;
|
||||
let tray: Tray | null = null;
|
||||
const trayShell = new TrayShell<Tray>();
|
||||
let quitting = false;
|
||||
const dataDir = resolveDataDir(opt('data-dir'));
|
||||
|
||||
@@ -148,6 +149,7 @@ function closeSplash(): void {
|
||||
}
|
||||
|
||||
function updateTray(): void {
|
||||
const tray = trayShell.get();
|
||||
if (!tray) return;
|
||||
if (!core) {
|
||||
tray.setImage(trayImage('off'));
|
||||
@@ -168,6 +170,7 @@ function updateTray(): void {
|
||||
}
|
||||
|
||||
function buildTrayMenu(): void {
|
||||
const tray = trayShell.get();
|
||||
if (!tray) return;
|
||||
if (!core) {
|
||||
tray.setContextMenu(
|
||||
@@ -203,7 +206,8 @@ async function quit(): Promise<void> {
|
||||
} catch (e) {
|
||||
log.error('종료 중 오류', e);
|
||||
}
|
||||
tray?.destroy();
|
||||
// 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다
|
||||
trayShell.dispose();
|
||||
app.exit(0);
|
||||
}
|
||||
|
||||
@@ -376,25 +380,26 @@ app.whenReady().then(async () => {
|
||||
if (starting) await starting;
|
||||
},
|
||||
});
|
||||
tray = new Tray(trayImage('off'));
|
||||
const tray = new Tray(trayImage('off'));
|
||||
tray.on('click', () => openWindow());
|
||||
trayShell.set(tray);
|
||||
refreshShell();
|
||||
a.on('change', onAuthChange);
|
||||
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
|
||||
let lastCheck = Date.now();
|
||||
const first = a.check();
|
||||
setInterval(() => {
|
||||
trayShell.every(15000, () => {
|
||||
const st = a.state.status;
|
||||
if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) {
|
||||
lastCheck = Date.now();
|
||||
void a.check().then(syncNames);
|
||||
}
|
||||
}, 15000);
|
||||
setInterval(() => {
|
||||
});
|
||||
trayShell.every(1500, () => {
|
||||
updateTray();
|
||||
buildTrayMenu();
|
||||
pushState();
|
||||
}, 1500);
|
||||
});
|
||||
splashText('로그인 확인 중…');
|
||||
await first;
|
||||
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');
|
||||
|
||||
31
app/src/main/tray-shell.ts
Normal file
31
app/src/main/tray-shell.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/** 트레이 아이콘과 그 갱신 타이머. 종료할 때 타이머를 먼저 멈추고 트레이를 없앤다 (v1.8.2: 'Tray is destroyed' 오류 창) */
|
||||
export interface TrayLike {
|
||||
isDestroyed(): boolean;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
export class TrayShell<T extends TrayLike> {
|
||||
private tray: T | null = null;
|
||||
private timers: NodeJS.Timeout[] = [];
|
||||
|
||||
set(tray: T): void {
|
||||
this.tray = tray;
|
||||
}
|
||||
|
||||
/** 쓸 수 있는 트레이 (없거나, 종료했거나, Windows 로그오프 등으로 Electron 이 먼저 없앴으면 null) */
|
||||
get(): T | null {
|
||||
return this.tray && !this.tray.isDestroyed() ? this.tray : null;
|
||||
}
|
||||
|
||||
every(ms: number, fn: () => void): void {
|
||||
this.timers.push(setInterval(fn, ms));
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const t of this.timers) clearInterval(t);
|
||||
this.timers = [];
|
||||
const tray = this.get();
|
||||
this.tray = null;
|
||||
tray?.destroy();
|
||||
}
|
||||
}
|
||||
142
app/test/stt-shutdown.test.ts
Normal file
142
app/test/stt-shutdown.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { SttPipeline } from '../src/core/stt/pipeline.ts';
|
||||
import { WorkerError } from '../src/core/stt/worker.ts';
|
||||
import { TrayShell } from '../src/main/tray-shell.ts';
|
||||
|
||||
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
|
||||
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
for (const id of ['s1', 's2']) {
|
||||
const f = path.join(dir, `${id}.ogg`);
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
|
||||
}
|
||||
const transcribing: string[] = [];
|
||||
let fail: ((e: Error) => void) | null = null;
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string, req: any) => {
|
||||
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
||||
if (op !== 'transcribe') return {};
|
||||
transcribing.push(path.basename(req.path, '.ogg'));
|
||||
return new Promise((_, rej) => (fail = rej));
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
||||
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
||||
await stt.load('realtime', 'm');
|
||||
const done: string[] = [];
|
||||
stt.onDone = (id) => {
|
||||
done.push(id);
|
||||
store.getUtterance(id); // 실제 앱의 녹음 파일 이름 맞추기도 DB 를 읽는다
|
||||
};
|
||||
stt.enqueue('s1', 'realtime');
|
||||
stt.enqueue('s2', 'realtime');
|
||||
assert.deepEqual(transcribing, ['s1']);
|
||||
|
||||
// core.stop 순서: stt.stop → 워커 종료 → DB 닫기 → (워커 프로세스 종료 이벤트로) 변환 요청 실패
|
||||
stt.stop();
|
||||
store.close();
|
||||
fail!(new WorkerError('worker_exit', '워커 종료'));
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
assert.deepEqual(done, [], '종료 중에는 변환 뒤 처리를 하지 않는다');
|
||||
assert.deepEqual(transcribing, ['s1']);
|
||||
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
|
||||
});
|
||||
|
||||
test('앱 종료: DB 를 닫은 뒤 변환 성공 응답이 와도 닫힌 DB 를 건드리지 않는다', async () => {
|
||||
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const f = path.join(dir, 's1.ogg');
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id: 's1', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
|
||||
let ok: ((r: unknown) => void) | null = null;
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string) => {
|
||||
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
|
||||
if (op !== 'transcribe') return {};
|
||||
return new Promise((res) => (ok = res));
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false } });
|
||||
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
||||
await stt.load('realtime', 'm');
|
||||
const errors: unknown[] = [];
|
||||
const done: string[] = [];
|
||||
stt.onDone = (id) => done.push(id);
|
||||
// run() 의 오류는 pump 의 catch 가 log.error 로만 남기므로, DB 접근을 감시한다
|
||||
const prepare = (store as any).db.prepare.bind((store as any).db);
|
||||
(store as any).db.prepare = (sql: string) => {
|
||||
try {
|
||||
return prepare(sql);
|
||||
} catch (e) {
|
||||
errors.push(e);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
stt.enqueue('s1', 'realtime');
|
||||
stt.stop();
|
||||
store.close();
|
||||
ok!({ text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 });
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
assert.deepEqual(errors, [], '닫힌 DB 에 접근하지 않는다');
|
||||
assert.deepEqual(done, []);
|
||||
});
|
||||
|
||||
test('트레이: 종료하면 갱신 타이머가 멈추고 트레이를 한 번만 없앤다 · 이미 없어진 트레이는 건드리지 않는다', (t) => {
|
||||
t.mock.timers.enable({ apis: ['setInterval'] });
|
||||
const fake = () => {
|
||||
const tr = { destroyed: false, destroys: 0, updates: 0, isDestroyed: () => tr.destroyed, destroy: () => ((tr.destroyed = true), tr.destroys++) };
|
||||
return tr;
|
||||
};
|
||||
// 갱신 함수는 main.ts 의 updateTray 처럼 shell.get() 으로 트레이를 얻는다 (없어진 트레이에 쓰면 Electron 이 던지는 것을 흉내)
|
||||
const shell = new TrayShell<ReturnType<typeof fake>>();
|
||||
let ticks = 0;
|
||||
const update = () => {
|
||||
ticks++;
|
||||
const tr = shell.get();
|
||||
if (!tr) return;
|
||||
if (tr.destroyed) throw new Error('Tray is destroyed');
|
||||
tr.updates++;
|
||||
};
|
||||
const a = fake();
|
||||
shell.set(a);
|
||||
shell.every(1500, update);
|
||||
t.mock.timers.tick(3000);
|
||||
assert.equal(a.updates, 2);
|
||||
shell.dispose();
|
||||
assert.equal(a.destroys, 1);
|
||||
assert.equal(shell.get(), null);
|
||||
t.mock.timers.tick(3000);
|
||||
assert.equal(a.updates, 2, '종료 뒤에는 갱신하지 않는다');
|
||||
assert.equal(ticks, 2, '종료하면 갱신 타이머가 멈춘다');
|
||||
shell.dispose();
|
||||
assert.equal(a.destroys, 1, '두 번 없애지 않는다');
|
||||
|
||||
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우
|
||||
const b = fake();
|
||||
const shell2 = new TrayShell<ReturnType<typeof fake>>();
|
||||
shell2.set(b);
|
||||
shell2.every(1500, () => {
|
||||
const tr = shell2.get();
|
||||
if (tr?.destroyed) throw new Error('Tray is destroyed');
|
||||
});
|
||||
b.destroyed = true;
|
||||
assert.equal(shell2.get(), null);
|
||||
assert.doesNotThrow(() => t.mock.timers.tick(1500));
|
||||
shell2.dispose();
|
||||
assert.equal(b.destroys, 0, '이미 없어진 트레이는 다시 없애지 않는다');
|
||||
});
|
||||
@@ -51,6 +51,33 @@
|
||||
- 개발 확인: 효과 하나만 따로 그리는 판(`~/.tmp/gvr/vfxHarness.ts` 를 `site/web/src/dev/` 에 잠시 두고 vite dev 에서 `import('/src/dev/vfxHarness.ts')`). 저장소에는 넣지 않았다.
|
||||
- 한계: 재질 그래프 근사라 색 · 무늬가 게임과 조금 다르다. 리본 · beam 일부, 화면 효과(섬광 눈부심 등)는 없다. 오멘 연막처럼 추출기가 클래스를 못 찾은 것은 예전 모양.
|
||||
|
||||
## 구운 조명 (2026-10-29, 실감 3단계)
|
||||
- 계기: aim.sheepu.dev(브라우저 발로란트 에임 연습장)의 맵이 게임처럼 보이는 이유를 보니 게임이 구워 둔 라이트맵(밝기 + SH 방향)을 그대로 쓴다. 우리 맵은 텍스처 × 장면 조명(하늘빛 + 해)이라 평평했다. 그 사이트 파일은 쓰지 않고 우리 추출기로 게임 파일에서 직접 뽑는다.
|
||||
- 게임 쪽: 레벨마다 `<레벨>_BuiltData` (UMapBuildDataRegistry). 컴포넌트 `LODData[0].MapBuildDataId` → FMeshMapBuildData → FLightMap2D (텍스처 · ScaleVectors/AddVectors · CoordinateScale/Bias), ISM 은 인스턴스마다 `PerInstanceLightmapData[i].LightmapUVBias` (HISM 은 `InstanceReorderTable`). 라이트맵 UV 채널은 메시 `LightMapCoordinateIndex`, LOD0 에만 있다 (구운 조명이 있는 배치는 LOD0, 삼각형은 거의 같다: 어센트 233만 → 235만).
|
||||
- HQ_Lightmap 텍스처(DXT5 1024²)는 위 절반 = 계수 0(UVW² · 로그 밝기), 아래 절반 = 계수 1(SH 방향 xyz · 밝기 나머지). 푸는 식은 UE `LightmapCommon.ush` GetLightMapColorHQ 와 같다. 햇빛 그림자까지 다 구워져 있다 (정적 조명).
|
||||
- 추출기 `src/Lightmaps.cs`: 메시가 차지한 칸마다 그 메시 범위로 풀어 irr(L·UVW·L0, sRGB/K) · sh(방향/L0, ±2) 두 장으로 → 칸 밖은 이웃 값으로 채움 → 1/2 씩 줄여 선반 쌓기 아틀라스(너비 `GVR_LIGHTMAP` 기본 2048, 넓이 약 그 제곱 안). 조명 없는 배치는 (0,0) 기본 칸(맵 평균 밝기).
|
||||
- glb: 모든 재질에 `occlusionTexture`(irr) · `emissiveTexture`(sh, 세기 0) 를 TEXCOORD_1 로, `extras.lightmap.k`. gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 옛 사이트는 aoMap 으로만 써서(어두워지기만) 깨지지 않는다.
|
||||
- pack.py 는 맵을 `-vtf`(UV 실수) 로: gltfpack 은 재질마다 TEXCOORD_0(반복, 수십 단위) · TEXCOORD_1 을 한 범위로 양자화해서 정수로 줄이면 라이트맵이 몇 텍셀씩 어긋난다.
|
||||
- 13.09 실측: 어센트 페이지 72 → 1864×1360(1/4) 2.5MB, 어비스 116 → 1864×2176(1/4) 3.4MB. 맵 압축 크기 어센트 14.7 → 18.8MB, 어비스 12.1 → 17.4MB.
|
||||
- 메모리: 배치를 모으는 동안은 칸 목록만 두고 Build 에서 페이지를 하나씩 풀어 바로 줄인다. 처음(모든 페이지를 원래 크기로 들고 있던 것)에는 페이지 200개 넘는 펄(Pitt)이 서비스 한도 6GB 에서 OutOfMemory 였다. 고친 뒤 펄 최대 2.7GB.
|
||||
- 사이트 `lib/map3d.ts` `installShader`: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 glb 법선 = UE 월드 법선 그대로), 0.8 위는 살짝 눌러 하얗게 날지 않게. 장면 조명은 맵에 쓰지 않는다 (요원 · 효과는 그대로 장면 조명).
|
||||
- 조사 명령: `gvr-map-extract lmprobe <레벨.umap>` (빌드 데이터 · 텍스처 · 연결 통계, `GVR_LM_DUMP=<폴더>` 면 라이트맵 png).
|
||||
- 13.09 전체 (2026-10-29 반영): 맵 23개 중 22개에 조명 (아이스박스 Port 는 BuiltData 에 라이트맵이 없어 예전 장면 조명), 아틀라스 1.2~4.7MB, 사이트 폴더 303 → 403MB. 맵 추출 26분 · 서비스 최대 메모리 5.9GB(스킬 재료 단계 포함).
|
||||
- 한계: 1/4 로 줄여 그림자 가장자리가 흐리다. 움직이는 것(요원)은 구운 조명을 받지 않는다 (볼륨 라이트맵은 아직 안 씀). 어비스 낭떠러지처럼 게임에서 어두운 곳은 그대로 어둡다.
|
||||
|
||||
## 1인칭 팔 · 총 · 조준점 (2026-10-29, 실감 4단계)
|
||||
- 계기: aim.sheepu.dev 훈련 화면(밴달 + 피닉스 팔 1인칭, 흰 십자 조준점, 탄흔 · 총소리)을 보고 우리 1인칭에 없던 것을 게임 파일에서 직접 뽑았다 (그 사이트 파일은 쓰지 않음).
|
||||
- 추출 `gvr-map-extract viewmodels <폴더>` (`src/Viewmodels.cs`, 13.09 전체 39초 · 최대 1.1GB):
|
||||
- `fparms_<코드>.glb` 요원 1인칭 팔 `Characters/<코드>/S0/1P/Models/FP_<코드>[_New]_S0_Skelmesh` (30명, 브리치는 `_New`). 팔 메시에 같이 든 스킬 · 3인칭 조각(재질 AB_ · ABTP_ · CS_ · TP_)은 뺀다 (네온 칼날 모양, 소바 활 장갑 등).
|
||||
- `fpweapon_<이름>.glb` 무기 1인칭 `<무기 폴더>/S0/1P/Models/(GN|EQ)_*_S0_Skelmesh` + 탄창(Magazine_Main 뼈 자식) + `GN_Core_*_S0_{Fire,Reload,Equip}` → gun_fire · gun_reload · gun_equip (22종, 칼 · 스파이크 포함).
|
||||
- `fpanim_<이름>.glb` 팔 동작(뼈 노드만, 공용 뼈대 `FP_Core_Retarget_Skelmesh`): `FP_Core_*_S0_` IdlePose|Idle · Fire|FireAdd · Reload · Equip · AltIdlePose(정조준) · WalkAdd · Activate(스파이크). 덧셈 동작은 CUE4Parse 가 기준 자세에 더해 준다.
|
||||
- 압축 합계 7.4MB, index.json `viewmodels`. update.sh 가 anims 다음에 돌린다.
|
||||
- 사이트 `lib/viewmodel.ts`: 맵과 따로 장면 하나(카메라 공간, 깊이를 지우고 맵 위에 그림). 무기 뿌리 = 팔 뼈 MasterWeapon × 회전 (0.5,−0.5,0.5,0.5) (총구 → 팔 앞, 탄창 → 아래가 되는 축 맞춤, 모든 총 같음). 눈 = 팔 Camera 뼈(대기 자세).
|
||||
- 자세는 시각만으로: 꺼내기(equips) > 재장전(states ReloadState) > 사격(shots, 60ms 총구 불꽃) > 걷기(0.2초에 30cm 넘게 움직임) > 정조준(ZoomState*) > 대기. 죽었거나 스킬 · 맨손이면 숨긴다.
|
||||
- 줌: 소총 등 1.25배, 저격총 2.5배(2단 5배) + 조준경 테두리(검은 원 · 가는 십자선), 저격 줌 중에는 팔 · 총을 숨긴다.
|
||||
- 조준점: 녹색 점 → 발로란트 기본 (흰 선 4개 · 가운데 틈 · 검은 외곽선). 1.8.2 부터 선수 조준점 · 내 조준점 (아래).
|
||||
- 안 한 것: 총소리 · 발소리(Wwise 사운드뱅크라 따로 풀어야 함), HUD 체력 · 탄약(리플레이에 값 없음), 탄흔(맞은 자리 `hits` 로 가능), 스킨(기본 스킨만), 스킬 1인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
|
||||
|
||||
## 남은 일
|
||||
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
|
||||
|
||||
@@ -69,3 +96,13 @@
|
||||
- 보관: nextcloud `claude/game-voice-recorder/valorant/13.08/` (nextcloud 에서는 `claude/` 폴더 안만 다룬다, 사용자 규칙) (abyss-13.08.tar.gz = glb · scene.json · 미리보기 · usmap · 도구 사본, usmap 단독). 계정은 secrets `nextcloud.192.168.10.10`.
|
||||
- 실험은 반드시 `systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0` 안에서.
|
||||
- 디스크: .9 는 150GB 이상 비워 둔다 (사용자 요청). 게임 파일은 다시 받을 수 있으므로 지웠다. 큰 결과물은 nextcloud(.10:8080)로 (로그인 정보 필요).
|
||||
|
||||
## 선수 조준점 · 내 조준점 (2026-10-29, v1.8.2)
|
||||
- 리플레이에 있다: `BombPlayerState` 에 선수마다 조준점 프로필이 복제된다 (관전자에게 보이는 조준점). 파서 형식에는 없어서 `gvr-replay <vrf> --fields` 로 필드 이름을 보고 찾았다.
|
||||
- 13.08 번호: 39~85 주 조준점, 86~132 정조준, 133~179 (값이 온 적 없음), 180~197 저격 조준경(가운데 점 색 · 크기 · 불투명도 · 표시) · `bUsePrimaryCrosshairForADS` · `bUseAdvancedOptions` · `ProfileName`.
|
||||
- 묶음 안 순서: 색 BGRA · 사용자 지정 색 BGRA · bUseCustomColor · 외곽선(켬 · 두께 · 색 · 불투명도) · 가운데 점(크기 · 불투명도 · 켬) · … · 안쪽 선 12개 · 바깥쪽 선 12개 (두께 · 길이 · 세로 길이 · 간격 · 세로 따로 · 이동 오차 · 사격 오차 · 최소 오차 · 불투명도 · 켬 · 사격 배율 · 이동 배율).
|
||||
- 기본값과 다를 때만 오고(색 흰색 255 · 숫자 0 · 끔), 바뀐 것만 다시 온다. 확인: 프로필 이름 "1 4 2 0" 선수 = 불투명도 1 · 길이 4 · 두께 2 · 간격 0, "점" 선수들 = 가운데 점만. 저격 점은 10명 모두 빨강(게임 기본).
|
||||
- 변환기 `src/Crosshair.cs`: 첫 읽기의 필드 목록에서 기준 번호를 찾고(이름이 모두 맞는 자리, 패치로 밀리면 ±80 안에서 찾음, 못 찾으면 조준점 없이 변환) 이 필드만 읽는 두 번째 읽기 (`IncludedPaths`, 어비스 리플레이 +0.4초). 출력 `players[].crosshair` = 바뀐 시각마다 전체 설정 (`t · name · primary · ads · sniper · adsFromPrimary · advanced`, color 는 실제 보이는 색).
|
||||
- 사이트 `lib/crosshair.ts` (그리기 · 발로란트 조준점 코드 읽기) · `components/CrosshairPanel.tsx`: 1인칭 "조준점" 버튼 → 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 내 조준점 직접 고치기 · 코드 가져오기 · 선수 조준점 복사. 설정은 브라우저 `gvr.settings.v1` `crosshair`.
|
||||
- 정조준(저격총 아님) 중에 고급 설정 + 정조준 조준점 따로면 ads, 저격 줌은 조준경 가운데 점. 사격 오차 · 이동 오차 켠 선은 쏜 뒤 0.35초 · 걷는 동안 벌어진다 (총마다 다른 실제 퍼짐이 아니라 대략).
|
||||
- 옛 리플레이 JSON 에는 없다. 앱은 버전이 바뀌면 다시 변환하므로 1.8.2 로 올리면 다음에 열 때 생긴다.
|
||||
|
||||
@@ -287,6 +287,20 @@ VOICE E2E PASS
|
||||
- 화면: 목 서버 + 헤드리스 크롬(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 에 새 버전 안내)
|
||||
|
||||
## v1.8.1 — 변환기: 무기 상태의 주인을 그 시각 주인으로 (2026-10-18)
|
||||
|
||||
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
|
||||
- 회귀 검사: `gvr-replay --self-test` (넘기기 전 · 넘긴 순간 · 뒤 · 첫 기록 전 · 기록 없음 · 순서 섞임 · 모르는 선수). 옛 동작(마지막 주인)으로 바꾸면 3개 실패하는 것 확인. Windows CI `replay_build` 에서 실행
|
||||
- 어비스 13.08 리플레이: 상태 16,974줄 중 1,189줄의 주인이 바뀜. 그중 그 시각 그 선수가 같은 무기를 들고 있던 비율 24% → 75%
|
||||
- Windows CI (a6cf73d, full) 8개 모두 PASS (self-test 통과 포함) → Gitea 릴리스 v1.8.1 (v1.8.0 · v1.7.0 에 새 버전 안내)
|
||||
|
||||
## v1.8.0 — 3D 리플레이 실감: 게임 스킬 효과 · 요원 동작 · 투사체 경로 (2026-10-18)
|
||||
|
||||
- 스킬 효과 추출기(`abilities`): 13.08 스킬 클래스 219 · 파티클 시스템 526 · 메시 377 · 텍스처 1064, 3.8분, 최대 메모리 1.7GB, 압축 41.8MB. 맵 · 요원 · 애니메이션과 함께 강제 갱신 13.9분 (서비스 최대 메모리 5.6GB, 상한 6GB) → .5 `data/maps3d/VALORANT_13.08-202610171648` (index.json `anims` · `abilities`)
|
||||
- 테스트: 앱 76 · 사이트 서버 30 통과, 타입 검사 · 화면 빌드 통과
|
||||
- 화면: 효과 하나씩 그리는 판 + 목 서버(사이트와 같은 CSP 미리보기, 오류 0)로 브림스톤 · 오멘 · 아스트라 · 클로브 · 제트 연막, 브림스톤 · 피닉스 장판, 피닉스 · 케이오 · 브리치 · 스카이 섬광, 소바 화살 · 브림스톤 몰리 꼬리, 체임버 덫 · 소바 드론 · 킬조이 포탑/알람봇 · 사이퍼 덫 확인. 바이퍼 연막 · 세이지 벽처럼 효과를 못 뽑은 것은 예전 기본 모양
|
||||
- 배포: 사이트 서버 다시 배포 (화면 번들에 vfx 코드 확인), Windows CI (735783c, full) 8개 모두 PASS (변환기 어비스 리플레이 7.0초, 앱 smoke 실제 변환 8.3초 · gzip 1.60MB) · 앱 버전 1.8.0 → Gitea 릴리스 v1.8.0 (v1.7.0 에 새 버전 안내)
|
||||
|
||||
## v1.7.0 — 3D 리플레이 완전 3D: 맵 색 · 요원 · 총 · 스킬 모양 · 1인칭/자유시점 (2026-10-17)
|
||||
|
||||
- 맵 추출기: 재질 · 텍스처(256px) · 두 층 섞기 · 법선. 22개 맵 9.7분, 받은 양 961MB, 압축 합계 약 255MB (맵당 4~19MB). 요원 30명 · 총 22종 0.9분 (압축 6.4MB · 1.5MB). 갱신 서비스 최대 메모리 5.7GB (상한 6GB)
|
||||
|
||||
166
site/web/src/components/CrosshairPanel.tsx
Normal file
166
site/web/src/components/CrosshairPanel.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { CROSS_COLORS, DEFAULT_CROSSHAIR, drawCrosshair, parseCrosshairCode, prepCanvas, type CrossLines, type CrossSet, type CrosshairAt, type CrosshairProfile } from '../lib/crosshair';
|
||||
|
||||
/** 조준점 미리보기 (어두운 바탕) */
|
||||
function Preview({ set }: { set: CrossSet }) {
|
||||
const ref = useRef<HTMLCanvasElement>(null);
|
||||
useEffect(() => {
|
||||
const g = ref.current && prepCanvas(ref.current);
|
||||
if (g) drawCrosshair(g.ctx, g.cx, g.cy, set);
|
||||
}, [set]);
|
||||
return <canvas ref={ref} className="r3d-xprev" aria-label="조준점 미리보기" />;
|
||||
}
|
||||
|
||||
function Range({ label, value, min, max, step, onChange }: { label: string; value: number; min: number; max: number; step: number; onChange: (v: number) => void }) {
|
||||
return (
|
||||
<label className="r3d-xrow">
|
||||
<span>{label}</span>
|
||||
<input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} />
|
||||
<span className="mono">{step < 1 ? value.toFixed(2) : value}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Check({ label, value, onChange }: { label: string; value: boolean; onChange: (v: boolean) => void }) {
|
||||
return (
|
||||
<label className="r3d-xcheck">
|
||||
<input type="checkbox" checked={value} onChange={(e) => onChange(e.target.checked)} /> {label}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function LinesEdit({ title, l, maxOffset, onChange }: { title: string; l: CrossLines; maxOffset: number; onChange: (l: CrossLines) => void }) {
|
||||
const up = (p: Partial<CrossLines>) => onChange({ ...l, ...p, ...(p.length != null ? { vLength: p.length } : {}) });
|
||||
return (
|
||||
<fieldset className="r3d-xset">
|
||||
<legend>
|
||||
<Check label={title} value={l.on} onChange={(on) => up({ on })} />
|
||||
</legend>
|
||||
{l.on && (
|
||||
<>
|
||||
<Range label="불투명도" value={l.opacity} min={0} max={1} step={0.05} onChange={(opacity) => up({ opacity })} />
|
||||
<Range label="길이" value={l.length} min={0} max={20} step={1} onChange={(length) => up({ length })} />
|
||||
<Range label="두께" value={l.thickness} min={0} max={10} step={1} onChange={(thickness) => up({ thickness })} />
|
||||
<Range label="간격" value={l.offset} min={0} max={maxOffset} step={1} onChange={(offset) => up({ offset })} />
|
||||
<Check label="이동 오차" value={l.moveError} onChange={(moveError) => up({ moveError })} />
|
||||
<Check label="사격 오차" value={l.fireError} onChange={(fireError) => up({ fireError })} />
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1인칭 조준점 설정: 선수 조준점을 쓸지, 사이트 전체에 쓰는 내 조준점 (직접 고치기 · 발로란트 조준점 코드 가져오기).
|
||||
* 설정은 이 브라우저에 저장한다
|
||||
*/
|
||||
export default function CrosshairPanel({ playerName, player, hasAny, onClose }: { playerName: string | null; player: CrosshairAt | null; hasAny: boolean; onClose: () => void }) {
|
||||
const cfg = useSettings().crosshair;
|
||||
const mine = cfg.mine;
|
||||
const [code, setCode] = useState(cfg.code ?? '');
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const save = (p: Partial<typeof cfg>) => settings.set({ crosshair: { ...cfg, ...p } });
|
||||
const setMine = (m: CrosshairProfile, c?: string) => save({ mine: m, code: c });
|
||||
// 직접 고치면 정조준 조준점도 같이 (발로란트 '정조준에도 주 조준점')
|
||||
const upSet = (p: Partial<CrossSet>) => {
|
||||
const primary = { ...mine.primary, ...p };
|
||||
setMine({ ...mine, primary, ads: primary, adsFromPrimary: true });
|
||||
};
|
||||
const presetIdx = CROSS_COLORS.findIndex((c) => c.hex === mine.primary.color.toLowerCase());
|
||||
const importCode = () => {
|
||||
const p = parseCrosshairCode(code);
|
||||
if (!p) {
|
||||
setErr('조준점 코드 형식이 아닙니다 (예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0)');
|
||||
return;
|
||||
}
|
||||
setErr(null);
|
||||
setMine(p, code.trim());
|
||||
};
|
||||
const s = mine.primary;
|
||||
return (
|
||||
<div className="r3d-xpanel" role="dialog" aria-label="조준점 설정">
|
||||
<div className="r3d-xhead">
|
||||
<b>조준점</b>
|
||||
<button className="chip" onClick={onClose} aria-label="닫기">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<label className="r3d-xcheck">
|
||||
<input type="radio" name="xmode" checked={cfg.usePlayer} onChange={() => save({ usePlayer: true })} /> 선수 조준점 (리플레이에 없으면 내 조준점)
|
||||
</label>
|
||||
<label className="r3d-xcheck">
|
||||
<input type="radio" name="xmode" checked={!cfg.usePlayer} onChange={() => save({ usePlayer: false })} /> 모든 선수에 내 조준점
|
||||
</label>
|
||||
{player ? (
|
||||
<div className="r3d-xplayer">
|
||||
<Preview set={player.primary} />
|
||||
<div>
|
||||
<div className="small">
|
||||
{playerName ?? '이 선수'} 조준점{player.name ? <span className="muted"> · {player.name}</span> : null}
|
||||
</div>
|
||||
<button className="chip" onClick={() => setMine({ primary: player.primary, ads: player.ads, sniper: player.sniper, adsFromPrimary: player.adsFromPrimary, advanced: player.advanced })}>
|
||||
내 조준점으로 복사
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="muted small">
|
||||
{hasAny ? '이 선수는 조준점 기록이 없어 내 조준점을 씁니다.' : '이 리플레이에는 선수 조준점 기록이 없어 내 조준점을 씁니다. 게임 PC 앱을 1.8.2 이상으로 올리면 리플레이를 열 때 다시 변환해 기록이 생깁니다.'}
|
||||
</div>
|
||||
)}
|
||||
<div className="r3d-xmine">
|
||||
<div className="r3d-xhead">
|
||||
<b className="small">내 조준점</b>
|
||||
<button className="chip" onClick={() => setMine(DEFAULT_CROSSHAIR)} title="발로란트 기본 조준점으로">
|
||||
기본값
|
||||
</button>
|
||||
</div>
|
||||
<Preview set={s} />
|
||||
<div className="r3d-xcode">
|
||||
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="발로란트 조준점 코드 붙여넣기" aria-label="조준점 코드" onKeyDown={(e) => e.key === 'Enter' && importCode()} />
|
||||
<button className="chip" onClick={importCode}>
|
||||
가져오기
|
||||
</button>
|
||||
</div>
|
||||
{err && <div className="small r3d-xerr">{err}</div>}
|
||||
<label className="r3d-xrow">
|
||||
<span>색</span>
|
||||
<select value={presetIdx >= 0 ? presetIdx : -1} onChange={(e) => Number(e.target.value) >= 0 && upSet({ color: CROSS_COLORS[Number(e.target.value)].hex })}>
|
||||
{CROSS_COLORS.map((c, i) => (
|
||||
<option key={c.hex} value={i}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
<option value={-1}>사용자 지정</option>
|
||||
</select>
|
||||
<input type="color" value={s.color} onChange={(e) => upSet({ color: e.target.value })} aria-label="사용자 지정 색" />
|
||||
</label>
|
||||
<fieldset className="r3d-xset">
|
||||
<legend>
|
||||
<Check label="외곽선" value={s.outline} onChange={(outline) => upSet({ outline })} />
|
||||
</legend>
|
||||
{s.outline && (
|
||||
<>
|
||||
<Range label="불투명도" value={s.outlineOpacity} min={0} max={1} step={0.05} onChange={(outlineOpacity) => upSet({ outlineOpacity })} />
|
||||
<Range label="두께" value={s.outlineThickness} min={1} max={6} step={1} onChange={(outlineThickness) => upSet({ outlineThickness })} />
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
<fieldset className="r3d-xset">
|
||||
<legend>
|
||||
<Check label="가운데 점" value={s.dot} onChange={(dot) => upSet({ dot })} />
|
||||
</legend>
|
||||
{s.dot && (
|
||||
<>
|
||||
<Range label="불투명도" value={s.dotOpacity} min={0} max={1} step={0.05} onChange={(dotOpacity) => upSet({ dotOpacity })} />
|
||||
<Range label="두께" value={s.dotSize} min={1} max={6} step={1} onChange={(dotSize) => upSet({ dotSize })} />
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
<LinesEdit title="안쪽 선" l={s.inner} maxOffset={20} onChange={(inner) => upSet({ inner })} />
|
||||
<LinesEdit title="바깥쪽 선" l={s.outer} maxOffset={40} onChange={(outer) => upSet({ outer })} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,9 +6,12 @@ import { player } from '../store/player';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { useData } from '../store/app';
|
||||
import { fmtClock } from '../lib/format';
|
||||
import { equipAt, equipLabel, equipTracks, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { equipAt, equipLabel, equipTracks, indexAt, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
|
||||
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon } from '../lib/agents3d';
|
||||
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon, weaponCat } from '../lib/agents3d';
|
||||
import { Viewmodel, viewmodelIndex } from '../lib/viewmodel';
|
||||
import { crossFor, crosshairAt, drawCrosshair, drawSniperDot, prepCanvas } from '../lib/crosshair';
|
||||
import CrosshairPanel from './CrosshairPanel';
|
||||
import { buildAnimIndex, rigInput } from '../lib/replayAnim';
|
||||
import { abilityLook, type AbilityLook } from '../lib/abilities';
|
||||
import { loadVfxDb, vfxCoverage, VfxObject, type Place, type VfxDb } from '../lib/vfx';
|
||||
@@ -130,6 +133,14 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
ceilRef.current = ceil;
|
||||
/** 지금 자르는 높이 (가장 낮은 층에서 cm, 화면 표시용) */
|
||||
const [ceilNow, setCeilNow] = useState<number | null>(null);
|
||||
// 1인칭 저격총 조준경 (줌 중)
|
||||
const [scoped, setScoped] = useState(false);
|
||||
// 1인칭 조준점 (그리는 캔버스 · 설정 창)
|
||||
const crossRef = useRef<HTMLCanvasElement>(null);
|
||||
const xhairRef = useRef(cfg.crosshair);
|
||||
xhairRef.current = cfg.crosshair;
|
||||
const [xOpen, setXOpen] = useState(false);
|
||||
const hasCrosshairs = useMemo(() => replay.players.some((p) => !!p.crosshair?.length), [replay]);
|
||||
|
||||
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
|
||||
const zBase = useMemo(() => {
|
||||
@@ -299,6 +310,13 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
let prevT = localT.current;
|
||||
|
||||
const animIx = buildAnimIndex(replay, equipByPlayer);
|
||||
// 1인칭 팔 · 총 (index.json viewmodels 가 있을 때만)
|
||||
let vm: Viewmodel | null = null;
|
||||
void viewmodelIndex().then((ix) => {
|
||||
if (!disposed && ix) vm = new Viewmodel(ix);
|
||||
});
|
||||
let vmOn = false;
|
||||
let scopedNow = false;
|
||||
|
||||
// 선택한 선수 이동 경로 (최근 6초)
|
||||
const trailGeo = new THREE.BufferGeometry();
|
||||
@@ -584,6 +602,53 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
let lastMode: CamMode = 'top';
|
||||
const tmp = new THREE.Vector3();
|
||||
const euler = new THREE.Euler(0, 0, 0, 'YXZ');
|
||||
/** 1인칭 선수의 손 상태 (모두 리플레이 시각 t 로만 정한다) */
|
||||
const fpState = (p: number, t: number) => {
|
||||
const ek = equipAt(animIx.equips[p], t);
|
||||
const kind = replay.equipKinds?.[ek];
|
||||
const ei = indexAt(animIx.equipT[p], t);
|
||||
const equipT = ei >= 0 && animIx.equips[p][ei][1] === ek ? animIx.equips[p][ei][0] : null;
|
||||
// 무기 상태: 이 무기를 든 뒤의 재장전 · 줌
|
||||
let reloadMs: number | null = null;
|
||||
let zoom = 0;
|
||||
let zoomSeen = false;
|
||||
const st = animIx.states[p];
|
||||
for (let i = indexAt(animIx.stateT[p], t), n = 0; i >= 0 && n < 60; i--, n++) {
|
||||
const [ts, sek, name] = st[i];
|
||||
if (equipT != null && ts < equipT) break;
|
||||
if (sek !== ek) continue;
|
||||
if (reloadMs == null && name === 'ReloadState' && !zoomSeen) reloadMs = t - ts;
|
||||
if (!zoomSeen && /^(ZoomState|BufferedZoomLevel)/.test(name)) {
|
||||
zoomSeen = true;
|
||||
zoom = /Level2/.test(name) ? 2 : /Level1/.test(name) ? 1 : 0;
|
||||
}
|
||||
if (zoomSeen && reloadMs != null) break;
|
||||
}
|
||||
const shots = animIx.shots[p];
|
||||
const si = indexAt(shots, t);
|
||||
const shotT = si >= 0 ? shots[si] : null;
|
||||
// 걷기: 0.2초 사이 움직인 거리
|
||||
const tr = replay.players[p].track;
|
||||
const a = samplePlayer(tr, t, replay.sampleMs * 6);
|
||||
const b = samplePlayer(tr, t - 200, replay.sampleMs * 6);
|
||||
const moving = !!a && !!b && Math.hypot(a.x - b.x, a.y - b.y) > 30;
|
||||
// 스파이크 설치 중 (이어지는 동작 Plant 구간)
|
||||
let activateMs: number | null = null;
|
||||
for (const [a0, a1, k] of animIx.actions[p]) if (k === 'Plant' && a0 <= t && t <= a1) activateMs = t - a0;
|
||||
return {
|
||||
kind,
|
||||
zoom,
|
||||
sniper: weaponCat(kind) === 'sniper',
|
||||
input: {
|
||||
equipMs: equipT != null ? t - equipT : null,
|
||||
shotMs: shotT != null && (equipT == null || shotT >= equipT) ? t - shotT : null,
|
||||
reloadMs,
|
||||
ads: zoom > 0,
|
||||
walkMs: moving ? t : null,
|
||||
activateMs: kind === 'Spike' ? activateMs : null,
|
||||
},
|
||||
};
|
||||
};
|
||||
const frame = (now: number) => {
|
||||
raf = requestAnimationFrame(frame);
|
||||
const dt = lastNow ? Math.min(0.1, (now - lastNow) / 1000) : 0;
|
||||
@@ -857,6 +922,35 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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));
|
||||
}
|
||||
// 1인칭 팔 · 총: 들고 있는 무기 · 꺼낸 때 · 사격 · 재장전 · 줌 · 걷기
|
||||
const fp = p && !isDead(replay, selIdx, t) ? fpState(selIdx, t) : null;
|
||||
const zoomFov = fp ? 70 / (fp.zoom === 0 ? 1 : fp.sniper ? (fp.zoom >= 2 ? 5 : 2.5) : 1.25) : 70;
|
||||
if (camera.fov !== zoomFov) {
|
||||
camera.fov = zoomFov;
|
||||
camera.updateProjectionMatrix();
|
||||
}
|
||||
const sc = !!fp && fp.sniper && fp.zoom > 0;
|
||||
if (sc !== scopedNow) setScoped((scopedNow = sc));
|
||||
const chr = replay.players[selIdx].character;
|
||||
vmOn = !!fp && !sc && !!vm && vm.has(chr, fp.kind);
|
||||
if (vmOn && vm && chr && fp) {
|
||||
vm.set(chr, fp.kind!);
|
||||
vm.pose(fp.input);
|
||||
}
|
||||
// 조준점: 선수 조준점(설정에 따라) 또는 내 조준점. 저격총 줌은 조준경 가운데 점, 정조준은 정조준 조준점
|
||||
const g = crossRef.current && prepCanvas(crossRef.current);
|
||||
if (g) {
|
||||
const xc = xhairRef.current;
|
||||
const prof = (xc.usePlayer ? crosshairAt(replay.players[selIdx].crosshair, t) : null) ?? xc.mine;
|
||||
if (sc) drawSniperDot(g.ctx, g.cx, g.cy, prof.sniper);
|
||||
else {
|
||||
const shot = fp?.input.shotMs;
|
||||
drawCrosshair(g.ctx, g.cx, g.cy, crossFor(prof, !!fp && fp.zoom > 0), {
|
||||
fire: shot != null && shot < 350 ? 1 - shot / 350 : 0,
|
||||
move: fp?.input.walkMs != null ? 1 : 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (mode === 'free') {
|
||||
euler.set(free.pitch, free.yaw, 0, 'YXZ');
|
||||
camera.quaternion.setFromEuler(euler);
|
||||
@@ -865,7 +959,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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();
|
||||
if (mode !== 'fp') {
|
||||
vmOn = false;
|
||||
if (scopedNow) setScoped((scopedNow = false));
|
||||
}
|
||||
renderer.render(scene, camera);
|
||||
if (vmOn && vm?.ready) vm.render(renderer, camera.fov, camera.aspect);
|
||||
if (now - lastUi > 100) {
|
||||
lastUi = now;
|
||||
setCeilNow((c) => {
|
||||
@@ -887,6 +986,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
renderer.domElement.removeEventListener('keyup', onKey);
|
||||
renderer.domElement.removeEventListener('blur', onBlur);
|
||||
controls.dispose();
|
||||
vm?.dispose();
|
||||
for (const v of views) v.rig?.dispose();
|
||||
for (const vo of vfxObjs.values()) vo.dispose();
|
||||
scene.traverse((o) => {
|
||||
@@ -975,7 +1075,16 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{cam === 'fp' && <div className="r3d-cross" />}
|
||||
{cam === 'fp' && scoped && <div className="r3d-scope" />}
|
||||
{cam === 'fp' && <canvas ref={crossRef} className="r3d-xcanvas" aria-hidden />}
|
||||
{cam === 'fp' && xOpen && (
|
||||
<CrosshairPanel
|
||||
playerName={selInfo?.name ?? null}
|
||||
player={sel != null ? crosshairAt(replay.players[sel].crosshair, ui.t) : null}
|
||||
hasAny={hasCrosshairs}
|
||||
onClose={() => setXOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{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">
|
||||
@@ -1042,6 +1151,11 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
{cam === 'fp' && (
|
||||
<button className={`chip${xOpen ? ' on' : ''}`} onClick={() => setXOpen((o) => !o)} aria-pressed={xOpen} title="1인칭 조준점: 선수 조준점 · 내 조준점 설정">
|
||||
조준점
|
||||
</button>
|
||||
)}
|
||||
{cam === 'top' && (
|
||||
<button className="chip" onClick={() => resetCam.current()} title="카메라 처음 위치로">
|
||||
전체 보기
|
||||
|
||||
230
site/web/src/lib/crosshair.ts
Normal file
230
site/web/src/lib/crosshair.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* 발로란트 조준점: 리플레이의 선수 조준점(변환기 players[].crosshair) · 사이트 전체 조준점 설정 · 조준점 코드 · 그리기.
|
||||
* 크기는 발로란트 설정 값 그대로 화면 픽셀로 그린다.
|
||||
*/
|
||||
|
||||
export interface CrossLines {
|
||||
on: boolean;
|
||||
length: number;
|
||||
/** 세로 길이 (따로 쓰지 않으면 length 와 같다) */
|
||||
vLength: number;
|
||||
thickness: number;
|
||||
offset: number;
|
||||
opacity: number;
|
||||
moveError: boolean;
|
||||
fireError: boolean;
|
||||
moveScale: number;
|
||||
fireScale: number;
|
||||
}
|
||||
export interface CrossSet {
|
||||
/** 보이는 색 #rrggbb */
|
||||
color: string;
|
||||
outline: boolean;
|
||||
outlineThickness: number;
|
||||
outlineOpacity: number;
|
||||
dot: boolean;
|
||||
dotSize: number;
|
||||
dotOpacity: number;
|
||||
inner: CrossLines;
|
||||
outer: CrossLines;
|
||||
}
|
||||
export interface SniperDot {
|
||||
color: string;
|
||||
dot: boolean;
|
||||
dotSize: number;
|
||||
dotOpacity: number;
|
||||
}
|
||||
export interface CrosshairProfile {
|
||||
primary: CrossSet;
|
||||
ads: CrossSet;
|
||||
sniper: SniperDot;
|
||||
/** 정조준에도 주 조준점 */
|
||||
adsFromPrimary: boolean;
|
||||
advanced: boolean;
|
||||
}
|
||||
/** 리플레이 기록: t(ms) 부터 이 설정 */
|
||||
export interface CrosshairAt extends CrosshairProfile {
|
||||
t: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** 발로란트 색 목록 (조준점 코드 c 번호 순, 8 = 사용자 지정) */
|
||||
export const CROSS_COLORS: { name: string; hex: string }[] = [
|
||||
{ name: '흰색', hex: '#ffffff' },
|
||||
{ name: '초록색', hex: '#00ff00' },
|
||||
{ name: '연두색', hex: '#7fff00' },
|
||||
{ name: '황록색', hex: '#dfff00' },
|
||||
{ name: '노란색', hex: '#ffff00' },
|
||||
{ name: '청록색', hex: '#00ffff' },
|
||||
{ name: '분홍색', hex: '#ff00ff' },
|
||||
{ name: '빨간색', hex: '#ff0000' },
|
||||
];
|
||||
|
||||
const INNER: CrossLines = { on: true, length: 6, vLength: 6, thickness: 2, offset: 3, opacity: 0.8, moveError: false, fireError: true, moveScale: 1, fireScale: 1 };
|
||||
const OUTER: CrossLines = { on: true, length: 2, vLength: 2, thickness: 2, offset: 10, opacity: 0.35, moveError: true, fireError: true, moveScale: 1, fireScale: 1 };
|
||||
const SET: CrossSet = { color: '#ffffff', outline: true, outlineThickness: 1, outlineOpacity: 0.5, dot: false, dotSize: 2, dotOpacity: 1, inner: INNER, outer: OUTER };
|
||||
/** 발로란트 기본 조준점 */
|
||||
export const DEFAULT_CROSSHAIR: CrosshairProfile = {
|
||||
primary: SET,
|
||||
ads: SET,
|
||||
sniper: { color: '#ff0000', dot: true, dotSize: 1, dotOpacity: 0.75 },
|
||||
adsFromPrimary: true,
|
||||
advanced: false,
|
||||
};
|
||||
|
||||
/** t 시점 선수 조준점 (그 전이면 첫 기록, 기록이 없으면 null) */
|
||||
export function crosshairAt(list: CrosshairAt[] | null | undefined, t: number): CrosshairAt | null {
|
||||
if (!list?.length) return null;
|
||||
let c = list[0];
|
||||
for (const x of list) {
|
||||
if (x.t > t) break;
|
||||
c = x;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/** 지금 쓸 조준점 묶음: 정조준(저격총 아님) 중이고 정조준 조준점을 따로 쓰면 ads */
|
||||
export function crossFor(p: CrosshairProfile, ads: boolean): CrossSet {
|
||||
return ads && p.advanced && !p.adsFromPrimary ? p.ads : p.primary;
|
||||
}
|
||||
|
||||
const num = (v: string | undefined, d: number) => {
|
||||
const n = v == null ? NaN : Number(v);
|
||||
return Number.isFinite(n) ? n : d;
|
||||
};
|
||||
|
||||
/**
|
||||
* 발로란트 조준점 코드 (설정 → 조준점 → 프로필 내보내기, 예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0) → 설정.
|
||||
* 코드에 없는 값은 발로란트 기본값. 형식이 아니면 null
|
||||
*/
|
||||
export function parseCrosshairCode(code: string): CrosshairProfile | null {
|
||||
const tok = code.trim().split(';').map((s) => s.trim());
|
||||
if (tok.length < 1 || !/^\d+$/.test(tok[0])) return null;
|
||||
const sec: Record<'G' | 'P' | 'A' | 'S', Record<string, string>> = { G: {}, P: {}, A: {}, S: {} };
|
||||
let cur: keyof typeof sec = 'G';
|
||||
for (let i = 1; i < tok.length; i++) {
|
||||
const k = tok[i];
|
||||
if (k === 'P' || k === 'A' || k === 'S') {
|
||||
cur = k;
|
||||
continue;
|
||||
}
|
||||
if (!k) continue;
|
||||
if (i + 1 >= tok.length) return null;
|
||||
sec[cur][k] = tok[++i];
|
||||
}
|
||||
const color = (s: Record<string, string>, d: string) => {
|
||||
const c = num(s.c, -1);
|
||||
if ((c === 8 || s.b === '1') && /^[0-9a-fA-F]{6}/.test(s.u ?? '')) return `#${s.u.slice(0, 6).toLowerCase()}`;
|
||||
return CROSS_COLORS[c]?.hex ?? d;
|
||||
};
|
||||
const lines = (s: Record<string, string>, p: '0' | '1', d: CrossLines): CrossLines => {
|
||||
const length = num(s[p + 'l'], d.length);
|
||||
return {
|
||||
on: s[p + 'b'] !== '0' && (s[p + 'b'] === '1' || d.on),
|
||||
length,
|
||||
vLength: s[p + 'g'] === '1' ? num(s[p + 'v'], length) : length,
|
||||
thickness: num(s[p + 't'], d.thickness),
|
||||
offset: num(s[p + 'o'], d.offset),
|
||||
opacity: num(s[p + 'a'], d.opacity),
|
||||
moveError: s[p + 'm'] != null ? s[p + 'm'] === '1' : d.moveError,
|
||||
fireError: s[p + 'f'] != null ? s[p + 'f'] === '1' : d.fireError,
|
||||
moveScale: num(s[p + 's'], d.moveScale),
|
||||
fireScale: num(s[p + 'e'], d.fireScale),
|
||||
};
|
||||
};
|
||||
const set = (s: Record<string, string>): CrossSet => ({
|
||||
color: color(s, SET.color),
|
||||
outline: s.h != null ? s.h === '1' : SET.outline,
|
||||
outlineThickness: num(s.t, SET.outlineThickness),
|
||||
outlineOpacity: num(s.o, SET.outlineOpacity),
|
||||
dot: s.d != null ? s.d === '1' : SET.dot,
|
||||
dotSize: num(s.z, SET.dotSize),
|
||||
dotOpacity: num(s.a, SET.dotOpacity),
|
||||
inner: lines(s, '0', INNER),
|
||||
outer: lines(s, '1', OUTER),
|
||||
});
|
||||
const S = sec.S;
|
||||
const sd = DEFAULT_CROSSHAIR.sniper;
|
||||
return {
|
||||
primary: set(sec.P),
|
||||
ads: set(sec.A),
|
||||
sniper: {
|
||||
color: color(S, sd.color),
|
||||
dot: S.d != null ? S.d === '1' : sd.dot,
|
||||
dotSize: num(S.s, sd.dotSize),
|
||||
dotOpacity: num(S.o, sd.dotOpacity),
|
||||
},
|
||||
adsFromPrimary: sec.G.p !== '0',
|
||||
advanced: sec.G.s === '1',
|
||||
};
|
||||
}
|
||||
|
||||
/** 사격 · 이동으로 벌어지는 정도 (픽셀): fire 0..1 (막 쏨 = 1), move 0..1 */
|
||||
export interface Spread {
|
||||
fire: number;
|
||||
move: number;
|
||||
}
|
||||
const FIRE_PX = 6;
|
||||
const MOVE_PX = 4;
|
||||
|
||||
function rgba(hex: string, a: number) {
|
||||
const n = parseInt(hex.slice(1, 7), 16);
|
||||
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${Math.max(0, Math.min(1, a))})`;
|
||||
}
|
||||
|
||||
/** (cx, cy) 를 가운데로 조준점을 그린다. 크기는 CSS 픽셀 (ctx 는 devicePixelRatio 로 미리 늘려 둔다) */
|
||||
export function drawCrosshair(ctx: CanvasRenderingContext2D, cx: number, cy: number, s: CrossSet, spread: Spread = { fire: 0, move: 0 }) {
|
||||
const rects: [number, number, number, number, number][] = [];
|
||||
const line = (l: CrossLines) => {
|
||||
if (!l.on || l.opacity <= 0 || l.thickness <= 0) return;
|
||||
const gap = l.offset + (l.fireError ? spread.fire * FIRE_PX * l.fireScale : 0) + (l.moveError ? spread.move * MOVE_PX * l.moveScale : 0);
|
||||
const th = l.thickness;
|
||||
if (l.length > 0) {
|
||||
rects.push([cx - gap - l.length, cy - th / 2, l.length, th, l.opacity]);
|
||||
rects.push([cx + gap, cy - th / 2, l.length, th, l.opacity]);
|
||||
}
|
||||
if (l.vLength > 0) {
|
||||
rects.push([cx - th / 2, cy - gap - l.vLength, th, l.vLength, l.opacity]);
|
||||
rects.push([cx - th / 2, cy + gap, th, l.vLength, l.opacity]);
|
||||
}
|
||||
};
|
||||
line(s.outer);
|
||||
line(s.inner);
|
||||
if (s.dot && s.dotSize > 0 && s.dotOpacity > 0) rects.push([cx - s.dotSize / 2, cy - s.dotSize / 2, s.dotSize, s.dotSize, s.dotOpacity]);
|
||||
// 픽셀 경계에 맞춘다 (두께 1 · 2 선이 흐려지지 않게)
|
||||
const px = rects.map(([x, y, w, h, a]) => [Math.round(x), Math.round(y), Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), a] as const);
|
||||
if (s.outline && s.outlineThickness > 0 && s.outlineOpacity > 0) {
|
||||
const o = s.outlineThickness;
|
||||
ctx.fillStyle = rgba('#000000', s.outlineOpacity);
|
||||
for (const [x, y, w, h] of px) ctx.fillRect(x - o, y - o, w + o * 2, h + o * 2);
|
||||
}
|
||||
for (const [x, y, w, h, a] of px) {
|
||||
ctx.fillStyle = rgba(s.color, a);
|
||||
ctx.fillRect(x, y, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
/** 저격총 조준경 가운데 점 */
|
||||
export function drawSniperDot(ctx: CanvasRenderingContext2D, cx: number, cy: number, d: SniperDot) {
|
||||
if (!d.dot || d.dotSize <= 0 || d.dotOpacity <= 0) return;
|
||||
ctx.fillStyle = rgba(d.color, d.dotOpacity);
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, Math.max(1, d.dotSize * 2), 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
/** 캔버스를 화면 크기 · devicePixelRatio 에 맞추고 지운 뒤 가운데 좌표 */
|
||||
export function prepCanvas(c: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; cx: number; cy: number } | null {
|
||||
const ctx = c.getContext('2d');
|
||||
if (!ctx) return null;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const w = c.clientWidth;
|
||||
const h = c.clientHeight;
|
||||
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {
|
||||
c.width = Math.round(w * dpr);
|
||||
c.height = Math.round(h * dpr);
|
||||
}
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
return { ctx, cx: Math.floor(w / 2), cy: Math.floor(h / 2) };
|
||||
}
|
||||
@@ -51,6 +51,8 @@ export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
|
||||
* glb 를 받아 장면 하나로. onProgress: 0~1
|
||||
* 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다.
|
||||
* 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다.
|
||||
* 구운 조명(extras.lightmap = {k}): 추출기가 aoMap(irr) · emissiveMap(sh) 자리에 TEXCOORD_1 로 넣어 둔 아틀라스로
|
||||
* 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선, tools/map-extract/src/Lightmaps.cs). 장면 조명은 쓰지 않는다.
|
||||
*/
|
||||
export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
|
||||
const loader = new GLTFLoader();
|
||||
@@ -73,6 +75,7 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
|
||||
}
|
||||
const src = mesh.material as THREE.MeshStandardMaterial;
|
||||
const blend = src.userData?.blend as { texture?: number; tint?: number[] } | undefined;
|
||||
const lm = src.userData?.lightmap as { k?: number } | undefined;
|
||||
// 정점 색은 색칠이 아니라 두 층 섞는 비율이다
|
||||
const col = mesh.geometry.getAttribute('color');
|
||||
if (col) {
|
||||
@@ -91,7 +94,20 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
|
||||
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));
|
||||
const shader: ShaderParts = {};
|
||||
if (lm?.k && m.aoMap && m.emissiveMap) {
|
||||
shader.lightmap = { k: lm.k };
|
||||
for (const t of [m.aoMap, m.emissiveMap]) {
|
||||
t.colorSpace = THREE.NoColorSpace; // 셰이더에서 직접 푼다
|
||||
t.anisotropy = 4;
|
||||
}
|
||||
} else {
|
||||
// 조명 없는 재질에 붙은 조명 텍스처는 쓰지 않는다
|
||||
m.aoMap = null;
|
||||
m.emissiveMap = null;
|
||||
}
|
||||
const ready = blend ? blendLayer(gltf.parser, blend).then((b) => void (shader.blend = b)) : Promise.resolve();
|
||||
pending.push(ready.then(() => installShader(m, shader)));
|
||||
done.set(src, m);
|
||||
mat = m;
|
||||
}
|
||||
@@ -105,8 +121,13 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
|
||||
});
|
||||
}
|
||||
|
||||
/** B 층 텍스처 · 색을 붙이고 셰이더에서 정점 색 R 로 섞는다 */
|
||||
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, m: THREE.MeshStandardMaterial, b: { texture?: number; tint?: number[] }) {
|
||||
interface ShaderParts {
|
||||
blend?: { texB: THREE.Texture | null; tintB: THREE.Color };
|
||||
lightmap?: { k: number };
|
||||
}
|
||||
|
||||
/** B 층 텍스처 · 색 (셰이더에서 정점 색 R 로 섞는다) */
|
||||
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, b: { texture?: number; tint?: number[] }) {
|
||||
let texB: THREE.Texture | null = null;
|
||||
if (b.texture != null) {
|
||||
// 텍스처 하나를 못 읽어도 맵 전체를 버리지 않고 B 층 색만 쓴다
|
||||
@@ -117,26 +138,65 @@ async function blendLayer(parser: { getDependency: (type: string, i: number) =>
|
||||
}
|
||||
}
|
||||
const tintB = new THREE.Color().setRGB(b.tint?.[0] ?? 1, b.tint?.[1] ?? 1, b.tint?.[2] ?? 1, THREE.SRGBColorSpace);
|
||||
return { texB, tintB };
|
||||
}
|
||||
|
||||
/** 두 층 섞기 · 구운 조명을 셰이더에 넣는다 */
|
||||
function installShader(m: THREE.MeshStandardMaterial, parts: ShaderParts) {
|
||||
const { blend, lightmap } = parts;
|
||||
if (!blend && !lightmap) return;
|
||||
const md = m as unknown as { defines?: Record<string, string> };
|
||||
md.defines = { ...(md.defines ?? {}), GVR_BLEND: '', ...(texB ? { GVR_BLEND_MAP: '' } : {}) };
|
||||
md.defines = { ...(md.defines ?? {}) };
|
||||
if (blend) {
|
||||
md.defines.GVR_BLEND = '';
|
||||
if (blend.texB) md.defines.GVR_BLEND_MAP = '';
|
||||
}
|
||||
if (lightmap) md.defines.GVR_LIGHTMAP = '';
|
||||
// 같은 프로그램을 나눠 쓰도록 (uniform 값만 재질마다 다름)
|
||||
m.customProgramCacheKey = () => `gvr:${blend ? (blend.texB ? 'bm' : 'b') : ''}:${lightmap ? 'l' : ''}`;
|
||||
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>
|
||||
if (blend) {
|
||||
sh.uniforms.mapB = { value: blend.texB };
|
||||
sh.uniforms.tintB = { value: blend.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);`,
|
||||
);
|
||||
);
|
||||
}
|
||||
if (lightmap) {
|
||||
sh.uniforms.lmK = { value: lightmap.k };
|
||||
sh.vertexShader = sh.vertexShader
|
||||
.replace('#include <common>', '#include <common>\nvarying vec3 vUeN;')
|
||||
.replace('#include <beginnormal_vertex>', '#include <beginnormal_vertex>\nvUeN = objectNormal;');
|
||||
sh.fragmentShader = sh.fragmentShader
|
||||
.replace('#include <common>', '#include <common>\nuniform float lmK;\nvarying vec3 vUeN;')
|
||||
.replace(
|
||||
'#include <opaque_fragment>',
|
||||
`{
|
||||
// 구운 조명 (UE HQ 라이트맵을 추출기가 풀어 둔 값): irr 는 sRGB, sh 는 ±2 → 0~1
|
||||
vec3 lmIrr = texture2D(aoMap, vAoMapUv).rgb;
|
||||
lmIrr = mix(lmIrr / 12.92, pow((lmIrr + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), lmIrr));
|
||||
vec3 lmSh = texture2D(emissiveMap, vEmissiveMapUv).rgb * 4.0 - 2.0;
|
||||
vec3 n = normalize(vUeN);
|
||||
float lmDir = max(0.0, 1.0 + dot(lmSh, n.yzx));
|
||||
vec3 lit = diffuseColor.rgb * lmIrr * (lmK * lmDir);
|
||||
// 밝은 곳이 하얗게 날아가지 않게 살짝 누른다
|
||||
outgoingLight = lit / (1.0 + max(lit - 0.8, 0.0));
|
||||
}
|
||||
#include <opaque_fragment>`,
|
||||
);
|
||||
}
|
||||
};
|
||||
m.needsUpdate = true;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KillData, MatchDetail } from '@gvr/shared';
|
||||
import type { CrosshairAt } from './crosshair';
|
||||
|
||||
/**
|
||||
* tools/replay-extract (gvr-replay v1 · v2) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위(cm).
|
||||
@@ -14,7 +15,13 @@ export interface ReplayFile {
|
||||
recordedAt: number;
|
||||
durationMs: number;
|
||||
sampleMs: number;
|
||||
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[]; f?: number[] } }[];
|
||||
players: {
|
||||
puuid: string | null;
|
||||
character: string | null;
|
||||
track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[]; f?: number[] };
|
||||
/** 조준점 설정이 바뀐 시각마다 전체 설정 (변환기 1.8.2~, 옛 JSON 은 없다) */
|
||||
crosshair?: CrosshairAt[] | null;
|
||||
}[];
|
||||
rounds: { num: number; buy: number; combat: number; end: number }[];
|
||||
phases: [number, number][];
|
||||
/** [t, killer, victim, deathAnim(v2, deathAnims 번호 · -1)] */
|
||||
|
||||
237
site/web/src/lib/viewmodel.ts
Normal file
237
site/web/src/lib/viewmodel.ts
Normal file
@@ -0,0 +1,237 @@
|
||||
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 { assetUrl } from './agents3d';
|
||||
import { loadIndex } from './map3d';
|
||||
|
||||
/**
|
||||
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
|
||||
* arms[캐릭터 클래스] 요원 1인칭 팔 (뼈대는 모든 요원 공용, Camera 뼈 = 눈)
|
||||
* weapons[무기 이름] 무기 1인칭 모델(총 동작 gun_*) + 그 무기를 든 팔 동작(idle · fire · reload · equip · ads · walk · activate)
|
||||
* 좌표는 게임(UE) cm. 무기 뿌리는 팔 뼈 MasterWeapon 에 GUN_Q 만큼 돌려 붙인다 (총 몸의 앞 = 팔의 앞, 탄창 = 아래).
|
||||
* 자세는 시각(ms)만으로 정한다 (되감기 · 멈춤 · 배속에도 같은 자세).
|
||||
*/
|
||||
export interface VmIndex {
|
||||
arms: Record<string, { code: string; file: string }>;
|
||||
weapons: Record<string, { file: string; anim: string; clips: string[]; gunClips: string[]; points?: { muzzle?: number[] } }>;
|
||||
}
|
||||
|
||||
const GUN_Q = new THREE.Quaternion(0.5, -0.5, 0.5, 0.5);
|
||||
/** UE(cm, X 앞 · Y 오른쪽 · Z 위) → 카메라 공간(m, -Z 앞 · X 오른쪽 · Y 위) */
|
||||
const UE_TO_VIEW = new THREE.Matrix4().set(0, 0.01, 0, 0, 0, 0, 0.01, 0, -0.01, 0, 0, 0, 0, 0, 0, 1);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export async function viewmodelIndex(): Promise<(VmIndex & { dir: string }) | null> {
|
||||
const idx = (await loadIndex()) as { dir: string | null; viewmodels?: VmIndex | null } | null;
|
||||
return idx?.dir && idx.viewmodels ? { ...idx.viewmodels, dir: idx.dir } : null;
|
||||
}
|
||||
|
||||
/** 지금 자세를 정하는 입력 (모두 ms, 없으면 null) */
|
||||
export interface VmInput {
|
||||
/** 이 무기를 꺼낸 지 */
|
||||
equipMs: number | null;
|
||||
/** 마지막 사격 뒤 */
|
||||
shotMs: number | null;
|
||||
/** 재장전 시작 뒤 */
|
||||
reloadMs: number | null;
|
||||
/** 정조준(줌) 중 */
|
||||
ads: boolean;
|
||||
/** 걷는 중이면 걸은 시간 (반복 동작 위치) */
|
||||
walkMs: number | null;
|
||||
/** 스파이크 설치 시작 뒤 (설치하는 동안만) */
|
||||
activateMs?: number | null;
|
||||
}
|
||||
|
||||
function findBone(root: THREE.Object3D, name: string): THREE.Object3D | null {
|
||||
let b: THREE.Object3D | null = null;
|
||||
root.traverse((o) => {
|
||||
if (!b && o.name === name) b = o;
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
function prep(root: THREE.Object3D) {
|
||||
root.traverse((o) => {
|
||||
const m = o as THREE.Mesh;
|
||||
if (!m.isMesh) return;
|
||||
m.frustumCulled = false;
|
||||
const mat = m.material as THREE.MeshStandardMaterial;
|
||||
mat.side = THREE.DoubleSide;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 1인칭 팔 + 무기. scene 을 따로 두고 카메라 공간에서 그린다 (맵보다 앞에, 깊이 따로).
|
||||
* set() 으로 요원 · 무기를 바꾸고(받는 동안은 이전 것), pose() 로 자세를 정한 뒤 render().
|
||||
*/
|
||||
export class Viewmodel {
|
||||
readonly scene = new THREE.Scene();
|
||||
readonly camera = new THREE.PerspectiveCamera(70, 1, 0.01, 20);
|
||||
private root = new THREE.Group();
|
||||
private arms: THREE.Object3D | null = null;
|
||||
private armsMixer: THREE.AnimationMixer | null = null;
|
||||
private gunMixer: THREE.AnimationMixer | null = null;
|
||||
private armClips = new Map<string, THREE.AnimationClip>();
|
||||
private gunClips = new Map<string, THREE.AnimationClip>();
|
||||
private flash: THREE.Sprite;
|
||||
private muzzle: THREE.Object3D | null = null;
|
||||
private want = '';
|
||||
private have = '';
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly idx: VmIndex & { dir: string }) {
|
||||
this.root.matrixAutoUpdate = false;
|
||||
this.scene.add(this.root);
|
||||
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.2));
|
||||
const sun = new THREE.DirectionalLight(0xfff4e0, 1.6);
|
||||
sun.position.set(0.4, 1, 0.6);
|
||||
this.scene.add(sun);
|
||||
// 총구 불꽃 (사격 직후 잠깐)
|
||||
const c = document.createElement('canvas');
|
||||
c.width = c.height = 64;
|
||||
const g = c.getContext('2d')!;
|
||||
const grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
|
||||
grd.addColorStop(0, 'rgba(255,250,220,1)');
|
||||
grd.addColorStop(0.3, 'rgba(255,200,90,0.85)');
|
||||
grd.addColorStop(1, 'rgba(255,120,20,0)');
|
||||
g.fillStyle = grd;
|
||||
g.fillRect(0, 0, 64, 64);
|
||||
this.flash = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthTest: false, transparent: true }));
|
||||
this.flash.scale.setScalar(0.12);
|
||||
this.flash.visible = false;
|
||||
this.scene.add(this.flash);
|
||||
}
|
||||
|
||||
/** 이 요원 · 무기에 1인칭 모델이 있는지 */
|
||||
has(character: string | null | undefined, weapon: string | null | undefined): boolean {
|
||||
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
|
||||
}
|
||||
|
||||
/** 요원 · 무기를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다 */
|
||||
set(character: string, weapon: string) {
|
||||
const key = `${character}|${weapon}`;
|
||||
if (key === this.want) return;
|
||||
this.want = key;
|
||||
const a = this.idx.arms[character];
|
||||
const w = this.idx.weapons[weapon];
|
||||
if (!a || !w) return;
|
||||
const url = (f: string) => assetUrl(this.idx.dir, f);
|
||||
void Promise.all([load(url(a.file)), load(url(w.file)), load(url(w.anim))])
|
||||
.then(([ag, wg, an]) => {
|
||||
if (this.disposed || this.want !== key) return;
|
||||
this.build(ag, wg, an);
|
||||
this.have = key;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
private build(ag: GLTF, wg: GLTF, an: GLTF) {
|
||||
if (this.arms) this.root.remove(this.arms);
|
||||
const arms = cloneSkinned(ag.scene);
|
||||
const gun = cloneSkinned(wg.scene);
|
||||
prep(arms);
|
||||
prep(gun);
|
||||
const attach = findBone(arms, 'MasterWeapon');
|
||||
if (attach) {
|
||||
gun.quaternion.copy(GUN_Q);
|
||||
attach.add(gun);
|
||||
}
|
||||
this.root.add(arms);
|
||||
this.arms = arms;
|
||||
this.muzzle = findBone(gun, 'Muzzle');
|
||||
this.armsMixer = new THREE.AnimationMixer(arms);
|
||||
this.gunMixer = new THREE.AnimationMixer(gun);
|
||||
this.armClips = new Map(an.animations.map((c) => [c.name, c]));
|
||||
this.gunClips = new Map(wg.animations.map((c) => [c.name, c]));
|
||||
// 눈 = 팔 Camera 뼈 (대기 자세)
|
||||
this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
|
||||
arms.updateMatrixWorld(true);
|
||||
// 팔 공간 좌표로 (root 에 이전 요원 · 무기의 변환이 남아 있어도 같은 값)
|
||||
const cam = findBone(arms, 'Camera');
|
||||
const cp = cam ? arms.worldToLocal(new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld)) : new THREE.Vector3(0, 0, 166);
|
||||
this.root.matrix.copy(UE_TO_VIEW).multiply(new THREE.Matrix4().makeTranslation(-cp.x, -cp.y, -cp.z));
|
||||
this.root.matrixWorldNeedsUpdate = true;
|
||||
}
|
||||
|
||||
get ready() {
|
||||
return this.have !== '' && this.have === this.want;
|
||||
}
|
||||
|
||||
private play(mixer: THREE.AnimationMixer, clip: THREE.AnimationClip | undefined, ms: number, loop: boolean) {
|
||||
mixer.stopAllAction();
|
||||
if (!clip) return false;
|
||||
const a = mixer.clipAction(clip);
|
||||
a.reset();
|
||||
a.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
|
||||
a.clampWhenFinished = true;
|
||||
a.play();
|
||||
const d = Math.max(clip.duration, 1e-3);
|
||||
a.time = loop ? (ms / 1000) % d : Math.min(ms / 1000, d);
|
||||
mixer.update(0);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 시각만으로 자세: 스파이크 설치 > 꺼내기 > 재장전 > 사격 > 걷기 > 정조준 > 대기 (설치 시작 때 스파이크를 꺼내므로 설치가 먼저) */
|
||||
pose(i: VmInput) {
|
||||
if (!this.armsMixer || !this.gunMixer) return;
|
||||
const dur = (n: string) => (this.armClips.get(n)?.duration ?? 0) * 1000;
|
||||
let role = 'idle';
|
||||
let ms = 0;
|
||||
let loop = false;
|
||||
if (i.activateMs != null && this.armClips.has('activate')) [role, ms] = ['activate', i.activateMs];
|
||||
else if (i.equipMs != null && i.equipMs < dur('equip')) [role, ms] = ['equip', i.equipMs];
|
||||
else if (i.reloadMs != null && i.reloadMs < dur('reload')) [role, ms] = ['reload', i.reloadMs];
|
||||
else if (i.shotMs != null && i.shotMs < dur('fire')) [role, ms] = ['fire', i.shotMs];
|
||||
else if (i.walkMs != null && this.armClips.has('walk') && !i.ads) [role, ms, loop] = ['walk', i.walkMs, true];
|
||||
else if (i.ads && this.armClips.has('ads')) role = 'ads';
|
||||
if (!this.play(this.armsMixer, this.armClips.get(role), ms, loop)) this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
|
||||
if (!this.play(this.gunMixer, this.gunClips.get('gun_' + role), ms, false)) this.gunMixer.stopAllAction();
|
||||
// 총구 불꽃: 사격 뒤 60ms
|
||||
const on = i.shotMs != null && i.shotMs < 60 && role === 'fire' && !!this.muzzle;
|
||||
this.flash.visible = on;
|
||||
if (on) {
|
||||
this.root.updateMatrixWorld(true);
|
||||
this.flash.position.setFromMatrixPosition(this.muzzle!.matrixWorld);
|
||||
this.flash.material.rotation = (i.shotMs! * 7) % (Math.PI * 2);
|
||||
}
|
||||
}
|
||||
|
||||
/** 맵을 그린 뒤 깊이만 지우고 그 위에 그린다 */
|
||||
render(renderer: THREE.WebGLRenderer, fov: number, aspect: number) {
|
||||
if (!this.arms) return;
|
||||
if (this.camera.fov !== fov || this.camera.aspect !== aspect) {
|
||||
this.camera.fov = fov;
|
||||
this.camera.aspect = aspect;
|
||||
this.camera.updateProjectionMatrix();
|
||||
}
|
||||
const clip = renderer.localClippingEnabled;
|
||||
const auto = renderer.autoClear;
|
||||
renderer.localClippingEnabled = false;
|
||||
renderer.autoClear = false;
|
||||
renderer.clearDepth();
|
||||
renderer.render(this.scene, this.camera);
|
||||
renderer.autoClear = auto;
|
||||
renderer.localClippingEnabled = clip;
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.disposed = true;
|
||||
this.armsMixer?.stopAllAction();
|
||||
this.gunMixer?.stopAllAction();
|
||||
this.flash.material.map?.dispose();
|
||||
this.flash.material.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { DEFAULT_CROSSHAIR, type CrosshairProfile } from '../lib/crosshair';
|
||||
|
||||
export type SfxKind = 'click' | 'play' | 'kill' | 'round' | 'chime';
|
||||
export interface Settings {
|
||||
@@ -10,6 +11,8 @@ export interface Settings {
|
||||
normalize: boolean;
|
||||
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
|
||||
playVolume: number;
|
||||
/** 3D 리플레이 1인칭 조준점: usePlayer 면 리플레이에 있는 선수 조준점(없으면 mine), 아니면 항상 mine */
|
||||
crosshair: { usePlayer: boolean; mine: CrosshairProfile; code?: string };
|
||||
/** 기본값을 바꾼 횟수 (예전에 저장한 설정을 한 번만 새 기본값으로 맞춘다) */
|
||||
defaultsRev?: number;
|
||||
}
|
||||
@@ -24,6 +27,7 @@ const DEFAULTS: Settings = {
|
||||
continuous: true,
|
||||
normalize: true,
|
||||
playVolume: 1,
|
||||
crosshair: { usePlayer: true, mine: DEFAULT_CROSSHAIR },
|
||||
defaultsRev: 1,
|
||||
};
|
||||
|
||||
@@ -32,7 +36,7 @@ function load(): Settings {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return DEFAULTS;
|
||||
const v = JSON.parse(raw) as Partial<Settings>;
|
||||
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
|
||||
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) }, crosshair: { ...DEFAULTS.crosshair, ...(v.crosshair ?? {}) } };
|
||||
// 예전 사이트는 설정을 하나만 바꿔도 효과음 켜짐/꺼짐을 전부 저장했다: 새 기본값(두 알림 끄기)을 한 번 적용
|
||||
if ((v.defaultsRev ?? 0) < 1) {
|
||||
out.sfx = { ...out.sfx, play: false, chime: false };
|
||||
|
||||
@@ -4084,18 +4084,125 @@ button.match:hover {
|
||||
border-radius: 6px;
|
||||
padding: 3px 6px;
|
||||
}
|
||||
.r3d-cross {
|
||||
/* 1인칭 조준점 (lib/crosshair.ts 가 그린다): 화면 가운데 */
|
||||
.r3d-stage canvas.r3d-xcanvas {
|
||||
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);
|
||||
width: 240px;
|
||||
height: 240px;
|
||||
margin: -120px 0 0 -120px;
|
||||
pointer-events: none;
|
||||
z-index: 3;
|
||||
cursor: default;
|
||||
}
|
||||
/* 조준점 설정 창 */
|
||||
.r3d-xpanel {
|
||||
position: absolute;
|
||||
z-index: 4;
|
||||
right: 10px;
|
||||
bottom: 10px;
|
||||
width: min(320px, calc(100% - 20px));
|
||||
max-height: calc(100% - 20px);
|
||||
overflow-y: auto;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(8, 14, 20, 0.92);
|
||||
border: 1px solid var(--line);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.r3d-xhead {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.r3d-xcheck {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.r3d-xplayer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.r3d-xplayer > div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
.r3d-stage canvas.r3d-xprev {
|
||||
width: 72px;
|
||||
height: 72px;
|
||||
flex: none;
|
||||
border-radius: 8px;
|
||||
background: #3a4651;
|
||||
cursor: default;
|
||||
}
|
||||
.r3d-xmine {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
border-top: 1px solid var(--line);
|
||||
padding-top: 8px;
|
||||
}
|
||||
.r3d-xmine > .r3d-xprev {
|
||||
align-self: center;
|
||||
}
|
||||
.r3d-xcode {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
}
|
||||
.r3d-xcode input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
.r3d-xerr {
|
||||
color: #ff9aa5;
|
||||
}
|
||||
.r3d-xrow {
|
||||
display: grid;
|
||||
grid-template-columns: 56px 1fr auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.r3d-xrow input[type='range'] {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.r3d-xrow .mono {
|
||||
min-width: 30px;
|
||||
text-align: right;
|
||||
}
|
||||
.r3d-xset {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 4px 8px 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.r3d-xset legend {
|
||||
padding: 0 4px;
|
||||
}
|
||||
/* 저격총 줌: 둥근 조준경 밖은 검게, 가는 십자선 */
|
||||
.r3d-scope {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
background:
|
||||
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 100% 1px no-repeat,
|
||||
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 1px 100% no-repeat,
|
||||
radial-gradient(circle at center, transparent 0, transparent min(46vh, 46%), #000 calc(min(46vh, 46%) + 1px));
|
||||
}
|
||||
.r3d-stage canvas:focus {
|
||||
outline: none;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# 맵 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
|
||||
# 코드를 고쳤으면 다시 실행하면 된다 (타이머를 꺼 뒀으면 꺼진 채로 둔다). 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
|
||||
@@ -26,6 +26,12 @@ chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
|
||||
|
||||
unit="$HOME/.config/systemd/user"
|
||||
mkdir -p "$unit"
|
||||
# 이미 설치돼 있는데 타이머를 꺼 뒀으면(사용자가 자동 갱신을 멈춤) 다시 켜지 않는다
|
||||
timer_was="$( [ -f "$unit/gvr-maps-update.timer" ] && (systemctl --user is-enabled gvr-maps-update.timer 2>/dev/null || true) || echo new)"
|
||||
# 알림 채널 · 토큰 파일: 환경변수로 주지 않았으면 이미 설치된 값을 그대로 쓴다 (다시 설치하면서 알림이 꺼지지 않게)
|
||||
prev_env() { sed -n "s/^Environment=$1=//p" "$unit/gvr-maps-update.service" 2>/dev/null | tail -1; }
|
||||
NOTIFY_CHANNEL="${NOTIFY_CHANNEL:-$(prev_env NOTIFY_CHANNEL)}"
|
||||
NOTIFY_ENV="${NOTIFY_ENV:-$(prev_env NOTIFY_ENV)}"
|
||||
node_dir="$(dirname "$(command -v node)")"
|
||||
cat > "$unit/gvr-maps-update.service" <<EOF
|
||||
[Unit]
|
||||
@@ -62,5 +68,9 @@ Persistent=true
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now gvr-maps-update.timer
|
||||
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
|
||||
if [ "$timer_was" = new ] || [ "$timer_was" = enabled ]; then
|
||||
systemctl --user enable --now gvr-maps-update.timer
|
||||
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
|
||||
else
|
||||
echo "설치 완료: $GVR_MAPS_HOME · 자동 갱신 타이머는 꺼진 채로 둠 (켜기: systemctl --user enable --now gvr-maps-update.timer, 한 번만: systemctl --user start gvr-maps-update)"
|
||||
fi
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
|
||||
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
|
||||
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons.
|
||||
viewmodels.json 이 있으면 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb, index.json viewmodels.
|
||||
anims.glb 가 있으면 공용 애니메이션 index.json anims, abilities/abilities.json 이 있으면 스킬 재료 index.json abilities)
|
||||
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
|
||||
-ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게
|
||||
-ke: 재질 extras(두 층 섞기 B 층 · 구운 조명 K) 유지
|
||||
-vtf: UV 를 실수 그대로. gltfpack 은 재질마다 TEXCOORD_0(반복 UV, 수십 단위) · TEXCOORD_1(라이트맵 아틀라스 0~1)을
|
||||
한 범위로 묶어 양자화해서, 정수로 줄이면 라이트맵 UV 가 몇 텍셀씩 어긋난다 (meshopt 압축 뒤 크기는 비슷)
|
||||
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
|
||||
import datetime, gzip, json, os, re, shutil, subprocess, sys
|
||||
|
||||
@@ -14,7 +17,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') or name == 'agents.json':
|
||||
if not name.endswith('.json') or name in ('agents.json', 'viewmodels.json'):
|
||||
continue
|
||||
info = json.load(open(os.path.join(src, name)))
|
||||
code = info['code']
|
||||
@@ -22,7 +25,7 @@ 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', '-ke', '-vt', '14'], check=True, stdout=subprocess.DEVNULL)
|
||||
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-ke', '-vtf'], 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)
|
||||
@@ -53,6 +56,24 @@ if os.path.exists(aj):
|
||||
if size:
|
||||
weapons[name] = {'file': v['file'], 'bytes': size, 'points': v.get('points') or {}}
|
||||
print(f'요원 {len(agents)} · 무기 {len(weapons)}')
|
||||
# 1인칭 팔 · 무기 · 팔 동작 (viewmodels 명령 결과 viewmodels.json): 뼈대 · 동작 · 노드 이름을 지킨다 (-kn)
|
||||
viewmodels = None
|
||||
vj = os.path.join(src, 'viewmodels.json')
|
||||
if os.path.exists(vj):
|
||||
v = json.load(open(vj))
|
||||
vm_arms, vm_weapons, total = {}, {}, 0
|
||||
for cls, a in v.get('arms', {}).items():
|
||||
size = pack_one(a['file'])
|
||||
if size:
|
||||
vm_arms[cls] = {'code': a['code'], 'file': a['file'], 'bytes': size}
|
||||
total += size
|
||||
for name, w in v.get('weapons', {}).items():
|
||||
s1, s2 = pack_one(w['file']), pack_one(w['anim'])
|
||||
if s1 and s2:
|
||||
vm_weapons[name] = {'file': w['file'], 'anim': w['anim'], 'clips': w.get('clips') or [], 'gunClips': w.get('gunClips') or [], 'points': w.get('points') or {}, 'bytes': s1 + s2}
|
||||
total += s1 + s2
|
||||
viewmodels = {'arms': vm_arms, 'weapons': vm_weapons}
|
||||
print(f'1인칭 팔 {len(vm_arms)} · 무기 {len(vm_weapons)} · {total / 1e6:.1f}MB')
|
||||
# 공용 애니메이션 (anims 명령 결과 anims.glb): 뼈 이름으로 요원 몸에 붙인다 (-kn)
|
||||
anims = None
|
||||
if os.path.exists(os.path.join(src, 'anims.glb')):
|
||||
@@ -73,7 +94,7 @@ if os.path.exists(os.path.join(ad, 'abilities.json')):
|
||||
total += os.path.getsize(os.path.join(out, d, f + '.gz'))
|
||||
abilities = {'file': 'abilities.json', 'bytes': os.path.getsize(os.path.join(out, d, 'abilities.json.gz'))}
|
||||
print(f'스킬 재료 {total / 1e6:.1f}MB')
|
||||
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims, 'abilities': abilities}
|
||||
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims, 'abilities': abilities, 'viewmodels': viewmodels}
|
||||
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'))
|
||||
|
||||
@@ -18,6 +18,10 @@ E
|
||||
cat > "$T/fakebin" <<'E'
|
||||
#!/bin/bash
|
||||
[ "$1" = manifest ] && { echo "https://x/releases/${FAKE_MANIFEST:-AAA}.manifest"; exit 0; }
|
||||
# 공용 애니메이션 · 1인칭 · 스킬 재료: 이 시험에서는 만들 것 없이 성공
|
||||
[ "$1" = anims ] && exit 0
|
||||
[ "$1" = viewmodels ] && exit 0
|
||||
[ "$1" = abilities ] && { mkdir -p "$2"; exit 0; }
|
||||
if [ "$1" = agents ]; then
|
||||
# 요원 · 무기: FAKE_FAIL=agents 면 아무것도 못 뽑고 실패, agents-partial 이면 하나만 뽑고 실패 (실제 추출기처럼 종료 코드 1)
|
||||
[ "${FAKE_FAIL:-}" = agents ] && exit 1
|
||||
@@ -66,6 +70,7 @@ ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_FAIL=agents-par
|
||||
ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_AGENTS=Wushu FAKE_STAMP=5 run)"; ok "추출은 성공했지만 요원이 빠진 결과: 안 올림 · 유지" '[[ "$o" == *"빠진 요원: Hunter_PC_C"* && "$(agents)" == "[2,1]" && "$(st failed)" == *EEE* ]]'
|
||||
o="$(FAKE_MANIFEST=EEE run)"; ok "실패 기록이 남아 변경 없음으로 넘기지 않음 (대기 후 재시도)" '[[ "$o" == *"이후 다시"* && "$o" != *"변경 없음"* ]]'
|
||||
ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_AGENTS="Wushu Hunter Sarge" FAKE_STAMP=6 run)"; ok "요원 복구: 새 요원 포함해 올림" '[[ "$o" == *"사이트 반영 완료"* && "$(agents)" == "[3,1]" && "$(st failCount)" == 0 ]]'
|
||||
o="$(FAKE_MANIFEST=FFF FAKE_MAPS="Ascent BIND Haven" FAKE_AGENTS="Wushu Hunter Sarge" FAKE_STAMP=7 run)"; ok "맵 경로 대소문자만 바뀐 것은 빠진 것이 아님 (사이트도 대소문자 무시)" '[[ "$o" == *"사이트 반영 완료"* && "$(maps)" == *BIND* && "$(maps)" != *Bind* ]]'
|
||||
mv "$T/uedb.json" "$T/uedb.bak"; o="$(FAKE_MANIFEST=CCC run)"; mv "$T/uedb.bak" "$T/uedb.json"; ok "uedb 장애: 확인 실패 횟수만 셈" '[[ "$o" == *"확인 실패 (1 번째"* ]]'
|
||||
o="$(FAKE_MANIFEST=DDD FAKE_MAPS=Ascent FAKE_STAMP=4 run --force)"; ok "--force 면 빠진 맵도 올림" '[[ "$(maps)" == "[\"/Game/Maps/Ascent/Ascent\"]" ]]'
|
||||
exit $fail
|
||||
|
||||
@@ -126,6 +126,8 @@ GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"
|
||||
stage="요원 추출"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" agents "$raw"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" anims "$raw"
|
||||
# 1인칭 팔 · 무기 · 동작 (사이트 1인칭 화면)
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" viewmodels "$raw"
|
||||
# 스킬 재료 (메시 · 파티클 · 텍스처, 사이트가 스킬 효과를 그린다)
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" abilities "$raw/abilities"
|
||||
stage="압축"
|
||||
@@ -134,11 +136,12 @@ dir="$(jq -r .dir "$out/index.json")"
|
||||
count="$(jq '.maps | length' "$out/index.json")"
|
||||
|
||||
# 지금 사이트에 있는 맵 · 요원 · 무기가 새 결과에 다 있어야 올린다 (일부만 뽑힌 결과로 덮어쓰지 않게)
|
||||
# 대소문자는 보지 않는다: 패치에서 폴더 이름 대소문자만 바뀌기도 하고(13.09 /Game/Maps/FoxTrot → Foxtrot) 사이트도 대소문자 무시로 찾는다
|
||||
stage="맵 목록 대조"
|
||||
cur="$(ssh -o BatchMode=yes "$SITE_HOST" "cat '$SITE_DATA/maps3d/index.json' 2>/dev/null || echo '{}'")"
|
||||
prev="$(jq -r '.dir // empty' <<<"$cur")"
|
||||
for kind in maps:맵 agents:요원 weapons:무기; do
|
||||
missing="$(jq -rn --arg f "${kind%%:*}" --argjson a "$cur" --slurpfile b "$out/index.json" '[($a[$f] // {}) | keys[] as $k | select((($b[0][$f] // {}) | has($k)) | not) | $k] | join(", ")')"
|
||||
missing="$(jq -rn --arg f "${kind%%:*}" --argjson a "$cur" --slurpfile b "$out/index.json" '(($b[0][$f] // {}) | keys | map(ascii_downcase)) as $nk | [($a[$f] // {}) | keys[] | select(ascii_downcase as $l | $nk | index([$l]) | not)] | join(", ")')"
|
||||
if [ -n "$missing" ] && [ "$FORCE" = 0 ]; then
|
||||
log "새 결과에 빠진 ${kind#*:}: $missing → 올리지 않음 (게임에서 정말 빠졌으면 update.sh --force)"
|
||||
false
|
||||
|
||||
@@ -69,12 +69,50 @@ public static class Agents
|
||||
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 glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var (boneNode, bones, skin, tris) = Skinned(provider, glb, tex, mesh, lodWant);
|
||||
|
||||
// 애니메이션
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>스켈레탈 메시 하나를 glb 에 넣는다: 뼈 노드(참조 자세) · 피부(역바인드) · 재질별 primitive · 메시 노드(최상위).
|
||||
/// 뼈 노드 번호 · 뼈 · skin 객체 · 삼각형 수를 돌려준다 (skin 은 Write 의 extra "skins" 에 넣는다)</summary>
|
||||
public static (int[] BoneNode, MeshBoneDto[] Bones, JsonObject Skin, int Tris) Skinned(IFileProvider provider, Glb glb, TexStore tex, USkeletalMesh mesh, int lodWant, int skinIndex = 0, Func<string, bool>? skipMaterial = null)
|
||||
{
|
||||
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];
|
||||
@@ -153,7 +191,7 @@ public static class Agents
|
||||
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 (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate" || m!.Name.Contains("Hidden", StringComparison.OrdinalIgnoreCase)) || (m != null && skipMaterial?.Invoke(m.Name) == true))
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("GVR_DEBUG") != null) Console.Error.WriteLine($" 뺀 재질 {m?.Name} {mp.BlendMode} {mp.Base} 삼각형 {sec.NumFaces}");
|
||||
continue;
|
||||
@@ -189,39 +227,10 @@ public static class Agents
|
||||
});
|
||||
}
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = 0, ["skin"] = 0 });
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = glb.Meshes.Count - 1, ["skin"] = skinIndex });
|
||||
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);
|
||||
return (boneNode, bones, skin, tris);
|
||||
}
|
||||
|
||||
internal static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)
|
||||
|
||||
@@ -77,12 +77,24 @@ public sealed class Glb
|
||||
return Accessor(v, 5126, data.Length / comps, type);
|
||||
}
|
||||
|
||||
/// <summary>텍스처 (반복 샘플러) 번호</summary>
|
||||
public int Texture(byte[] image, string mime)
|
||||
private int _clampSampler = -1;
|
||||
|
||||
/// <summary>텍스처 번호 (기본 반복 샘플러, clamp 면 가장자리 고정 샘플러)</summary>
|
||||
public int Texture(byte[] image, string mime, bool clamp = false)
|
||||
{
|
||||
if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 });
|
||||
var sampler = 0;
|
||||
if (clamp)
|
||||
{
|
||||
if (_clampSampler < 0)
|
||||
{
|
||||
Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 33071, ["wrapT"] = 33071 });
|
||||
_clampSampler = Samplers.Count - 1;
|
||||
}
|
||||
sampler = _clampSampler;
|
||||
}
|
||||
Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime });
|
||||
Textures.Add(new JsonObject { ["sampler"] = 0, ["source"] = Images.Count - 1 });
|
||||
Textures.Add(new JsonObject { ["sampler"] = sampler, ["source"] = Images.Count - 1 });
|
||||
return Textures.Count - 1;
|
||||
}
|
||||
|
||||
|
||||
315
tools/map-extract/src/Lightmaps.cs
Normal file
315
tools/map-extract/src/Lightmaps.cs
Normal file
@@ -0,0 +1,315 @@
|
||||
using CUE4Parse.UE4.Assets.Exports.BuildData;
|
||||
using CUE4Parse.UE4.Assets.Exports.Texture;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats.Jpeg;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>게임에 구워 둔 조명(HQ 라이트맵)을 맵 하나에 아틀라스 두 장으로 모은다.
|
||||
///
|
||||
/// 게임 라이트맵 텍스처(LightMapTexture2D, DXT5)는 위 절반이 계수 0(색 UVW² · 로그 밝기), 아래 절반이 계수 1(SH 방향 · 밝기 나머지)이다.
|
||||
/// 메시마다(FLightMap2D) 범위(ScaleVectors · AddVectors)가 달라서, 메시가 차지한 칸(UV × CoordinateScale + Bias)마다 그 범위로 푼다
|
||||
/// (UE LightmapCommon.ush GetLightMapColorHQ 와 같은 식).
|
||||
///
|
||||
/// 결과
|
||||
/// irr: sRGB(밝기 / K) — 표면 방향을 빼고 본 조명 색 (L · UVW · L0)
|
||||
/// sh : 방향 계수 / L0 를 ±2 → 0~1 로 — 사이트에서 조명 = irr · K · max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선)
|
||||
/// 칸 밖 텍셀은 이웃 값으로 채워(번짐 방지) 줄인 뒤 페이지째 아틀라스에 놓는다. 라이트맵이 없는 배치는 (0,0) 의 기본 칸(맵 평균 밝기, 방향 없음)을 쓴다.
|
||||
///
|
||||
/// 메모리: 배치를 모으는 동안은 텍스처 크기 · 칸 목록만 들고 있다가, Build 에서 페이지를 하나씩 풀어 바로 줄인다
|
||||
/// (페이지가 200개 넘는 맵도 원래 크기 값은 한 장 분량만 메모리에 있다).</summary>
|
||||
public sealed class Lightmaps
|
||||
{
|
||||
/// <summary>메시 하나가 차지한 칸: 범위(계수 0 · 1) · 페이지 안 위치</summary>
|
||||
private readonly record struct Alloc(FVector4 S0, FVector4 A0, FVector4 S1, FVector4 A1, float Bx, float By, float Cx, float Cy);
|
||||
|
||||
private sealed class PageData
|
||||
{
|
||||
public required string Key;
|
||||
public required UTexture2D Tex;
|
||||
public required int W, H; // 계수 하나(텍스처 절반) 크기
|
||||
public readonly List<Alloc> Allocs = new();
|
||||
public int Ox, Oy, Sw, Sh2; // 아틀라스 위치 · 줄인 크기
|
||||
public float[]? Irr, Sh; // 줄인 값 (Sw × Sh2 × 3)
|
||||
public bool[]? Valid;
|
||||
}
|
||||
|
||||
private readonly List<PageData> _pages = new();
|
||||
private readonly Dictionary<string, int> _byKey = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly HashSet<(int, float, float)> _done = new();
|
||||
public int Allocations, Failed;
|
||||
private int _atlasW, _atlasH;
|
||||
private const int Pad = 4; // 페이지 사이 여백 (밉맵 번짐 방지)
|
||||
private const int DefaultCell = 8;
|
||||
|
||||
/// <summary>라이트맵 텍스처 → 페이지 번호 (못 읽으면 -1). 여기서는 크기만 본다</summary>
|
||||
public int Page(FLightMap2D lm)
|
||||
{
|
||||
var idx = lm.Textures?[0];
|
||||
if (idx == null || idx.IsNull) return -1;
|
||||
var key = idx.ResolvedObject?.GetPathName() ?? idx.Name;
|
||||
if (_byKey.TryGetValue(key, out var p)) return p;
|
||||
try
|
||||
{
|
||||
var t = idx.Load<UTexture2D>();
|
||||
var w = t?.PlatformData?.SizeX ?? 0;
|
||||
var h = (t?.PlatformData?.SizeY ?? 0) / 2;
|
||||
if (t == null || w < 1 || h < 1) { Failed++; return _byKey[key] = -1; }
|
||||
_pages.Add(new PageData { Key = key, Tex = t, W = w, H = h });
|
||||
return _byKey[key] = _pages.Count - 1;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Failed++;
|
||||
if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {key}: {e.GetType().Name} {e.Message}");
|
||||
return _byKey[key] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>메시 하나가 차지한 칸을 적어 둔다 (같은 칸은 한 번만, 푸는 건 Build 에서)</summary>
|
||||
public void Allocate(int page, FLightMap2D lm, FVector2D bias)
|
||||
{
|
||||
if (page < 0 || !_done.Add((page, bias.X, bias.Y))) return;
|
||||
Allocations++;
|
||||
var cs = lm.CoordinateScale ?? new FVector2D(1, 1);
|
||||
_pages[page].Allocs.Add(new Alloc(lm.ScaleVectors![0], lm.AddVectors![0], lm.ScaleVectors![1], lm.AddVectors![1], bias.X, bias.Y, cs.X, cs.Y));
|
||||
}
|
||||
|
||||
/// <summary>페이지 공간 UV(0~1) → 아틀라스 UV. page < 0 이면 기본 칸 가운데</summary>
|
||||
public (float u, float v) ToAtlas(int page, float u, float v)
|
||||
{
|
||||
if (page < 0 || _atlasW == 0) return ((DefaultCell / 2f) / Math.Max(1, _atlasW), (DefaultCell / 2f) / Math.Max(1, _atlasH));
|
||||
var p = _pages[page];
|
||||
u = Math.Clamp(u, 0, 1);
|
||||
v = Math.Clamp(v, 0, 1);
|
||||
return ((p.Ox + u * p.Sw) / _atlasW, (p.Oy + v * p.Sh2) / _atlasH);
|
||||
}
|
||||
|
||||
public bool Any => _pages.Count > 0;
|
||||
public float K { get; private set; } = 1;
|
||||
public int AtlasW => _atlasW;
|
||||
public int AtlasH => _atlasH;
|
||||
public int Factor { get; private set; } = 1;
|
||||
public int Pages => _pages.Count;
|
||||
|
||||
/// <summary>아틀라스를 만든다 (너비 maxSide · 넓이 약 maxSide² 안에 들어가게 페이지를 1/2 씩 줄인다). 이 뒤에 ToAtlas 를 쓴다</summary>
|
||||
public (byte[] irr, byte[] sh)? Build(int maxSide)
|
||||
{
|
||||
if (_pages.Count == 0) return null;
|
||||
// 줄이는 배율: 너비 maxSide · 높이 2×maxSide · 넓이 1.25×maxSide² 안에 들어갈 때까지 1/2 씩
|
||||
var f = 1;
|
||||
while (!Pack(f, maxSide) && f < 64) f *= 2;
|
||||
Factor = f;
|
||||
|
||||
// 페이지마다: 풀기 → 칸 밖 채우기 → 줄이기 (원래 크기 값은 한 장 분량만)
|
||||
var lum = new List<float>();
|
||||
double sr = 0, sg = 0, sb = 0;
|
||||
long n = 0;
|
||||
foreach (var p in _pages)
|
||||
{
|
||||
float[] irrF, shF;
|
||||
bool[] valid;
|
||||
try
|
||||
{
|
||||
(irrF, shF, valid) = Decode(p);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Failed++;
|
||||
if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {p.Key}: {e.GetType().Name} {e.Message}");
|
||||
continue; // 이 페이지는 평균 밝기로 남는다
|
||||
}
|
||||
for (var i = 0; i < valid.Length; i++)
|
||||
if (valid[i])
|
||||
{
|
||||
if ((i & 7) == 0) lum.Add(MathF.Max(irrF[i * 3], MathF.Max(irrF[i * 3 + 1], irrF[i * 3 + 2])));
|
||||
sr += irrF[i * 3]; sg += irrF[i * 3 + 1]; sb += irrF[i * 3 + 2];
|
||||
n++;
|
||||
}
|
||||
Dilate(p.W, p.H, irrF, shF, valid, 8);
|
||||
Shrink(p, f, irrF, shF, valid);
|
||||
}
|
||||
if (n == 0) return null;
|
||||
lum.Sort();
|
||||
K = Math.Max(0.05f, lum[(int)(lum.Count * 0.998)]);
|
||||
var avg = new[] { (float)(sr / n), (float)(sg / n), (float)(sb / n) };
|
||||
|
||||
using var irr = new Image<Rgb24>(_atlasW, _atlasH);
|
||||
using var sh = new Image<Rgb24>(_atlasW, _atlasH, new Rgb24(128, 128, 128));
|
||||
static byte Enc(float v) => (byte)Math.Clamp(MathF.Round(v * 255), 0, 255);
|
||||
static float Srgb(float v) => v <= 0.0031308f ? v * 12.92f : 1.055f * MathF.Pow(v, 1 / 2.4f) - 0.055f;
|
||||
Rgb24 IrrPx(float r, float g, float b) => new(Enc(Srgb(Math.Min(1, r / K))), Enc(Srgb(Math.Min(1, g / K))), Enc(Srgb(Math.Min(1, b / K))));
|
||||
static Rgb24 ShPx(float x, float y, float z) => new(Enc(x / 4 + 0.5f), Enc(y / 4 + 0.5f), Enc(z / 4 + 0.5f));
|
||||
// 기본 칸
|
||||
for (var y = 0; y < DefaultCell; y++)
|
||||
for (var x = 0; x < DefaultCell; x++) irr[x, y] = IrrPx(avg[0], avg[1], avg[2]);
|
||||
foreach (var p in _pages)
|
||||
{
|
||||
// 여백은 가장자리 값으로
|
||||
for (var y = -Pad; y < p.Sh2 + Pad; y++)
|
||||
for (var x = -Pad; x < p.Sw + Pad; x++)
|
||||
{
|
||||
var k = Math.Clamp(y, 0, p.Sh2 - 1) * p.Sw + Math.Clamp(x, 0, p.Sw - 1);
|
||||
var ax = p.Ox + x;
|
||||
var ay = p.Oy + y;
|
||||
if (p.Valid == null || !p.Valid[k])
|
||||
{
|
||||
irr[ax, ay] = IrrPx(avg[0], avg[1], avg[2]);
|
||||
continue;
|
||||
}
|
||||
irr[ax, ay] = IrrPx(p.Irr![k * 3], p.Irr[k * 3 + 1], p.Irr[k * 3 + 2]);
|
||||
sh[ax, ay] = ShPx(p.Sh![k * 3], p.Sh[k * 3 + 1], p.Sh[k * 3 + 2]);
|
||||
}
|
||||
p.Irr = p.Sh = null;
|
||||
p.Valid = null;
|
||||
}
|
||||
var enc = new JpegEncoder { Quality = 90, ColorType = JpegEncodingColor.YCbCrRatio444 };
|
||||
using var mi = new MemoryStream();
|
||||
irr.SaveAsJpeg(mi, enc);
|
||||
using var ms = new MemoryStream();
|
||||
sh.SaveAsJpeg(ms, enc);
|
||||
return (mi.ToArray(), ms.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>페이지 텍스처를 풀어 칸마다 그 범위로 irr · sh 를 계산한다 (원래 크기)</summary>
|
||||
private static (float[] irr, float[] sh, bool[] valid) Decode(PageData p)
|
||||
{
|
||||
var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(p.Tex) ?? throw new InvalidDataException("텍스처를 못 풂");
|
||||
var bgra = c.PixelFormat == EPixelFormat.PF_B8G8R8A8;
|
||||
if (!bgra && c.PixelFormat != EPixelFormat.PF_R8G8B8A8) throw new InvalidDataException("형식 " + c.PixelFormat);
|
||||
if (c.Width != p.W || c.Height < p.H * 2 || c.Data.Length < c.Width * c.Height * 4) throw new InvalidDataException($"크기 {c.Width}x{c.Height}");
|
||||
var src = c.Data;
|
||||
int R = bgra ? 2 : 0, B = bgra ? 0 : 2;
|
||||
var irr = new float[p.W * p.H * 3];
|
||||
var sh = new float[p.W * p.H * 3];
|
||||
var valid = new bool[p.W * p.H];
|
||||
const float LogBlackPoint = 0.01858136f;
|
||||
float C(int i) => src[i] / 255f;
|
||||
foreach (var a in p.Allocs)
|
||||
{
|
||||
// 칸 + 1 텍셀 (UE 는 칸 둘레에 여백을 두고 구운 값을 채운다)
|
||||
var x0 = Math.Max(0, (int)Math.Floor(a.Bx * p.W) - 1);
|
||||
var y0 = Math.Max(0, (int)Math.Floor(a.By * p.H) - 1);
|
||||
var x1 = Math.Min(p.W, (int)Math.Ceiling((a.Bx + a.Cx) * p.W) + 1);
|
||||
var y1 = Math.Min(p.H, (int)Math.Ceiling((a.By + a.Cy) * p.H) + 1);
|
||||
for (var y = y0; y < y1; y++)
|
||||
for (var x = x0; x < x1; x++)
|
||||
{
|
||||
var i0 = (y * p.W + x) * 4;
|
||||
var i1 = ((y + p.H) * p.W + x) * 4;
|
||||
var logL = C(i0 + 3) + C(i1 + 3) / 255f - 0.5f / 255f;
|
||||
logL = logL * a.S0.W + a.A0.W;
|
||||
var l = MathF.Max(0, MathF.Pow(2, logL) - LogBlackPoint);
|
||||
var r = C(i0 + R) * C(i0 + R) * a.S0.X + a.A0.X;
|
||||
var g = C(i0 + 1) * C(i0 + 1) * a.S0.Y + a.A0.Y;
|
||||
var b = C(i0 + B) * C(i0 + B) * a.S0.Z + a.A0.Z;
|
||||
var l0 = C(i1 + 3) * a.S1.W + a.A1.W;
|
||||
if (l0 < 1e-4f) l0 = 0.282095f;
|
||||
var o = (y * p.W + x) * 3;
|
||||
irr[o] = MathF.Max(0, l * r * l0);
|
||||
irr[o + 1] = MathF.Max(0, l * g * l0);
|
||||
irr[o + 2] = MathF.Max(0, l * b * l0);
|
||||
sh[o] = (C(i1 + R) * a.S1.X + a.A1.X) / l0;
|
||||
sh[o + 1] = (C(i1 + 1) * a.S1.Y + a.A1.Y) / l0;
|
||||
sh[o + 2] = (C(i1 + B) * a.S1.Z + a.A1.Z) / l0;
|
||||
valid[y * p.W + x] = true;
|
||||
}
|
||||
}
|
||||
return (irr, sh, valid);
|
||||
}
|
||||
|
||||
/// <summary>f×f 평균으로 줄여 페이지에 둔다 (칸 밖 · 채우지 못한 텍셀은 빼고)</summary>
|
||||
private static void Shrink(PageData p, int f, float[] irrF, float[] shF, bool[] validF)
|
||||
{
|
||||
p.Irr = new float[p.Sw * p.Sh2 * 3];
|
||||
p.Sh = new float[p.Sw * p.Sh2 * 3];
|
||||
p.Valid = new bool[p.Sw * p.Sh2];
|
||||
for (var y = 0; y < p.Sh2; y++)
|
||||
for (var x = 0; x < p.Sw; x++)
|
||||
{
|
||||
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
|
||||
var cnt = 0;
|
||||
for (var dy = 0; dy < f; dy++)
|
||||
for (var dx = 0; dx < f; dx++)
|
||||
{
|
||||
var px = Math.Min(p.W - 1, x * f + dx);
|
||||
var py = Math.Min(p.H - 1, y * f + dy);
|
||||
var k = py * p.W + px;
|
||||
if (!validF[k]) continue;
|
||||
r += irrF[k * 3]; g += irrF[k * 3 + 1]; b += irrF[k * 3 + 2];
|
||||
hx += shF[k * 3]; hy += shF[k * 3 + 1]; hz += shF[k * 3 + 2];
|
||||
cnt++;
|
||||
}
|
||||
if (cnt == 0) continue;
|
||||
var o = (y * p.Sw + x) * 3;
|
||||
p.Irr[o] = r / cnt; p.Irr[o + 1] = g / cnt; p.Irr[o + 2] = b / cnt;
|
||||
p.Sh[o] = hx / cnt; p.Sh[o + 1] = hy / cnt; p.Sh[o + 2] = hz / cnt;
|
||||
p.Valid[y * p.Sw + x] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>1/f 로 줄인 페이지를 너비 maxSide 선반에 쌓는다 (높은 것부터). 한도 안이면 true</summary>
|
||||
private bool Pack(int f, int maxSide)
|
||||
{
|
||||
foreach (var p in _pages)
|
||||
{
|
||||
p.Sw = Math.Max(1, p.W / f);
|
||||
p.Sh2 = Math.Max(1, p.H / f);
|
||||
}
|
||||
var order = Enumerable.Range(0, _pages.Count).OrderByDescending(i => _pages[i].Sh2).ThenByDescending(i => _pages[i].Sw).ToList();
|
||||
int cx = DefaultCell + Pad, cy = 0, shelf = DefaultCell, wMax = 0;
|
||||
foreach (var i in order)
|
||||
{
|
||||
var p = _pages[i];
|
||||
if (p.Sw + Pad * 2 > maxSide) return false;
|
||||
if (cx + p.Sw + Pad * 2 > maxSide) { cx = 0; cy += shelf; shelf = 0; }
|
||||
p.Ox = cx + Pad;
|
||||
p.Oy = cy + Pad;
|
||||
cx += p.Sw + Pad * 2;
|
||||
shelf = Math.Max(shelf, p.Sh2 + Pad * 2);
|
||||
wMax = Math.Max(wMax, cx);
|
||||
}
|
||||
// WebGL2 는 2 의 거듭제곱이 아니어도 밉맵을 쓴다 → 8 의 배수로만 (JPEG 블록)
|
||||
_atlasW = (wMax + 7) / 8 * 8;
|
||||
_atlasH = (cy + shelf + 7) / 8 * 8;
|
||||
return _atlasH <= maxSide * 2 && (long)_atlasW * _atlasH <= (long)maxSide * maxSide * 5 / 4;
|
||||
}
|
||||
|
||||
/// <summary>칸 밖 텍셀을 이웃 칸 값으로 채운다 (줄이기 · 선형 보간에서 검은 테두리가 번지지 않게)</summary>
|
||||
private static void Dilate(int w, int h, float[] irr, float[] sh, bool[] valid, int passes)
|
||||
{
|
||||
var add = new List<int>();
|
||||
for (var pass = 0; pass < passes; pass++)
|
||||
{
|
||||
add.Clear();
|
||||
for (var y = 0; y < h; y++)
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var k = y * w + x;
|
||||
if (valid[k]) continue;
|
||||
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
|
||||
var cnt = 0;
|
||||
for (var dy = -1; dy <= 1; dy++)
|
||||
for (var dx = -1; dx <= 1; dx++)
|
||||
{
|
||||
var nx = x + dx;
|
||||
var ny = y + dy;
|
||||
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
||||
var j = ny * w + nx;
|
||||
if (!valid[j]) continue;
|
||||
r += irr[j * 3]; g += irr[j * 3 + 1]; b += irr[j * 3 + 2];
|
||||
hx += sh[j * 3]; hy += sh[j * 3 + 1]; hz += sh[j * 3 + 2];
|
||||
cnt++;
|
||||
}
|
||||
if (cnt == 0) continue;
|
||||
irr[k * 3] = r / cnt; irr[k * 3 + 1] = g / cnt; irr[k * 3 + 2] = b / cnt;
|
||||
sh[k * 3] = hx / cnt; sh[k * 3 + 1] = hy / cnt; sh[k * 3 + 2] = hz / cnt;
|
||||
add.Add(k);
|
||||
}
|
||||
if (add.Count == 0) break;
|
||||
foreach (var k in add) valid[k] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.BuildData;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
@@ -80,13 +81,19 @@ 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>메시 한 LOD: 위치 · 법선 · UV · 라이트맵 UV(LOD0 만) · 정점 색 · 삼각형 · 재질 구간</summary>
|
||||
private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, float[]? Lm, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod);
|
||||
|
||||
/// <summary>배치 하나의 라이트맵 자리: 페이지 · 페이지 안 UV = 라이트맵 UV × Scale + Bias</summary>
|
||||
private readonly record struct LmPlace(int Page, float Sx, float Sy, float Bx, float By);
|
||||
private readonly Lightmaps _lm = new();
|
||||
public int LitPlacements;
|
||||
|
||||
/// <summary>재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다</summary>
|
||||
private sealed class Bucket
|
||||
{
|
||||
public readonly List<float> Pos = new(), Nrm = new(), Uv = new();
|
||||
public readonly List<float> Pos = new(), Nrm = new(), Uv = new(), Lm = new();
|
||||
public readonly List<int> LmPage = new();
|
||||
public readonly List<byte> Col = new();
|
||||
public readonly List<uint> Idx = new();
|
||||
}
|
||||
@@ -130,6 +137,12 @@ public sealed class MapScene
|
||||
{
|
||||
s._levels.Add(Path.GetFileNameWithoutExtension(level));
|
||||
var pkg = provider.LoadPackage(level);
|
||||
// 이 레벨에 구워 둔 조명 (<레벨>_BuiltData)
|
||||
UMapBuildDataRegistry? reg = null;
|
||||
var bd = level[..^".umap".Length] + "_BuiltData.uasset";
|
||||
if (provider.Files.ContainsKey(bd))
|
||||
try { reg = provider.LoadPackage(bd).GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault(); }
|
||||
catch (Exception e) { Console.Error.WriteLine($"{bd}: 조명 읽기 실패 {e.GetType().Name} {e.Message}"); }
|
||||
foreach (var lazy in pkg.ExportsLazy)
|
||||
{
|
||||
UObject o;
|
||||
@@ -141,13 +154,21 @@ public sealed class MapScene
|
||||
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))
|
||||
// 구운 조명이 있으면 LOD0 (라이트맵 UV 는 LOD0 에만 있다), 없으면 가장 낮은 LOD
|
||||
FLightMap2D? lm = null;
|
||||
FMeshMapBuildData? bdata = null;
|
||||
if (reg?.MeshBuildData != null && c.LODData is { Length: > 0 } ld0 && reg.MeshBuildData.TryGetValue(ld0[0].MapBuildDataId, out bdata)
|
||||
&& bdata.LightMap is FLightMap2D l2 && l2.Textures?[0] is { IsNull: false } && l2.ScaleVectors != null && l2.AddVectors != null) lm = l2;
|
||||
var lmIdx = lm != null ? mesh.GetOrDefault("LightMapCoordinateIndex", 0) : -1;
|
||||
var key = lm != null ? $"{path}#lm{lmIdx}" : path;
|
||||
if (!meshCache.TryGetValue(key, out var geo))
|
||||
{
|
||||
try { geo = Geometry(mesh); } catch { geo = null; s.Failed++; }
|
||||
meshCache[path] = geo;
|
||||
try { geo = Geometry(mesh, lmIdx); } catch { geo = null; s.Failed++; }
|
||||
meshCache[key] = geo;
|
||||
if (geo != null) s.Meshes++;
|
||||
}
|
||||
if (geo == null) continue;
|
||||
var page = lm != null && geo.Lm != null ? s._lm.Page(lm) : -1;
|
||||
FTransform w;
|
||||
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
|
||||
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
|
||||
@@ -164,26 +185,44 @@ public sealed class MapScene
|
||||
// 칠한 정점 색 (두 층 섞기에 쓴다): 컴포넌트 값이 정점 수와 맞을 때만
|
||||
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;
|
||||
var cs = lm?.CoordinateScale ?? new FVector2D(1, 1);
|
||||
LmPlace? Place(FVector2D bias)
|
||||
{
|
||||
if (page < 0) return null;
|
||||
s._lm.Allocate(page, lm!, bias);
|
||||
return new LmPlace(page, cs.X, cs.Y, bias.X, bias.Y);
|
||||
}
|
||||
if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data)
|
||||
foreach (var d in data) s.Add(geo, mats, col, d.TransformData * w);
|
||||
else s.Add(geo, mats, col, w);
|
||||
{
|
||||
// 인스턴스마다 라이트맵 칸이 따로 (FPerInstanceLightmapData). HISM 은 순서가 바뀌어 있을 수 있다 (InstanceReorderTable)
|
||||
var per = bdata?.PerInstanceLightmapData ?? [];
|
||||
var reorder = c.GetOrDefault<int[]>("InstanceReorderTable", []);
|
||||
for (var i = 0; i < data.Length; i++)
|
||||
{
|
||||
var ri = reorder.Length == data.Length ? reorder[i] : i;
|
||||
var lp = ri >= 0 && ri < per.Length ? Place(per[ri].LightmapUVBias) : null;
|
||||
s.Add(geo, mats, col, data[i].TransformData * w, lp);
|
||||
}
|
||||
}
|
||||
else s.Add(geo, mats, col, w, lm != null ? Place(lm.CoordinateBias ?? new FVector2D(0, 0)) : null);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다)</summary>
|
||||
private static Geo? Geometry(UStaticMesh mesh)
|
||||
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다). lmIdx ≥ 0 이면 LOD0 + 그 UV 채널(라이트맵)</summary>
|
||||
private static Geo? Geometry(UStaticMesh mesh, int lmIdx = -1)
|
||||
{
|
||||
var lods = mesh.RenderData?.LODs;
|
||||
if (lods == null) return null;
|
||||
for (var l = lods.Length - 1; l >= 0; l--)
|
||||
for (var l = lmIdx >= 0 ? 0 : lods.Length - 1; l >= 0 && l < lods.Length; l += lmIdx >= 0 ? 1 : -1)
|
||||
{
|
||||
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 uvItems = lod.VertexBuffer?.UV;
|
||||
var n = new FVector[v.Length];
|
||||
var uv = new float[v.Length * 2];
|
||||
var lmUv = lmIdx >= 0 && uvItems != null && uvItems.Length == v.Length && uvItems.All(x => x.UV != null && x.UV.Length > lmIdx) ? new float[v.Length * 2] : null;
|
||||
if (uvItems != null && uvItems.Length == v.Length)
|
||||
for (var i = 0; i < v.Length; i++)
|
||||
{
|
||||
@@ -194,17 +233,23 @@ public sealed class MapScene
|
||||
uv[i * 2] = it.UV[0].U;
|
||||
uv[i * 2 + 1] = it.UV[0].V;
|
||||
}
|
||||
if (lmUv != null)
|
||||
{
|
||||
lmUv[i * 2] = it.UV[lmIdx].U;
|
||||
lmUv[i * 2 + 1] = it.UV[lmIdx].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 new Geo(v, n, uv, lmUv, col, ib.Select(x => (uint)x).ToArray(), secs, l);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t)
|
||||
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t, LmPlace? lp)
|
||||
{
|
||||
Placements++;
|
||||
if (lp != null) LitPlacements++;
|
||||
// UE 는 왼손 좌표계라 glTF(오른손, 반시계 앞면) 로 그대로 옮기면 앞뒤가 바뀐다 → 기본으로 뒤집는다.
|
||||
// 크기가 음수(거울)면 한 번 더 뒤집힌다
|
||||
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z >= 0;
|
||||
@@ -228,6 +273,16 @@ public sealed class MapScene
|
||||
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 (lp is { } q && g.Lm != null)
|
||||
{
|
||||
b.Lm.Add(g.Lm[i * 2] * q.Sx + q.Bx); b.Lm.Add(g.Lm[i * 2 + 1] * q.Sy + q.By);
|
||||
b.LmPage.Add(q.Page);
|
||||
}
|
||||
else
|
||||
{
|
||||
b.Lm.Add(0); b.Lm.Add(0);
|
||||
b.LmPage.Add(-1);
|
||||
}
|
||||
if (m.Blend)
|
||||
{
|
||||
var c = col != null ? col[i] : new FColor(255, 255, 255, 255);
|
||||
@@ -255,7 +310,8 @@ public sealed class MapScene
|
||||
public long Triangles => _tris;
|
||||
public int Materials => _buckets.Count;
|
||||
public int TextureCount, TextureFailed;
|
||||
public long TextureBytes;
|
||||
public long TextureBytes, LightmapBytes;
|
||||
public string LightmapSummary => _lm.Any ? $"조명 {LitPlacements}/{Placements} 배치 · 페이지 {_lm.Pages}(실패 {_lm.Failed}) · 칸 {_lm.Allocations} · 아틀라스 {_lm.AtlasW}x{_lm.AtlasH} (1/{_lm.Factor}) {LightmapBytes >> 10}KB · K {_lm.K:F2}" : "조명 없음";
|
||||
|
||||
/// <summary>glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색).
|
||||
/// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다)</summary>
|
||||
@@ -264,6 +320,16 @@ public sealed class MapScene
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var prims = new System.Text.Json.Nodes.JsonArray();
|
||||
// 구운 조명 아틀라스: 모든 재질에 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) 로 TEXCOORD_1 에 붙인다.
|
||||
// (gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 사이트는 둘을 떼어 조명으로 쓴다)
|
||||
int? irrTex = null, shTex = null;
|
||||
var lmMax = int.Parse(Environment.GetEnvironmentVariable("GVR_LIGHTMAP") ?? "2048");
|
||||
if (lmMax > 0 && _lm.Build(lmMax) is var (irrJpg, shJpg))
|
||||
{
|
||||
irrTex = glb.Texture(irrJpg, "image/jpeg", clamp: true);
|
||||
shTex = glb.Texture(shJpg, "image/jpeg", clamp: true);
|
||||
LightmapBytes = irrJpg.Length + shJpg.Length;
|
||||
}
|
||||
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))
|
||||
{
|
||||
@@ -279,6 +345,12 @@ public sealed class MapScene
|
||||
};
|
||||
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 (irrTex is { } it && shTex is { } st)
|
||||
{
|
||||
mat["occlusionTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = it, ["texCoord"] = 1, ["strength"] = 1 };
|
||||
mat["emissiveTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = st, ["texCoord"] = 1 };
|
||||
mat["emissiveFactor"] = new System.Text.Json.Nodes.JsonArray(0, 0, 0);
|
||||
}
|
||||
if (m.Translucent) mat["alphaMode"] = "BLEND";
|
||||
else if (m.Masked && a is { alpha: true })
|
||||
{
|
||||
@@ -286,12 +358,16 @@ public sealed class MapScene
|
||||
mat["alphaCutoff"] = 0.333;
|
||||
mat["doubleSided"] = true;
|
||||
}
|
||||
var extras = new System.Text.Json.Nodes.JsonObject();
|
||||
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 };
|
||||
extras["blend"] = ex;
|
||||
}
|
||||
// 구운 조명: irr 텍스처 값(sRGB) 1 = 밝기 K
|
||||
if (irrTex != null) extras["lightmap"] = new System.Text.Json.Nodes.JsonObject { ["k"] = _lm.K, ["v"] = 1 };
|
||||
if (extras.Count > 0) mat["extras"] = extras;
|
||||
glb.Materials.Add(mat);
|
||||
var attrs = new System.Text.Json.Nodes.JsonObject
|
||||
{
|
||||
@@ -300,6 +376,13 @@ public sealed class MapScene
|
||||
["TEXCOORD_0"] = glb.Floats(b.Uv.ToArray(), 2),
|
||||
};
|
||||
if (m.Blend) attrs["COLOR_0"] = glb.Bytes(b.Col.ToArray(), 4);
|
||||
if (irrTex != null)
|
||||
{
|
||||
var lmuv = new float[b.Lm.Count];
|
||||
for (var i = 0; i < b.LmPage.Count; i++)
|
||||
(lmuv[i * 2], lmuv[i * 2 + 1]) = _lm.ToAtlas(b.LmPage[i], b.Lm[i * 2], b.Lm[i * 2 + 1]);
|
||||
attrs["TEXCOORD_1"] = glb.Floats(lmuv, 2);
|
||||
}
|
||||
prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 });
|
||||
}
|
||||
glb.Meshes.Add(new System.Text.Json.Nodes.JsonObject { ["name"] = _code, ["primitives"] = prims });
|
||||
@@ -327,6 +410,7 @@ public sealed class MapScene
|
||||
textures = TextureCount,
|
||||
texturesFailed = TextureFailed,
|
||||
textureBytes = TextureBytes,
|
||||
lightmap = _lm.Any ? new { placements = LitPlacements, pages = _lm.Pages, failed = _lm.Failed, allocations = _lm.Allocations, atlas = new[] { _lm.AtlasW, _lm.AtlasH }, factor = _lm.Factor, bytes = LightmapBytes, k = _lm.K } : null,
|
||||
skipped = Skipped,
|
||||
failed = Failed,
|
||||
manifest,
|
||||
|
||||
76
tools/map-extract/src/ProbeLight.cs
Normal file
76
tools/map-extract/src/ProbeLight.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using SixLabors.ImageSharp;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.BuildData;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.Texture;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>조사용: 레벨 BuiltData 의 라이트맵</summary>
|
||||
public static class ProbeLight
|
||||
{
|
||||
public static void Run(IFileProvider provider, string umap)
|
||||
{
|
||||
var bd = umap[..^".umap".Length] + "_BuiltData.uasset";
|
||||
var pkg = provider.LoadPackage(bd);
|
||||
var reg = pkg.GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault();
|
||||
Console.WriteLine($"{bd}: exports {string.Join(',', pkg.GetExports().GroupBy(e => e.ExportType).Select(g => g.Key + "x" + g.Count()))}");
|
||||
if (reg == null) return;
|
||||
Console.WriteLine($"mesh build data {reg.MeshBuildData?.Count} light {reg.LightBuildData?.Count} vlm {reg.LevelPrecomputedVolumetricLightmapBuildData?.Count}");
|
||||
var dump = Environment.GetEnvironmentVariable("GVR_LM_DUMP");
|
||||
foreach (var t in pkg.GetExports().OfType<UTexture2D>().Where(t => !t.Name.StartsWith("AOMaterial")))
|
||||
{
|
||||
Console.WriteLine($" tex {t.Name} {t.ExportType} {t.PlatformData?.SizeX}x{t.PlatformData?.SizeY} {t.Format} mips {t.PlatformData?.Mips?.Length} srgb {t.SRGB}");
|
||||
if (dump == null) continue;
|
||||
var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(t);
|
||||
if (c == null) { Console.WriteLine(" decode null"); continue; }
|
||||
Console.WriteLine($" decoded {c.Width}x{c.Height} {c.PixelFormat} {c.Data.Length}");
|
||||
Directory.CreateDirectory(dump);
|
||||
var px = c.Data;
|
||||
using var rgb = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.Rgba32>(c.Width, c.Height);
|
||||
using var a = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.L8>(c.Width, c.Height);
|
||||
var bgra = c.PixelFormat == CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_B8G8R8A8;
|
||||
for (var y = 0; y < c.Height; y++) for (var x = 0; x < c.Width; x++)
|
||||
{
|
||||
var i = (y * c.Width + x) * 4;
|
||||
rgb[x, y] = bgra ? new(px[i + 2], px[i + 1], px[i], 255) : new(px[i], px[i + 1], px[i + 2], 255);
|
||||
a[x, y] = new(px[i + 3]);
|
||||
}
|
||||
rgb.SaveAsPng(Path.Combine(dump, t.Name + ".rgb.png"));
|
||||
a.SaveAsPng(Path.Combine(dump, t.Name + ".a.png"));
|
||||
}
|
||||
var n = 0;
|
||||
foreach (var (g, d) in reg.MeshBuildData ?? new())
|
||||
{
|
||||
if (n++ >= 4) break;
|
||||
if (d.LightMap is FLightMap2D lm)
|
||||
Console.WriteLine($" {g}: tex {lm.Textures?[0]?.Name}/{lm.Textures?[1]?.Name} vt {lm.VirtualTextures?[0]?.Name} sky {lm.SkyOcclusionTexture?.Name} scale {string.Join(' ', lm.ScaleVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} add {string.Join(' ', lm.AddVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} cs {lm.CoordinateScale} cb {lm.CoordinateBias} inst {d.PerInstanceLightmapData.Length} shadow {d.ShadowMap?.GetType().Name}");
|
||||
else Console.WriteLine($" {g}: lightmap {d.LightMap?.GetType().Name ?? "none"} inst {d.PerInstanceLightmapData.Length}");
|
||||
}
|
||||
// 레벨 컴포넌트 → 빌드 데이터 연결
|
||||
var lvl = provider.LoadPackage(umap);
|
||||
int comps = 0, hit = 0, ism = 0, ismHit = 0, lodMulti = 0;
|
||||
foreach (var lazy in lvl.ExportsLazy)
|
||||
{
|
||||
UObject o;
|
||||
try { o = lazy.Value; } catch { continue; }
|
||||
if (o is not UStaticMeshComponent c) continue;
|
||||
comps++;
|
||||
var ids = c.LODData?.Select(l => l.MapBuildDataId).ToArray() ?? [];
|
||||
if (ids.Length > 1) lodMulti++;
|
||||
var ok = ids.Length > 0 && reg.MeshBuildData!.ContainsKey(ids[0]);
|
||||
if (ok) hit++;
|
||||
if (c is UInstancedStaticMeshComponent im) { ism++; if (ok) ismHit++; }
|
||||
if (comps <= 5)
|
||||
{
|
||||
UStaticMesh? mesh = null;
|
||||
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { }
|
||||
var lods = mesh?.RenderData?.LODs;
|
||||
Console.WriteLine($" comp {c.Name} {c.ExportType} lods {ids.Length} [{string.Join(',', ids.Select(i => reg.MeshBuildData!.ContainsKey(i) ? "Y" : "n"))}] mesh {mesh?.Name} lmIdx {mesh?.GetOrDefault<int>("LightMapCoordinateIndex")} lmRes {mesh?.GetOrDefault<int>("LightMapResolution")} meshLods {lods?.Length} uvs {string.Join('/', lods?.Select(l => l.VertexBuffer?.NumTexCoords ?? 0) ?? [])} compLmRes {c.GetOrDefault<int>("OverriddenLightMapRes")}");
|
||||
}
|
||||
}
|
||||
Console.WriteLine($"comps {comps} with build data {hit}; ism {ism} hit {ismHit}; multi-lod {lodMulti}");
|
||||
}
|
||||
}
|
||||
@@ -18,12 +18,14 @@ using GvrMapExtract;
|
||||
// gvr-map-extract agents <출력 폴더> [요원...] 요원 몸 agent_<코드>.glb · 무기 weapon_<이름>.glb + agents.json
|
||||
// gvr-map-extract anims <출력 폴더> 모든 요원 공용 애니메이션 anims.glb
|
||||
// gvr-map-extract abilities <출력 폴더> [요원 · 클래스...] 스킬 재료 abilities.json + m_*.glb + t_*.png
|
||||
// gvr-map-extract viewmodels <출력 폴더> [요원...|weapons] 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb + viewmodels.json
|
||||
//
|
||||
// 환경변수
|
||||
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
|
||||
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
|
||||
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
|
||||
// GVR_TEX 텍스처 최대 크기 (기본 256)
|
||||
// GVR_LIGHTMAP 구운 조명 아틀라스 너비 (기본 2048, 넓이도 약 이것의 제곱 안. 0 이면 조명을 넣지 않는다)
|
||||
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
|
||||
|
||||
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
|
||||
@@ -102,7 +104,7 @@ switch (args[0])
|
||||
var r = MapScene.Build(provider, m);
|
||||
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.Materials} · 텍스처 {r.TextureCount}({r.TextureBytes >> 20}MB, 실패 {r.TextureFailed}) · 빠짐 {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.LightmapSummary} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -179,9 +181,15 @@ switch (args[0])
|
||||
Console.WriteLine($"끝: 공용 애니메이션 {r.Clips} · 실패 {r.Failed}{(r.Missing.Count > 0 ? " · 빠짐 " + string.Join(',', r.Missing) : "")} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
|
||||
return r.Failed == 0 ? 0 : 1;
|
||||
}
|
||||
case "viewmodels":
|
||||
// 1인칭 팔 · 무기 · 동작: fparms_*.glb · fpweapon_*.glb · fpanim_*.glb + viewmodels.json (Viewmodels.cs)
|
||||
return Viewmodels.Run(provider, args[1], args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase), int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512"));
|
||||
case "abilities":
|
||||
// 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs)
|
||||
return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store);
|
||||
case "lmprobe":
|
||||
foreach (var a in args.Skip(1)) ProbeLight.Run(provider, a);
|
||||
break;
|
||||
case "anim":
|
||||
foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a);
|
||||
break;
|
||||
|
||||
203
tools/map-extract/src/Viewmodels.cs
Normal file
203
tools/map-extract/src/Viewmodels.cs
Normal file
@@ -0,0 +1,203 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports.Animation;
|
||||
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Objects.UObject;
|
||||
using CUE4Parse_Conversion.Animations;
|
||||
using CUE4Parse_Conversion.Dto;
|
||||
using CUE4Parse_Conversion.Options;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>
|
||||
/// 1인칭 화면(뷰모델): 요원 1인칭 팔 · 무기 1인칭 모델 · 동작. 좌표는 게임(UE) 그대로 cm.
|
||||
/// fparms_<코드>.glb 요원 1인칭 팔 (Characters/<코드>/S0/1P/Models/FP_<코드>_S0_Skelmesh). 뼈대는 모든 요원 공용 (Camera 뼈 = 눈)
|
||||
/// fpweapon_<이름>.glb 무기 1인칭 모델 (<무기 폴더>/S0/1P/Models/GN|EQ_*_S0_Skelmesh) + 탄창 + 총 동작(gun_fire · gun_reload · gun_equip)
|
||||
/// fpanim_<이름>.glb 그 무기를 든 팔 동작 (뼈 노드만): idle · fire · reload · equip · ads · walk · activate
|
||||
/// 사이트는 팔 뼈 MasterWeapon 에 무기 뿌리를 붙이고, 팔 Camera 뼈가 화면 카메라에 오게 놓는다.
|
||||
/// 덧셈 동작(FireAdd · WalkAdd)은 CUE4Parse 가 기준 자세에 더해 온전한 자세로 바꿔 준다.
|
||||
/// </summary>
|
||||
public static class Viewmodels
|
||||
{
|
||||
private static readonly (string Role, string[] Names)[] ArmClips =
|
||||
[
|
||||
("idle", ["IdlePose", "Idle"]),
|
||||
("fire", ["Fire", "FireAdd"]),
|
||||
("reload", ["Reload"]),
|
||||
("equip", ["Equip"]),
|
||||
("ads", ["AltIdlePose"]),
|
||||
("walk", ["WalkAdd"]),
|
||||
("activate", ["Activate"]),
|
||||
];
|
||||
private static readonly (string Role, string[] Names)[] GunClips =
|
||||
[
|
||||
("gun_fire", ["Fire", "FireAdd"]),
|
||||
("gun_reload", ["Reload"]),
|
||||
("gun_equip", ["Equip"]),
|
||||
];
|
||||
|
||||
private static readonly System.Text.RegularExpressions.Regex SpareMaterial = new(@"^(AB|ABTP|CS|TP)_", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
|
||||
public static string ArmsFile(string code) => $"fparms_{code}.glb";
|
||||
public static string WeaponFile(string name) => "fpweapon_" + name.Replace(' ', '_') + ".glb";
|
||||
public static string AnimFile(string name) => "fpanim_" + name.Replace(' ', '_') + ".glb";
|
||||
|
||||
public static int Run(IFileProvider provider, string outDir, IReadOnlyCollection<string> want, int maxTex)
|
||||
{
|
||||
Directory.CreateDirectory(outDir);
|
||||
var failed = 0;
|
||||
var arms = new SortedDictionary<string, object>();
|
||||
USkeletalMesh? refArms = null;
|
||||
foreach (var (code, _) in Agents.Find(provider).Where(a => want.Count == 0 || want.Contains(a.Code)))
|
||||
{
|
||||
// 보통 FP_<코드>_S0_Skelmesh, 바뀐 요원은 FP_<코드>_New_S0_Skelmesh (브리치)
|
||||
var mdir = $"ShooterGame/Content/Characters/{code}/S0/1P/Models/";
|
||||
var mre = new System.Text.RegularExpressions.Regex($@"/FP_{code}(_[A-Za-z0-9]+)?_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var mf = provider.Files.Keys.Where(k => k.StartsWith(mdir, StringComparison.OrdinalIgnoreCase) && mre.IsMatch(k)).OrderBy(k => k.Length).FirstOrDefault();
|
||||
if (mf == null) { Console.WriteLine($"{code}: 1인칭 팔 없음 (건너뜀)"); continue; }
|
||||
try
|
||||
{
|
||||
var mesh = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
|
||||
refArms ??= mesh;
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
// 1인칭 팔 메시에 같이 든 스킬 · 3인칭 조각(AB_ · ABTP_ · CS_ · TP_ 재질)은 평소에 안 보이므로 뺀다 (모든 구간이 그런 요원은 그대로)
|
||||
var names = mesh.SkeletalMaterials.Select(x => x.MaterialInterface?.Name ?? "").ToList();
|
||||
var spare = SpareMaterial;
|
||||
var (_, bones, skin, tris) = Agents.Skinned(provider, glb, tex, mesh, 0, 0, names.All(n => spare.IsMatch(n)) ? null : n => spare.IsMatch(n));
|
||||
glb.Write(Path.Combine(outDir, ArmsFile(code)), new JsonObject { ["skins"] = new JsonArray(skin) });
|
||||
arms[code + "_PC_C"] = new { code, file = ArmsFile(code), triangles = tris };
|
||||
Console.WriteLine($"{code}: 1인칭 팔 삼각형 {tris} · 뼈 {bones.Length} · 텍스처 {tex.Count}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"{code}: 1인칭 팔 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
// 팔 동작의 뼈 노드는 공용 뼈대 메시(없으면 처음 뽑은 요원 팔)로
|
||||
try { refArms = provider.LoadPackageObject<USkeletalMesh>("/Game/Characters/_Core/1P/Models/FP_Core_Retarget_Skelmesh.FP_Core_Retarget_Skelmesh"); } catch { }
|
||||
|
||||
var weapons = new SortedDictionary<string, object>();
|
||||
if (want.Count == 0 || want.Contains("weapons"))
|
||||
foreach (var (name, bp) in Weapons.List)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dir = "ShooterGame/Content" + bp["/Game".Length..bp.LastIndexOf('/')] + "/S0/1P/";
|
||||
var re = new System.Text.RegularExpressions.Regex(@"/(GN|EQ)_([A-Za-z0-9]+)_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var mf = provider.Files.Keys.Where(k => k.StartsWith(dir + "Models/", StringComparison.OrdinalIgnoreCase) && re.IsMatch(k) && !k.Contains("Defuser", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k.Length).FirstOrDefault();
|
||||
if (mf == null) { Console.WriteLine($"무기 {name}: 1인칭 모델 없음 (건너뜀)"); continue; }
|
||||
var gun = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
|
||||
var anims = provider.Files.Keys.Where(k => k.StartsWith(dir + "Anims/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".uasset", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
string? Find(string prefix, string[] names) =>
|
||||
names.Select(n => anims.FirstOrDefault(k => Path.GetFileNameWithoutExtension(k) is var f && f.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && f.EndsWith("_S0_" + n, StringComparison.OrdinalIgnoreCase))).FirstOrDefault(x => x != null);
|
||||
|
||||
// 무기: 몸(뼈대) + 탄창 + 총 동작
|
||||
var (_, mag) = Weapons.Find(provider, bp);
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var (boneNode, bones, skin, tris) = Agents.Skinned(provider, glb, tex, gun, 0);
|
||||
if (mag != null) tris += Weapons.AttachStatic(provider, glb, tex, mag, boneNode, bones, "Magazine_Main");
|
||||
var gunClips = Clips(provider, glb, gun, boneNode, bones, GunClips.Select(c => (c.Role, Find("GN_Core_", c.Names))));
|
||||
var points = new JsonObject();
|
||||
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target") })
|
||||
{
|
||||
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0) continue;
|
||||
var g = CUE4Parse.UE4.Objects.Core.Math.FTransform.Identity;
|
||||
for (var i = bi; i >= 0; i = bones[i].ParentIndex) g = g * bones[i].Transform;
|
||||
points[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
|
||||
}
|
||||
glb.Write(Path.Combine(outDir, WeaponFile(name)), new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = gunClips.json });
|
||||
|
||||
// 팔 동작 (뼈 노드만)
|
||||
var armRoles = new List<string>();
|
||||
if (refArms != null)
|
||||
{
|
||||
var ag = new Glb();
|
||||
var adto = new SkeletalMeshDto(refArms, EMeshQuality.All);
|
||||
var aNodes = BoneNodes(ag, adto.Bones);
|
||||
var ac = Clips(provider, ag, refArms, aNodes, adto.Bones, ArmClips.Select(c => (c.Role, Find("FP_Core_", c.Names))));
|
||||
armRoles = ac.roles;
|
||||
ag.Write(Path.Combine(outDir, AnimFile(name)), new JsonObject { ["animations"] = ac.json });
|
||||
}
|
||||
weapons[name] = new { file = WeaponFile(name), anim = AnimFile(name), mesh = gun.Name, triangles = tris, clips = armRoles, gunClips = gunClips.roles, points };
|
||||
Console.WriteLine($"무기 {name}: {gun.Name} 삼각형 {tris} · 팔 동작 {string.Join(',', armRoles)} · 총 동작 {string.Join(',', gunClips.roles)}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"무기 {name}: 1인칭 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
File.WriteAllText(Path.Combine(outDir, "viewmodels.json"), System.Text.Json.JsonSerializer.Serialize(new { arms, weapons }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"끝: 1인칭 팔 {arms.Count} · 무기 {weapons.Count} · 실패 {failed}");
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static string ObjPath(string file)
|
||||
{
|
||||
var p = "/Game" + file["ShooterGame/Content".Length..^".uasset".Length];
|
||||
return p + "." + p[(p.LastIndexOf('/') + 1)..];
|
||||
}
|
||||
|
||||
/// <summary>뼈 노드만 (참조 자세 TRS, 부모-자식). 최상위는 Roots 에</summary>
|
||||
private static int[] BoneNodes(Glb glb, MeshBoneDto[] bones)
|
||||
{
|
||||
var node = 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"] = new JsonArray(t.Translation.X, t.Translation.Y, t.Translation.Z),
|
||||
["rotation"] = new JsonArray(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
|
||||
});
|
||||
node[i] = glb.Nodes.Count - 1;
|
||||
}
|
||||
for (var i = 0; i < bones.Length; i++)
|
||||
{
|
||||
var p = bones[i].ParentIndex;
|
||||
if (p < 0) { glb.Roots.Add(node[i]); continue; }
|
||||
var parent = glb.Nodes[node[p]]!.AsObject();
|
||||
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
|
||||
ch.Add(node[i]);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/// <summary>역할마다 동작 하나 (모든 뼈, 움직이면 이동도). 못 찾거나 못 읽은 역할은 뺀다</summary>
|
||||
private static (JsonArray json, List<string> roles) Clips(IFileProvider provider, Glb glb, USkeletalMesh mesh, int[] boneNode, MeshBoneDto[] bones, IEnumerable<(string Role, string? File)> list)
|
||||
{
|
||||
var json = new JsonArray();
|
||||
var roles = new List<string>();
|
||||
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
|
||||
var all = Enumerable.Range(0, bones.Length).ToHashSet();
|
||||
foreach (var (role, file) in list)
|
||||
{
|
||||
if (file == null) continue;
|
||||
try
|
||||
{
|
||||
var a = provider.LoadPackageObject<UAnimSequence>(ObjPath(file));
|
||||
var set = a.ConvertAnims();
|
||||
var seq = set.Sequences[0];
|
||||
seq.RetargetTracks(mesh.ReferenceSkeleton);
|
||||
var clip = Agents.Clip(glb, seq, set.Skeleton, nameToBone, all, boneNode, bones, role, []);
|
||||
if (clip == null) continue;
|
||||
json.Add(clip);
|
||||
roles.Add(role);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine($" 동작 {role} ({Path.GetFileNameWithoutExtension(file)}) 실패: {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
}
|
||||
return (json, roles);
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,34 @@ public static class Weapons
|
||||
return tris;
|
||||
}
|
||||
|
||||
/// <summary>정적 메시(탄창)를 뼈 노드의 자식 메시로 붙인다 (뼈 공간 그대로). 붙인 삼각형 수</summary>
|
||||
public static int AttachStatic(IFileProvider provider, Glb glb, TexStore tex, UStaticMesh sm, int[] boneNode, MeshBoneDto[] bones, string bone)
|
||||
{
|
||||
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0 || sm.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is not { } ml || ml.PositionVertexBuffer?.Verts is not { Length: > 0 } mv || ml.IndexBuffer?.Buffer is not { } mib) return 0;
|
||||
var pos = new List<float>();
|
||||
var nrm = new List<float>();
|
||||
var uv = new List<float>();
|
||||
for (var i = 0; i < mv.Length; i++)
|
||||
{
|
||||
pos.AddRange([mv[i].X, mv[i].Y, mv[i].Z]);
|
||||
var it = ml.VertexBuffer?.UV is { } u && i < u.Length ? u[i] : null;
|
||||
var n = it?.Normal is { Length: >= 3 } nn ? (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 secs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < sm.StaticMaterials.Length ? sm.StaticMaterials[s.MaterialIndex].MaterialInterface : null))).ToList();
|
||||
var prims = new JsonArray();
|
||||
var tris = AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), secs);
|
||||
if (prims.Count == 0) return 0;
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = sm.Name, ["primitives"] = prims });
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = sm.Name, ["mesh"] = glb.Meshes.Count - 1 });
|
||||
var parent = glb.Nodes[boneNode[bi]]!.AsObject();
|
||||
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
|
||||
ch.Add(glb.Nodes.Count - 1);
|
||||
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);
|
||||
|
||||
@@ -62,6 +62,9 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
[GeneratedRegex(@"^Default__(GameObject_|Patch_|Pawn_|Projectile_|TimedBomb_C$)")]
|
||||
private static partial Regex ObjectClass();
|
||||
|
||||
/// PlayerState 액터 → 선수 puuid
|
||||
public string? SubjectOfState(uint state) => _subjectByState.GetValueOrDefault(state);
|
||||
|
||||
public void Emit(ReplayEvent e)
|
||||
{
|
||||
switch (e)
|
||||
@@ -460,10 +463,10 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
equips.Add([e.T, e.P, EquipKind(e.Name)]);
|
||||
}
|
||||
|
||||
// 무기 · 스킬 상태: 장비 액터 → 선수 (인벤토리 기록, 없으면 Instigator)
|
||||
var equipOwner = new Dictionary<uint, int>();
|
||||
foreach (var (_, ch, eq) in _equips)
|
||||
if (indexByCharacter.TryGetValue(ch, out var pi)) equipOwner[eq] = pi;
|
||||
// 무기 · 스킬 상태: 장비 액터 → 그 시각의 선수 (인벤토리 기록, 없으면 Instigator).
|
||||
// 무기는 떨어뜨리고 주울 수 있어서 마지막 주인이 아니라 상태가 생긴 때의 주인을 쓴다
|
||||
var equipOwners = EquipOwners.Build(_equips.Select(e => (e.T, e.Equip, indexByCharacter.TryGetValue(e.Character, out var p) ? p : -1)));
|
||||
var fallbackOwner = new Dictionary<uint, int>();
|
||||
var stateKinds = new List<string>();
|
||||
var stateKindIndex = new Dictionary<string, int>();
|
||||
var states = new List<int[]>();
|
||||
@@ -474,7 +477,12 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
if (st is "InactiveState" or "ZoomStateDisabled") continue;
|
||||
if (lastState.TryGetValue(eq, out var ls) && ls == st) continue;
|
||||
lastState[eq] = st;
|
||||
if (!equipOwner.TryGetValue(eq, out var pi)) { pi = OwnerOf(eq); if (pi < 0) continue; equipOwner[eq] = pi; }
|
||||
var pi = EquipOwners.At(equipOwners, eq, t);
|
||||
if (pi < 0)
|
||||
{
|
||||
if (!fallbackOwner.TryGetValue(eq, out pi)) fallbackOwner[eq] = pi = OwnerOf(eq);
|
||||
if (pi < 0) continue;
|
||||
}
|
||||
var name = _equipName.TryGetValue(eq, out var en) ? en : _archetypeByActor.TryGetValue(eq, out var ea) ? Simplify(ea) : null;
|
||||
if (name is null) continue;
|
||||
if (!stateKindIndex.TryGetValue(st, out var sk)) { sk = stateKinds.Count; stateKinds.Add(st); stateKindIndex[st] = sk; }
|
||||
@@ -510,3 +518,32 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>장비 액터의 주인 시간표: 인벤토리 기록 (t, 장비, 선수) → 시각별 주인</summary>
|
||||
public static class EquipOwners
|
||||
{
|
||||
public static Dictionary<uint, List<(int T, int Player)>> Build(IEnumerable<(int T, uint Equip, int Player)> rows)
|
||||
{
|
||||
var d = new Dictionary<uint, List<(int, int)>>();
|
||||
foreach (var (t, eq, p) in rows.OrderBy(r => r.T))
|
||||
{
|
||||
if (p < 0) continue;
|
||||
if (!d.TryGetValue(eq, out var l)) d[eq] = l = [];
|
||||
l.Add((t, p));
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/// <summary>t 시각 주인: t 이하 마지막 기록, 첫 기록보다 앞이면 첫 주인. 기록이 없으면 -1</summary>
|
||||
public static int At(Dictionary<uint, List<(int T, int Player)>> owners, uint eq, int t)
|
||||
{
|
||||
if (!owners.TryGetValue(eq, out var l) || l.Count == 0) return -1;
|
||||
var who = l[0].Player;
|
||||
foreach (var (rt, p) in l)
|
||||
{
|
||||
if (rt > t) break;
|
||||
who = p;
|
||||
}
|
||||
return who;
|
||||
}
|
||||
}
|
||||
|
||||
195
tools/replay-extract/src/Crosshair.cs
Normal file
195
tools/replay-extract/src/Crosshair.cs
Normal file
@@ -0,0 +1,195 @@
|
||||
using System.Text.Json;
|
||||
using Replay.Encoding.Archives;
|
||||
using Replay.Models.Descriptors;
|
||||
using Replay.Models.Events;
|
||||
using Replay.Unreal.Parsing;
|
||||
using Replay.Valorant;
|
||||
using Replay.Valorant.Descriptors;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
/// <summary>
|
||||
/// 선수 조준점 설정. BombPlayerState 에 선수마다 조준점 프로필(주 조준점 · 정조준 · 저격 조준경 · 프로필 이름)이 복제된다
|
||||
/// (관전자에게 보이는 조준점). 파서의 BombPlayerState 형식에는 이 필드가 없어서, 첫 번째 읽기에서 받은 필드 목록으로
|
||||
/// 번호(handle)를 찾고 이 필드만 읽는 두 번째 읽기를 한다.
|
||||
/// 필드는 기본값(색 흰색 255 · 숫자 0 · 끔)과 다를 때만 오고, 바뀐 필드만 다시 온다.
|
||||
/// </summary>
|
||||
public static class Crosshair
|
||||
{
|
||||
public const string StatePath = "/Game/GameModes/Bomb/BombPlayerState.BombPlayerState_C";
|
||||
// 13.08 · 13.09 에서 주 조준점 색(B)의 번호. 패치로 앞에 필드가 늘면 이름이 맞는 곳으로 옮겨 찾는다
|
||||
private const int KnownBase = 39;
|
||||
|
||||
private static readonly string[] Lines =
|
||||
[
|
||||
"LineThickness", "LineLength", "LineLengthVertical", "LineOffset", "bAllowVertScaling", "bShowMovementError",
|
||||
"bShowShootingError", "bShowMinError", "Opacity", "bShowLines", "FiringErrorScale", "MovementErrorScale",
|
||||
];
|
||||
private static readonly string?[] Cross =
|
||||
[
|
||||
"B", "G", "R", "A", "B", "G", "R", "A", "bUseCustomColor", "bHasOutline", "OutlineThickness", "B", "G", "R", "A",
|
||||
"OutlineOpacity", "CenterDotSize", "CenterDotOpacity", "bDisplayCenterDot", "bFadeCrosshairWithFiringError",
|
||||
"bShowSpectatedPlayerCrosshair", null, "bFixMinErrorAcrossWeapons", .. Lines, .. Lines,
|
||||
];
|
||||
private static readonly string?[] Sniper =
|
||||
[
|
||||
"B", "G", "R", "A", "B", "G", "R", "A", "CenterDotSize", "CenterDotOpacity", "bDisplayCenterDot", null,
|
||||
"bUsePrimaryCrosshairForADS", null, null, "bUseAdvancedOptions", null, "ProfileName",
|
||||
];
|
||||
|
||||
/// 기준 번호부터의 (이름, 열쇠). 세 번째 조준점 묶음(번호 94~140)은 값이 오는 것을 본 적이 없어 읽지 않는다
|
||||
private static readonly (string? Name, string? Key)[] Layout = BuildLayout();
|
||||
|
||||
private static (string?, string?)[] BuildLayout()
|
||||
{
|
||||
var o = new List<(string?, string?)>();
|
||||
string?[] lineKeys = ["thickness", "length", "vLength", "offset", "allowVert", "moveError", "fireError", "minError", "opacity", "on", "fireScale", "moveScale"];
|
||||
string?[] crossKeys =
|
||||
[
|
||||
"cb", "cg", "cr", null, "ub", "ug", "ur", null, "useCustom", "outline", "outlineThickness", null, null, null, null,
|
||||
"outlineOpacity", "dotSize", "dotOpacity", "dot", null, null, null, null,
|
||||
.. lineKeys.Select(k => "i." + k), .. lineKeys.Select(k => "o." + k),
|
||||
];
|
||||
foreach (var prefix in new[] { "p.", "a.", null })
|
||||
for (var i = 0; i < Cross.Length; i++)
|
||||
o.Add(prefix is null ? (null, null) : (Cross[i], crossKeys[i] is { } k ? prefix + k : null));
|
||||
string?[] sniperKeys = ["s.cb", "s.cg", "s.cr", null, null, null, null, null, "s.dotSize", "s.dotOpacity", "s.dot", null, "adsFromPrimary", null, null, "advanced", null, "name"];
|
||||
for (var i = 0; i < Sniper.Length; i++) o.Add((Sniper[i], sniperKeys[i]));
|
||||
return [.. o];
|
||||
}
|
||||
|
||||
/// <summary>필드 목록(번호 → 이름)에서 조준점 기준 번호. 이름이 하나라도 어긋나면 그 자리는 아니다. 못 찾으면 null</summary>
|
||||
public static int? FindBase(IReadOnlyDictionary<int, string> names)
|
||||
{
|
||||
int? best = null;
|
||||
var bestHits = 0;
|
||||
for (var d = 0; d <= 80; d++)
|
||||
foreach (var b in d == 0 ? new[] { KnownBase } : new[] { KnownBase + d, KnownBase - d })
|
||||
{
|
||||
if (b < 0) continue;
|
||||
var hits = 0;
|
||||
var bad = false;
|
||||
foreach (var (h, name) in names)
|
||||
{
|
||||
var i = h - b;
|
||||
if (i < 0 || i >= Layout.Length || Layout[i].Name is not { } want) continue;
|
||||
if (want != name) { bad = true; break; }
|
||||
hits++;
|
||||
}
|
||||
// 프로필 이름 + 몇 개 이상 맞아야 한다 (조준점을 하나도 안 바꾼 경기면 필드가 거의 안 온다)
|
||||
if (!bad && hits > bestHits && names.GetValueOrDefault(b + Layout.Length - 1) == "ProfileName")
|
||||
{
|
||||
best = b;
|
||||
bestHits = hits;
|
||||
}
|
||||
}
|
||||
return bestHits >= 3 ? best : null;
|
||||
}
|
||||
|
||||
/// <summary>두 번째 읽기: PlayerState 액터 → 조준점이 바뀐 시각마다 전체 설정</summary>
|
||||
public static Dictionary<uint, List<CrosshairAt>> Read(string path, ValorantReplayReadResult first)
|
||||
{
|
||||
var group = first.ExportGroups.FirstOrDefault(g => g.PathName == StatePath);
|
||||
if (group is null) return [];
|
||||
var names = new Dictionary<int, string>();
|
||||
foreach (var f in group.Fields)
|
||||
if (f.Name is { } n) names[(int)f.Handle] = n;
|
||||
if (FindBase(names) is not { } b) return [];
|
||||
|
||||
var keyByHandle = new Dictionary<int, string>();
|
||||
var fields = new List<FieldDescriptor>();
|
||||
for (var i = 0; i < Layout.Length; i++)
|
||||
{
|
||||
if (Layout[i] is not { Name: { } name, Key: { } key }) continue;
|
||||
var h = b + i;
|
||||
keyByHandle[h] = key;
|
||||
fields.Add(new FieldDescriptor
|
||||
{
|
||||
Handle = (uint)h,
|
||||
ExportName = name,
|
||||
PropertyName = key,
|
||||
Categories = ExportCategory.GameState,
|
||||
Decoder = name == "ProfileName" ? PrimitiveDecoders.FString
|
||||
: name.Length == 1 ? PrimitiveDecoders.Byte
|
||||
: name.StartsWith('b') ? PrimitiveDecoders.Bool
|
||||
: PrimitiveDecoders.Float,
|
||||
});
|
||||
}
|
||||
// 기본 목록(경로 별칭 · 하위 객체 등 읽기에 필요)에서 BombPlayerState 만 조준점 필드로 바꾼다 (같은 경로는 나중 것이 쓰인다)
|
||||
var catalog = ValorantDescriptors.CreateCatalog();
|
||||
catalog.Add(new ExportGroupDescriptor(StatePath, ExportCategory.GameState, ExportGroupKind.Actor, fields: fields));
|
||||
var sink = new Sink(keyByHandle);
|
||||
var profile = new ParseProfile
|
||||
{
|
||||
EnabledCategories = ExportCategory.All,
|
||||
CaptureDiagnosticFields = true,
|
||||
IncludedPaths = [StatePath],
|
||||
};
|
||||
using var file = File.OpenRead(path);
|
||||
using var archive = new FBinaryArchive(file);
|
||||
new ValorantReplayReader(null, sink, profile, catalog).Read(archive);
|
||||
return sink.Result;
|
||||
}
|
||||
|
||||
private sealed class Sink(Dictionary<int, string> keyByHandle) : IReplayEventSink
|
||||
{
|
||||
private readonly Dictionary<uint, Dictionary<string, object>> _now = [];
|
||||
public Dictionary<uint, List<CrosshairAt>> Result { get; } = [];
|
||||
|
||||
public void Emit(ReplayEvent e)
|
||||
{
|
||||
if (e is not ExportGroupReceived x || x.ExportGroupPath != StatePath || x.DiagnosticFields.Count == 0) return;
|
||||
if (!_now.TryGetValue(x.ActorNetGuid, out var v)) _now[x.ActorNetGuid] = v = [];
|
||||
var changed = false;
|
||||
foreach (var f in x.DiagnosticFields)
|
||||
{
|
||||
if (!keyByHandle.TryGetValue(f.Handle, out var key)) continue;
|
||||
object val = f.Value.Kind switch
|
||||
{
|
||||
DecodedFieldValueKind.Bool => f.Value.BoolValue,
|
||||
DecodedFieldValueKind.Byte => (int)f.Value.ByteValue,
|
||||
DecodedFieldValueKind.Float => Math.Round(f.Value.FloatValue, 3),
|
||||
DecodedFieldValueKind.String => (f.Value.StringValue ?? "").TrimEnd('\0'),
|
||||
_ => null!,
|
||||
};
|
||||
if (val is null) continue;
|
||||
v[key] = val;
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return;
|
||||
var t = (int)Math.Round(x.TimeSeconds * 1000.0);
|
||||
var at = Snapshot(t, v);
|
||||
if (!Result.TryGetValue(x.ActorNetGuid, out var list)) Result[x.ActorNetGuid] = list = [];
|
||||
// 같은 시각에 나눠 온 것은 하나로, 바뀐 것이 없으면 넣지 않는다
|
||||
if (list.Count > 0 && list[^1].T == t) list.RemoveAt(list.Count - 1);
|
||||
if (list.Count > 0 && Same(list[^1], at)) return;
|
||||
list.Add(at);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Same(CrosshairAt a, CrosshairAt b) =>
|
||||
JsonSerializer.Serialize(a with { T = 0 }, ReplayJson.Options) == JsonSerializer.Serialize(b with { T = 0 }, ReplayJson.Options);
|
||||
|
||||
public static CrosshairAt Snapshot(int t, IReadOnlyDictionary<string, object> v)
|
||||
{
|
||||
// 오지 않은 필드는 기본값: 색 255 · 숫자 0 · 끔
|
||||
int C(string k) => v.TryGetValue(k, out var o) ? (int)o : 255;
|
||||
double F(string k) => v.TryGetValue(k, out var o) ? (double)o : 0;
|
||||
bool B(string k) => v.TryGetValue(k, out var o) && (bool)o;
|
||||
string Hex(string p) => $"#{C(p + "r"):x2}{C(p + "g"):x2}{C(p + "b"):x2}";
|
||||
CrossLines L(string p) => new(B(p + "on"), F(p + "length"), B(p + "allowVert") ? F(p + "vLength") : F(p + "length"),
|
||||
F(p + "thickness"), F(p + "offset"), F(p + "opacity"), B(p + "moveError"), B(p + "fireError"), F(p + "moveScale"), F(p + "fireScale"));
|
||||
CrossSet S(string p) => new(Hex(p + (B(p + "useCustom") ? "u" : "c")), B(p + "outline"), F(p + "outlineThickness"), F(p + "outlineOpacity"),
|
||||
B(p + "dot"), F(p + "dotSize"), F(p + "dotOpacity"), L(p + "i."), L(p + "o."));
|
||||
return new CrosshairAt(t, v.TryGetValue("name", out var n) ? (string)n : "", S("p."), S("a."),
|
||||
new SniperDot(Hex("s.c"), B("s.dot"), F("s.dotSize"), F("s.dotOpacity")), B("adsFromPrimary"), B("advanced"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 조준점 설정 (t 부터). ads 는 adsFromPrimary 가 꺼져 있을 때 정조준에 쓴다. 크기는 발로란트 설정 값 그대로 (화면 픽셀)
|
||||
public sealed record CrosshairAt(int T, string Name, CrossSet Primary, CrossSet Ads, SniperDot Sniper, bool AdsFromPrimary, bool Advanced);
|
||||
/// color 는 실제로 보이는 색 (사용자 지정 색을 쓰면 그 색)
|
||||
public sealed record CrossSet(string Color, bool Outline, double OutlineThickness, double OutlineOpacity, bool Dot, double DotSize, double DotOpacity, CrossLines Inner, CrossLines Outer);
|
||||
/// vLength 는 세로 길이를 따로 쓰지 않으면 length 와 같다
|
||||
public sealed record CrossLines(bool On, double Length, double VLength, double Thickness, double Offset, double Opacity, bool MoveError, bool FireError, double MoveScale, double FireScale);
|
||||
public sealed record SniperDot(string Color, bool Dot, double DotSize, double DotOpacity);
|
||||
@@ -53,6 +53,8 @@ public sealed class ReplayPlayer
|
||||
public string? Character { get; set; }
|
||||
/// 이동 기록. 열 별 배열 (같은 길이): t, x, y, z, yaw(도), pitch(도)
|
||||
public PlayerTrack Track { get; set; } = new();
|
||||
/// 조준점 설정이 바뀐 시각마다 전체 설정 (시간 순). 리플레이에 없으면 null
|
||||
public List<CrosshairAt>? Crosshair { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PlayerTrack
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v2)
|
||||
// gvr-replay <file.vrf> <out.json> [--hz 10]
|
||||
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
|
||||
// gvr-replay <file.vrf> --fields (디버그: 복제 필드 목록 <경로\t이름>, 번호 순)
|
||||
// gvr-replay --self-test (회귀 검사: 무기 주인 시간표 · 조준점 필드 자리)
|
||||
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
@@ -13,8 +15,51 @@ namespace GvrReplay;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
/// <summary>회귀 검사 (리플레이 파일 없이): 무기를 넘겨받아도 넘기기 전 상태는 이전 주인 것</summary>
|
||||
private static int SelfTest()
|
||||
{
|
||||
var fails = new List<string>();
|
||||
void Eq(string name, int got, int want)
|
||||
{
|
||||
if (got != want) fails.Add($"{name}: {got} (기대 {want})");
|
||||
}
|
||||
// 선수 0 이 1초에 들고 2초에 재장전, 10초에 선수 1 이 주움
|
||||
var o = EquipOwners.Build([(1000, 7u, 0), (10000, 7u, 1)]);
|
||||
Eq("주기 전 재장전(2초)", EquipOwners.At(o, 7, 2000), 0);
|
||||
Eq("주운 순간(10초)", EquipOwners.At(o, 7, 10000), 1);
|
||||
Eq("주운 뒤(12초)", EquipOwners.At(o, 7, 12000), 1);
|
||||
Eq("첫 기록 전(0.5초)", EquipOwners.At(o, 7, 500), 0);
|
||||
Eq("기록 없는 장비", EquipOwners.At(o, 8, 2000), -1);
|
||||
// 같은 시각 순서가 뒤섞여 들어와도 시간 순으로
|
||||
var o2 = EquipOwners.Build([(5000, 9u, 2), (1000, 9u, 3)]);
|
||||
Eq("순서 섞임(3초)", EquipOwners.At(o2, 9, 3000), 3);
|
||||
Eq("순서 섞임(6초)", EquipOwners.At(o2, 9, 6000), 2);
|
||||
// 선수를 모르는 기록(-1)은 건너뛴다
|
||||
var o3 = EquipOwners.Build([(1000, 4u, 5), (2000, 4u, -1)]);
|
||||
Eq("모르는 선수 건너뜀", EquipOwners.At(o3, 4, 3000), 5);
|
||||
// 조준점 필드 자리: 13.08 번호 그대로 · 앞에 필드가 2개 늘어난 패치 · 이름이 어긋나면 못 찾음
|
||||
Dictionary<int, string> Names(int b) => new()
|
||||
{
|
||||
[b] = "B", [b + 8] = "bUseCustomColor", [b + 23] = "LineThickness", [b + 35] = "LineThickness",
|
||||
[b + 70] = "LineThickness", [b + 153] = "bUsePrimaryCrosshairForADS", [b + 158] = "ProfileName", [b - 13] = "AssignedTeamState",
|
||||
};
|
||||
Eq("조준점 자리 13.08", Crosshair.FindBase(Names(39)) ?? -1, 39);
|
||||
Eq("조준점 자리 +2", Crosshair.FindBase(Names(41)) ?? -1, 41);
|
||||
var wrong = Names(39);
|
||||
wrong[39 + 23] = "LineOffset";
|
||||
Eq("조준점 이름 어긋남", Crosshair.FindBase(wrong) ?? -1, -1);
|
||||
// 기본값: 오지 않은 색은 흰색, 사용자 지정 색을 쓰면 그 색
|
||||
var cs = Crosshair.Snapshot(0, new Dictionary<string, object> { ["p.cb"] = 0, ["p.cg"] = 0, ["a.useCustom"] = true, ["a.ur"] = 0 });
|
||||
if (cs.Primary.Color != "#ff0000") fails.Add($"주 조준점 색: {cs.Primary.Color} (기대 #ff0000)");
|
||||
if (cs.Ads.Color != "#00ffff") fails.Add($"정조준 사용자 지정 색: {cs.Ads.Color} (기대 #00ffff)");
|
||||
foreach (var f in fails) Console.Error.WriteLine("FAIL " + f);
|
||||
Console.WriteLine(JsonSerializer.Serialize(new { ok = fails.Count == 0, selfTest = true, failed = fails.Count }));
|
||||
return fails.Count == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
if (args.Length == 1 && args[0] == "--self-test") return SelfTest();
|
||||
if (args.Length < 2)
|
||||
{
|
||||
Console.Error.WriteLine("사용법: gvr-replay <file.vrf> <out.json> [--hz 10] | gvr-replay <file.vrf> --stats");
|
||||
@@ -37,6 +82,13 @@ public static class Program
|
||||
var result = ValorantReplayReader.CreateDefault(null, enricher, profile).Read(archive);
|
||||
enricher.Complete();
|
||||
var info = result.Metadata.ReplayInfo;
|
||||
if (args[1] == "--fields")
|
||||
{
|
||||
foreach (var g in result.ExportGroups)
|
||||
foreach (var f in g.Fields)
|
||||
Console.WriteLine(g.PathName + "\t" + f.Name);
|
||||
return 0;
|
||||
}
|
||||
if (stats)
|
||||
{
|
||||
collector.PrintStats();
|
||||
@@ -47,6 +99,21 @@ public static class Program
|
||||
FDateTimeToUnixMs(info.Timestamp),
|
||||
info.LengthInMs,
|
||||
hz);
|
||||
// 선수 조준점 (두 번째 읽기). 못 읽어도 나머지 변환은 그대로 쓴다
|
||||
var crosshairs = 0;
|
||||
try
|
||||
{
|
||||
foreach (var (state, list) in Crosshair.Read(input, result))
|
||||
if (collector.SubjectOfState(state) is { } subject && replay.Players.FirstOrDefault(p => p.Puuid == subject) is { } pl)
|
||||
{
|
||||
pl.Crosshair = list;
|
||||
crosshairs++;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine("조준점 읽기 실패: " + e.Message);
|
||||
}
|
||||
var tmp = args[1] + ".tmp";
|
||||
using (var fs = File.Create(tmp))
|
||||
JsonSerializer.Serialize(fs, replay, ReplayJson.Options);
|
||||
@@ -60,6 +127,7 @@ public static class Program
|
||||
players = replay.Players.Count,
|
||||
rounds = replay.Rounds.Count,
|
||||
kills = replay.Kills.Count,
|
||||
crosshairs,
|
||||
elapsedMs = sw.ElapsedMilliseconds,
|
||||
status = result.Status.ToString(),
|
||||
warnings = result.TotalDiagnosticCount,
|
||||
|
||||
@@ -151,6 +151,9 @@ try {
|
||||
$exe = Join-Path $tx 'out\win\gvr-replay.exe'
|
||||
if (-not (Test-Path $exe)) { throw 'gvr-replay.exe 없음' }
|
||||
"gvr-replay.exe $([math]::Round((Get-Item $exe).Length / 1MB, 1)) MB"
|
||||
# 회귀 검사 (리플레이 파일 없이: 무기 주인 시간표 등)
|
||||
& $exe --self-test
|
||||
if ($LASTEXITCODE -ne 0) { throw "gvr-replay --self-test exit $LASTEXITCODE" }
|
||||
# 실제 13.08 리플레이 변환 (호스트가 serve/ 에 둔 시험 파일, 없으면 건너뜀)
|
||||
$vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf'
|
||||
try { Invoke-WebRequest -Uri 'http://10.0.2.2:8099/gvr-test.vrf' -OutFile $vrf -UseBasicParsing -TimeoutSec 600 } catch { Remove-Item $vrf -Force -ErrorAction SilentlyContinue; "시험 리플레이 없음: $($_.Exception.Message)" }
|
||||
|
||||
Reference in New Issue
Block a user