1552 lines
59 KiB
C#
1552 lines
59 KiB
C#
using System;
|
|
using System.Buffers.Binary;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using Godot;
|
|
using RustToDust.Core;
|
|
|
|
namespace RustToDust.Client;
|
|
|
|
/// <summary>
|
|
/// Runtime GLB asset loader & template cache for all 15 Brokkr vehicles (resolved via
|
|
/// <see cref="VehiclePackage.ModelAsset"/> + <see cref="VehicleCatalogLoader.LocateVehiclesDirectory"/>)
|
|
/// and all 6 modular gear GLBs in <c>assets/gear/</c>.
|
|
/// Parses the glTF JSON chunk to map <c>rtd.id</c>, <c>rtd.kind</c>, <c>rtd.size</c>, and <c>rtd.joint</c>
|
|
/// deterministically to exact <see cref="NodePath"/>s inside the Godot scene tree generated by
|
|
/// <see cref="GltfDocument"/> + <see cref="GltfState"/>.
|
|
/// </summary>
|
|
public sealed class VehicleAssetCache : IDisposable
|
|
{
|
|
public sealed record GlbAnchorInfo(
|
|
string Id,
|
|
string Kind,
|
|
Vector3 Size,
|
|
NodePath RelativePath,
|
|
Transform3D ModelSpaceTransform);
|
|
|
|
public sealed record GlbJointInfo(
|
|
string JointId,
|
|
string NodeName,
|
|
Vector3 Axis,
|
|
float MinVal,
|
|
float MaxVal,
|
|
NodePath RelativePath);
|
|
|
|
public sealed record GlbPartNodeInfo(
|
|
string NodeName,
|
|
int CellX,
|
|
int CellY,
|
|
string Kind,
|
|
NodePath RelativePath,
|
|
bool HasProtectedDescendant);
|
|
|
|
public sealed class VehicleTemplate
|
|
{
|
|
public required VehiclePackage Package { get; init; }
|
|
public required string GlbPath { get; init; }
|
|
public required Node3D SceneTemplate { get; init; }
|
|
public required ArrayMesh BakedStaticMesh { get; init; }
|
|
public required ArrayMesh BakedLodFarMesh { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required float MaxY { get; init; }
|
|
public required IReadOnlyDictionary<string, GlbAnchorInfo> Anchors { get; init; }
|
|
public required IReadOnlyDictionary<string, GlbJointInfo> Joints { get; init; }
|
|
public required IReadOnlyDictionary<string, NodePath> NodesByOriginalName { get; init; }
|
|
public required IReadOnlyList<GlbPartNodeInfo> DetachableParts { get; init; }
|
|
public required IReadOnlyList<NodePath> MobilityNodePaths { get; init; }
|
|
}
|
|
|
|
public sealed class GearTemplate
|
|
{
|
|
public required string Id { get; init; }
|
|
public required string GlbPath { get; init; }
|
|
public required Node3D SceneTemplate { get; init; }
|
|
public required Vector3 Size { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required Vector3 LocalModelForward { get; init; }
|
|
}
|
|
|
|
public static readonly string[] ExpectedGearIds =
|
|
{
|
|
"mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator"
|
|
};
|
|
|
|
private readonly Dictionary<string, VehicleTemplate> _vehicles = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, GearTemplate> _gear = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly string _vehiclesDir;
|
|
private readonly string _gearDir;
|
|
private bool _disposed;
|
|
|
|
public VehicleAssetCache()
|
|
{
|
|
_vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
|
|
string assetsDir = Directory.GetParent(_vehiclesDir)?.FullName
|
|
?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{_vehiclesDir}'.");
|
|
_gearDir = Path.Combine(assetsDir, "gear");
|
|
if (!Directory.Exists(_gearDir))
|
|
{
|
|
throw new DirectoryNotFoundException($"Could not locate gear directory '{_gearDir}'.");
|
|
}
|
|
}
|
|
|
|
public IReadOnlyDictionary<string, VehicleTemplate> Vehicles => _vehicles;
|
|
public IReadOnlyDictionary<string, GearTemplate> Gear => _gear;
|
|
|
|
public void PreloadAll()
|
|
{
|
|
foreach (var pkg in Catalog.PackagesById.Values)
|
|
{
|
|
GetOrLoadVehicle(pkg.Id);
|
|
}
|
|
foreach (string gearId in ExpectedGearIds)
|
|
{
|
|
GetOrLoadGear(gearId);
|
|
}
|
|
}
|
|
|
|
public VehicleTemplate GetOrLoadVehicle(string vehicleId)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
string resolvedId = ResolveModelId(vehicleId);
|
|
if (_vehicles.TryGetValue(resolvedId, out var cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
var pkg = Catalog.TryGetPackage(resolvedId)
|
|
?? throw new KeyNotFoundException($"Unknown vehicle '{vehicleId}' in Catalog.PackagesById.");
|
|
|
|
string glbPath = Path.Combine(_vehiclesDir, pkg.Id, pkg.ModelAsset);
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing vehicle GLB for '{pkg.Id}': {glbPath}", glbPath);
|
|
}
|
|
|
|
var template = LoadVehicleTemplate(pkg, glbPath);
|
|
_vehicles[pkg.Id] = template;
|
|
return template;
|
|
}
|
|
|
|
public static string ResolveModelId(string chassisId) =>
|
|
string.Equals(chassisId, "exemplar_frame", StringComparison.OrdinalIgnoreCase)
|
|
? "raptor"
|
|
: chassisId;
|
|
|
|
public GearTemplate GetOrLoadGear(string gearId)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (_gear.TryGetValue(gearId, out var cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
string glbPath = Path.Combine(_gearDir, $"{gearId}.glb");
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing gear GLB '{gearId}': {glbPath}", glbPath);
|
|
}
|
|
|
|
var template = LoadGearTemplate(gearId, glbPath);
|
|
_gear[gearId] = template;
|
|
return template;
|
|
}
|
|
|
|
private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath)
|
|
{
|
|
byte[] jsonBytes = ReadGlbJsonChunk(glbPath);
|
|
using var gltfJson = JsonDocument.Parse(jsonBytes);
|
|
JsonElement jsonRoot = gltfJson.RootElement;
|
|
|
|
var doc = new GltfDocument();
|
|
var state = new GltfState();
|
|
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
|
|
if (err != Error.Ok)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
generated?.QueueFree();
|
|
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for '{glbPath}'.");
|
|
}
|
|
ClearOwnerRecursive(sceneRoot);
|
|
|
|
var gltfNodes = state.GetNodes();
|
|
var jsonNodes = jsonRoot.GetProperty("nodes");
|
|
int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength());
|
|
|
|
var pathByGltfIndex = new NodePath[nodeCount];
|
|
var nodeByGltfIndex = new Node3D?[nodeCount];
|
|
var origNameByIndex = new string[nodeCount];
|
|
var nodesByOriginalName = new Dictionary<string, NodePath>(StringComparer.Ordinal);
|
|
var anchors = new Dictionary<string, GlbAnchorInfo>(StringComparer.Ordinal);
|
|
var joints = new Dictionary<string, GlbJointInfo>(StringComparer.Ordinal);
|
|
var protectedIndices = new HashSet<int>();
|
|
var parentByIndex = new Dictionary<int, int>();
|
|
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
JsonElement jn = jsonNodes[i];
|
|
if (jn.TryGetProperty("children", out var childrenEl) && childrenEl.ValueKind == JsonValueKind.Array)
|
|
{
|
|
foreach (var ch in childrenEl.EnumerateArray())
|
|
{
|
|
parentByIndex[ch.GetInt32()] = i;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Resolve every glTF node deterministically to its exact Godot Node3D via GltfNode.GetSceneNodePath(state)
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
GltfNode gn = gltfNodes[i];
|
|
JsonElement jn = jsonNodes[i];
|
|
string origName = !string.IsNullOrEmpty(gn.OriginalName)
|
|
? gn.OriginalName
|
|
: (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}");
|
|
origNameByIndex[i] = origName;
|
|
|
|
Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName);
|
|
if (resolved is Node3D n3d)
|
|
{
|
|
NodePath relPath = BuildRelativeNodePath(sceneRoot, n3d);
|
|
pathByGltfIndex[i] = relPath;
|
|
nodeByGltfIndex[i] = n3d;
|
|
nodesByOriginalName.TryAdd(origName, relPath);
|
|
}
|
|
else
|
|
{
|
|
pathByGltfIndex[i] = new NodePath();
|
|
}
|
|
}
|
|
|
|
// Compute model-space transforms once from sceneRoot
|
|
var modelTransforms = new Dictionary<Node, Transform3D>();
|
|
CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms);
|
|
|
|
// Extract rtd.* extras from glTF JSON chunk & mark protected structural/joint/hardpoint nodes
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
JsonElement jn = jsonNodes[i];
|
|
Node3D? node = nodeByGltfIndex[i];
|
|
if (node is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
NodePath relPath = pathByGltfIndex[i];
|
|
if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (extras.TryGetProperty("rtd.id", out var rtdIdEl) && rtdIdEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string hpId = rtdIdEl.GetString()!;
|
|
string hpKind = extras.TryGetProperty("rtd.kind", out var kEl) && kEl.ValueKind == JsonValueKind.String
|
|
? kEl.GetString()!
|
|
: "weapon";
|
|
Vector3 hpSize = ReadVec3(extras, "rtd.size", new Vector3(0.5f, 0.5f, 0.1f));
|
|
Transform3D modelXform = modelTransforms.TryGetValue(node, out var xf) ? xf : Transform3D.Identity;
|
|
anchors[hpId] = new GlbAnchorInfo(hpId, hpKind, hpSize, relPath, modelXform);
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
|
|
if (extras.TryGetProperty("rtd.joint", out var rtdJointEl) && rtdJointEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string jId = rtdJointEl.GetString()!;
|
|
Vector3 axis = ReadVec3(extras, "rtd.axis", Vector3.Up);
|
|
if (axis.LengthSquared() < 1e-6f) axis = Vector3.Up;
|
|
axis = axis.Normalized();
|
|
float minVal = extras.TryGetProperty("rtd.min", out var mnEl) ? mnEl.GetSingle() : -180f;
|
|
float maxVal = extras.TryGetProperty("rtd.max", out var mxEl) ? mxEl.GetSingle() : 180f;
|
|
joints[jId] = new GlbJointInfo(jId, origNameByIndex[i], axis, minVal, maxVal, relPath);
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
|
|
// Also mark structural mechanism/skeleton/mobility nodes and their ancestors protected
|
|
var mobilityPaths = new List<NodePath>();
|
|
var mechNames = new HashSet<string>(StringComparer.Ordinal);
|
|
if (pkg.Mechanisms is not null)
|
|
{
|
|
foreach (var d in pkg.Mechanisms.Dofs) mechNames.Add(d.Name);
|
|
foreach (var r in pkg.Mechanisms.Rams)
|
|
{
|
|
mechNames.Add(r.Name);
|
|
mechNames.Add(r.BarrelBone);
|
|
mechNames.Add(r.RodBone);
|
|
}
|
|
foreach (var sc in pkg.Mechanisms.Scissors)
|
|
{
|
|
mechNames.Add(sc.Name);
|
|
mechNames.Add(sc.UpperBone);
|
|
mechNames.Add(sc.LowerBone);
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
string nm = origNameByIndex[i];
|
|
if (mechNames.Contains(nm) || IsStructuralNodeName(nm))
|
|
{
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
|
|
foreach (var pc in pkg.PartCells)
|
|
{
|
|
if (string.Equals(pc.Kind, "mobility", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (nodesByOriginalName.TryGetValue(pc.NodeName, out var mobPath))
|
|
{
|
|
mobilityPaths.Add(mobPath);
|
|
}
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
if (string.Equals(origNameByIndex[i], pc.NodeName, StringComparison.Ordinal))
|
|
{
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Compute protected-descendant flag for each glTF node index
|
|
var hasProtectedDesc = new bool[nodeCount];
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
if (protectedIndices.Contains(i))
|
|
{
|
|
int cur = i;
|
|
while (parentByIndex.TryGetValue(cur, out int p))
|
|
{
|
|
hasProtectedDesc[p] = true;
|
|
cur = p;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Index detachable exterior armor/shroud (and safe leaf cladding) parts mapped to cells
|
|
var indexByName = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
indexByName.TryAdd(origNameByIndex[i], i);
|
|
}
|
|
|
|
var detachableParts = new List<GlbPartNodeInfo>();
|
|
foreach (var pc in pkg.PartCells)
|
|
{
|
|
if (!indexByName.TryGetValue(pc.NodeName, out int idx))
|
|
{
|
|
continue;
|
|
}
|
|
Node3D? node = nodeByGltfIndex[idx];
|
|
if (node is not MeshInstance3D)
|
|
{
|
|
continue;
|
|
}
|
|
if (protectedIndices.Contains(idx) || hasProtectedDesc[idx])
|
|
{
|
|
continue;
|
|
}
|
|
if (!IsDetachablePartKind(pc.Kind, pc.NodeName, node.GetChildCount()))
|
|
{
|
|
continue;
|
|
}
|
|
detachableParts.Add(new GlbPartNodeInfo(
|
|
pc.NodeName,
|
|
pc.CellX,
|
|
pc.CellY,
|
|
pc.Kind,
|
|
pathByGltfIndex[idx],
|
|
hasProtectedDesc[idx]));
|
|
}
|
|
|
|
// Verify all VehiclePackage hardpoint AnchorIds & Joints resolved
|
|
foreach (var hp in pkg.Hardpoints)
|
|
{
|
|
if (!anchors.ContainsKey(hp.AnchorId))
|
|
{
|
|
sceneRoot.QueueFree();
|
|
throw new InvalidOperationException($"{pkg.Id}: failed to resolve hardpoint AnchorId '{hp.AnchorId}' in '{glbPath}'.");
|
|
}
|
|
}
|
|
foreach (var j in pkg.Joints)
|
|
{
|
|
if (!joints.ContainsKey(j.Id))
|
|
{
|
|
sceneRoot.QueueFree();
|
|
throw new InvalidOperationException($"{pkg.Id}: failed to resolve joint '{j.Id}' in '{glbPath}'.");
|
|
}
|
|
}
|
|
|
|
ComputeSceneMeshBoundsY(sceneRoot, out float minY, out float maxY);
|
|
|
|
// Build full set of protected structural/rig/joint/anchor/mobility Godot nodes
|
|
var protectedNodes = new HashSet<Node> { sceneRoot };
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
if ((protectedIndices.Contains(i) || hasProtectedDesc[i]) && nodeByGltfIndex[i] is { } pn)
|
|
{
|
|
MarkNodeAndAncestorsProtected(pn, sceneRoot, protectedNodes);
|
|
}
|
|
}
|
|
foreach (var a in anchors.Values)
|
|
{
|
|
if (sceneRoot.GetNodeOrNull(a.RelativePath) is { } an)
|
|
{
|
|
MarkNodeAndAncestorsProtected(an, sceneRoot, protectedNodes);
|
|
}
|
|
}
|
|
foreach (var j in joints.Values)
|
|
{
|
|
if (sceneRoot.GetNodeOrNull(j.RelativePath) is { } jn)
|
|
{
|
|
MarkNodeAndAncestorsProtected(jn, sceneRoot, protectedNodes);
|
|
}
|
|
}
|
|
foreach (var mp in mobilityPaths)
|
|
{
|
|
if (sceneRoot.GetNodeOrNull(mp) is { } mn)
|
|
{
|
|
MarkNodeAndAncestorsProtected(mn, sceneRoot, protectedNodes);
|
|
}
|
|
}
|
|
|
|
// Map original detachable MeshInstance3Ds so we can merge them per (rigidParent, CellX, CellY)
|
|
var detachableByNode = new Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)>();
|
|
foreach (var dp in detachableParts)
|
|
{
|
|
if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D mi && !protectedNodes.Contains(mi))
|
|
{
|
|
detachableByNode.TryAdd(mi, (dp.CellX, dp.CellY, dp.Kind));
|
|
}
|
|
}
|
|
|
|
// A & B: Merge detachable armor per (rigidParent, CellX, CellY) and static meshes per rigidParent
|
|
var mergedDetachableInfos = MergeVehicleSubMeshes(sceneRoot, protectedNodes, detachableByNode);
|
|
|
|
// Prune stale nodesByOriginalName entries that were collapsed into merged meshes
|
|
var survivingNames = new Dictionary<string, NodePath>(StringComparer.Ordinal);
|
|
foreach (var (origName, relPath) in nodesByOriginalName)
|
|
{
|
|
Node? resolved = relPath.ToString() == "." ? sceneRoot : sceneRoot.GetNodeOrNull(relPath);
|
|
if (resolved is not null)
|
|
{
|
|
survivingNames[origName] = relPath;
|
|
}
|
|
}
|
|
|
|
// C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
|
|
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
|
|
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true);
|
|
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f);
|
|
|
|
return new VehicleTemplate
|
|
{
|
|
Package = pkg,
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
BakedStaticMesh = bakedStaticMesh,
|
|
BakedLodFarMesh = bakedLodFarMesh,
|
|
MinY = minY,
|
|
MaxY = maxY,
|
|
Anchors = anchors,
|
|
Joints = joints,
|
|
NodesByOriginalName = survivingNames,
|
|
DetachableParts = mergedDetachableInfos,
|
|
MobilityNodePaths = mobilityPaths
|
|
};
|
|
}
|
|
|
|
private static readonly HashSet<string> PreservedGearPartNames = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
"barrel_inner", "receiver", "muzzle_brake_L", "gun_housing",
|
|
"sight_tube", "breech_band", "condenser_ring_2", "ivory_cowl"
|
|
};
|
|
|
|
private static GearTemplate LoadGearTemplate(string gearId, string glbPath)
|
|
{
|
|
var doc = new GltfDocument();
|
|
var state = new GltfState();
|
|
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
|
|
if (err != Error.Ok)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for gear '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
generated?.QueueFree();
|
|
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for gear '{glbPath}'.");
|
|
}
|
|
ClearOwnerRecursive(sceneRoot);
|
|
|
|
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
|
MergeGearSubMeshes(sceneRoot, gearId);
|
|
Vector3 localFwd = new Vector3(0f, 0f, 1f);
|
|
|
|
return new GearTemplate
|
|
{
|
|
Id = gearId,
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
Size = bMax - bMin,
|
|
MinY = bMin.Y,
|
|
LocalModelForward = localFwd
|
|
};
|
|
}
|
|
|
|
private static readonly HashSet<string> ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
"chassis", "hull", "pelvis", "core", "trunk", "waist", "torso.pose", "aim.turret", "hull.pose",
|
|
"legl.hip", "legr.hip", "legl.shin", "legr.shin", "legl.foot", "legr.foot",
|
|
"legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle",
|
|
"legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon",
|
|
"legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork",
|
|
"legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow",
|
|
"legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1",
|
|
"legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1",
|
|
"legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1",
|
|
"legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2",
|
|
"footfl", "footfr", "footbl", "footbr",
|
|
"thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr",
|
|
"shin.fl", "shin.fr", "shin.rl", "shin.rr",
|
|
"ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr"
|
|
};
|
|
|
|
private static bool IsStructuralNodeName(string name) =>
|
|
ExactStructuralNodeNames.Contains(name);
|
|
|
|
private static void ClearOwnerRecursive(Node cur)
|
|
{
|
|
cur.Owner = null;
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
ClearOwnerRecursive(cur.GetChild(i));
|
|
}
|
|
}
|
|
|
|
private static bool IsDetachablePartKind(string kind, string nodeName, int childCount)
|
|
{
|
|
if (string.Equals(kind, "armor", StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(kind, "shroud", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
if (!string.Equals(kind, "hull", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
string low = nodeName.ToLowerInvariant();
|
|
// Safe exterior cladding panels (e.g., buggy hood/side panels, skirt/tasset/cod plates, mech dress panels)
|
|
if (low.Contains("hood") || low.Contains("side.") || low.Contains("roof") ||
|
|
low.Contains("tasset") || low.Contains("cod") || low.Contains("cuisse") ||
|
|
low.Contains(".panels") || low.Contains(".dress.") || low.Contains("brow") ||
|
|
low.Contains("pauldron") || low.Contains("wing") && !low.Contains("stub_wing"))
|
|
{
|
|
return true;
|
|
}
|
|
return childCount == 0 && (low.Contains("canopy") || low.Contains("hatch") || low.Contains("visor"));
|
|
}
|
|
|
|
private static void MarkNodeAndAncestorsProtected(Node node, Node root, HashSet<Node> protectedNodes)
|
|
{
|
|
Node? cur = node;
|
|
while (cur is not null)
|
|
{
|
|
protectedNodes.Add(cur);
|
|
if (ReferenceEquals(cur, root))
|
|
{
|
|
break;
|
|
}
|
|
cur = cur.GetParent();
|
|
}
|
|
}
|
|
|
|
private static Node3D FindNearestProtectedParent(Node node, Node3D sceneRoot, HashSet<Node> protectedNodes)
|
|
{
|
|
Node? cur = node.GetParent();
|
|
while (cur is not null)
|
|
{
|
|
if (cur is Node3D n3d && protectedNodes.Contains(cur))
|
|
{
|
|
return n3d;
|
|
}
|
|
if (ReferenceEquals(cur, sceneRoot))
|
|
{
|
|
break;
|
|
}
|
|
cur = cur.GetParent();
|
|
}
|
|
return sceneRoot;
|
|
}
|
|
|
|
private static Transform3D ComputeRelativeTransform(Node3D ancestor, Node descendant)
|
|
{
|
|
Transform3D xf = Transform3D.Identity;
|
|
Node? cur = descendant;
|
|
while (cur is not null && !ReferenceEquals(cur, ancestor))
|
|
{
|
|
if (cur is Node3D n3d)
|
|
{
|
|
xf = n3d.Transform * xf;
|
|
}
|
|
cur = cur.GetParent();
|
|
}
|
|
return xf;
|
|
}
|
|
|
|
private static bool CanMergeMeshInstance(MeshInstance3D mi)
|
|
{
|
|
if (mi.Mesh is null || mi.Mesh.GetSurfaceCount() == 0)
|
|
{
|
|
return false;
|
|
}
|
|
if (mi.Mesh is ArrayMesh am)
|
|
{
|
|
int surfCount = am.GetSurfaceCount();
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
if (am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private static void CollectAllMeshInstances(Node cur, List<MeshInstance3D> outList)
|
|
{
|
|
if (cur is MeshInstance3D mi)
|
|
{
|
|
outList.Add(mi);
|
|
}
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
CollectAllMeshInstances(cur.GetChild(i), outList);
|
|
}
|
|
}
|
|
|
|
private static void ReparentChildrenAndRemove(MeshInstance3D mi)
|
|
{
|
|
Node? parent = mi.GetParent();
|
|
if (parent is not null)
|
|
{
|
|
for (int i = mi.GetChildCount() - 1; i >= 0; i--)
|
|
{
|
|
Node ch = mi.GetChild(i);
|
|
mi.RemoveChild(ch);
|
|
if (ch is Node3D ch3d)
|
|
{
|
|
ch3d.Transform = mi.Transform * ch3d.Transform;
|
|
}
|
|
parent.AddChild(ch);
|
|
}
|
|
parent.RemoveChild(mi);
|
|
}
|
|
mi.QueueFree();
|
|
}
|
|
|
|
private static List<GlbPartNodeInfo> MergeVehicleSubMeshes(
|
|
Node3D sceneRoot,
|
|
HashSet<Node> protectedNodes,
|
|
Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)> detachableByNode)
|
|
{
|
|
var allMeshes = new List<MeshInstance3D>();
|
|
CollectAllMeshInstances(sceneRoot, allMeshes);
|
|
|
|
var detachableGroups = new Dictionary<(Node3D RigidParent, int CellX, int CellY), (string Kind, List<(MeshInstance3D Mi, Transform3D RelXf)> Items)>();
|
|
var staticGroups = new Dictionary<Node3D, List<(MeshInstance3D Mi, Transform3D RelXf)>>();
|
|
var detachResultNodes = new List<(MeshInstance3D Node, int CellX, int CellY, string Kind)>();
|
|
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (!CanMergeMeshInstance(mi))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (detachableByNode.TryGetValue(mi, out var detInfo))
|
|
{
|
|
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
|
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
|
var key = (rigidParent, detInfo.CellX, detInfo.CellY);
|
|
if (!detachableGroups.TryGetValue(key, out var group))
|
|
{
|
|
group = (detInfo.Kind, new List<(MeshInstance3D, Transform3D)>());
|
|
detachableGroups[key] = group;
|
|
}
|
|
group.Items.Add((mi, relXf));
|
|
}
|
|
else if (!protectedNodes.Contains(mi))
|
|
{
|
|
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
|
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
|
if (!staticGroups.TryGetValue(rigidParent, out var list))
|
|
{
|
|
list = new List<(MeshInstance3D, Transform3D)>();
|
|
staticGroups[rigidParent] = list;
|
|
}
|
|
list.Add((mi, relXf));
|
|
}
|
|
}
|
|
|
|
// B. Merge detachable armor parts per (rigidParent, CellX, CellY)
|
|
int detSeq = 0;
|
|
foreach (var ((rigidParent, cellX, cellY), (kind, items)) in detachableGroups)
|
|
{
|
|
if (items.Count == 1 && ReferenceEquals(items[0].Mi.GetParent(), rigidParent))
|
|
{
|
|
// Already a single child directly under rigidParent — keep as-is
|
|
detachResultNodes.Add((items[0].Mi, cellX, cellY, kind));
|
|
continue;
|
|
}
|
|
|
|
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
|
if (merged is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var chunkNode = new MeshInstance3D
|
|
{
|
|
Name = $"ArmorCell_{cellX}_{cellY}_{detSeq++}",
|
|
Mesh = merged
|
|
};
|
|
rigidParent.AddChild(chunkNode);
|
|
detachResultNodes.Add((chunkNode, cellX, cellY, kind));
|
|
|
|
for (int i = 0; i < items.Count; i++)
|
|
{
|
|
ReparentChildrenAndRemove(items[i].Mi);
|
|
}
|
|
}
|
|
|
|
// A. Merge static non-detachable sub-meshes per rigid articulated parent
|
|
foreach (var (rigidParent, items) in staticGroups)
|
|
{
|
|
if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi))
|
|
{
|
|
var combined = new List<(MeshInstance3D, Transform3D)>(items.Count + 1)
|
|
{
|
|
(parentMi, Transform3D.Identity)
|
|
};
|
|
combined.AddRange(items);
|
|
ArrayMesh? merged = BuildMergedArrayMesh(combined);
|
|
if (merged is not null)
|
|
{
|
|
parentMi.MaterialOverride = null;
|
|
parentMi.Mesh = merged;
|
|
for (int i = 0; i < items.Count; i++)
|
|
{
|
|
ReparentChildrenAndRemove(items[i].Mi);
|
|
}
|
|
}
|
|
}
|
|
else if (items.Count > 1 || (items.Count == 1 && !ReferenceEquals(items[0].Mi.GetParent(), rigidParent)))
|
|
{
|
|
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
|
if (merged is not null)
|
|
{
|
|
var staticNode = new MeshInstance3D
|
|
{
|
|
Name = $"{rigidParent.Name}_StaticMerged",
|
|
Mesh = merged
|
|
};
|
|
rigidParent.AddChild(staticNode);
|
|
for (int i = 0; i < items.Count; i++)
|
|
{
|
|
ReparentChildrenAndRemove(items[i].Mi);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Prune empty non-protected grouping nodes left behind
|
|
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes);
|
|
|
|
var result = new List<GlbPartNodeInfo>(detachResultNodes.Count);
|
|
for (int i = 0; i < detachResultNodes.Count; i++)
|
|
{
|
|
var (node, cellX, cellY, kind) = detachResultNodes[i];
|
|
if (!GodotObject.IsInstanceValid(node) || !sceneRoot.IsAncestorOf(node))
|
|
{
|
|
continue;
|
|
}
|
|
result.Add(new GlbPartNodeInfo(
|
|
node.Name,
|
|
cellX,
|
|
cellY,
|
|
kind,
|
|
BuildRelativeNodePath(sceneRoot, node),
|
|
HasProtectedDescendant: false));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private static void MergeGearSubMeshes(Node3D sceneRoot, string gearId)
|
|
{
|
|
var keptNodes = new HashSet<Node> { sceneRoot };
|
|
var allMeshes = new List<MeshInstance3D>();
|
|
CollectAllMeshInstances(sceneRoot, allMeshes);
|
|
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (PreservedGearPartNames.Contains(mi.Name))
|
|
{
|
|
MarkNodeAndAncestorsProtected(mi, sceneRoot, keptNodes);
|
|
}
|
|
}
|
|
|
|
var mergeList = new List<(MeshInstance3D Mi, Transform3D RelXf)>();
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (!keptNodes.Contains(mi) && CanMergeMeshInstance(mi))
|
|
{
|
|
mergeList.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
|
}
|
|
}
|
|
|
|
if (mergeList.Count <= 1)
|
|
{
|
|
return;
|
|
}
|
|
|
|
ArrayMesh? merged = BuildMergedArrayMesh(mergeList);
|
|
if (merged is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var mergedNode = new MeshInstance3D
|
|
{
|
|
Name = $"{gearId}_StaticMerged",
|
|
Mesh = merged
|
|
};
|
|
sceneRoot.AddChild(mergedNode);
|
|
for (int i = 0; i < mergeList.Count; i++)
|
|
{
|
|
ReparentChildrenAndRemove(mergeList[i].Mi);
|
|
}
|
|
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes);
|
|
}
|
|
|
|
private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false)
|
|
{
|
|
var allMeshes = new List<MeshInstance3D>();
|
|
CollectAllMeshInstances(sceneRoot, allMeshes);
|
|
|
|
var items = new List<(MeshInstance3D Mi, Transform3D RelXf)>(allMeshes.Count);
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (CanMergeMeshInstance(mi))
|
|
{
|
|
items.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
|
}
|
|
}
|
|
|
|
return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh();
|
|
}
|
|
|
|
private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
|
|
{
|
|
for (int i = cur.GetChildCount() - 1; i >= 0; i--)
|
|
{
|
|
Node ch = cur.GetChild(i);
|
|
PruneEmptyNonProtectedNodes(ch, sceneRoot, protectedNodes);
|
|
if (!ReferenceEquals(ch, sceneRoot) &&
|
|
!protectedNodes.Contains(ch) &&
|
|
ch is not MeshInstance3D &&
|
|
ch.GetChildCount() == 0)
|
|
{
|
|
cur.RemoveChild(ch);
|
|
ch.QueueFree();
|
|
}
|
|
}
|
|
}
|
|
|
|
private readonly record struct StandardMatKey(
|
|
int PaintTag,
|
|
int R,
|
|
int G,
|
|
int B,
|
|
int A,
|
|
int Metallic,
|
|
int Roughness,
|
|
bool EmissionEnabled,
|
|
int EmR,
|
|
int EmG,
|
|
int EmB,
|
|
int EmEnergy,
|
|
int Transparency,
|
|
int CullMode);
|
|
|
|
private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key)
|
|
{
|
|
if (mat is StandardMaterial3D sm &&
|
|
sm.AlbedoTexture is null &&
|
|
sm.NormalTexture is null &&
|
|
sm.RoughnessTexture is null &&
|
|
sm.MetallicTexture is null &&
|
|
sm.EmissionTexture is null)
|
|
{
|
|
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
|
int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1
|
|
: (mName.Contains("signal") || mName.Contains("orange")) ? 2
|
|
: 0;
|
|
float colorScale = coarse ? 6f : 255f;
|
|
float pbrScale = coarse ? 2f : 100f;
|
|
key = new StandardMatKey(
|
|
paintTag,
|
|
(int)MathF.Round(sm.AlbedoColor.R * colorScale),
|
|
(int)MathF.Round(sm.AlbedoColor.G * colorScale),
|
|
(int)MathF.Round(sm.AlbedoColor.B * colorScale),
|
|
(int)MathF.Round(sm.AlbedoColor.A * 10f),
|
|
(int)MathF.Round(sm.Metallic * pbrScale),
|
|
(int)MathF.Round(sm.Roughness * pbrScale),
|
|
sm.EmissionEnabled,
|
|
(int)MathF.Round(sm.Emission.R * colorScale),
|
|
(int)MathF.Round(sm.Emission.G * colorScale),
|
|
(int)MathF.Round(sm.Emission.B * colorScale),
|
|
(int)MathF.Round(sm.EmissionEnergyMultiplier * pbrScale),
|
|
(int)sm.Transparency,
|
|
(int)sm.CullMode);
|
|
return true;
|
|
}
|
|
key = default;
|
|
return false;
|
|
}
|
|
|
|
private sealed class MaterialSurfaceBucket
|
|
{
|
|
public required Material? Material;
|
|
public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new();
|
|
}
|
|
|
|
private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false)
|
|
{
|
|
if (items.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var buckets = new List<MaterialSurfaceBucket>();
|
|
var bucketByMatId = new Dictionary<ulong, MaterialSurfaceBucket>();
|
|
var bucketByMatVal = new Dictionary<StandardMatKey, MaterialSurfaceBucket>();
|
|
MaterialSurfaceBucket? nullMatBucket = null;
|
|
|
|
for (int i = 0; i < items.Count; i++)
|
|
{
|
|
var (mi, relXf) = items[i];
|
|
if (mi.Mesh is not { } mesh)
|
|
{
|
|
continue;
|
|
}
|
|
int surfCount = mesh.GetSurfaceCount();
|
|
var am = mesh as ArrayMesh;
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
|
|
{
|
|
continue;
|
|
}
|
|
Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s);
|
|
MaterialSurfaceBucket bucket;
|
|
if (mat is null)
|
|
{
|
|
nullMatBucket ??= new MaterialSurfaceBucket { Material = null };
|
|
if (!buckets.Contains(nullMatBucket))
|
|
{
|
|
buckets.Add(nullMatBucket);
|
|
}
|
|
bucket = nullMatBucket;
|
|
}
|
|
else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey))
|
|
{
|
|
if (!bucketByMatVal.TryGetValue(matKey, out bucket!))
|
|
{
|
|
bucket = new MaterialSurfaceBucket { Material = mat };
|
|
bucketByMatVal[matKey] = bucket;
|
|
buckets.Add(bucket);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
ulong id = mat.GetInstanceId();
|
|
if (!bucketByMatId.TryGetValue(id, out bucket!))
|
|
{
|
|
bucket = new MaterialSurfaceBucket { Material = mat };
|
|
bucketByMatId[id] = bucket;
|
|
buckets.Add(bucket);
|
|
}
|
|
}
|
|
bucket.Sources.Add((mesh, s, relXf));
|
|
}
|
|
}
|
|
|
|
if (buckets.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var outMesh = new ArrayMesh();
|
|
for (int b = 0; b < buckets.Count; b++)
|
|
{
|
|
var bucket = buckets[b];
|
|
bool anyNormal = false;
|
|
bool anyTangent = false;
|
|
bool anyUv = false;
|
|
bool anyUv2 = false;
|
|
bool anyColor = false;
|
|
int totalVerts = 0;
|
|
int totalIndices = 0;
|
|
|
|
var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count);
|
|
for (int s = 0; s < bucket.Sources.Count; s++)
|
|
{
|
|
var (mesh, surfIdx, relXf) = bucket.Sources[s];
|
|
var arr = mesh.SurfaceGetArrays(surfIdx);
|
|
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
|
|
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
|
|
{
|
|
continue;
|
|
}
|
|
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
if (verts.Length == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) anyNormal = true;
|
|
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) anyTangent = true;
|
|
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) anyUv = true;
|
|
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) anyUv2 = true;
|
|
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) anyColor = true;
|
|
|
|
int idxCount = verts.Length;
|
|
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
|
|
{
|
|
idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length;
|
|
}
|
|
|
|
totalVerts += verts.Length;
|
|
totalIndices += idxCount;
|
|
cachedArrays.Add((arr, relXf, verts.Length, idxCount));
|
|
}
|
|
|
|
if (totalVerts == 0 || totalIndices == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var outVerts = new Vector3[totalVerts];
|
|
Vector3[]? outNormals = anyNormal ? new Vector3[totalVerts] : null;
|
|
float[]? outTangents = anyTangent ? new float[totalVerts * 4] : null;
|
|
Vector2[]? outUvs = anyUv ? new Vector2[totalVerts] : null;
|
|
Vector2[]? outUv2s = anyUv2 ? new Vector2[totalVerts] : null;
|
|
Color[]? outColors = anyColor ? new Color[totalVerts] : null;
|
|
var outIndices = new int[totalIndices];
|
|
|
|
int vOffset = 0;
|
|
int iOffset = 0;
|
|
for (int c = 0; c < cachedArrays.Count; c++)
|
|
{
|
|
var (arr, relXf, vCount, idxCount) = cachedArrays[c];
|
|
Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
bool flipWinding = relXf.Basis.Determinant() < 0f;
|
|
Basis normBasis = relXf.Basis.Inverse().Transposed();
|
|
|
|
for (int v = 0; v < vCount; v++)
|
|
{
|
|
outVerts[vOffset + v] = relXf * srcVerts[v];
|
|
}
|
|
|
|
if (outNormals is not null)
|
|
{
|
|
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array)
|
|
{
|
|
Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array();
|
|
for (int v = 0; v < vCount; v++)
|
|
{
|
|
Vector3 n = normBasis * srcN[v];
|
|
outNormals[vOffset + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
for (int v = 0; v < vCount; v++) outNormals[vOffset + v] = Vector3.Up;
|
|
}
|
|
}
|
|
|
|
if (outTangents is not null)
|
|
{
|
|
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array)
|
|
{
|
|
float[] srcT = arr[(int)Mesh.ArrayType.Tangent].AsFloat32Array();
|
|
for (int v = 0; v < vCount; v++)
|
|
{
|
|
int sBase = v * 4;
|
|
int dBase = (vOffset + v) * 4;
|
|
Vector3 t = relXf.Basis * new Vector3(srcT[sBase], srcT[sBase + 1], srcT[sBase + 2]);
|
|
t = t.LengthSquared() > 1e-10f ? t.Normalized() : Vector3.Right;
|
|
outTangents[dBase] = t.X;
|
|
outTangents[dBase + 1] = t.Y;
|
|
outTangents[dBase + 2] = t.Z;
|
|
outTangents[dBase + 3] = flipWinding ? -srcT[sBase + 3] : srcT[sBase + 3];
|
|
}
|
|
}
|
|
else
|
|
{
|
|
for (int v = 0; v < vCount; v++)
|
|
{
|
|
int dBase = (vOffset + v) * 4;
|
|
outTangents[dBase] = 1f;
|
|
outTangents[dBase + 3] = 1f;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (outUvs is not null)
|
|
{
|
|
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array)
|
|
{
|
|
Array.Copy(arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(), 0, outUvs, vOffset, vCount);
|
|
}
|
|
}
|
|
|
|
if (outUv2s is not null)
|
|
{
|
|
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array)
|
|
{
|
|
Array.Copy(arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(), 0, outUv2s, vOffset, vCount);
|
|
}
|
|
}
|
|
|
|
if (outColors is not null)
|
|
{
|
|
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
|
|
{
|
|
Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOffset, vCount);
|
|
}
|
|
else
|
|
{
|
|
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White;
|
|
}
|
|
}
|
|
|
|
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
|
|
int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
|
|
if (!flipWinding)
|
|
{
|
|
if (srcIdx is not null)
|
|
{
|
|
for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = srcIdx[k] + vOffset;
|
|
}
|
|
else
|
|
{
|
|
for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = k + vOffset;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
for (int k = 0; k + 2 < idxCount; k += 3)
|
|
{
|
|
int a = srcIdx is not null ? srcIdx[k] : k;
|
|
int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1;
|
|
int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2;
|
|
outIndices[iOffset + k] = a + vOffset;
|
|
outIndices[iOffset + k + 1] = cIdx + vOffset;
|
|
outIndices[iOffset + k + 2] = bIdx + vOffset;
|
|
}
|
|
}
|
|
|
|
vOffset += vCount;
|
|
iOffset += idxCount;
|
|
}
|
|
|
|
var surfArrays = new Godot.Collections.Array();
|
|
surfArrays.Resize((int)Mesh.ArrayType.Max);
|
|
surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts;
|
|
if (outNormals is not null) surfArrays[(int)Mesh.ArrayType.Normal] = outNormals;
|
|
if (outTangents is not null) surfArrays[(int)Mesh.ArrayType.Tangent] = outTangents;
|
|
if (outUvs is not null) surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs;
|
|
if (outUv2s is not null) surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s;
|
|
if (outColors is not null) surfArrays[(int)Mesh.ArrayType.Color] = outColors;
|
|
surfArrays[(int)Mesh.ArrayType.Index] = outIndices;
|
|
|
|
int newSurf = outMesh.GetSurfaceCount();
|
|
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays);
|
|
if (bucket.Material is not null)
|
|
{
|
|
outMesh.SurfaceSetMaterial(newSurf, bucket.Material);
|
|
}
|
|
}
|
|
|
|
return outMesh.GetSurfaceCount() > 0 ? outMesh : null;
|
|
}
|
|
|
|
private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize)
|
|
{
|
|
var outMesh = new ArrayMesh();
|
|
float invCell = 1f / MathF.Max(0.02f, cellSize);
|
|
int surfCount = src.GetSurfaceCount();
|
|
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
var arr = src.SurfaceGetArrays(s);
|
|
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
|
|
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
if (verts.Length == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array;
|
|
Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null;
|
|
|
|
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
|
|
int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
|
|
int triVertCount = indices is not null ? indices.Length : verts.Length;
|
|
|
|
var cellToNewIdx = new Dictionary<(int, int, int), int>(verts.Length / 2 + 16);
|
|
var vertToCellIdx = new int[verts.Length];
|
|
var accumPos = new List<Vector3>(verts.Length / 2 + 16);
|
|
var accumNorm = norms is not null ? new List<Vector3>(verts.Length / 2 + 16) : null;
|
|
var counts = new List<int>(verts.Length / 2 + 16);
|
|
|
|
for (int v = 0; v < verts.Length; v++)
|
|
{
|
|
Vector3 p = verts[v];
|
|
var key = (
|
|
(int)MathF.Floor(p.X * invCell),
|
|
(int)MathF.Floor(p.Y * invCell),
|
|
(int)MathF.Floor(p.Z * invCell));
|
|
|
|
if (!cellToNewIdx.TryGetValue(key, out int ci))
|
|
{
|
|
ci = accumPos.Count;
|
|
cellToNewIdx[key] = ci;
|
|
accumPos.Add(p);
|
|
if (accumNorm is not null) accumNorm.Add(norms![v]);
|
|
counts.Add(1);
|
|
}
|
|
else
|
|
{
|
|
accumPos[ci] += p;
|
|
if (accumNorm is not null) accumNorm[ci] += norms![v];
|
|
counts[ci]++;
|
|
}
|
|
vertToCellIdx[v] = ci;
|
|
}
|
|
|
|
var outIndices = new List<int>(triVertCount / 2 + 12);
|
|
for (int k = 0; k + 2 < triVertCount; k += 3)
|
|
{
|
|
int i0 = indices is not null ? indices[k] : k;
|
|
int i1 = indices is not null ? indices[k + 1] : k + 1;
|
|
int i2 = indices is not null ? indices[k + 2] : k + 2;
|
|
int c0 = vertToCellIdx[i0];
|
|
int c1 = vertToCellIdx[i1];
|
|
int c2 = vertToCellIdx[i2];
|
|
if (c0 != c1 && c1 != c2 && c0 != c2)
|
|
{
|
|
outIndices.Add(c0);
|
|
outIndices.Add(c1);
|
|
outIndices.Add(c2);
|
|
}
|
|
}
|
|
|
|
if (outIndices.Count == 0)
|
|
{
|
|
// Keep original tiny surface intact if grid collapsed all triangles
|
|
int fallbackSurf = outMesh.GetSurfaceCount();
|
|
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arr);
|
|
Material? fMat = src.SurfaceGetMaterial(s);
|
|
if (fMat is not null) outMesh.SurfaceSetMaterial(fallbackSurf, fMat);
|
|
continue;
|
|
}
|
|
|
|
var outVerts = new Vector3[accumPos.Count];
|
|
Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null;
|
|
for (int i = 0; i < accumPos.Count; i++)
|
|
{
|
|
outVerts[i] = accumPos[i] / counts[i];
|
|
if (outNorms is not null)
|
|
{
|
|
Vector3 n = accumNorm![i];
|
|
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up;
|
|
}
|
|
}
|
|
|
|
var newArr = new Godot.Collections.Array();
|
|
newArr.Resize((int)Mesh.ArrayType.Max);
|
|
newArr[(int)Mesh.ArrayType.Vertex] = outVerts;
|
|
if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms;
|
|
newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray();
|
|
|
|
int newSurf = outMesh.GetSurfaceCount();
|
|
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newArr);
|
|
Material? mat = src.SurfaceGetMaterial(s);
|
|
if (mat is not null)
|
|
{
|
|
outMesh.SurfaceSetMaterial(newSurf, mat);
|
|
}
|
|
}
|
|
|
|
return outMesh.GetSurfaceCount() > 0 ? outMesh : src;
|
|
}
|
|
|
|
private static void MarkAncestorsProtected(int idx, Dictionary<int, int> parentByIndex, HashSet<int> protectedSet)
|
|
{
|
|
int cur = idx;
|
|
while (true)
|
|
{
|
|
if (!protectedSet.Add(cur))
|
|
{
|
|
// Still continue up in case a parent wasn't marked yet, or break if parent already marked
|
|
}
|
|
if (!parentByIndex.TryGetValue(cur, out int parent))
|
|
{
|
|
break;
|
|
}
|
|
cur = parent;
|
|
}
|
|
}
|
|
|
|
private static Node? ResolveSceneNode(Node3D sceneRoot, NodePath scenePath, string originalName)
|
|
{
|
|
if (!scenePath.IsEmpty)
|
|
{
|
|
Node? direct = sceneRoot.GetNodeOrNull(scenePath);
|
|
if (direct is not null)
|
|
{
|
|
return direct;
|
|
}
|
|
|
|
string raw = scenePath.ToString();
|
|
if (raw == "." || raw == sceneRoot.Name)
|
|
{
|
|
return sceneRoot;
|
|
}
|
|
|
|
int slash = raw.IndexOf('/');
|
|
if (slash >= 0)
|
|
{
|
|
string sub = raw[(slash + 1)..];
|
|
Node? trimmed = sceneRoot.GetNodeOrNull(sub);
|
|
if (trimmed is not null)
|
|
{
|
|
return trimmed;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fallback: sanitized name match
|
|
string sanitized = originalName.Replace('.', '_').Replace(':', '_').Replace('@', '_').Replace('/', '_');
|
|
return FindNodeRecursive(sceneRoot, originalName, sanitized);
|
|
}
|
|
|
|
private static Node? FindNodeRecursive(Node cur, string exactName, string sanitized)
|
|
{
|
|
string nm = cur.Name;
|
|
if (string.Equals(nm, exactName, StringComparison.Ordinal) ||
|
|
string.Equals(nm, sanitized, StringComparison.Ordinal))
|
|
{
|
|
return cur;
|
|
}
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
Node? found = FindNodeRecursive(cur.GetChild(i), exactName, sanitized);
|
|
if (found is not null)
|
|
{
|
|
return found;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private static NodePath BuildRelativeNodePath(Node root, Node target)
|
|
{
|
|
if (ReferenceEquals(root, target))
|
|
{
|
|
return new NodePath(".");
|
|
}
|
|
|
|
var segments = new List<string>();
|
|
Node? cur = target;
|
|
while (cur is not null && !ReferenceEquals(cur, root))
|
|
{
|
|
segments.Add(cur.Name);
|
|
cur = cur.GetParent();
|
|
}
|
|
if (!ReferenceEquals(cur, root))
|
|
{
|
|
return new NodePath(".");
|
|
}
|
|
segments.Reverse();
|
|
return new NodePath(string.Join("/", segments));
|
|
}
|
|
|
|
private static void CollectModelTransforms(Node cur, Transform3D parentTransform, Dictionary<Node, Transform3D> map)
|
|
{
|
|
Transform3D world = cur is Node3D n3d ? parentTransform * n3d.Transform : parentTransform;
|
|
map[cur] = world;
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
CollectModelTransforms(cur.GetChild(i), world, map);
|
|
}
|
|
}
|
|
|
|
private static void ComputeSceneMeshBoundsY(Node3D root, out float minY, out float maxY)
|
|
{
|
|
ComputeSceneMeshBounds(root, out Vector3 mn, out Vector3 mx);
|
|
minY = mn.Y;
|
|
maxY = mx.Y;
|
|
}
|
|
|
|
private static void ComputeSceneMeshBounds(Node3D root, out Vector3 boundsMin, out Vector3 boundsMax)
|
|
{
|
|
Vector3 mn = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
|
|
Vector3 mx = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
|
|
AccumulateBounds(root, Transform3D.Identity, ref mn, ref mx);
|
|
|
|
if (!float.IsFinite(mn.X))
|
|
{
|
|
mn = Vector3.Zero;
|
|
mx = Vector3.One;
|
|
}
|
|
boundsMin = mn;
|
|
boundsMax = mx;
|
|
}
|
|
|
|
private static void AccumulateBounds(Node cur, Transform3D parentXf, ref Vector3 mn, ref Vector3 mx)
|
|
{
|
|
Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf;
|
|
if (cur is MeshInstance3D mi && mi.Mesh is not null)
|
|
{
|
|
bool usedVertices = false;
|
|
int surfCount = mi.Mesh.GetSurfaceCount();
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
var arrays = mi.Mesh.SurfaceGetArrays(s);
|
|
if (arrays.Count > (int)Mesh.ArrayType.Vertex)
|
|
{
|
|
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
if (verts.Length > 0)
|
|
{
|
|
usedVertices = true;
|
|
for (int v = 0; v < verts.Length; v++)
|
|
{
|
|
Vector3 w = xf * verts[v];
|
|
mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z));
|
|
mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!usedVertices)
|
|
{
|
|
Aabb aabb = mi.Mesh.GetAabb();
|
|
Vector3 p = aabb.Position;
|
|
Vector3 sz = aabb.Size;
|
|
for (int ix = 0; ix < 2; ix++)
|
|
{
|
|
for (int iy = 0; iy < 2; iy++)
|
|
{
|
|
for (int iz = 0; iz < 2; iz++)
|
|
{
|
|
Vector3 corner = new(p.X + ix * sz.X, p.Y + iy * sz.Y, p.Z + iz * sz.Z);
|
|
Vector3 w = xf * corner;
|
|
mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z));
|
|
mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
AccumulateBounds(cur.GetChild(i), xf, ref mn, ref mx);
|
|
}
|
|
}
|
|
|
|
private static byte[] ReadGlbJsonChunk(string glbPath)
|
|
{
|
|
byte[] data = File.ReadAllBytes(glbPath);
|
|
if (data.Length < 20)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: GLB smaller than 20-byte header.");
|
|
}
|
|
|
|
uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4));
|
|
uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4));
|
|
if (magic != 0x46546C67 || version != 2)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: invalid GLB header magic=0x{magic:X8} version={version}.");
|
|
}
|
|
|
|
uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4));
|
|
uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4));
|
|
if (jsonType != 0x4E4F534A)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: first GLB chunk is not JSON (0x{jsonType:X8}).");
|
|
}
|
|
|
|
return data.AsSpan(20, (int)jsonLen).ToArray();
|
|
}
|
|
|
|
private static Vector3 ReadVec3(JsonElement obj, string propName, Vector3 fallback)
|
|
{
|
|
if (!obj.TryGetProperty(propName, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array || arr.GetArrayLength() < 3)
|
|
{
|
|
return fallback;
|
|
}
|
|
return new Vector3(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle());
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
foreach (var v in _vehicles.Values)
|
|
{
|
|
if (GodotObject.IsInstanceValid(v.SceneTemplate))
|
|
{
|
|
v.SceneTemplate.QueueFree();
|
|
}
|
|
}
|
|
foreach (var g in _gear.Values)
|
|
{
|
|
if (GodotObject.IsInstanceValid(g.SceneTemplate))
|
|
{
|
|
g.SceneTemplate.QueueFree();
|
|
}
|
|
}
|
|
_vehicles.Clear();
|
|
_gear.Clear();
|
|
}
|
|
}
|