3D 리플레이 실감 3단계: 게임에 구워 둔 조명(라이트맵)으로 맵을 칠한다
- 추출기: 레벨 BuiltData 의 HQ 라이트맵을 메시 칸마다 풀어 irr · sh 아틀라스 두 장으로 (src/Lightmaps.cs), 조명 있는 배치는 LOD0 + 라이트맵 UV(TEXCOORD_1), ISM 은 인스턴스마다 칸 - glb: 재질 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) · extras.lightmap.k. pack.py 는 맵 UV 를 실수로(-vtf, gltfpack 이 두 UV 채널을 한 범위로 양자화해서 라이트맵이 어긋나던 것) - 사이트 map3d.ts: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)). 옛 glb 는 그대로 - install.sh: 꺼 둔 자동 갱신 타이머는 다시 켜지 않는다 - 조사 명령 lmprobe · 작업 노트 docs/dev/replay-3d.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
271
tools/map-extract/src/Lightmaps.cs
Normal file
271
tools/map-extract/src/Lightmaps.cs
Normal file
@@ -0,0 +1,271 @@
|
||||
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) 의 기본 칸(맵 평균 밝기, 방향 없음)을 쓴다.</summary>
|
||||
public sealed class Lightmaps
|
||||
{
|
||||
private sealed class PageData
|
||||
{
|
||||
public required string Key;
|
||||
public required int W, H; // 계수 하나(텍스처 절반) 크기
|
||||
public required byte[] Src; // RGBA, W × 2H
|
||||
public Half[] Irr = null!, Sh = null!; // 메모리를 줄이려고 반 정밀도 (맵 하나에 페이지 100개 넘게)
|
||||
public bool[] Valid = null!;
|
||||
public int Ox, Oy, Sw, Sh2; // 아틀라스 위치 · 줄인 크기
|
||||
}
|
||||
|
||||
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 c = t == null ? null : CUE4Parse_Conversion.Textures.TextureDecoder.Decode(t);
|
||||
if (c == null || c.Height < 2 || c.Data.Length < c.Width * c.Height * 4) { Failed++; return _byKey[key] = -1; }
|
||||
var bgra = c.PixelFormat == EPixelFormat.PF_B8G8R8A8;
|
||||
if (!bgra && c.PixelFormat != EPixelFormat.PF_R8G8B8A8) { Failed++; return _byKey[key] = -1; }
|
||||
var src = c.Data;
|
||||
if (bgra)
|
||||
{
|
||||
src = (byte[])src.Clone();
|
||||
for (var i = 0; i < src.Length; i += 4) (src[i], src[i + 2]) = (src[i + 2], src[i]);
|
||||
}
|
||||
var w = c.Width;
|
||||
var h = c.Height / 2;
|
||||
_pages.Add(new PageData { Key = key, W = w, H = h, Src = src, Irr = new Half[w * h * 3], Sh = new Half[w * h * 3], Valid = new bool[w * 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>메시 하나가 차지한 칸을 풀어 둔다 (같은 칸은 한 번만)</summary>
|
||||
public void Allocate(int page, FLightMap2D lm, FVector2D bias)
|
||||
{
|
||||
if (page < 0 || !_done.Add((page, bias.X, bias.Y))) return;
|
||||
Allocations++;
|
||||
var p = _pages[page];
|
||||
var cs = lm.CoordinateScale ?? new FVector2D(1, 1);
|
||||
var s0 = lm.ScaleVectors![0];
|
||||
var a0 = lm.AddVectors![0];
|
||||
var s1 = lm.ScaleVectors![1];
|
||||
var a1 = lm.AddVectors![1];
|
||||
// 칸 + 1 텍셀 (UE 는 칸 둘레에 여백을 두고 구운 값을 채운다)
|
||||
var x0 = Math.Max(0, (int)Math.Floor(bias.X * p.W) - 1);
|
||||
var y0 = Math.Max(0, (int)Math.Floor(bias.Y * p.H) - 1);
|
||||
var x1 = Math.Min(p.W, (int)Math.Ceiling((bias.X + cs.X) * p.W) + 1);
|
||||
var y1 = Math.Min(p.H, (int)Math.Ceiling((bias.Y + cs.Y) * p.H) + 1);
|
||||
const float LogBlackPoint = 0.01858136f;
|
||||
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;
|
||||
float C(int i) => p.Src[i] / 255f;
|
||||
var logL = C(i0 + 3) + C(i1 + 3) / 255f - 0.5f / 255f;
|
||||
logL = logL * s0.W + a0.W;
|
||||
var l = MathF.Max(0, MathF.Pow(2, logL) - LogBlackPoint);
|
||||
var r = C(i0) * C(i0) * s0.X + a0.X;
|
||||
var g = C(i0 + 1) * C(i0 + 1) * s0.Y + a0.Y;
|
||||
var b = C(i0 + 2) * C(i0 + 2) * s0.Z + a0.Z;
|
||||
var l0 = C(i1 + 3) * s1.W + a1.W;
|
||||
if (l0 < 1e-4f) l0 = 0.282095f;
|
||||
var o = (y * p.W + x) * 3;
|
||||
p.Irr[o] = (Half)(MathF.Max(0, l * r * l0));
|
||||
p.Irr[o + 1] = (Half)(MathF.Max(0, l * g * l0));
|
||||
p.Irr[o + 2] = (Half)(MathF.Max(0, l * b * l0));
|
||||
p.Sh[o] = (Half)((C(i1) * s1.X + a1.X) / l0);
|
||||
p.Sh[o + 1] = (Half)((C(i1 + 1) * s1.Y + a1.Y) / l0);
|
||||
p.Sh[o + 2] = (Half)((C(i1 + 2) * s1.Z + a1.Z) / l0);
|
||||
p.Valid[y * p.W + x] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>아틀라스를 만든다 (너비 maxSide · 넓이 약 maxSide² 안에 들어가게 페이지를 1/2 씩 줄인다). 이 뒤에 ToAtlas 를 쓴다</summary>
|
||||
public (byte[] irr, byte[] sh)? Build(int maxSide)
|
||||
{
|
||||
if (_pages.Count == 0) return null;
|
||||
// 맵 평균 · 최대 밝기
|
||||
var lum = new List<float>();
|
||||
double sr = 0, sg = 0, sb = 0;
|
||||
long n = 0;
|
||||
foreach (var p in _pages)
|
||||
for (var i = 0; i < p.Valid.Length; i++)
|
||||
if (p.Valid[i])
|
||||
{
|
||||
var m = MathF.Max((float)p.Irr[i * 3], MathF.Max((float)p.Irr[i * 3 + 1], (float)p.Irr[i * 3 + 2]));
|
||||
if ((i & 7) == 0) lum.Add(m);
|
||||
sr += (float)p.Irr[i * 3]; sg += (float)p.Irr[i * 3 + 1]; sb += (float)p.Irr[i * 3 + 2];
|
||||
n++;
|
||||
}
|
||||
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) };
|
||||
|
||||
foreach (var p in _pages) Dilate(p, 8);
|
||||
// 줄이는 배율: 너비 maxSide · 높이 2×maxSide · 넓이 1.25×maxSide² 안에 들어갈 때까지 1/2 씩
|
||||
var f = 1;
|
||||
while (!Pack(f, maxSide) && f < 64) f *= 2;
|
||||
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)
|
||||
{
|
||||
// 줄이기 (f×f 평균) + 여백은 가장자리 값으로
|
||||
for (var y = -Pad; y < p.Sh2 + Pad; y++)
|
||||
for (var x = -Pad; x < p.Sw + Pad; x++)
|
||||
{
|
||||
var sx = Math.Clamp(x, 0, p.Sw - 1);
|
||||
var sy = Math.Clamp(y, 0, p.Sh2 - 1);
|
||||
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, sx * f + dx);
|
||||
var py = Math.Min(p.H - 1, sy * f + dy);
|
||||
var k = py * p.W + px;
|
||||
if (!p.Valid[k]) continue;
|
||||
r += (float)p.Irr[k * 3]; g += (float)p.Irr[k * 3 + 1]; b += (float)p.Irr[k * 3 + 2];
|
||||
hx += (float)p.Sh[k * 3]; hy += (float)p.Sh[k * 3 + 1]; hz += (float)p.Sh[k * 3 + 2];
|
||||
cnt++;
|
||||
}
|
||||
var ax = p.Ox + x;
|
||||
var ay = p.Oy + y;
|
||||
if (cnt == 0)
|
||||
{
|
||||
irr[ax, ay] = IrrPx(avg[0], avg[1], avg[2]);
|
||||
continue;
|
||||
}
|
||||
irr[ax, ay] = IrrPx(r / cnt, g / cnt, b / cnt);
|
||||
sh[ax, ay] = ShPx(hx / cnt, hy / cnt, hz / cnt);
|
||||
}
|
||||
}
|
||||
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);
|
||||
Factor = f;
|
||||
foreach (var p in _pages) { p.Src = []; p.Irr = []; p.Sh = []; }
|
||||
return (mi.ToArray(), ms.ToArray());
|
||||
}
|
||||
|
||||
public int Factor { get; private set; } = 1;
|
||||
|
||||
/// <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;
|
||||
}
|
||||
public int Pages => _pages.Count;
|
||||
|
||||
/// <summary>칸 밖 텍셀을 이웃 칸 값으로 채운다 (줄이기 · 선형 보간에서 검은 테두리가 번지지 않게)</summary>
|
||||
private static void Dilate(PageData p, int passes)
|
||||
{
|
||||
for (var pass = 0; pass < passes; pass++)
|
||||
{
|
||||
var add = new List<int>();
|
||||
for (var y = 0; y < p.H; y++)
|
||||
for (var x = 0; x < p.W; x++)
|
||||
{
|
||||
var k = y * p.W + x;
|
||||
if (p.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 >= p.W || ny >= p.H) continue;
|
||||
var j = ny * p.W + nx;
|
||||
if (!p.Valid[j]) continue;
|
||||
r += (float)p.Irr[j * 3]; g += (float)p.Irr[j * 3 + 1]; b += (float)p.Irr[j * 3 + 2];
|
||||
hx += (float)p.Sh[j * 3]; hy += (float)p.Sh[j * 3 + 1]; hz += (float)p.Sh[j * 3 + 2];
|
||||
cnt++;
|
||||
}
|
||||
if (cnt == 0) continue;
|
||||
p.Irr[k * 3] = (Half)(r / cnt); p.Irr[k * 3 + 1] = (Half)(g / cnt); p.Irr[k * 3 + 2] = (Half)(b / cnt);
|
||||
p.Sh[k * 3] = (Half)(hx / cnt); p.Sh[k * 3 + 1] = (Half)(hy / cnt); p.Sh[k * 3 + 2] = (Half)(hz / cnt);
|
||||
add.Add(k);
|
||||
}
|
||||
if (add.Count == 0) break;
|
||||
foreach (var k in add) p.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}");
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ using GvrMapExtract;
|
||||
// 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 +103,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)
|
||||
{
|
||||
@@ -182,6 +183,9 @@ switch (args[0])
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user