3D 리플레이 무기 스킨: 뽑아 둔 스킨이면 3인칭 손의 총 · 1인칭 총을 그 모델로 (없거나 못 받으면 기본 총), 없는 스킨은 POST /site/maps3d/skins/want 로 요청 (기본 스킨 · 실패한 것 제외) · 서버 GET /site/maps3d/skins · want.json (형식 검사 · 중복 제거 · 다른 사이트 요청 막음 · 최대 2000) · 목 서버 · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -368,7 +368,7 @@ export async function buildServer(
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요)
|
||||
registerMaps3d(app, cfg.dataDir, requireSession);
|
||||
registerMaps3d(app, cfg.dataDir, requireSession, cfg.publicUrl);
|
||||
|
||||
app.get('/healthz', async () => 'ok\n');
|
||||
|
||||
|
||||
@@ -13,6 +13,13 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
*
|
||||
* GET /site/maps3d → index.json (없으면 {maps:{}})
|
||||
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
|
||||
*
|
||||
* 무기 스킨 (본 것만 뽑는다, tools/map-extract/scripts/skins-update.sh 가 몇 분마다 요청을 가져가 뽑아 올린다):
|
||||
* <dataDir>/maps3d/skins/index.json {skins:{"스킨|단계|색상":{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}
|
||||
* <dataDir>/maps3d/skins/skin3p_<서명>.glb.gz · skin1p_<서명>.glb.gz (파일 이름이 모습마다 달라 오래 캐시한다)
|
||||
* <dataDir>/maps3d/skins/want.json 사이트가 받은 요청 (아직 없는 열쇠, 시간 순 · 최대 MAX_WANT)
|
||||
* GET /site/maps3d/skins → skins/index.json (없으면 빈 목록)
|
||||
* POST /site/maps3d/skins/want {keys:[열쇠]} → 없는 것만 want.json 에 더한다
|
||||
*/
|
||||
export interface Maps3dIndex {
|
||||
version: string;
|
||||
@@ -24,7 +31,40 @@ export interface Maps3dIndex {
|
||||
/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */
|
||||
const TYPES: Record<string, string> = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
|
||||
|
||||
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>) {
|
||||
/** 스킨 요청 열쇠 "스킨|단계|색상" (게임 데이터 에셋 경로, 단계 · 색상은 비어도 된다). 추출기 Skins.ValidKey 와 같다 */
|
||||
const SKIN_KEY = /^\/Game\/Equippables\/[A-Za-z0-9_/-]+\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?$/;
|
||||
export const isSkinKey = (k: unknown): k is string => typeof k === 'string' && k.length < 600 && SKIN_KEY.test(k);
|
||||
const MAX_WANT = 2000;
|
||||
const MAX_WANT_PER_REQUEST = 100;
|
||||
|
||||
/** JSON 파일을 mtime 이 바뀔 때만 다시 읽는다 (없거나 깨졌으면 null) */
|
||||
function jsonFile<T>(file: string): () => T | null {
|
||||
let cache: { mtime: number; data: T | null } = { mtime: -1, data: null };
|
||||
return () => {
|
||||
let st: fs.Stats;
|
||||
try {
|
||||
st = fs.statSync(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (st.mtimeMs !== cache.mtime) {
|
||||
try {
|
||||
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(file, 'utf8')) as T };
|
||||
} catch {
|
||||
cache = { mtime: st.mtimeMs, data: null };
|
||||
}
|
||||
}
|
||||
return cache.data;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SkinsIndex {
|
||||
skins: Record<string, { weapon: string; sig: string }>;
|
||||
looks: Record<string, { w3p?: string; points?: Record<string, number[]>; w1p?: string; points1p?: Record<string, number[]>; gunClips?: string[] }>;
|
||||
failed?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>, publicUrl?: string) {
|
||||
const root = path.join(dataDir, 'maps3d');
|
||||
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
|
||||
const index = (): Maps3dIndex | null => {
|
||||
@@ -51,6 +91,39 @@ export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSes
|
||||
return index() ?? { version: null, dir: null, maps: {} };
|
||||
});
|
||||
|
||||
const skinsDir = path.join(root, 'skins');
|
||||
const skins = jsonFile<SkinsIndex>(path.join(skinsDir, 'index.json'));
|
||||
app.get('/site/maps3d/skins', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
reply.header('cache-control', 'private, no-cache');
|
||||
return skins() ?? { skins: {}, looks: {} };
|
||||
});
|
||||
app.post<{ Body: { keys?: unknown } }>('/site/maps3d/skins/want', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (origin && publicUrl && origin !== publicUrl) return reply.code(403).send({ error: 'bad_origin' });
|
||||
const keys = Array.isArray(req.body?.keys) ? req.body.keys.slice(0, MAX_WANT_PER_REQUEST).filter(isSkinKey) : [];
|
||||
const idx = skins();
|
||||
const file = path.join(skinsDir, 'want.json');
|
||||
let want: string[] = [];
|
||||
try {
|
||||
const w = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
|
||||
if (Array.isArray(w)) want = w.filter(isSkinKey);
|
||||
} catch {
|
||||
/* 처음이거나 깨졌으면 새로 */
|
||||
}
|
||||
const have = new Set(want);
|
||||
const add = [...new Set(keys)].filter((k) => !have.has(k) && !idx?.skins?.[k] && !idx?.failed?.[k]);
|
||||
if (add.length === 0) return { queued: 0 };
|
||||
// 다 뽑은 것은 뺀다 (뽑는 쪽은 이 파일을 읽기만 한다)
|
||||
want = [...want.filter((k) => !idx?.skins?.[k] && !idx?.failed?.[k]), ...add].slice(-MAX_WANT);
|
||||
fs.mkdirSync(skinsDir, { recursive: true });
|
||||
fs.writeFileSync(file + '.tmp', JSON.stringify(want));
|
||||
fs.renameSync(file + '.tmp', file);
|
||||
req.log.info({ area: 'skins', add: add.length, total: want.length }, '무기 스킨 요청');
|
||||
return { queued: add.length };
|
||||
});
|
||||
|
||||
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
const { dir, file } = req.params;
|
||||
|
||||
@@ -51,7 +51,7 @@ async function stack() {
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
||||
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
|
||||
};
|
||||
return { base, store, login, close: async () => (await app.close(), dc.close()) };
|
||||
return { base, store, login, dataDir: cfg.dataDir, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
|
||||
@@ -91,3 +91,39 @@ test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('무기 스킨: 목록 · 파일은 로그인한 사람만, 요청은 없는 것만 want.json 에 쌓인다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const sk = path.join(s.dataDir, 'maps3d', 'skins');
|
||||
fs.mkdirSync(sk, { recursive: true });
|
||||
const have = '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset||';
|
||||
const bad = '/Game/Equippables/Melee/Broken/Melee_Broken_PrimaryAsset||';
|
||||
fs.writeFileSync(path.join(sk, 'index.json'), JSON.stringify({ skins: { [have]: { weapon: 'Vandal', sig: 'abc' } }, looks: { abc: { w3p: 'skin3p_abc.glb' } }, failed: { [bad]: '메시 없음' } }));
|
||||
fs.writeFileSync(path.join(sk, 'skin3p_abc.glb.gz'), zlib.gzipSync(Buffer.from('skin')));
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/skins')).status, 401);
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"keys":[]}' })).status, 401);
|
||||
const cookie = await s.login();
|
||||
const idx = (await (await fetch(s.base + '/site/maps3d/skins', { headers: { cookie } })).json()) as any;
|
||||
assert.equal(idx.skins[have].sig, 'abc');
|
||||
const f = await fetch(s.base + '/site/maps3d/skins/skin3p_abc.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
|
||||
assert.equal(f.status, 200);
|
||||
assert.equal(await f.text(), 'skin');
|
||||
|
||||
const want = (keys: unknown[], origin?: string) =>
|
||||
fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { cookie, 'content-type': 'application/json', ...(origin ? { origin } : {}) }, body: JSON.stringify({ keys }) });
|
||||
const k1 = '/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Carbine_SpecOps_PrimaryAsset|/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Levels/Carbine_SpecOps_Lv2_PrimaryAsset|';
|
||||
// 이미 있는 것 · 실패한 것 · 형식이 틀린 것은 넣지 않는다
|
||||
const r = await want([k1, have, bad, '../../etc/passwd||', 7, k1]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(await r.json(), { queued: 1 });
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
|
||||
// 같은 것을 다시 요청하면 그대로
|
||||
assert.deepEqual(await (await want([k1])).json(), { queued: 0 });
|
||||
// 다른 사이트에서 온 요청은 막는다
|
||||
assert.equal((await want([k1.replace('Lv2', 'Lv3')], 'https://evil.example')).status, 403);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
48
site/server/test/replay-skins.test.ts
Normal file
48
site/server/test/replay-skins.test.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
// 사이트 3D 리플레이: 무기 스킨 찾기 (site/web/src/lib/skins.ts · replay.ts skinTracks)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { equipAt, skinTracks, type ReplayFile, type SkinInfo } from '../../web/src/lib/replay.ts';
|
||||
import { isDefaultSkin, lookOf, missingSkins, skinKey } from '../../web/src/lib/skins.ts';
|
||||
|
||||
const hype: SkinInfo = {
|
||||
skin: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset',
|
||||
level: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_Lv4_PrimaryAsset',
|
||||
chroma: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/Chromas/Blue/AssaultRifle_AK_HypeBeast_Blue_PrimaryAsset',
|
||||
};
|
||||
const knife: SkinInfo = { skin: '/Game/Equippables/Melee/Standard/Melee_Base_Standard_PrimaryAsset', level: null, chroma: '/Game/Equippables/Melee/Standard/Chromas/Standard/Melee_Base_Standard_Standard_PrimaryAsset' };
|
||||
const ghost: SkinInfo = { skin: '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset', level: null, chroma: null };
|
||||
|
||||
test('스킨: 선수가 그 시각에 든 총의 스킨 (주운 총은 그 총의 스킨, 옛 JSON 은 -1)', () => {
|
||||
const r = {
|
||||
players: [{}, {}],
|
||||
skins: [hype, ghost],
|
||||
// 선수 0: 1초 밴달(hype) · 5초 칼(스킨 기록 없음) · 9초 주운 고스트. 선수 1: 옛 3열 줄
|
||||
equips: [[1000, 0, 0, 0], [5000, 0, 1, -1], [9000, 0, 2, 1], [2000, 1, 0]],
|
||||
} as unknown as ReplayFile;
|
||||
const tr = skinTracks(r);
|
||||
assert.equal(equipAt(tr[0], 500), -1);
|
||||
assert.equal(equipAt(tr[0], 3000), 0);
|
||||
assert.equal(equipAt(tr[0], 6000), -1);
|
||||
assert.equal(equipAt(tr[0], 9500), 1);
|
||||
assert.equal(equipAt(tr[1], 3000), -1);
|
||||
});
|
||||
|
||||
test('스킨: 뽑아 둔 것은 그 모습, 기본 스킨 · 없는 것은 null, 없는 것만 요청 목록에', () => {
|
||||
assert.equal(isDefaultSkin(knife), true);
|
||||
assert.equal(isDefaultSkin(hype), false);
|
||||
assert.equal(isDefaultSkin({ skin: '/Game/Equippables/Guns/Sidearms/Compact/Compact_Standard_PrimaryAsset', level: null, chroma: null }), true);
|
||||
const idx = {
|
||||
skins: { [skinKey(hype)]: { weapon: 'Vandal', sig: 's1' } },
|
||||
looks: { s1: { w3p: 'skin3p_s1.glb', w1p: 'skin1p_s1.glb' } },
|
||||
failed: {} as Record<string, string>,
|
||||
};
|
||||
assert.equal(lookOf(idx, hype)?.w3p, 'skin3p_s1.glb');
|
||||
assert.equal(lookOf(idx, ghost), null);
|
||||
assert.equal(lookOf(idx, knife), null);
|
||||
// 같은 스킨이 여러 번 나와도 한 번, 기본 스킨은 요청하지 않는다
|
||||
assert.deepEqual(missingSkins(idx, { skins: [hype, ghost, knife, { ...ghost }] }), [skinKey(ghost)]);
|
||||
// 뽑다 실패한 것은 다시 요청하지 않는다
|
||||
idx.failed[skinKey(ghost)] = '메시 없음';
|
||||
assert.deepEqual(missingSkins(idx, { skins: [ghost] }), []);
|
||||
assert.equal(skinKey(ghost), '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset||');
|
||||
});
|
||||
@@ -218,6 +218,12 @@ async function handle(req, res) {
|
||||
const root = process.env.GVR_MOCK_MAPS3D;
|
||||
if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' });
|
||||
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
|
||||
// 무기 스킨: <폴더>/skins/index.json (없으면 빈 목록), 요청은 받기만 한다 (뽑는 쪽이 없다)
|
||||
if (p === '/site/maps3d/skins') {
|
||||
const f = path.join(root, 'skins', 'index.json');
|
||||
return json(res, 200, fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : { skins: {}, looks: {} });
|
||||
}
|
||||
if (p === '/site/maps3d/skins/want') return json(res, 200, { queued: 0 });
|
||||
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
|
||||
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
|
||||
const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()];
|
||||
|
||||
@@ -6,7 +6,8 @@ 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, indexAt, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { equipAt, equipLabel, equipTracks, indexAt, isDead, roundAt, samplePath, samplePlayer, skinTracks, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { loadSkins, lookOf, requestMissing } from '../lib/skins';
|
||||
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
|
||||
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon, weaponCat } from '../lib/agents3d';
|
||||
import { Viewmodel, viewmodelIndex } from '../lib/viewmodel';
|
||||
@@ -386,6 +387,19 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
});
|
||||
let vmOn = false;
|
||||
let scopedNow = false;
|
||||
// 무기 스킨: 뽑아 둔 것만 그 스킨으로, 없는 것은 뽑아 달라고 요청한다 (다음에 열면 보인다)
|
||||
const skinByPlayer = skinTracks(replay);
|
||||
let skinIdx: Awaited<ReturnType<typeof loadSkins>> = null;
|
||||
if (replay.skins?.length) {
|
||||
void loadSkins().then((ix) => {
|
||||
if (!disposed) skinIdx = ix;
|
||||
});
|
||||
void requestMissing(replay);
|
||||
}
|
||||
const skinLookAt = (p: number, t: number) => {
|
||||
const s = equipAt(skinByPlayer[p], t);
|
||||
return s >= 0 ? lookOf(skinIdx, replay.skins?.[s]) : null;
|
||||
};
|
||||
|
||||
// 선택한 선수 이동 경로 (최근 6초)
|
||||
const trailGeo = new THREE.BufferGeometry();
|
||||
@@ -821,7 +835,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
const vy = q && !dead ? ((p.y - q.y) * 1000) / 150 : 0;
|
||||
const a = (p.yaw * Math.PI) / 180;
|
||||
const ek = replay.equipKinds?.[kind];
|
||||
v.rig.setWeapon(isGun(ek) ? ek : null);
|
||||
v.rig.setWeapon(isGun(ek) ? ek : null, isGun(ek) ? skinLookAt(v.idx, t) : null);
|
||||
const inp = rigInput(replay, animIx, v.idx, t, { dt: dtR, fwd: vx * Math.cos(a) + vy * Math.sin(a), right: -vx * Math.sin(a) + vy * Math.cos(a), pitch: p.pitch });
|
||||
v.rig.setShot(inp.shotMs);
|
||||
v.rig.update(inp);
|
||||
@@ -1022,7 +1036,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
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.set(chr, fp.kind!, skinLookAt(selIdx, t));
|
||||
vm.pose(fp.input);
|
||||
}
|
||||
// 조준점: 선수 조준점(설정에 따라) 또는 내 조준점. 저격총 줌은 조준경 가운데 점, 정조준은 정조준 조준점
|
||||
|
||||
@@ -3,6 +3,7 @@ import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'
|
||||
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
|
||||
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
|
||||
import { loadIndex } from './map3d';
|
||||
import { skinFileUrl, type SkinLook } from './skins';
|
||||
|
||||
/**
|
||||
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
|
||||
@@ -37,8 +38,12 @@ export async function loadAgent(characterClass: string): Promise<GLTF | null> {
|
||||
return a && idx?.dir ? load(assetUrl(idx.dir, a.file)) : null;
|
||||
}
|
||||
|
||||
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 없으면 null */
|
||||
export async function loadWeapon(name: string): Promise<GLTF | null> {
|
||||
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 스킨 3인칭 모델이 있으면 그것 (받지 못하면 기본 스킨). 없으면 null */
|
||||
export async function loadWeapon(name: string, skin?: SkinLook | null): Promise<GLTF | null> {
|
||||
if (skin?.w3p) {
|
||||
const g = await load(skinFileUrl(skin.w3p)).catch(() => null);
|
||||
if (g) return g;
|
||||
}
|
||||
const idx = await loadIndex();
|
||||
const w = idx?.dir ? idx.weapons?.[name] : undefined;
|
||||
return w && idx?.dir ? load(assetUrl(idx.dir, w.file)) : null;
|
||||
@@ -161,6 +166,7 @@ export class AgentRig {
|
||||
/** 총구 불꽃 (사격 순간에 잠깐) */
|
||||
readonly muzzle: THREE.Sprite;
|
||||
private gunName: string | null = null;
|
||||
private gunSkin: SkinLook | null = null;
|
||||
private gunReq = 0;
|
||||
private gunTip = 60;
|
||||
private readonly tmp = new THREE.Vector3();
|
||||
@@ -198,14 +204,15 @@ export class AgentRig {
|
||||
return a;
|
||||
}
|
||||
|
||||
/** 들고 있는 총 바꾸기 (이름 없으면 맨손) */
|
||||
setWeapon(name: string | null) {
|
||||
if (name === this.gunName) return;
|
||||
/** 들고 있는 총 바꾸기 (이름 없으면 맨손, 스킨 모습이 있으면 그 스킨) */
|
||||
setWeapon(name: string | null, skin?: SkinLook | null) {
|
||||
if (name === this.gunName && (skin ?? null) === this.gunSkin) return;
|
||||
this.gunName = name;
|
||||
this.gunSkin = skin ?? null;
|
||||
const req = ++this.gunReq;
|
||||
for (const c of [...this.gunSlot.children]) if (c !== this.muzzle) this.gunSlot.remove(c);
|
||||
if (!name) return;
|
||||
void loadWeapon(name)
|
||||
void loadWeapon(name, skin)
|
||||
.then((g) => {
|
||||
if (!g || req !== this.gunReq) return;
|
||||
const gun = g.scene.clone(true);
|
||||
|
||||
@@ -45,13 +45,24 @@ export interface ReplayFile {
|
||||
/** 이어지는 동작 [t0, t1, player, actionKind] (Plant · Defuse · Rope) */
|
||||
actions?: [number, number, number, number][];
|
||||
actionKinds?: string[];
|
||||
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
|
||||
equips?: [number, number, number][];
|
||||
/** 들고 있는 것이 바뀐 시각 [t, player, kind, skin] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다. skin = skins 번호 · 모르면 -1, 변환기 1.10.0~) */
|
||||
equips?: [number, number, number, number?][];
|
||||
equipKinds?: string[];
|
||||
/** 무기 스킨 (게임 데이터 에셋 경로). 줍거나 떨어뜨려도 그 총의 스킨은 처음 주인 것 (변환기 1.10.0~) */
|
||||
skins?: SkinInfo[];
|
||||
/** 점수판 (게임 Tab): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (모르는 값 -1, 변환기 1.10.0~) */
|
||||
scoreboard?: number[][];
|
||||
}
|
||||
|
||||
/** 무기 스킨: 스킨 · 단계 · 색상 · 총 장식 (예: /Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset) */
|
||||
export interface SkinInfo {
|
||||
skin: string;
|
||||
level: string | null;
|
||||
chroma: string | null;
|
||||
charm?: string | null;
|
||||
charmLevel?: string | null;
|
||||
}
|
||||
|
||||
export interface ObjectPath {
|
||||
o: number;
|
||||
t: number[];
|
||||
@@ -145,6 +156,13 @@ export function equipTracks(r: ReplayFile): [number, number][][] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 선수별 [t, skin] 목록 (equipTracks 와 같은 시각, equipAt 으로 찾는다. 스킨 기록이 없으면 -1) */
|
||||
export function skinTracks(r: ReplayFile): [number, number][][] {
|
||||
const out: [number, number][][] = r.players.map(() => []);
|
||||
for (const [t, p, , s] of r.equips ?? []) out[p]?.push([t, s ?? -1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** t 시점에 들고 있던 것 (kind 번호, 없으면 -1) */
|
||||
export function equipAt(track: [number, number][] | undefined, t: number): number {
|
||||
if (!track?.length || t < track[0][0]) return -1;
|
||||
|
||||
72
site/web/src/lib/skins.ts
Normal file
72
site/web/src/lib/skins.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { ReplayFile, SkinInfo } from './replay';
|
||||
|
||||
/**
|
||||
* 무기 스킨 3D (사이트 서버 /site/maps3d/skins, 로그인 필요).
|
||||
* 리플레이 skins 의 스킨 · 단계 · 색상으로 찾는다. 아직 없는 스킨은 요청만 해 두고 기본 스킨으로 그린다
|
||||
* (이 서버가 몇 분 안에 그 스킨만 뽑아 올리므로 다음에 열면 보인다, tools/map-extract/scripts/skins-update.sh).
|
||||
* skins[열쇠] = {weapon, sig}, looks[sig] = {w3p(3인칭 glb), w1p(1인칭 glb, 총 동작 포함), …}. 파일은 /site/maps3d/skins/<파일>
|
||||
*/
|
||||
export interface SkinLook {
|
||||
w3p?: string;
|
||||
w1p?: string;
|
||||
points?: Record<string, number[]>;
|
||||
points1p?: Record<string, number[]>;
|
||||
gunClips?: string[];
|
||||
}
|
||||
interface SkinsIndex {
|
||||
skins: Record<string, { weapon: string; sig: string }>;
|
||||
looks: Record<string, SkinLook>;
|
||||
failed?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const skinKey = (s: SkinInfo) => `${s.skin}|${s.level ?? ''}|${s.chroma ?? ''}`;
|
||||
|
||||
/** 기본 스킨 (…_Standard_PrimaryAsset, 예: Melee_Base_Standard · Compact_Standard): 따로 뽑지 않고 기본 무기 모델을 쓴다 */
|
||||
export const isDefaultSkin = (s: SkinInfo) => /_Standard_PrimaryAsset$/.test(s.skin);
|
||||
|
||||
export const skinFileUrl = (file: string) => `/site/maps3d/skins/${encodeURIComponent(file)}`;
|
||||
|
||||
let indexP: Promise<SkinsIndex | null> | null = null;
|
||||
export function loadSkins(): Promise<SkinsIndex | null> {
|
||||
indexP ??= fetch('/site/maps3d/skins', { credentials: 'same-origin' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<SkinsIndex>) : null))
|
||||
.catch(() => null)
|
||||
.then((d) => {
|
||||
if (!d) indexP = null;
|
||||
return d;
|
||||
});
|
||||
return indexP;
|
||||
}
|
||||
|
||||
/** 이 스킨의 모습 (없거나 기본 스킨이면 null) */
|
||||
export function lookOf(idx: SkinsIndex | null, s: SkinInfo | undefined | null): SkinLook | null {
|
||||
if (!idx || !s || isDefaultSkin(s)) return null;
|
||||
const e = idx.skins[skinKey(s)];
|
||||
return (e && idx.looks[e.sig]) || null;
|
||||
}
|
||||
|
||||
/** 리플레이에 나온 스킨 중 아직 없는 것 (기본 스킨 · 실패한 것은 빼고) */
|
||||
export function missingSkins(idx: SkinsIndex, r: Pick<ReplayFile, 'skins'>): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const s of r.skins ?? []) {
|
||||
if (isDefaultSkin(s)) continue;
|
||||
const k = skinKey(s);
|
||||
if (!idx.skins[k] && !idx.failed?.[k]) out.add(k);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** 없는 스킨을 뽑아 달라고 요청한다 (한 번에 100개까지, 실패해도 그냥 기본 스킨) */
|
||||
export async function requestMissing(r: Pick<ReplayFile, 'skins'>): Promise<number> {
|
||||
const idx = await loadSkins();
|
||||
if (!idx) return 0;
|
||||
const keys = missingSkins(idx, r).slice(0, 100);
|
||||
if (!keys.length) return 0;
|
||||
const res = await fetch('/site/maps3d/skins/want', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ keys }),
|
||||
}).catch(() => null);
|
||||
return res?.ok ? (((await res.json()) as { queued?: number }).queued ?? 0) : 0;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.j
|
||||
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
|
||||
import { assetUrl } from './agents3d';
|
||||
import { loadIndex } from './map3d';
|
||||
import { skinFileUrl, type SkinLook } from './skins';
|
||||
|
||||
/**
|
||||
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
|
||||
@@ -120,16 +121,17 @@ export class Viewmodel {
|
||||
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
|
||||
}
|
||||
|
||||
/** 요원 · 무기를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다 */
|
||||
set(character: string, weapon: string) {
|
||||
const key = `${character}|${weapon}`;
|
||||
/** 요원 · 무기(· 스킨)를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다. 스킨 1인칭 모델을 받지 못하면 기본 스킨 */
|
||||
set(character: string, weapon: string, skin?: SkinLook | null) {
|
||||
const key = `${character}|${weapon}|${skin?.w1p ?? ''}`;
|
||||
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))])
|
||||
const gun = skin?.w1p ? load(skinFileUrl(skin.w1p)).catch(() => load(url(w.file))) : load(url(w.file));
|
||||
void Promise.all([load(url(a.file)), gun, load(url(w.anim))])
|
||||
.then(([ag, wg, an]) => {
|
||||
if (this.disposed || this.want !== key) return;
|
||||
this.build(ag, wg, an);
|
||||
|
||||
Reference in New Issue
Block a user