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; /// 게임에 구워 둔 조명(HQ 라이트맵)을 맵 하나에 아틀라스 두 장으로 모은다. /// /// 게임 라이트맵 텍스처(LightMapTexture2D, DXT5)는 위 절반이 계수 0(색 UVW² · 로그 밝기), 아래 절반이 계수 1(SH 방향 · 밝기 나머지)이다. /// 메시마다(FLightMap2D) 범위(ScaleVectors · AddVectors)가 달라서, 메시가 차지한 칸(UV × CoordinateScale + Bias)마다 그 범위로 푼다 /// (UE LightmapCommon.ush GetLightMapColorHQ 와 같은 식). /// /// 결과 /// irr: sRGB(밝기 / K) — 표면 방향을 빼고 본 조명 색 (L · UVW · L0) /// sh : 방향 계수 / L0 를 ±2 → 0~1 로 — 사이트에서 조명 = irr · K · max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선) /// 칸 밖 텍셀은 이웃 값으로 채워(번짐 방지) 줄인 뒤 페이지째 아틀라스에 놓는다. 라이트맵이 없는 배치는 (0,0) 의 기본 칸(맵 평균 밝기, 방향 없음)을 쓴다. /// /// 메모리: 배치를 모으는 동안은 텍스처 크기 · 칸 목록만 들고 있다가, Build 에서 페이지를 하나씩 풀어 바로 줄인다 /// (페이지가 200개 넘는 맵도 원래 크기 값은 한 장 분량만 메모리에 있다). public sealed class Lightmaps { /// 메시 하나가 차지한 칸: 범위(계수 0 · 1) · 페이지 안 위치 private readonly record struct Alloc(FVector4 S0, FVector4 A0, FVector4 S1, FVector4 A1, float Bx, float By, float Cx, float Cy); private sealed class PageData { public required string Key; public required UTexture2D Tex; public required int W, H; // 계수 하나(텍스처 절반) 크기 public readonly List Allocs = new(); public int Ox, Oy, Sw, Sh2; // 아틀라스 위치 · 줄인 크기 public float[]? Irr, Sh; // 줄인 값 (Sw × Sh2 × 3) public bool[]? Valid; } private readonly List _pages = new(); private readonly Dictionary _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; /// 라이트맵 텍스처 → 페이지 번호 (못 읽으면 -1). 여기서는 크기만 본다 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(); var w = t?.PlatformData?.SizeX ?? 0; var h = (t?.PlatformData?.SizeY ?? 0) / 2; if (t == null || w < 1 || h < 1) { Failed++; return _byKey[key] = -1; } _pages.Add(new PageData { Key = key, Tex = t, W = w, H = h }); return _byKey[key] = _pages.Count - 1; } catch (Exception e) { Failed++; if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {key}: {e.GetType().Name} {e.Message}"); return _byKey[key] = -1; } } /// 메시 하나가 차지한 칸을 적어 둔다 (같은 칸은 한 번만, 푸는 건 Build 에서) public void Allocate(int page, FLightMap2D lm, FVector2D bias) { if (page < 0 || !_done.Add((page, bias.X, bias.Y))) return; Allocations++; var cs = lm.CoordinateScale ?? new FVector2D(1, 1); _pages[page].Allocs.Add(new Alloc(lm.ScaleVectors![0], lm.AddVectors![0], lm.ScaleVectors![1], lm.AddVectors![1], bias.X, bias.Y, cs.X, cs.Y)); } /// 페이지 공간 UV(0~1) → 아틀라스 UV. page < 0 이면 기본 칸 가운데 public (float u, float v) ToAtlas(int page, float u, float v) { if (page < 0 || _atlasW == 0) return ((DefaultCell / 2f) / Math.Max(1, _atlasW), (DefaultCell / 2f) / Math.Max(1, _atlasH)); var p = _pages[page]; u = Math.Clamp(u, 0, 1); v = Math.Clamp(v, 0, 1); return ((p.Ox + u * p.Sw) / _atlasW, (p.Oy + v * p.Sh2) / _atlasH); } public bool Any => _pages.Count > 0; public float K { get; private set; } = 1; public int AtlasW => _atlasW; public int AtlasH => _atlasH; public int Factor { get; private set; } = 1; public int Pages => _pages.Count; /// 아틀라스를 만든다 (너비 maxSide · 넓이 약 maxSide² 안에 들어가게 페이지를 1/2 씩 줄인다). 이 뒤에 ToAtlas 를 쓴다 public (byte[] irr, byte[] sh)? Build(int maxSide) { if (_pages.Count == 0) return null; // 줄이는 배율: 너비 maxSide · 높이 2×maxSide · 넓이 1.25×maxSide² 안에 들어갈 때까지 1/2 씩 var f = 1; while (!Pack(f, maxSide) && f < 64) f *= 2; Factor = f; // 페이지마다: 풀기 → 칸 밖 채우기 → 줄이기 (원래 크기 값은 한 장 분량만) var lum = new List(); double sr = 0, sg = 0, sb = 0; long n = 0; foreach (var p in _pages) { float[] irrF, shF; bool[] valid; try { (irrF, shF, valid) = Decode(p); } catch (Exception e) { Failed++; if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {p.Key}: {e.GetType().Name} {e.Message}"); continue; // 이 페이지는 평균 밝기로 남는다 } for (var i = 0; i < valid.Length; i++) if (valid[i]) { if ((i & 7) == 0) lum.Add(MathF.Max(irrF[i * 3], MathF.Max(irrF[i * 3 + 1], irrF[i * 3 + 2]))); sr += irrF[i * 3]; sg += irrF[i * 3 + 1]; sb += irrF[i * 3 + 2]; n++; } Dilate(p.W, p.H, irrF, shF, valid, 8); Shrink(p, f, irrF, shF, valid); } if (n == 0) return null; lum.Sort(); K = Math.Max(0.05f, lum[(int)(lum.Count * 0.998)]); var avg = new[] { (float)(sr / n), (float)(sg / n), (float)(sb / n) }; using var irr = new Image(_atlasW, _atlasH); using var sh = new Image(_atlasW, _atlasH, new Rgb24(128, 128, 128)); static byte Enc(float v) => (byte)Math.Clamp(MathF.Round(v * 255), 0, 255); static float Srgb(float v) => v <= 0.0031308f ? v * 12.92f : 1.055f * MathF.Pow(v, 1 / 2.4f) - 0.055f; Rgb24 IrrPx(float r, float g, float b) => new(Enc(Srgb(Math.Min(1, r / K))), Enc(Srgb(Math.Min(1, g / K))), Enc(Srgb(Math.Min(1, b / K)))); static Rgb24 ShPx(float x, float y, float z) => new(Enc(x / 4 + 0.5f), Enc(y / 4 + 0.5f), Enc(z / 4 + 0.5f)); // 기본 칸 for (var y = 0; y < DefaultCell; y++) for (var x = 0; x < DefaultCell; x++) irr[x, y] = IrrPx(avg[0], avg[1], avg[2]); foreach (var p in _pages) { // 여백은 가장자리 값으로 for (var y = -Pad; y < p.Sh2 + Pad; y++) for (var x = -Pad; x < p.Sw + Pad; x++) { var k = Math.Clamp(y, 0, p.Sh2 - 1) * p.Sw + Math.Clamp(x, 0, p.Sw - 1); var ax = p.Ox + x; var ay = p.Oy + y; if (p.Valid == null || !p.Valid[k]) { irr[ax, ay] = IrrPx(avg[0], avg[1], avg[2]); continue; } irr[ax, ay] = IrrPx(p.Irr![k * 3], p.Irr[k * 3 + 1], p.Irr[k * 3 + 2]); sh[ax, ay] = ShPx(p.Sh![k * 3], p.Sh[k * 3 + 1], p.Sh[k * 3 + 2]); } p.Irr = p.Sh = null; p.Valid = null; } var enc = new JpegEncoder { Quality = 90, ColorType = JpegEncodingColor.YCbCrRatio444 }; using var mi = new MemoryStream(); irr.SaveAsJpeg(mi, enc); using var ms = new MemoryStream(); sh.SaveAsJpeg(ms, enc); return (mi.ToArray(), ms.ToArray()); } /// 페이지 텍스처를 풀어 칸마다 그 범위로 irr · sh 를 계산한다 (원래 크기) private static (float[] irr, float[] sh, bool[] valid) Decode(PageData p) { var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(p.Tex) ?? throw new InvalidDataException("텍스처를 못 풂"); var bgra = c.PixelFormat == EPixelFormat.PF_B8G8R8A8; if (!bgra && c.PixelFormat != EPixelFormat.PF_R8G8B8A8) throw new InvalidDataException("형식 " + c.PixelFormat); if (c.Width != p.W || c.Height < p.H * 2 || c.Data.Length < c.Width * c.Height * 4) throw new InvalidDataException($"크기 {c.Width}x{c.Height}"); var src = c.Data; int R = bgra ? 2 : 0, B = bgra ? 0 : 2; var irr = new float[p.W * p.H * 3]; var sh = new float[p.W * p.H * 3]; var valid = new bool[p.W * p.H]; const float LogBlackPoint = 0.01858136f; float C(int i) => src[i] / 255f; foreach (var a in p.Allocs) { // 칸 + 1 텍셀 (UE 는 칸 둘레에 여백을 두고 구운 값을 채운다) var x0 = Math.Max(0, (int)Math.Floor(a.Bx * p.W) - 1); var y0 = Math.Max(0, (int)Math.Floor(a.By * p.H) - 1); var x1 = Math.Min(p.W, (int)Math.Ceiling((a.Bx + a.Cx) * p.W) + 1); var y1 = Math.Min(p.H, (int)Math.Ceiling((a.By + a.Cy) * p.H) + 1); for (var y = y0; y < y1; y++) for (var x = x0; x < x1; x++) { var i0 = (y * p.W + x) * 4; var i1 = ((y + p.H) * p.W + x) * 4; var logL = C(i0 + 3) + C(i1 + 3) / 255f - 0.5f / 255f; logL = logL * a.S0.W + a.A0.W; var l = MathF.Max(0, MathF.Pow(2, logL) - LogBlackPoint); var r = C(i0 + R) * C(i0 + R) * a.S0.X + a.A0.X; var g = C(i0 + 1) * C(i0 + 1) * a.S0.Y + a.A0.Y; var b = C(i0 + B) * C(i0 + B) * a.S0.Z + a.A0.Z; var l0 = C(i1 + 3) * a.S1.W + a.A1.W; if (l0 < 1e-4f) l0 = 0.282095f; var o = (y * p.W + x) * 3; irr[o] = MathF.Max(0, l * r * l0); irr[o + 1] = MathF.Max(0, l * g * l0); irr[o + 2] = MathF.Max(0, l * b * l0); sh[o] = (C(i1 + R) * a.S1.X + a.A1.X) / l0; sh[o + 1] = (C(i1 + 1) * a.S1.Y + a.A1.Y) / l0; sh[o + 2] = (C(i1 + B) * a.S1.Z + a.A1.Z) / l0; valid[y * p.W + x] = true; } } return (irr, sh, valid); } /// f×f 평균으로 줄여 페이지에 둔다 (칸 밖 · 채우지 못한 텍셀은 빼고) private static void Shrink(PageData p, int f, float[] irrF, float[] shF, bool[] validF) { p.Irr = new float[p.Sw * p.Sh2 * 3]; p.Sh = new float[p.Sw * p.Sh2 * 3]; p.Valid = new bool[p.Sw * p.Sh2]; for (var y = 0; y < p.Sh2; y++) for (var x = 0; x < p.Sw; x++) { float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0; var cnt = 0; for (var dy = 0; dy < f; dy++) for (var dx = 0; dx < f; dx++) { var px = Math.Min(p.W - 1, x * f + dx); var py = Math.Min(p.H - 1, y * f + dy); var k = py * p.W + px; if (!validF[k]) continue; r += irrF[k * 3]; g += irrF[k * 3 + 1]; b += irrF[k * 3 + 2]; hx += shF[k * 3]; hy += shF[k * 3 + 1]; hz += shF[k * 3 + 2]; cnt++; } if (cnt == 0) continue; var o = (y * p.Sw + x) * 3; p.Irr[o] = r / cnt; p.Irr[o + 1] = g / cnt; p.Irr[o + 2] = b / cnt; p.Sh[o] = hx / cnt; p.Sh[o + 1] = hy / cnt; p.Sh[o + 2] = hz / cnt; p.Valid[y * p.Sw + x] = true; } } /// 1/f 로 줄인 페이지를 너비 maxSide 선반에 쌓는다 (높은 것부터). 한도 안이면 true 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; } /// 칸 밖 텍셀을 이웃 칸 값으로 채운다 (줄이기 · 선형 보간에서 검은 테두리가 번지지 않게) private static void Dilate(int w, int h, float[] irr, float[] sh, bool[] valid, int passes) { var add = new List(); for (var pass = 0; pass < passes; pass++) { add.Clear(); for (var y = 0; y < h; y++) for (var x = 0; x < w; x++) { var k = y * w + x; if (valid[k]) continue; float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0; var cnt = 0; for (var dy = -1; dy <= 1; dy++) for (var dx = -1; dx <= 1; dx++) { var nx = x + dx; var ny = y + dy; if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue; var j = ny * w + nx; if (!valid[j]) continue; r += irr[j * 3]; g += irr[j * 3 + 1]; b += irr[j * 3 + 2]; hx += sh[j * 3]; hy += sh[j * 3 + 1]; hz += sh[j * 3 + 2]; cnt++; } if (cnt == 0) continue; irr[k * 3] = r / cnt; irr[k * 3 + 1] = g / cnt; irr[k * 3 + 2] = b / cnt; sh[k * 3] = hx / cnt; sh[k * 3 + 1] = hy / cnt; sh[k * 3 + 2] = hz / cnt; add.Add(k); } if (add.Count == 0) break; foreach (var k in add) valid[k] = true; } } }