발로란트 맵 3D: 모든 맵을 Riot CDN 에서 바로 추출해 3D 리플레이에 붙임 · 매핑 업데이트 자동 적용

- tools/map-extract (C#, CUE4Parse 고정 커밋): 게임 파일을 받지 않고 매니페스트 조각만 HTTP Range 로 읽어
  맵 22개(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트)를 월드 좌표 glb 로. 3.1분 · 587MB 받음
- scripts/pack.py (gltfpack -cc + gzip, 맵당 0.5~4.6MB) · update.sh (uedb 매핑 · 라이브 패치 확인 → 매핑 보관 →
  추출 → .5 data/maps3d 반영) · install.sh (systemd 사용자 타이머 30분, 메모리 6GB 상한)
- 사이트 서버: GET /site/maps3d* (로그인 필요, gzip 그대로). CSP 에 'wasm-unsafe-eval' (meshopt 압축 풀기만)
- 3D 재생기: 맵 3D 위에 선수 표시, 천장 자르기(자동 · 없음 · 직접), 높이 색칠. 맵이 없거나 실패하면 미니맵
- 리플레이 칸: 리플레이를 아직 안 보내는 앱 버전이면 그렇게 안내
- 테스트: maps3d.test.ts 2개, CSP 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 14:01:22 +09:00
parent 86f422e8f0
commit 0c1e726168
23 changed files with 1350 additions and 9 deletions

4
tools/map-extract/.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
vendor/
bin/
obj/
out/

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- 발로란트 맵 3D 모양 추출: Riot CDN 에서 필요한 부분만 읽어(게임 설치 · 전체 다운로드 없음) 맵마다 glb 하나.
CUE4Parse 는 fetch-cue4parse.sh 로 vendor/ 에 받는다. 빌드: CUE4PARSE_SKIP_NATIVE=1 dotnet build -c Release -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>gvr-map-extract</AssemblyName>
<InvariantGlobalization>true</InvariantGlobalization>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<ServerGarbageCollection>false</ServerGarbageCollection>
<ConcurrentGarbageCollection>false</ConcurrentGarbageCollection>
</PropertyGroup>
<ItemGroup>
<Compile Include="src/**/*.cs" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse/CUE4Parse.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# CUE4Parse (Apache-2.0, https://github.com/FabianFG/CUE4Parse) 를 고정 커밋으로 받아 vendor/ 에 둔다.
# 발로란트 패치로 읽기가 깨지면 CUE4PARSE_COMMIT 을 새 커밋으로 올린다.
set -euo pipefail
CUE4PARSE_COMMIT="${CUE4PARSE_COMMIT:-605672df7a993a90094bad92d30c388d87ae6c1a}"
here="$(cd "$(dirname "$0")" && pwd)"
dst="$here/vendor/CUE4Parse"
if [ ! -d "$dst/.git" ]; then
git clone --quiet https://github.com/FabianFG/CUE4Parse "$dst"
fi
if [ "$(git -C "$dst" rev-parse HEAD)" != "$CUE4PARSE_COMMIT" ]; then
git -C "$dst" fetch --quiet origin
git -C "$dst" checkout --quiet --force "$CUE4PARSE_COMMIT"
fi
echo "CUE4Parse @ $(git -C "$dst" rev-parse --short HEAD)"

View File

@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# 맵 3D 자동 갱신을 이 리눅스 서버(.9)에 설치한다. 저장소에서: tools/map-extract/scripts/install.sh
# - gvr-map-extract 를 빌드해 $GVR_MAPS_HOME/bin 에 둔다 (저장소 작업 폴더가 바뀌어도 타이머는 그대로 돈다)
# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup
# 코드를 고쳤으면 다시 실행하면 된다. 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
export PATH="$HOME/.dotnet:$PATH" DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DOTNET_CLI_TELEMETRY_OPTOUT=1
"$here/fetch-cue4parse.sh"
rm -rf "$GVR_MAPS_HOME/bin.new"
CUE4PARSE_SKIP_NATIVE=1 dotnet build "$here/MapExtract.csproj" -c Release -o "$GVR_MAPS_HOME/bin.new" -v quiet -nologo -clp:ErrorsOnly
rm -rf "$GVR_MAPS_HOME/bin.old"
[ -d "$GVR_MAPS_HOME/bin" ] && mv "$GVR_MAPS_HOME/bin" "$GVR_MAPS_HOME/bin.old"
mv "$GVR_MAPS_HOME/bin.new" "$GVR_MAPS_HOME/bin"
# Oodle 압축 풀기 라이브러리: 처음 실행 때 받는다. 이전 설치에 있으면 옮겨 둔다
[ -f "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" ] && cp "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" "$GVR_MAPS_HOME/bin/"
rm -rf "$GVR_MAPS_HOME/bin.old"
mkdir -p "$GVR_MAPS_HOME/scripts"
cp "$here/scripts/update.sh" "$here/scripts/pack.py" "$here/scripts/preview.py" "$GVR_MAPS_HOME/scripts/"
chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
unit="$HOME/.config/systemd/user"
mkdir -p "$unit"
node_dir="$(dirname "$(command -v node)")"
cat > "$unit/gvr-maps-update.service" <<EOF
[Unit]
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (uedb 매핑 · 라이브 패치 확인 → 추출 → 사이트 반영)
After=network-online.target
[Service]
Type=oneshot
Environment=GVR_MAPS_HOME=$GVR_MAPS_HOME
Environment=DOTNET_ROOT=$DOTNET_ROOT
Environment=PATH=$node_dir:$HOME/.dotnet:/usr/local/bin:/usr/bin:/bin
Environment=TMPDIR=$HOME/.tmp
Environment=NOTIFY_CHANNEL=${NOTIFY_CHANNEL:-}
Environment=NOTIFY_ENV=${NOTIFY_ENV:-}
ExecStart=$GVR_MAPS_HOME/scripts/update.sh
MemoryMax=6G
MemorySwapMax=0
CPUQuota=300%
CPUWeight=50
Nice=10
TimeoutStartSec=2h
EOF
cat > "$unit/gvr-maps-update.timer" <<EOF
[Unit]
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (30분마다)
[Timer]
OnBootSec=5min
OnUnitActiveSec=30min
RandomizedDelaySec=2min
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now gvr-maps-update.timer
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
import datetime, gzip, json, os, re, shutil, subprocess, sys
src, out, version = sys.argv[1], sys.argv[2], sys.argv[3]
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d%H%M')
d = re.sub(r'[^\w.-]', '_', f'{version}-{stamp}')
os.makedirs(os.path.join(out, d), exist_ok=True)
maps = {}
for name in sorted(os.listdir(src)):
if not name.endswith('.json'):
continue
info = json.load(open(os.path.join(src, name)))
code = info['code']
glb = os.path.join(src, code + '.glb')
if not os.path.exists(glb) or info.get('triangles', 0) == 0:
continue
packed = os.path.join(out, d, code + '.glb')
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc'], check=True, stdout=subprocess.DEVNULL)
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
shutil.copyfileobj(f, g)
os.remove(packed)
size = os.path.getsize(packed + '.gz')
maps[info['mapUrl']] = {'code': code, 'file': code + '.glb', 'bytes': size, 'triangles': info['triangles']}
print(f"{code}: {info['triangles']} 삼각형 → {size / 1e6:.1f}MB")
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps}
tmp = os.path.join(out, 'index.json.tmp')
json.dump(idx, open(tmp, 'w'), ensure_ascii=False, indent=1)
os.replace(tmp, os.path.join(out, 'index.json'))
print(f'index.json: 맵 {len(maps)}개 · 폴더 {d}')

View File

@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""추출한 맵 glb 를 위에서 본 그림(PNG)으로 그린다. 확인용.
preview.py <맵.glb> <출력.png> [천장 cm (이보다 높은 삼각형 제외)]
삼각형마다 무게중심 · 꼭짓점을 찍고 높은 것이 위에 오게 칠한다 (빠른 근사)."""
import json, struct, sys
import numpy as np
from PIL import Image
src, dst = sys.argv[1], sys.argv[2]
zmax = float(sys.argv[3]) if len(sys.argv) > 3 else None
b = open(src, 'rb').read()
jl = struct.unpack('<I', b[12:16])[0]
j = json.loads(b[20:20 + jl])
bin_ = b[20 + jl + 8:]
pa, ia = j['accessors'][0], j['accessors'][1]
pv, iv = j['bufferViews'][pa['bufferView']], j['bufferViews'][ia['bufferView']]
P = np.frombuffer(bin_, '<f4', pa['count'] * 3, pv.get('byteOffset', 0)).reshape(-1, 3)
I = np.frombuffer(bin_, '<u4', ia['count'], iv.get('byteOffset', 0)).reshape(-1, 3)
T = P[I] # (n,3,3)
if zmax is not None:
T = T[T[:, :, 2].max(1) < zmax]
# 면 방향 음영
n = np.cross(T[:, 1] - T[:, 0], T[:, 2] - T[:, 0])
n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-9
lum = 0.35 + 0.65 * np.abs(n @ np.array([0.3, 0.5, 0.81]))
pts = np.concatenate([T.mean(1), T[:, 0], T[:, 1], T[:, 2], (T[:, 0] + T[:, 1]) / 2, (T[:, 1] + T[:, 2]) / 2, (T[:, 0] + T[:, 2]) / 2])
L = np.tile(lum, 7)
lo, hi = np.percentile(pts, 0.5, axis=0), np.percentile(pts, 99.5, axis=0)
size = 1400
s = (size - 20) / max(hi[0] - lo[0], hi[1] - lo[1])
# 미니맵과 같은 방향: 화면 x = 월드 y, 화면 아래 = 월드 x 감소
x = ((pts[:, 1] - lo[1]) * s + 10).astype(int)
y = ((hi[0] - pts[:, 0]) * s + 10).astype(int)
W, H = int((hi[1] - lo[1]) * s + 20), int((hi[0] - lo[0]) * s + 20)
ok = (x >= 0) & (x < W) & (y >= 0) & (y < H)
x, y, z, L = x[ok], y[ok], pts[ok, 2], L[ok]
order = np.argsort(z) # 낮은 것 먼저, 높은 것이 덮는다
img = np.zeros((H, W, 3), np.float32) + np.array([18, 20, 26], np.float32) / 255
zn = np.clip((z - lo[2]) / (hi[2] - lo[2] + 1e-9), 0, 1)
col = np.stack([0.35 + 0.45 * zn, 0.40 + 0.35 * zn, 0.55 - 0.15 * zn], 1) * L[:, None]
img[y[order], x[order]] = col[order]
Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8)).save(dst)
print(dst, W, H, 'triangles', len(T), 'z', lo[2].round(), hi[2].round())

View File

@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# 발로란트 맵 3D 자동 갱신 (systemd 타이머가 30분마다 실행, install.sh 참고)
#
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝
# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/
# 3. 모든 맵을 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다
#
# 실패하면 사이트는 이전 맵을 그대로 쓴다. 같은 (매핑, 패치) 조합은 한 번 실패하면 다음 변경 때까지 다시 하지 않는다.
# 강제로 다시: update.sh --force
set -euo pipefail
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
SITE_HOST="${SITE_HOST:-root@192.168.10.5}"
SITE_DATA="${SITE_DATA:-/root/other/game-voice-recorder/data}"
UEDB="https://uedb.dev/svc/api/v1/valorant/mappings"
SECRETS="${SECRETS:-$HOME/.config/ejclaw/secrets.json}"
export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
BIN="$GVR_MAPS_HOME/bin/gvr-map-extract"
STATE="$GVR_MAPS_HOME/state.json"
mkdir -p "$GVR_MAPS_HOME/mappings" "$GVR_MAPS_HOME/work"
exec 9>"$GVR_MAPS_HOME/.lock"
flock -n 9 || { echo "이미 실행 중"; exit 0; }
log() { echo "[$(date '+%F %T')] $*"; }
# 결과 알림 (선택): NOTIFY_CHANNEL=<디스코드 채널 id>, NOTIFY_ENV=<DISCORD_OWNER_BOT_TOKEN 이 든 .env>
notify() {
[ -n "${NOTIFY_CHANNEL:-}" ] && [ -f "${NOTIFY_ENV:-}" ] || return 0
local token
token="$(grep -E '^DISCORD_OWNER_BOT_TOKEN=' "$NOTIFY_ENV" | head -1 | sed -E 's/^[^=]+=//' | tr -d '"'\''\r')"
[ -n "$token" ] || return 0
curl -sS -o /dev/null --max-time 20 -X POST "https://discord.com/api/v10/channels/$NOTIFY_CHANNEL/messages" \
-H "Authorization: Bot $token" -H 'Content-Type: application/json' \
-d "$(jq -nc --arg c "$1" '{content:$c, allowed_mentions:{parse:[]}}')" || true
}
st() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])) if __import__("os").path.exists(sys.argv[1]) else {}; print(d.get(sys.argv[2],""))' "$STATE" "$1"; }
set_state() { python3 - "$STATE" "$@" <<'P'
import json, os, sys
f = sys.argv[1]
d = json.load(open(f)) if os.path.exists(f) else {}
for kv in sys.argv[2:]:
k, v = kv.split('=', 1)
d[k] = v
json.dump(d, open(f + '.tmp', 'w'), indent=1)
os.replace(f + '.tmp', f)
P
}
# 1. 바뀐 것이 있나
meta="$(curl -fsS --max-time 30 "$UEDB")"
version="$(jq -r .version <<<"$meta")"
updated="$(jq -r .updated <<<"$meta")"
usmap_url="$(jq -r '.mappings.Brotli // .mappings.ZStandard' <<<"$meta")"
[ -n "$version" ] && [ "$version" != null ] && [ -n "$usmap_url" ] && [ "$usmap_url" != null ] || { log "uedb 응답 이상: $meta"; exit 1; }
manifest="$("$BIN" manifest)"
key="$version|$updated|$manifest"
if [ "${1:-}" != "--force" ]; then
[ "$key" = "$(st published)" ] && { log "변경 없음 ($version, $(basename "$manifest"))"; exit 0; }
[ "$key" = "$(st failed)" ] && { log "이 조합은 이미 실패함, 다음 변경까지 대기 ($version, $(basename "$manifest"))"; exit 0; }
fi
log "새로 뽑기: 매핑 $version ($updated) · 패치 $(basename "$manifest")"
# 2. 매핑 받기 · 보관
stamp="$(date -u -d "$updated" +%Y%m%d%H%M 2>/dev/null || date -u +%Y%m%d%H%M)"
usmap="$GVR_MAPS_HOME/mappings/${version}_${stamp}_$(basename "$usmap_url" | sed 's/^.*_\(br\|zs\)\.usmap$/\1/').usmap"
if [ ! -s "$usmap" ]; then
curl -fsS --max-time 300 -o "$usmap.part" "$usmap_url"
mv "$usmap.part" "$usmap"
log "매핑 저장 $usmap ($(stat -c %s "$usmap") 바이트)"
# nextcloud 보관 (claude/ 폴더 안만 쓴다, 사용자 규칙)
if [ -f "$SECRETS" ]; then
read -r nc_host nc_user nc_token < <(python3 -c 'import json,sys; c=json.load(open(sys.argv[1]))["credentials"]["nextcloud.192.168.10.10"]; print(c["host"], c["username"], c["token"])' "$SECRETS") || true
if [ -n "${nc_token:-}" ]; then
dav="$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant/mappings"
curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$nc_host/remote.php/dav/files/$nc_user/claude/game-voice-recorder/valorant" >/dev/null 2>&1 || true
curl -fsS -u "$nc_user:$nc_token" -X MKCOL "$dav" >/dev/null 2>&1 || true
if curl -fsS -u "$nc_user:$nc_token" -T "$usmap" "$dav/$(basename "$usmap")" >/dev/null; then log "nextcloud 보관 완료"; else log "nextcloud 보관 실패 (계속 진행)"; fi
fi
fi
fi
# 3. 뽑기 · 압축
raw="$GVR_MAPS_HOME/work/raw"
out="$GVR_MAPS_HOME/work/out"
rm -rf "$raw" "$out"
mkdir -p "$raw" "$out"
if ! GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"; then
set_state "failed=$key" "failedAt=$(date -Is)"
log "추출 실패 → 사이트는 이전 맵 유지"
notify "⚠️ 발로란트 맵 3D 자동 갱신 실패 (매핑 $version · 패치 $(basename "$manifest" .manifest)). 사이트는 이전 맵을 그대로 씁니다. 로그: journalctl --user -u gvr-maps-update"
exit 1
fi
python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version"
dir="$(jq -r .dir "$out/index.json")"
count="$(jq '.maps | length' "$out/index.json")"
[ "$count" -gt 0 ] || { set_state "failed=$key"; log "맵 0개 → 올리지 않음"; exit 1; }
# 4. 사이트 서버에 올리기 (폴더 먼저, index.json 은 마지막에 바꿔 끼움)
ssh -o BatchMode=yes "$SITE_HOST" "mkdir -p '$SITE_DATA/maps3d'"
tar -C "$out" -cf - "$dir" | ssh -o BatchMode=yes "$SITE_HOST" "tar -xf - -C '$SITE_DATA/maps3d'"
scp -q -o BatchMode=yes "$out/index.json" "$SITE_HOST:$SITE_DATA/maps3d/index.json.tmp"
prev="$(ssh -o BatchMode=yes "$SITE_HOST" "cat '$SITE_DATA/maps3d/index.json' 2>/dev/null" | jq -r '.dir // empty' 2>/dev/null || true)"
ssh -o BatchMode=yes "$SITE_HOST" "mv '$SITE_DATA/maps3d/index.json.tmp' '$SITE_DATA/maps3d/index.json'"
# 지금 것과 바로 전 것(이미 열어 둔 화면용)만 남긴다
ssh -o BatchMode=yes "$SITE_HOST" "cd '$SITE_DATA/maps3d' && for d in */; do d=\${d%/}; [ \"\$d\" = '$dir' ] || [ \"\$d\" = '$prev' ] || rm -rf -- \"\$d\"; done"
set_state "published=$key" "publishedAt=$(date -Is)" "dir=$dir" "failed="
rm -rf "$raw" "$out"
log "사이트 반영 완료: 맵 $count 개 · $dir"
notify "🗺️ 발로란트 맵 3D 자동 갱신: 매핑 $version · 맵 ${count}개를 사이트에 반영했습니다"

View File

@@ -0,0 +1,220 @@
using System.Net;
using System.Net.Http.Headers;
using CUE4Parse.UE4.Readers;
using CUE4Parse.UE4.Versions;
namespace GvrMapExtract;
/// <summary>Riot CDN 번들에서 매니페스트 조각을 필요할 때만 받는다 (HTTP Range).
/// 받은 조각은 압축을 풀어 메모리에 둔다 (오래 안 쓴 것부터 버림). 디스크는 쓰지 않는다.</summary>
public sealed class CdnStore(string bundleBase, long cacheBytes)
{
private readonly HttpClient _http = new(new SocketsHttpHandler { MaxConnectionsPerServer = 8, AutomaticDecompression = DecompressionMethods.None })
{
Timeout = TimeSpan.FromSeconds(90),
};
private readonly object _lock = new();
private readonly Dictionary<(ulong, uint), LinkedListNode<((ulong, uint) key, byte[] data)>> _map = new();
private readonly LinkedList<((ulong, uint) key, byte[] data)> _lru = new();
private readonly Dictionary<(ulong, uint), Task> _inflight = new();
private long _cached;
public long DownloadedBytes;
public long Requests;
private bool TryGet((ulong, uint) key, out byte[] data)
{
lock (_lock)
{
if (_map.TryGetValue(key, out var node))
{
_lru.Remove(node);
_lru.AddFirst(node);
data = node.Value.data;
return true;
}
}
data = [];
return false;
}
private void Put((ulong, uint) key, byte[] data)
{
lock (_lock)
{
if (_map.ContainsKey(key)) return;
_map[key] = _lru.AddFirst((key, data));
_cached += data.Length;
while (_cached > cacheBytes && _lru.Last is { } last)
{
_lru.RemoveLast();
_map.Remove(last.Value.key);
_cached -= last.Value.data.Length;
}
}
}
/// <summary>파일의 i 번째 조각. 없으면 뒤로 이어진 조각(같은 번들 · 연속 위치)까지 한 번에 받는다</summary>
public byte[] Get(Rman.RFile f, int i)
{
var c = f.Chunks[i];
var key = (c.BundleId, c.BundleOffset);
for (var attempt = 0; ; attempt++)
{
if (TryGet(key, out var hit)) return hit;
Task? wait;
TaskCompletionSource? mine = null;
lock (_lock)
{
if (!_inflight.TryGetValue(key, out wait))
{
mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_inflight[key] = mine.Task;
}
}
if (mine == null)
{
try { wait!.Wait(); } catch { /* 받던 쪽이 실패하면 다시 시도 */ }
if (attempt > 4) throw new IOException("조각 받기 실패 (반복)");
continue;
}
// 이어 받을 조각 범위
var run = new List<int> { i };
long total = c.CompressedSize;
for (var j = i + 1; j < f.Chunks.Length && run.Count < 64 && total < 8 << 20; j++)
{
var n = f.Chunks[j];
var prev = f.Chunks[j - 1];
if (n.BundleId != c.BundleId || n.BundleOffset != prev.BundleOffset + prev.CompressedSize) break;
lock (_lock) if (_map.ContainsKey((n.BundleId, n.BundleOffset)) || _inflight.ContainsKey((n.BundleId, n.BundleOffset))) break;
run.Add(j);
total += n.CompressedSize;
}
lock (_lock) foreach (var j in run.Skip(1)) _inflight.TryAdd((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), mine.Task);
try
{
var raw = Fetch(c.BundleId, c.BundleOffset, total);
var pos = 0;
using var z = new ZstdSharp.Decompressor();
foreach (var j in run)
{
var cj = f.Chunks[j];
var outBuf = new byte[cj.UncompressedSize];
var n = z.Unwrap(raw.AsSpan(pos, (int)cj.CompressedSize), outBuf);
if (n != cj.UncompressedSize) throw new IOException("조각 크기가 다름");
pos += (int)cj.CompressedSize;
Put((cj.BundleId, cj.BundleOffset), outBuf);
}
mine.SetResult();
}
catch (Exception e)
{
mine.SetException(e);
if (attempt > 4) throw;
}
finally
{
lock (_lock) foreach (var j in run) if (_inflight.TryGetValue((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), out var t) && t == mine.Task) _inflight.Remove((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset));
}
}
}
private byte[] Fetch(ulong bundle, uint offset, long length)
{
var url = $"{bundleBase}/{bundle:X16}.bundle";
for (var attempt = 0; ; attempt++)
{
try
{
using var req = new HttpRequestMessage(HttpMethod.Get, url);
req.Headers.Range = new RangeHeaderValue(offset, offset + length - 1);
using var res = _http.Send(req, HttpCompletionOption.ResponseHeadersRead);
if (res.StatusCode != HttpStatusCode.PartialContent) throw new IOException($"{url} {(int)res.StatusCode}");
using var s = res.Content.ReadAsStream();
var buf = new byte[length];
s.ReadExactly(buf);
Interlocked.Add(ref DownloadedBytes, length);
Interlocked.Increment(ref Requests);
return buf;
}
catch (Exception) when (attempt < 4)
{
Thread.Sleep(1000 * (attempt + 1));
}
}
}
public async Task<byte[]> GetBytes(string url) => await _http.GetByteArrayAsync(url);
}
/// <summary>매니페스트 파일 하나를 CUE4Parse 가 읽는 파일처럼 보이게 한다 (임의 위치 읽기)</summary>
public sealed class CdnArchive : FArchive
{
private readonly CdnStore _store;
private readonly Rman.RFile _file;
private readonly long[] _starts;
public CdnArchive(CdnStore store, Rman.RFile file, VersionContainer? versions) : base(versions)
{
_store = store;
_file = file;
_starts = file.Chunks.Select(c => c.FileOffset).ToArray();
Name = file.Path;
}
public override string Name { get; }
public override bool CanSeek => true;
public override long Length => _file.Size;
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
var n = ReadAt(Position, buffer, offset, count);
Position += n;
return n;
}
public override int ReadAt(long position, byte[] buffer, int offset, int count)
{
if (position >= Length) return 0;
count = (int)Math.Min(count, Length - position);
var done = 0;
var i = Array.BinarySearch(_starts, position);
if (i < 0) i = ~i - 1;
while (done < count)
{
var c = _file.Chunks[i];
var data = _store.Get(_file, i);
var inChunk = (int)(position + done - c.FileOffset);
var n = Math.Min(count - done, data.Length - inChunk);
Buffer.BlockCopy(data, inChunk, buffer, offset + done, n);
done += n;
i++;
}
return done;
}
public override Task<int> ReadAtAsync(long position, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
=> Task.FromResult(ReadAt(position, buffer, offset, count));
public override ValueTask<int> ReadAtAsync(long position, Memory<byte> memory, CancellationToken cancellationToken = default)
{
var tmp = new byte[memory.Length];
var n = ReadAt(position, tmp, 0, tmp.Length);
tmp.AsSpan(0, n).CopyTo(memory.Span);
return ValueTask.FromResult(n);
}
public override long Seek(long offset, SeekOrigin origin)
{
Position = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => Position + offset,
SeekOrigin.End => Length + offset,
_ => throw new ArgumentOutOfRangeException(nameof(origin)),
};
return Position;
}
public override object Clone() => new CdnArchive(_store, _file, Versions) { Position = Position };
}

View File

@@ -0,0 +1,225 @@
using System.Text;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Objects.Core.Math;
namespace GvrMapExtract;
/// <param name="Code">영구 레벨 이름 (Ascent, HURM_Alley …)</param>
/// <param name="MapUrl">경기 기록의 맵 경로 (/Game/Maps/Ascent/Ascent)</param>
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</summary>
public sealed class MapScene
{
public int Placements, Meshes, Failed, Skipped;
public long Triangles => _idx.Count / 3;
private readonly List<float> _pos = new();
private readonly List<uint> _idx = new();
private readonly List<string> _levels = new();
private string _code = "";
private string _mapUrl = "";
/// <summary>맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록의 맵 경로 "/Game/Maps/Ascent/Ascent" 와 같다).
/// 연습장 · 튜토리얼 · 메뉴처럼 경기가 없는 곳은 뺀다</summary>
public static List<MapInfo> FindMaps(IFileProvider provider, Action<string>? log = null)
{
var umaps = provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Maps/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".umap", StringComparison.OrdinalIgnoreCase)).ToList();
var byDir = umaps.GroupBy(k => k[..k.LastIndexOf('/')]).ToDictionary(g => g.Key, g => g.Select(x => Path.GetFileNameWithoutExtension(x)).ToList());
var res = new List<MapInfo>();
foreach (var k in umaps.OrderBy(x => x))
{
var dir = k[..k.LastIndexOf('/')];
var name = Path.GetFileNameWithoutExtension(k);
if (NotPlayable.Any(x => k.Contains(x, StringComparison.OrdinalIgnoreCase))) continue;
if (!byDir[dir].Any(o => o.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))) continue;
List<(string level, string cls, string props)> subs;
try { subs = StreamingLevels(provider, k); } catch (Exception e) { log?.Invoke($"{k}: 레벨 목록 실패 {e.Message}"); continue; }
var levels = subs.Where(x => x.cls == "LevelStreamingAlwaysLoaded" && IsVisualLevel(x.level))
.Select(x => "ShooterGame/Content" + x.level["/Game".Length..] + ".umap")
.Where(provider.Files.ContainsKey).ToList();
if (levels.Count == 0) continue;
levels.Insert(0, k);
res.Add(new MapInfo(name, "/Game" + k["ShooterGame/Content".Length..^".umap".Length], levels));
}
return res;
}
private static readonly string[] NotPlayable = ["/Poveglia", "/NPE", "/Menu/", "/Init/", "/Pregame", "_Copy/", "/SharedSubLevels/"];
// 보이는 모양이 아닌 하위 레벨 (게임 규칙 · 빛 · 소리 · 부피 · 길찾기 · 카메라 · 효과 · 먼 배경 · 이벤트 장식)
private static readonly string[] NotVisual = ["Gameplay", "Lighting", "Volume", "NavMesh", "Audio", "Sound", "_BV", "Callout", "VFX", "_FX", "Vista", "Background", "Decal",
"Activation", "Birthday", "Snow", "LiveStory", "Sequence", "Camera", "Probe", "Profiling", "Greybox", "Blockout", "Design", "Layout", "Lanes", "Mode_", "Spawns_Proto", "SpawnPoints", "Skybox", "AuxiliaryZones", "KillVol", "Barrier", "Collider"];
/// <summary>영구 레벨이 불러오는 하위 레벨들 (패키지 경로 · 형 · b 로 시작하는 속성)</summary>
public static List<(string level, string cls, string props)> StreamingLevels(IFileProvider provider, string umap)
{
var res = new List<(string, string, string)>();
var pkg = provider.LoadPackage(umap);
var world = pkg.GetExports().OfType<CUE4Parse.UE4.Objects.Engine.UWorld>().FirstOrDefault();
if (world?.StreamingLevels == null) return res;
foreach (var r in world.StreamingLevels)
{
var ls = r.Load<CUE4Parse.UE4.Objects.Engine.ULevelStreaming>();
if (ls?.WorldAsset == null) continue;
var pkgName = ls.WorldAsset.Value.AssetPathName.Text.Split('.')[0];
var props = string.Join(' ', ls.Properties.Where(p => p.Name.Text.StartsWith('b')).Select(p => $"{p.Name.Text}={p.Tag?.GenericValue}"));
res.Add((pkgName, ls.ExportType, props));
}
return res;
}
public static bool IsVisualLevel(string level)
{
var name = level[(level.LastIndexOf('/') + 1)..];
return !NotVisual.Any(x => name.Contains(x, StringComparison.OrdinalIgnoreCase));
}
// 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다
private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"];
public static MapScene Build(IFileProvider provider, MapInfo map)
{
var s = new MapScene { _code = map.Code, _mapUrl = map.MapUrl };
var meshCache = new Dictionary<string, (FVector[] v, uint[] i)?>();
foreach (var level in map.Levels)
{
s._levels.Add(Path.GetFileNameWithoutExtension(level));
var pkg = provider.LoadPackage(level);
foreach (var lazy in pkg.ExportsLazy)
{
UObject o;
try { o = lazy.Value; } catch { s.Failed++; continue; }
if (o is not UStaticMeshComponent c) continue;
if (c.GetOrDefault<bool>("bHiddenInGame") || !c.GetOrDefault("bVisible", true)) { s.Skipped++; continue; }
UStaticMesh? mesh;
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { s.Failed++; continue; }
if (mesh == null) continue;
var path = mesh.GetPathName();
if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; }
if (!meshCache.TryGetValue(path, out var geo))
{
geo = Geometry(mesh);
meshCache[path] = geo;
if (geo != null) s.Meshes++;
}
if (geo == null) continue;
FTransform w;
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data)
foreach (var d in data) s.Add(geo.Value, d.TransformData * w);
else s.Add(geo.Value, w);
}
}
return s;
}
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
{
var lods = mesh.RenderData?.LODs;
if (lods == null) return null;
for (var l = lods.Length - 1; l >= 0; l--)
{
var lod = lods[l];
if (lod.SkipLod || lod.PositionVertexBuffer?.Verts is not { Length: > 0 } v || lod.IndexBuffer?.Buffer is not { Length: > 0 } ib) continue;
var idx = new List<uint>();
foreach (var sec in lod.Sections)
for (var k = 0; k < sec.NumTriangles * 3; k++) idx.Add(ib[sec.FirstIndex + k]);
return (v, idx.ToArray());
}
return null;
}
private void Add((FVector[] v, uint[] i) g, FTransform t)
{
Placements++;
var b = (uint)(_pos.Count / 3);
foreach (var p in g.v)
{
var w = t.TransformPosition(p);
_pos.Add(w.X);
_pos.Add(w.Y);
_pos.Add(w.Z);
}
// 크기가 음수(거울)면 삼각형 방향이 뒤집힌다
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z < 0;
for (var k = 0; k + 2 < g.i.Length; k += 3)
{
_idx.Add(b + g.i[k]);
_idx.Add(b + g.i[flip ? k + 2 : k + 1]);
_idx.Add(b + g.i[flip ? k + 1 : k + 2]);
}
}
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
public void WriteGlb(string file)
{
var pos = _pos.ToArray();
var idx = _idx.ToArray();
float[] min = [float.MaxValue, float.MaxValue, float.MaxValue], max = [float.MinValue, float.MinValue, float.MinValue];
for (var i = 0; i < pos.Length; i++)
{
min[i % 3] = Math.Min(min[i % 3], pos[i]);
max[i % 3] = Math.Max(max[i % 3], pos[i]);
}
var posBytes = pos.Length * 4;
var idxBytes = idx.Length * 4;
var gltf = new
{
asset = new { version = "2.0", generator = "gvr-map-extract" },
scene = 0,
scenes = new[] { new { nodes = new[] { 0 } } },
nodes = new[] { new { mesh = 0, name = _code } },
meshes = new[] { new { name = _code, primitives = new[] { new { attributes = new { POSITION = 0 }, indices = 1, mode = 4 } } } },
accessors = new object[]
{
new { bufferView = 0, componentType = 5126, count = pos.Length / 3, type = "VEC3", min, max },
new { bufferView = 1, componentType = 5125, count = idx.Length, type = "SCALAR" },
},
bufferViews = new[]
{
new { buffer = 0, byteOffset = 0, byteLength = posBytes, target = 34962 },
new { buffer = 0, byteOffset = posBytes, byteLength = idxBytes, target = 34963 },
},
buffers = new[] { new { byteLength = posBytes + idxBytes } },
};
var json = Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(gltf));
var jsonPad = (4 - json.Length % 4) % 4;
using var fs = File.Create(file);
using var w = new BinaryWriter(fs);
var total = 12 + 8 + json.Length + jsonPad + 8 + posBytes + idxBytes;
w.Write(0x46546C67u); // glTF
w.Write(2u);
w.Write((uint)total);
w.Write((uint)(json.Length + jsonPad));
w.Write(0x4E4F534Au); // JSON
w.Write(json);
for (var i = 0; i < jsonPad; i++) w.Write((byte)' ');
w.Write((uint)(posBytes + idxBytes));
w.Write(0x004E4942u); // BIN
foreach (var f in pos) w.Write(f);
foreach (var i in idx) w.Write(i);
}
public void WriteInfo(string file, string manifest, string? usmap)
{
var info = new
{
code = _code,
mapUrl = _mapUrl,
levels = _levels,
placements = Placements,
meshes = Meshes,
triangles = Triangles,
skipped = Skipped,
failed = Failed,
manifest,
usmap = usmap == null ? null : Path.GetFileName(usmap),
extractedAt = DateTimeOffset.UtcNow.ToString("o"),
};
File.WriteAllText(file, System.Text.Json.JsonSerializer.Serialize(info, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
}
}

View File

@@ -0,0 +1,124 @@
using Serilog;
using System.Diagnostics;
using System.Text.RegularExpressions;
using CUE4Parse;
using CUE4Parse.Compression;
using CUE4Parse.Encryption.Aes;
using CUE4Parse.FileProvider;
using CUE4Parse.MappingsProvider.Usmap;
using CUE4Parse.UE4.Objects.Core.Misc;
using CUE4Parse.UE4.Versions;
using GvrMapExtract;
// gvr-map-extract: 발로란트 맵 3D 모양을 Riot CDN 에서 바로 뽑는다 (게임 설치 · 전체 다운로드 없음)
//
// gvr-map-extract ls <정규식> [개수] 파일 목록
// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수)
// gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json
//
// 환경변수
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
CUE4ParseLog.UseLogger(Serilog.Log.Logger);
const string AesKey = "0x4BE71AF2459CF83899EC9DC2CB60E22AC4B3047E0211034BBABE9D174C069DD6"; // 발로란트 공개 키 (모든 패치 같음)
const string BundleBase = "https://valorant.secure.dyn.riotcdn.net/channels/public/bundles";
const string Patchlines = "https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines";
if (args.Length == 0)
{
Console.Error.WriteLine("사용법: gvr-map-extract ls <정규식> | maps | extract <출력 폴더> [맵...] | manifest");
return 2;
}
var sw = Stopwatch.StartNew();
var store = new CdnStore(BundleBase, long.Parse(Environment.GetEnvironmentVariable("GVR_CACHE_MB") ?? "1500") << 20);
var manifestUrl = Environment.GetEnvironmentVariable("GVR_MANIFEST") ?? await LiveManifest(store);
if (args[0] == "manifest")
{
Console.WriteLine(manifestUrl);
return 0;
}
var rman = Rman.Parse(await store.GetBytes(manifestUrl));
Console.Error.WriteLine($"매니페스트 {manifestUrl} 파일 {rman.Files.Count}");
var oodle = Environment.GetEnvironmentVariable("GVR_OODLE") ?? Path.Combine(AppContext.BaseDirectory, OodleHelper.OodleFileName);
await OodleHelper.InitializeAsync(oodle);
var versions = new VersionContainer(EGame.GAME_Valorant);
var provider = new StreamedFileProvider("VALORANT", versions, StringComparer.OrdinalIgnoreCase);
provider.Initialize();
foreach (var f in rman.Files.Values.Where(f => f.Path.StartsWith("ShooterGame/Content/Paks/", StringComparison.OrdinalIgnoreCase)))
{
var ext = Path.GetExtension(f.Path).ToLowerInvariant();
if (ext == ".utoc")
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, open =>
rman.Files.TryGetValue(open, out var c) ? new CdnArchive(store, c, versions) : throw new FileNotFoundException(open));
else if (ext == ".pak")
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, null);
}
provider.SubmitKey(new FGuid(), new FAesKey(AesKey));
provider.PostMount();
var usmap = Environment.GetEnvironmentVariable("GVR_USMAP");
if (usmap != null) provider.MappingsContainer = new FileUsmapTypeMappingsProvider(usmap);
Console.Error.WriteLine($"파일 {provider.Files.Count} · 묶음 {provider.MountedVfs.Count} (못 연 것 {provider.UnloadedVfs.Count}) · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalSeconds:F0}초");
switch (args[0])
{
case "ls":
{
var re = new Regex(args[1], RegexOptions.IgnoreCase);
foreach (var k in provider.Files.Keys.Where(k => re.IsMatch(k)).OrderBy(k => k).Take(args.Length > 2 ? int.Parse(args[2]) : 200)) Console.WriteLine(k);
break;
}
case "levels":
foreach (var (lvl, cls, props) in MapScene.StreamingLevels(provider, args[1]))
Console.WriteLine($"{lvl}\t{cls}\t{props}");
break;
case "maps":
foreach (var m in MapScene.FindMaps(provider, Console.Error.WriteLine)) Console.WriteLine($"{m.Code}\t{m.MapUrl}\t{m.Levels.Count}\t{string.Join(',', m.Levels.Select(Path.GetFileNameWithoutExtension))}");
break;
case "extract":
{
var outDir = args[1];
Directory.CreateDirectory(outDir);
var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase);
var maps = MapScene.FindMaps(provider, Console.Error.WriteLine).Where(m => want.Count == 0 || want.Contains(m.Code)).ToList();
var failed = 0;
foreach (var m in maps)
{
var t0 = sw.Elapsed;
var d0 = store.DownloadedBytes;
try
{
var r = MapScene.Build(provider, m);
r.WriteGlb(Path.Combine(outDir, m.Code + ".glb"));
r.WriteInfo(Path.Combine(outDir, m.Code + ".json"), manifestUrl, usmap);
Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
}
catch (Exception e)
{
failed++;
Console.WriteLine($"{m.Code}: 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
Console.WriteLine($"끝: 맵 {maps.Count - failed}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분");
return failed == 0 ? 0 : 1;
}
default:
Console.Error.WriteLine("모르는 명령 " + args[0]);
return 2;
}
return 0;
static async Task<string> LiveManifest(CdnStore store)
{
var json = System.Text.Json.JsonDocument.Parse(await store.GetBytes(Patchlines));
var live = json.RootElement.GetProperty("keystone.products.valorant.patchlines.live");
foreach (var c in live.GetProperty("platforms").GetProperty("win").GetProperty("configurations").EnumerateArray())
if (c.TryGetProperty("patch_url", out var u)) return u.GetString()!;
throw new InvalidOperationException("라이브 매니페스트를 못 찾음");
}

View File

@@ -0,0 +1,119 @@
using System.Buffers.Binary;
using System.Text;
namespace GvrMapExtract;
/// <summary>Riot 매니페스트(.manifest, RMAN 2.x) 읽기. 본문은 zstd 로 압축된 FlatBuffers.
/// 구조는 Morilli/ManifestDownloader rman.c 를 따랐다.</summary>
public sealed class Rman
{
public sealed record Chunk(ulong BundleId, uint BundleOffset, uint CompressedSize, uint UncompressedSize, long FileOffset);
public sealed record RFile(string Path, long Size, Chunk[] Chunks);
public ulong ManifestId { get; private set; }
public Dictionary<string, RFile> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
public static Rman Parse(byte[] data)
{
if (data.Length < 28 || Encoding.ASCII.GetString(data, 0, 4) != "RMAN") throw new InvalidDataException("RMAN 아님");
if (data[4] != 2) throw new InvalidDataException($"모르는 매니페스트 버전 {data[4]}.{data[5]}");
var contentOffset = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8));
var compressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12));
var r = new Rman { ManifestId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) };
var uncompressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24));
var body = new byte[uncompressedSize];
using (var z = new ZstdSharp.Decompressor())
{
var n = z.Unwrap(data.AsSpan((int)contentOffset, (int)compressedSize), body);
if (n != uncompressedSize) throw new InvalidDataException("매니페스트 압축 풀기 실패");
}
r.ParseBody(new Fb(body));
return r;
}
private void ParseBody(Fb b)
{
var root = b.Root();
// 번들 → 조각 (번들 안 위치는 앞 조각 크기의 누적)
var chunks = new Dictionary<ulong, (ulong bundle, uint off, uint comp, uint raw)>();
foreach (var bt in b.Tables(root, 0))
{
var bundleId = b.U64(bt, 0);
uint off = 0;
foreach (var ct in b.Tables(bt, 1))
{
var comp = b.U32(ct, 1);
chunks[b.U64(ct, 0)] = (bundleId, off, comp, b.U32(ct, 2));
off += comp;
}
}
// 폴더
var dirs = new Dictionary<ulong, (ulong parent, string name)>();
foreach (var dt in b.Tables(root, 3)) dirs[b.U64(dt, 0)] = (b.U64(dt, 1), b.Str(dt, 2));
// 파일
foreach (var ft in b.Tables(root, 2))
{
var name = b.Str(ft, 3);
var dir = b.U64(ft, 1);
while (dir != 0 && dirs.TryGetValue(dir, out var d))
{
if (d.name.Length > 0) name = d.name + "/" + name;
dir = d.parent;
}
var ids = b.U64Vector(ft, 7);
var list = new Chunk[ids.Length];
long fo = 0;
for (var i = 0; i < ids.Length; i++)
{
var c = chunks[ids[i]];
list[i] = new Chunk(c.bundle, c.off, c.comp, c.raw, fo);
fo += c.raw;
}
Files[name] = new RFile(name, (long)b.U64(ft, 2), list);
}
}
/// <summary>아주 작은 FlatBuffers 읽기 (필요한 형만)</summary>
private sealed class Fb(byte[] d)
{
private uint U32At(int p) => BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p));
public int Root() => (int)U32At(0);
/// <summary>테이블 필드 위치. 없으면 -1</summary>
private int Field(int table, int idx)
{
var vt = table - BinaryPrimitives.ReadInt32LittleEndian(d.AsSpan(table));
var vsize = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt));
if (4 + idx * 2 >= vsize) return -1;
var off = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt + 4 + idx * 2));
return off == 0 ? -1 : table + off;
}
private int Ref(int p) => p + (int)U32At(p);
public ulong U64(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(p)); }
public uint U32(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : U32At(p); }
public string Str(int t, int i)
{
var p = Field(t, i);
if (p < 0) return "";
var v = Ref(p);
return Encoding.UTF8.GetString(d, v + 4, (int)U32At(v));
}
public ulong[] U64Vector(int t, int i)
{
var p = Field(t, i);
if (p < 0) return [];
var v = Ref(p);
var n = (int)U32At(v);
var a = new ulong[n];
for (var k = 0; k < n; k++) a[k] = BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(v + 4 + k * 8));
return a;
}
public IEnumerable<int> Tables(int t, int i)
{
var p = Field(t, i);
if (p < 0) yield break;
var v = Ref(p);
var n = (int)U32At(v);
for (var k = 0; k < n; k++) yield return Ref(v + 4 + k * 4);
}
}
}