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:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user