맵 3D: 재질 · 텍스처(디퓨즈 256px) · 두 층 섞기 · 법선 포함 glb, 사이트가 glb 재질로 그림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 19:40:19 +09:00
parent 1ee753bc79
commit 6d71abaabd
10 changed files with 598 additions and 87 deletions

View File

@@ -3,7 +3,9 @@ using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Objects.Core.Math;
using CUE4Parse.UE4.Objects.UObject;
namespace GvrMapExtract;
@@ -12,13 +14,10 @@ namespace GvrMapExtract;
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</summary>
/// 재질마다 텍스처(디퓨즈, 작게 줄임) · 색을 붙인다.</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 = "";
@@ -80,10 +79,53 @@ 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>재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다</summary>
private sealed class Bucket
{
public readonly List<float> Pos = new(), Nrm = new(), Uv = new();
public readonly List<byte> Col = new();
public readonly List<uint> Idx = new();
}
/// <summary>사이트에 쓸 재질 요약. Blend = 정점 색(R)으로 두 층(A · B) 섞기</summary>
private sealed record Mat(string Key, string Name, string? TexA, string? TexB, float[] TintA, float[] TintB, bool Masked, bool Translucent, bool Blend);
private readonly Dictionary<string, Mat?> _mats = new();
private readonly Dictionary<string, Bucket> _buckets = new();
private long _verts, _tris;
private Mat? MaterialOf(UMaterialInterface? m)
{
var key = m?.GetPathName() ?? "";
if (_mats.TryGetValue(key, out var r)) return r;
if (m == null) return _mats[key] = new Mat("", "(없음)", null, null, [0.6f, 0.6f, 0.6f], [1, 1, 1], false, false, false);
var p = MatParams.Resolve(m);
if (p.BlendMode is "BLEND_Additive" or "BLEND_Modulate" || p.Base.Contains("/VFX/Materials/")) return _mats[key] = null;
string? Tex(params string[] names) => names.Select(n => p.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
?? (names.Length > 0 && names[0] == "Diffuse" ? p.Textures.FirstOrDefault(kv => kv.Key.Contains("Diffuse", StringComparison.OrdinalIgnoreCase) && !kv.Key.Contains("Low") && !kv.Key.EndsWith(" B")).Value : null);
float[] Tint(params string[] names)
{
foreach (var n in names)
if (p.Vectors.TryGetValue(n, out var c)) return [c.R, c.G, c.B];
return [1, 1, 1];
}
var blend = p.Base.Contains("Blend", StringComparison.OrdinalIgnoreCase) && p.Textures.ContainsKey("Diffuse B");
var texA = blend ? Tex("Diffuse A", "Diffuse") : Tex("Diffuse", "Diffuse A", "Albedo", "Base Color", "Texture");
var tintA = blend ? Tint("Layer A Tint") : Tint("DiffuseColor", "Diffuse Tint", "Layer A Tint", "Tree Base Color");
// 텍스처가 없으면 색만 (없으면 회색)
if (texA == null && !p.Vectors.Keys.Any(k => k is "DiffuseColor" or "Diffuse Tint" or "Layer A Tint" or "Tree Base Color")) tintA = [0.6f, 0.6f, 0.6f];
return _mats[key] = new Mat(key, m.Name, texA, blend ? p.Textures["Diffuse B"] : null, tintA, Tint("Layer B Tint"),
p.BlendMode == "BLEND_Masked", p.BlendMode == "BLEND_Translucent", blend);
}
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)?>();
var meshCache = new Dictionary<string, Geo?>();
foreach (var level in map.Levels)
{
s._levels.Add(Path.GetFileNameWithoutExtension(level));
@@ -101,23 +143,37 @@ public sealed class MapScene
if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; }
if (!meshCache.TryGetValue(path, out var geo))
{
geo = Geometry(mesh);
try { geo = Geometry(mesh); } catch { geo = null; s.Failed++; }
meshCache[path] = geo;
if (geo != null) s.Meshes++;
}
if (geo == null) continue;
FTransform w;
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
var over = c.GetOrDefault<FPackageIndex[]>("OverrideMaterials", []);
var mats = new Mat?[geo.Secs.Length];
for (var k = 0; k < geo.Secs.Length; k++)
{
var mi = geo.Secs[k].Mat;
var idx = mi < over.Length && over[mi] is { IsNull: false } ov ? ov : mi < mesh.StaticMaterials.Length ? mesh.StaticMaterials[mi].MaterialInterface : null;
UMaterialInterface? mat = null;
try { mat = idx?.Load<UMaterialInterface>(); } catch { }
mats[k] = s.MaterialOf(mat);
}
// 칠한 정점 색 (두 층 섞기에 쓴다): 컴포넌트 값이 정점 수와 맞을 때만
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;
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);
foreach (var d in data) s.Add(geo, mats, col, d.TransformData * w);
else s.Add(geo, mats, col, w);
}
}
return s;
}
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다)</summary>
private static Geo? Geometry(UStaticMesh mesh)
{
var lods = mesh.RenderData?.LODs;
if (lods == null) return null;
@@ -125,85 +181,137 @@ public sealed class MapScene
{
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());
var uvItems = lod.VertexBuffer?.UV;
var n = new FVector[v.Length];
var uv = new float[v.Length * 2];
if (uvItems != null && uvItems.Length == v.Length)
for (var i = 0; i < v.Length; i++)
{
var it = uvItems[i];
if (it.Normal is { Length: >= 3 }) n[i] = (FVector)it.Normal[2];
if (it.UV is { Length: > 0 })
{
uv[i * 2] = it.UV[0].U;
uv[i * 2 + 1] = it.UV[0].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 null;
}
private void Add((FVector[] v, uint[] i) g, FTransform t)
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t)
{
Placements++;
var b = (uint)(_pos.Count / 3);
foreach (var p in g.v)
// UE 는 왼손 좌표계라 glTF(오른손, 반시계 앞면) 로 그대로 옮기면 앞뒤가 바뀐다 → 기본으로 뒤집는다.
// 크기가 음수(거울)면 한 번 더 뒤집힌다
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z >= 0;
var inv = new FVector(1 / NonZero(t.Scale3D.X), 1 / NonZero(t.Scale3D.Y), 1 / NonZero(t.Scale3D.Z));
for (var k = 0; k < g.Secs.Length; k++)
{
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]);
var m = mats[k];
if (m == null) continue;
var sec = g.Secs[k];
if (!_buckets.TryGetValue(m.Key, out var b)) _buckets[m.Key] = b = new Bucket();
// 이 구간이 쓰는 정점만 옮긴다
var map = new Dictionary<uint, uint>();
uint Vert(uint i)
{
if (map.TryGetValue(i, out var o)) return o;
o = (uint)(b.Pos.Count / 3);
var p = t.TransformPosition(g.V[i]);
b.Pos.Add(p.X); b.Pos.Add(p.Y); b.Pos.Add(p.Z);
var nn = t.Rotation.RotateVector(g.N[i] * inv);
var len = nn.Size();
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 (m.Blend)
{
var c = col != null ? col[i] : new FColor(255, 255, 255, 255);
b.Col.Add(c.R); b.Col.Add(c.G); b.Col.Add(c.B); b.Col.Add(c.A);
}
map[i] = o;
_verts++;
return o;
}
for (var j = 0; j < sec.Tris; j++)
{
var i0 = g.Ib[sec.First + j * 3];
var i1 = g.Ib[sec.First + j * 3 + 1];
var i2 = g.Ib[sec.First + j * 3 + 2];
b.Idx.Add(Vert(i0));
b.Idx.Add(Vert(flip ? i2 : i1));
b.Idx.Add(Vert(flip ? i1 : i2));
_tris++;
}
}
}
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
public void WriteGlb(string file)
private static float NonZero(float v) => Math.Abs(v) < 1e-6f ? 1e-6f : v;
public long Triangles => _tris;
public int Materials => _buckets.Count;
public int TextureCount, TextureFailed;
public long TextureBytes;
/// <summary>glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색).
/// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다)</summary>
public void WriteGlb(IFileProvider provider, string file, int maxTex)
{
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++)
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var prims = new System.Text.Json.Nodes.JsonArray();
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))
{
min[i % 3] = Math.Min(min[i % 3], pos[i]);
max[i % 3] = Math.Max(max[i % 3], pos[i]);
if (b.Idx.Count == 0) continue;
var m = byKey[key];
var a = tex.Get(m.TexA);
var bt = m.Blend ? tex.Get(m.TexB) : null;
var pbr = new System.Text.Json.Nodes.JsonObject
{
["baseColorFactor"] = new System.Text.Json.Nodes.JsonArray(Clamp(m.TintA[0]), Clamp(m.TintA[1]), Clamp(m.TintA[2]), m.Translucent ? 0.45f : 1f),
["metallicFactor"] = 0,
["roughnessFactor"] = 0.9,
};
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 (m.Translucent) mat["alphaMode"] = "BLEND";
else if (m.Masked && a is { alpha: true })
{
mat["alphaMode"] = "MASK";
mat["alphaCutoff"] = 0.333;
mat["doubleSided"] = true;
}
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 };
}
glb.Materials.Add(mat);
var attrs = new System.Text.Json.Nodes.JsonObject
{
["POSITION"] = glb.Floats(b.Pos.ToArray(), 3, bounds: true),
["NORMAL"] = glb.Floats(b.Nrm.ToArray(), 3),
["TEXCOORD_0"] = glb.Floats(b.Uv.ToArray(), 2),
};
if (m.Blend) attrs["COLOR_0"] = glb.Bytes(b.Col.ToArray(), 4);
prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 });
}
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);
glb.Meshes.Add(new System.Text.Json.Nodes.JsonObject { ["name"] = _code, ["primitives"] = prims });
glb.Nodes.Add(new System.Text.Json.Nodes.JsonObject { ["mesh"] = 0, ["name"] = _code });
glb.Write(file);
TextureCount = tex.Count;
TextureFailed = tex.Failed;
TextureBytes = tex.Bytes;
}
private static float Clamp(float v) => Math.Clamp(v, 0f, 1f);
public void WriteInfo(string file, string manifest, string? usmap)
{
var info = new
@@ -214,6 +322,11 @@ public sealed class MapScene
placements = Placements,
meshes = Meshes,
triangles = Triangles,
vertices = _verts,
materials = Materials,
textures = TextureCount,
texturesFailed = TextureFailed,
textureBytes = TextureBytes,
skipped = Skipped,
failed = Failed,
manifest,