Add GLB VehicleAssetCache, hardpoint snap-on gear, and part-by-cell DebrisSystem
This commit is contained in:
parent
b5f1bf7753
commit
808ff19434
3 changed files with 1762 additions and 0 deletions
722
client/VehicleAssetCache.cs
Normal file
722
client/VehicleAssetCache.cs
Normal file
|
|
@ -0,0 +1,722 @@
|
|||
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 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}'.");
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return new VehicleTemplate
|
||||
{
|
||||
Package = pkg,
|
||||
GlbPath = glbPath,
|
||||
SceneTemplate = sceneRoot,
|
||||
MinY = minY,
|
||||
MaxY = maxY,
|
||||
Anchors = anchors,
|
||||
Joints = joints,
|
||||
NodesByOriginalName = nodesByOriginalName,
|
||||
DetachableParts = detachableParts,
|
||||
MobilityNodePaths = mobilityPaths
|
||||
};
|
||||
}
|
||||
|
||||
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}'.");
|
||||
}
|
||||
|
||||
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
||||
// recoilless.glb has its 0.82m barrel extending along -Z in the exported GLB; mg_762, autocannon, gilded_lance extend along +Z.
|
||||
Vector3 localFwd = string.Equals(gearId, "recoilless", StringComparison.OrdinalIgnoreCase)
|
||||
? new Vector3(0f, 0f, -1f)
|
||||
: new Vector3(0f, 0f, 1f);
|
||||
|
||||
return new GearTemplate
|
||||
{
|
||||
Id = gearId,
|
||||
GlbPath = glbPath,
|
||||
SceneTemplate = sceneRoot,
|
||||
Size = bMax - bMin,
|
||||
MinY = bMin.Y,
|
||||
LocalModelForward = localFwd
|
||||
};
|
||||
}
|
||||
|
||||
private static bool IsStructuralNodeName(string name)
|
||||
{
|
||||
string low = name.ToLowerInvariant();
|
||||
if (low is "chassis" or "hull" or "pelvis" or "core" or "trunk" or "waist" or "torso.pose" or "aim.turret" or "hull.pose")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (low.StartsWith("slot_frame.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("hp.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("joint.", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (low.StartsWith("leg", StringComparison.Ordinal) &&
|
||||
!low.Contains("shield") && !low.Contains("armor") && !low.Contains("plate") &&
|
||||
!low.Contains("greave") && !low.Contains("shroud") && !low.Contains("skirt") &&
|
||||
!low.Contains("cheek") && !low.Contains("collar"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return low.Contains("hip") && !low.Contains("cap") && !low.Contains("fender") && !low.Contains("flange") && !low.Contains("guard") && !low.Contains("shroud")
|
||||
|| low.Contains("thigh") && !low.Contains("shield") && !low.Contains("guard") && !low.Contains("shroud") && !low.Contains("lame") && !low.Contains("cuisse")
|
||||
|| low.Contains("shin") && !low.Contains("greave") && !low.Contains("guard") && !low.Contains("cheek") && !low.Contains("shroud")
|
||||
|| low.Contains("oleo") || low.Contains("torque") || low.Contains("recessram")
|
||||
|| low.StartsWith("arm", StringComparison.Ordinal) || low.StartsWith("shoulder", StringComparison.Ordinal)
|
||||
|| low.StartsWith("forearm", StringComparison.Ordinal) || low.StartsWith("elbow", StringComparison.Ordinal)
|
||||
|| low.StartsWith("tail.", StringComparison.Ordinal) || low.StartsWith("foot", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
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 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();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue