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
287
client/DebrisSystem.cs
Normal file
287
client/DebrisSystem.cs
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Godot;
|
||||
using RustToDust.Core;
|
||||
|
||||
namespace RustToDust.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Manages physically detached armor plates and sheared hardpoint gear as tumbling,
|
||||
/// terrain-bouncing debris pieces that settle and fade out cleanly after 8 seconds.
|
||||
/// </summary>
|
||||
public partial class DebrisSystem : Node3D
|
||||
{
|
||||
private const float Gravity = -20f;
|
||||
private const float DefaultLifetime = 8.0f;
|
||||
private const float FadeDuration = 2.0f;
|
||||
private const int MaxActiveDebris = 160;
|
||||
|
||||
private sealed class DebrisPiece
|
||||
{
|
||||
public required Node3D Node;
|
||||
public required Vector3 Velocity;
|
||||
public required Vector3 AngularVelocity;
|
||||
public required List<StandardMaterial3D> FadeMaterials;
|
||||
public required float[] BaseAlphas;
|
||||
public float Age;
|
||||
public float Lifetime;
|
||||
public bool Settled;
|
||||
}
|
||||
|
||||
private readonly List<DebrisPiece> _pieces = new();
|
||||
private uint _rngState = 0x9E3779B9u;
|
||||
|
||||
public int ActiveCount => _pieces.Count;
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
for (int i = 0; i < _pieces.Count; i++)
|
||||
{
|
||||
if (GodotObject.IsInstanceValid(_pieces[i].Node))
|
||||
{
|
||||
_pieces[i].Node.QueueFree();
|
||||
}
|
||||
}
|
||||
_pieces.Clear();
|
||||
|
||||
for (int i = GetChildCount() - 1; i >= 0; i--)
|
||||
{
|
||||
Node ch = GetChild(i);
|
||||
RemoveChild(ch);
|
||||
ch.QueueFree();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reparents <paramref name="part"/> from its vehicle hierarchy at its exact world transform
|
||||
/// into <see cref="DebrisSystem"/> and launches it with an outward blast impulse and tumble.
|
||||
/// </summary>
|
||||
public void SpawnDetachedPart(
|
||||
Node3D part,
|
||||
Vector3 blastOriginWorld,
|
||||
Vector3 inheritedVelocity,
|
||||
float impulseScale = 1.0f,
|
||||
bool applyScorch = true)
|
||||
{
|
||||
if (!GodotObject.IsInstanceValid(part))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict oldest settled or oldest piece if we hit the cap so debris never leaks indefinitely
|
||||
while (_pieces.Count >= MaxActiveDebris)
|
||||
{
|
||||
RemoveAt(0);
|
||||
}
|
||||
|
||||
Transform3D worldXform = part.IsInsideTree() ? part.GlobalTransform : part.Transform;
|
||||
Node? oldParent = part.GetParent();
|
||||
oldParent?.RemoveChild(part);
|
||||
AddChild(part);
|
||||
|
||||
if (part.IsInsideTree() && IsInsideTree())
|
||||
{
|
||||
part.GlobalTransform = worldXform;
|
||||
}
|
||||
else
|
||||
{
|
||||
part.Transform = worldXform;
|
||||
}
|
||||
|
||||
Vector3 outward = worldXform.Origin - blastOriginWorld;
|
||||
outward.Y = 0f;
|
||||
if (outward.LengthSquared() < 1e-4f)
|
||||
{
|
||||
float ang = NextFloat() * MathF.Tau;
|
||||
outward = new Vector3(MathF.Cos(ang), 0f, MathF.Sin(ang));
|
||||
}
|
||||
else
|
||||
{
|
||||
outward = outward.Normalized();
|
||||
}
|
||||
|
||||
float horizSpeed = (4.2f + NextFloat() * 4.8f) * impulseScale;
|
||||
float upSpeed = (4.0f + NextFloat() * 4.5f) * impulseScale;
|
||||
Vector3 vel = inheritedVelocity * 0.45f + outward * horizSpeed + Vector3.Up * upSpeed;
|
||||
|
||||
Vector3 angVel = new(
|
||||
(NextFloat() * 2f - 1f) * 7.5f,
|
||||
(NextFloat() * 2f - 1f) * 7.5f,
|
||||
(NextFloat() * 2f - 1f) * 7.5f);
|
||||
|
||||
var fadeMats = new List<StandardMaterial3D>();
|
||||
PrepareInstanceMaterials(part, fadeMats, applyScorch);
|
||||
var baseAlphas = new float[fadeMats.Count];
|
||||
for (int i = 0; i < fadeMats.Count; i++)
|
||||
{
|
||||
baseAlphas[i] = fadeMats[i].AlbedoColor.A;
|
||||
}
|
||||
|
||||
_pieces.Add(new DebrisPiece
|
||||
{
|
||||
Node = part,
|
||||
Velocity = vel,
|
||||
AngularVelocity = angVel,
|
||||
FadeMaterials = fadeMats,
|
||||
BaseAlphas = baseAlphas,
|
||||
Age = 0f,
|
||||
Lifetime = DefaultLifetime,
|
||||
Settled = false
|
||||
});
|
||||
}
|
||||
|
||||
public void Step(float dt, TerrainField terrain)
|
||||
{
|
||||
if (dt <= 0f || !float.IsFinite(dt))
|
||||
{
|
||||
return;
|
||||
}
|
||||
float stepDt = Math.Clamp(dt, 0f, 0.05f);
|
||||
|
||||
for (int i = _pieces.Count - 1; i >= 0; i--)
|
||||
{
|
||||
DebrisPiece p = _pieces[i];
|
||||
if (!GodotObject.IsInstanceValid(p.Node))
|
||||
{
|
||||
_pieces.RemoveAt(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
p.Age += stepDt;
|
||||
if (p.Age >= p.Lifetime)
|
||||
{
|
||||
RemoveAt(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!p.Settled)
|
||||
{
|
||||
p.Velocity += new Vector3(0f, Gravity * stepDt, 0f);
|
||||
Vector3 pos = p.Node.Position + p.Velocity * stepDt;
|
||||
|
||||
Basis basis = p.Node.Basis;
|
||||
float spinLen = p.AngularVelocity.Length();
|
||||
if (spinLen > 1e-4f)
|
||||
{
|
||||
basis = new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * basis;
|
||||
basis = basis.Orthonormalized();
|
||||
}
|
||||
|
||||
float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f;
|
||||
if (pos.Y <= floorY)
|
||||
{
|
||||
pos.Y = floorY;
|
||||
if (p.Velocity.Y < -1.4f)
|
||||
{
|
||||
p.Velocity = new Vector3(
|
||||
p.Velocity.X * 0.62f,
|
||||
-p.Velocity.Y * 0.32f,
|
||||
p.Velocity.Z * 0.62f);
|
||||
p.AngularVelocity *= 0.55f;
|
||||
}
|
||||
else
|
||||
{
|
||||
p.Velocity = Vector3.Zero;
|
||||
p.AngularVelocity = Vector3.Zero;
|
||||
p.Settled = true;
|
||||
}
|
||||
}
|
||||
|
||||
p.Node.Position = pos;
|
||||
p.Node.Basis = basis;
|
||||
}
|
||||
|
||||
// Smooth alpha fade during final 2 seconds
|
||||
float remaining = p.Lifetime - p.Age;
|
||||
if (remaining < FadeDuration)
|
||||
{
|
||||
float alphaFrac = Math.Clamp(remaining / FadeDuration, 0f, 1f);
|
||||
for (int m = 0; m < p.FadeMaterials.Count; m++)
|
||||
{
|
||||
StandardMaterial3D sm = p.FadeMaterials[m];
|
||||
if (sm.Transparency == BaseMaterial3D.TransparencyEnum.Disabled)
|
||||
{
|
||||
sm.Transparency = BaseMaterial3D.TransparencyEnum.Alpha;
|
||||
}
|
||||
Color col = sm.AlbedoColor;
|
||||
col.A = p.BaseAlphas[m] * alphaFrac;
|
||||
sm.AlbedoColor = col;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveAt(int index)
|
||||
{
|
||||
DebrisPiece p = _pieces[index];
|
||||
_pieces.RemoveAt(index);
|
||||
if (GodotObject.IsInstanceValid(p.Node))
|
||||
{
|
||||
if (p.Node.GetParent() == this)
|
||||
{
|
||||
RemoveChild(p.Node);
|
||||
}
|
||||
p.Node.QueueFree();
|
||||
}
|
||||
}
|
||||
|
||||
private static void PrepareInstanceMaterials(Node cur, List<StandardMaterial3D> outMats, bool applyScorch)
|
||||
{
|
||||
if (cur is MeshInstance3D mi && mi.Mesh is not null)
|
||||
{
|
||||
if (mi.MaterialOverride is StandardMaterial3D ov)
|
||||
{
|
||||
var copy = (StandardMaterial3D)ov.Duplicate();
|
||||
if (applyScorch)
|
||||
{
|
||||
ApplyScorchTint(copy);
|
||||
}
|
||||
mi.MaterialOverride = copy;
|
||||
outMats.Add(copy);
|
||||
}
|
||||
else
|
||||
{
|
||||
int surfCount = mi.Mesh.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
Material? src = mi.GetActiveMaterial(s);
|
||||
StandardMaterial3D copy = src is StandardMaterial3D sm
|
||||
? (StandardMaterial3D)sm.Duplicate()
|
||||
: new StandardMaterial3D { AlbedoColor = new Color(0.28f, 0.25f, 0.23f), Roughness = 0.78f, Metallic = 0.45f };
|
||||
if (applyScorch)
|
||||
{
|
||||
ApplyScorchTint(copy);
|
||||
}
|
||||
mi.SetSurfaceOverrideMaterial(s, copy);
|
||||
outMats.Add(copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
PrepareInstanceMaterials(cur.GetChild(i), outMats, applyScorch);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyScorchTint(StandardMaterial3D mat)
|
||||
{
|
||||
Color c = mat.AlbedoColor;
|
||||
mat.AlbedoColor = new Color(c.R * 0.42f + 0.04f, c.G * 0.36f + 0.03f, c.B * 0.34f + 0.02f, c.A);
|
||||
mat.Roughness = MathF.Max(mat.Roughness, 0.78f);
|
||||
mat.EmissionEnabled = true;
|
||||
mat.Emission = new Color(0.95f, 0.32f, 0.06f);
|
||||
mat.EmissionEnergyMultiplier = 0.35f;
|
||||
}
|
||||
|
||||
private float NextFloat()
|
||||
{
|
||||
uint x = _rngState;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
_rngState = x;
|
||||
return (x & 0x00FFFFFFu) / 16777216f;
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
753
client/VehicleVisualInstance.cs
Normal file
753
client/VehicleVisualInstance.cs
Normal file
|
|
@ -0,0 +1,753 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Godot;
|
||||
using RustToDust.Core;
|
||||
|
||||
namespace RustToDust.Client;
|
||||
|
||||
public enum VehicleVisualRole
|
||||
{
|
||||
Player,
|
||||
Rival,
|
||||
SpectatorTourist,
|
||||
SpectatorPatron,
|
||||
SpectatorExemplar,
|
||||
SalvageDrop
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Live Godot 3D instance of a Brokkr vehicle/mech GLB, managing:
|
||||
/// - grounded model alignment (<c>minY = 0</c> at physics chassis bottom <c>-HalfHeight</c>),
|
||||
/// - exterior hardpoint anchor bindings and snap-on modular gear GLBs,
|
||||
/// - joint pivot bindings with rest transforms and vehicle-space axes,
|
||||
/// - part-by-cell armor/shroud detachment and hardpoint gear shearing into <see cref="DebrisSystem"/>,
|
||||
/// - per-cell scorch/damage darkening and thermal heat glow.
|
||||
/// </summary>
|
||||
public sealed class VehicleVisualInstance
|
||||
{
|
||||
public sealed class BoundJoint
|
||||
{
|
||||
public required string JointId;
|
||||
public required Node3D Node;
|
||||
public required Transform3D RestLocal;
|
||||
public required Vector3 AxisInParent;
|
||||
public required float MinRad;
|
||||
public required float MaxRad;
|
||||
}
|
||||
|
||||
private sealed class BoundHardpoint
|
||||
{
|
||||
public required HardpointSpec Spec;
|
||||
public required VehicleAssetCache.GlbAnchorInfo AnchorInfo;
|
||||
public required Node3D AnchorNode;
|
||||
public string? MountedModuleId;
|
||||
public Node3D? GearNode;
|
||||
public readonly List<StandardMaterial3D> GearHeatMaterials = new();
|
||||
}
|
||||
|
||||
private sealed class CellPartBinding
|
||||
{
|
||||
public required MeshInstance3D Node;
|
||||
public readonly List<(StandardMaterial3D Mat, Color BaseColor, float BaseRoughness)> Materials = new();
|
||||
public bool Detached;
|
||||
public float LastTintScore = -1f;
|
||||
}
|
||||
|
||||
private readonly record struct GearVisualRecipe(
|
||||
string GearGlbId,
|
||||
Vector3 VariantScale,
|
||||
Color? PaintTint,
|
||||
Color? AccentTint);
|
||||
|
||||
private static readonly Color RivalArmorColor = Color.FromHtml("#5d4d42");
|
||||
private static readonly Color RivalAccentColor = Color.FromHtml("#b64a32");
|
||||
private static readonly Color TouristGold = Color.FromHtml("#e6b838");
|
||||
private static readonly Color TouristIvory = Color.FromHtml("#f2ead8");
|
||||
private static readonly Color PatronTeal = Color.FromHtml("#2d7a78");
|
||||
private static readonly Color PatronBronze = Color.FromHtml("#a86c36");
|
||||
private static readonly Color ExemplarObsidian = Color.FromHtml("#1b1b22");
|
||||
private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a");
|
||||
private static readonly Color SalvageSteel = Color.FromHtml("#545b5c");
|
||||
private static readonly Color SalvageCyan = Color.FromHtml("#44d9e8");
|
||||
|
||||
private readonly VehicleAssetCache _cache;
|
||||
private readonly VehicleAssetCache.VehicleTemplate _template;
|
||||
private readonly Dictionary<string, BoundHardpoint> _hardpoints = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, BoundJoint> _joints = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Node3D> _namedNodes = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Transform3D> _restLocalByName = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, Transform3D> _restModelByName = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<Node3D, Transform3D> _restModelByNode = new();
|
||||
private readonly List<CellPartBinding>[,] _cellParts;
|
||||
private readonly bool[,] _strippedCells;
|
||||
private readonly HashSet<string> _shearedHardpoints = new(StringComparer.Ordinal);
|
||||
private readonly VehicleRigAnimator.RigState _rigState = new();
|
||||
|
||||
private readonly string _chassisId;
|
||||
|
||||
private VehicleVisualInstance(
|
||||
VehicleAssetCache cache,
|
||||
VehicleAssetCache.VehicleTemplate template,
|
||||
Node3D root,
|
||||
Node3D modelRoot,
|
||||
string chassisId)
|
||||
{
|
||||
_cache = cache;
|
||||
_template = template;
|
||||
Root = root;
|
||||
ModelRoot = modelRoot;
|
||||
_chassisId = chassisId;
|
||||
|
||||
int w = template.Package.GridWidth;
|
||||
int h = template.Package.GridHeight;
|
||||
_cellParts = new List<CellPartBinding>[w, h];
|
||||
_strippedCells = new bool[w, h];
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
_cellParts[x, y] = new List<CellPartBinding>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Node3D Root { get; }
|
||||
public Node3D ModelRoot { get; }
|
||||
public VehicleAssetCache.VehicleTemplate Template => _template;
|
||||
public VehiclePackage Package => _template.Package;
|
||||
public string ChassisId => _chassisId;
|
||||
public string ModelId => _template.Package.Id;
|
||||
public VehicleRigAnimator.RigState RigState => _rigState;
|
||||
public IReadOnlyDictionary<string, BoundJoint> Joints => _joints;
|
||||
public int BoundHardpointCount => _hardpoints.Count;
|
||||
|
||||
public static VehicleVisualInstance Create(
|
||||
VehicleAssetCache cache,
|
||||
string chassisId,
|
||||
VehicleVisualRole role,
|
||||
float visualScale = 1.0f,
|
||||
float? targetHalfHeight = null)
|
||||
{
|
||||
var template = cache.GetOrLoadVehicle(chassisId);
|
||||
var pkg = template.Package;
|
||||
float halfHeight = targetHalfHeight ?? pkg.HalfHeight;
|
||||
float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f
|
||||
? visualScale * (targetHalfHeight.Value / pkg.HalfHeight)
|
||||
: visualScale;
|
||||
|
||||
var root = new Node3D { Name = $"Actor_{chassisId}" };
|
||||
|
||||
if (template.SceneTemplate.Duplicate() is not Node3D modelRoot)
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to duplicate GLB scene template for '{pkg.Id}'.");
|
||||
}
|
||||
modelRoot.Name = $"Model_{pkg.Id}";
|
||||
modelRoot.Scale = new Vector3(effectiveScale, effectiveScale, effectiveScale);
|
||||
// Align glTF grounded minY=0 to physics chassis bottom (-halfHeight)
|
||||
modelRoot.Position = new Vector3(0f, -halfHeight - template.MinY * effectiveScale, 0f);
|
||||
root.AddChild(modelRoot);
|
||||
|
||||
var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId);
|
||||
instance.BindAll(role);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void BindAll(VehicleVisualRole role)
|
||||
{
|
||||
var pkg = _template.Package;
|
||||
|
||||
// Collect cumulative pure glTF model-space transforms (minY=0, unscaled) starting at ModelRoot = Identity
|
||||
var modelXforms = new Dictionary<Node, Transform3D>
|
||||
{
|
||||
[ModelRoot] = Transform3D.Identity
|
||||
};
|
||||
int modelChildCount = ModelRoot.GetChildCount();
|
||||
for (int i = 0; i < modelChildCount; i++)
|
||||
{
|
||||
CollectNodeTransforms(ModelRoot.GetChild(i), Transform3D.Identity, modelXforms);
|
||||
}
|
||||
|
||||
// Bind named nodes for procedural/mechanism rigs
|
||||
foreach (var (origName, relPath) in _template.NodesByOriginalName)
|
||||
{
|
||||
Node3D? node = ResolveRelative(ModelRoot, relPath);
|
||||
if (node is not null)
|
||||
{
|
||||
_namedNodes[origName] = node;
|
||||
_restLocalByName[origName] = node.Transform;
|
||||
if (modelXforms.TryGetValue(node, out var mxf))
|
||||
{
|
||||
_restModelByName[origName] = mxf;
|
||||
_restModelByNode[node] = mxf;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bind all joints from rtd.joint metadata
|
||||
foreach (var (jointId, jInfo) in _template.Joints)
|
||||
{
|
||||
Node3D? jNode = ResolveRelative(ModelRoot, jInfo.RelativePath);
|
||||
if (jNode is null)
|
||||
{
|
||||
throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing joint node '{jInfo.NodeName}' ({jointId}).");
|
||||
}
|
||||
|
||||
Basis parentModelBasis = Basis.Identity;
|
||||
Node? parent = jNode.GetParent();
|
||||
if (parent is not null && modelXforms.TryGetValue(parent, out var pxf))
|
||||
{
|
||||
parentModelBasis = pxf.Basis.Orthonormalized();
|
||||
}
|
||||
|
||||
Vector3 axisInParent = parentModelBasis.Inverse() * jInfo.Axis;
|
||||
axisInParent = axisInParent.LengthSquared() > 1e-6f ? axisInParent.Normalized() : Vector3.Up;
|
||||
|
||||
_joints[jointId] = new BoundJoint
|
||||
{
|
||||
JointId = jointId,
|
||||
Node = jNode,
|
||||
RestLocal = jNode.Transform,
|
||||
AxisInParent = axisInParent,
|
||||
MinRad = Mathf.DegToRad(jInfo.MinVal),
|
||||
MaxRad = Mathf.DegToRad(jInfo.MaxVal)
|
||||
};
|
||||
}
|
||||
|
||||
// Bind every ChassisSpec hardpoint to its exact exterior anchor Node3D
|
||||
ChassisSpec spec = pkg.ToChassisSpec();
|
||||
var pkgHpById = new Dictionary<string, VehicleHardpointRecord>(StringComparer.Ordinal);
|
||||
foreach (var rec in pkg.Hardpoints)
|
||||
{
|
||||
pkgHpById[rec.Id] = rec;
|
||||
}
|
||||
|
||||
for (int i = 0; i < spec.Hardpoints.Length; i++)
|
||||
{
|
||||
HardpointSpec hp = spec.Hardpoints[i];
|
||||
if (!pkgHpById.TryGetValue(hp.Id, out var rec) ||
|
||||
!_template.Anchors.TryGetValue(rec.AnchorId, out var anchorInfo))
|
||||
{
|
||||
throw new InvalidOperationException($"{pkg.Id}: missing AnchorId for hardpoint '{hp.Id}'.");
|
||||
}
|
||||
|
||||
Node3D? anchorNode = ResolveRelative(ModelRoot, anchorInfo.RelativePath);
|
||||
if (anchorNode is null)
|
||||
{
|
||||
throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'.");
|
||||
}
|
||||
|
||||
_hardpoints[hp.Id] = new BoundHardpoint
|
||||
{
|
||||
Spec = hp,
|
||||
AnchorInfo = anchorInfo,
|
||||
AnchorNode = anchorNode
|
||||
};
|
||||
}
|
||||
|
||||
// Apply role palette tinting to painted hull meshes before binding per-cell damage clones
|
||||
if (role != VehicleVisualRole.Player)
|
||||
{
|
||||
ApplyRoleTint(ModelRoot, role);
|
||||
}
|
||||
|
||||
// Bind detachable exterior armor/shroud parts to their (CellX, CellY)
|
||||
int w = pkg.GridWidth;
|
||||
int h = pkg.GridHeight;
|
||||
foreach (var dp in _template.DetachableParts)
|
||||
{
|
||||
if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (ResolveRelative(ModelRoot, dp.RelativePath) is MeshInstance3D mi)
|
||||
{
|
||||
_cellParts[dp.CellX, dp.CellY].Add(new CellPartBinding { Node = mi });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Node3D? GetNamedNode(string name) =>
|
||||
_namedNodes.TryGetValue(name, out var n) && GodotObject.IsInstanceValid(n) ? n : null;
|
||||
|
||||
public bool TryGetRestLocal(string name, out Transform3D xform) =>
|
||||
_restLocalByName.TryGetValue(name, out xform);
|
||||
|
||||
public bool TryGetRestModel(string name, out Transform3D xform) =>
|
||||
_restModelByName.TryGetValue(name, out xform);
|
||||
|
||||
public bool TryGetRestModel(Node3D node, out Transform3D xform) =>
|
||||
_restModelByNode.TryGetValue(node, out xform);
|
||||
|
||||
public Node3D? GetHardpointAnchorNode(string hardpointId) =>
|
||||
_hardpoints.TryGetValue(hardpointId, out var bh) ? bh.AnchorNode : null;
|
||||
|
||||
public Node3D? GetMountedGearNode(string hardpointId) =>
|
||||
_hardpoints.TryGetValue(hardpointId, out var bh) && GodotObject.IsInstanceValid(bh.GearNode) ? bh.GearNode : null;
|
||||
|
||||
public int CountDetachablePartsForCell(int x, int y) =>
|
||||
x >= 0 && x < _template.Package.GridWidth && y >= 0 && y < _template.Package.GridHeight
|
||||
? _cellParts[x, y].Count
|
||||
: 0;
|
||||
|
||||
/// <summary>
|
||||
/// Synchronizes visible exterior gear GLBs on all hardpoint anchors with <paramref name="grid"/>.
|
||||
/// </summary>
|
||||
public void SyncMountedGear(ChassisGrid grid)
|
||||
{
|
||||
foreach (var bh in _hardpoints.Values)
|
||||
{
|
||||
if (_shearedHardpoints.Contains(bh.Spec.Id) || !grid.IsHardpointOperational(bh.Spec))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id);
|
||||
string? desiredId = mounted?.Spec.Id;
|
||||
|
||||
if (string.Equals(bh.MountedModuleId, desiredId, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Clear old gear visual if unmounted or swapped
|
||||
if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode))
|
||||
{
|
||||
bh.GearNode.GetParent()?.RemoveChild(bh.GearNode);
|
||||
bh.GearNode.QueueFree();
|
||||
}
|
||||
bh.GearNode = null;
|
||||
bh.GearHeatMaterials.Clear();
|
||||
bh.MountedModuleId = desiredId;
|
||||
|
||||
if (mounted is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Node3D gearNode = InstantiateGearForHardpoint(mounted.Spec, bh.Spec, bh.AnchorInfo, bh.GearHeatMaterials);
|
||||
bh.AnchorNode.AddChild(gearNode);
|
||||
bh.GearNode = gearNode;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches exterior armor/shroud plates when <c>Armor[x, y] <= 0.01f</c>,
|
||||
/// shears mounted gear off non-operational hardpoints, and applies scorch/heat glow.
|
||||
/// </summary>
|
||||
public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity)
|
||||
{
|
||||
int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth);
|
||||
int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight);
|
||||
Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position;
|
||||
|
||||
// 1. Part-by-cell detachment & cell scorch/heat tinting
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
if (!grid.Spec.IsActive(x, y))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float armor = grid.Armor[x, y];
|
||||
var parts = _cellParts[x, y];
|
||||
if (!_strippedCells[x, y] && armor <= 0.01f)
|
||||
{
|
||||
_strippedCells[x, y] = true;
|
||||
for (int i = 0; i < parts.Count; i++)
|
||||
{
|
||||
var pb = parts[i];
|
||||
if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node))
|
||||
{
|
||||
pb.Detached = true;
|
||||
debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parts.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]);
|
||||
float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f);
|
||||
float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f);
|
||||
float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f;
|
||||
|
||||
if (dmgFrac < 0.25f && heatGlow < 0.05f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int i = 0; i < parts.Count; i++)
|
||||
{
|
||||
var pb = parts[i];
|
||||
if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
pb.LastTintScore = tintScore;
|
||||
ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Hardpoint shear & mounted gear heat glow
|
||||
foreach (var bh in _hardpoints.Values)
|
||||
{
|
||||
if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec))
|
||||
{
|
||||
_shearedHardpoints.Add(bh.Spec.Id);
|
||||
if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode))
|
||||
{
|
||||
Node3D sheared = bh.GearNode;
|
||||
bh.GearNode = null;
|
||||
bh.MountedModuleId = null;
|
||||
bh.GearHeatMaterials.Clear();
|
||||
debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (bh.GearNode is null || bh.GearHeatMaterials.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id);
|
||||
if (mounted is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float heatFrac = Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f);
|
||||
for (int m = 0; m < bh.GearHeatMaterials.Count; m++)
|
||||
{
|
||||
StandardMaterial3D gm = bh.GearHeatMaterials[m];
|
||||
gm.EmissionEnabled = heatFrac > 0.02f;
|
||||
gm.Emission = new Color(1.0f, 0.34f, 0.08f);
|
||||
gm.EmissionEnergyMultiplier = heatFrac * 2.2f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod)
|
||||
{
|
||||
var list = new List<StandardMaterial3D>();
|
||||
GearVisualRecipe recipe = ResolveGearRecipe(mod);
|
||||
var template = cache.GetOrLoadGear(recipe.GearGlbId);
|
||||
if (template.SceneTemplate.Duplicate() is not Node3D node)
|
||||
{
|
||||
return new Node3D { Name = $"Gear_{mod.Id}" };
|
||||
}
|
||||
node.Name = $"GearDrop_{mod.Id}";
|
||||
node.Scale = recipe.VariantScale;
|
||||
node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f);
|
||||
if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue)
|
||||
{
|
||||
ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private Node3D InstantiateGearForHardpoint(
|
||||
ModuleSpec mod,
|
||||
HardpointSpec hp,
|
||||
VehicleAssetCache.GlbAnchorInfo anchorInfo,
|
||||
List<StandardMaterial3D> heatMaterialsOut)
|
||||
{
|
||||
GearVisualRecipe recipe = ResolveGearRecipe(mod);
|
||||
VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId);
|
||||
if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode)
|
||||
{
|
||||
throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'.");
|
||||
}
|
||||
gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}";
|
||||
|
||||
// Compute outward socket normal & desired gear forward direction in vehicle/model space
|
||||
Basis anchorModelBasis = anchorInfo.ModelSpaceTransform.Basis.Orthonormalized();
|
||||
Vector3 upOut = anchorModelBasis.Y.Normalized();
|
||||
if (upOut.LengthSquared() < 1e-6f) upOut = Vector3.Up;
|
||||
|
||||
Vector3 vehForward = new(0f, 0f, 1f);
|
||||
Vector3 desiredGearFwd;
|
||||
|
||||
if (hp.Kind == HardpointKind.Weapon)
|
||||
{
|
||||
// Special guard for forward-facing chin mounts (e.g. manticore hp.weapon.chin):
|
||||
// drop the turret base under the chin (-Y) so the barrel points straight forward (+Z) instead of up into the nose.
|
||||
if (upOut.Z > 0.72f)
|
||||
{
|
||||
upOut = upOut.Y <= 0.1f ? new Vector3(0f, -1f, 0f) : new Vector3(0f, 1f, 0f);
|
||||
desiredGearFwd = vehForward;
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector3 proj = vehForward - upOut * vehForward.Dot(upOut);
|
||||
desiredGearFwd = proj.LengthSquared() > 1e-4f
|
||||
? proj.Normalized()
|
||||
: anchorModelBasis.Z.Normalized();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Non-weapon modules (radiator / engine / armor): align neatly to hull tangent plane
|
||||
if (MathF.Abs(upOut.Z) > 0.78f)
|
||||
{
|
||||
Vector3 upProj = Vector3.Up - upOut * Vector3.Up.Dot(upOut);
|
||||
desiredGearFwd = upProj.LengthSquared() > 1e-4f ? upProj.Normalized() : Vector3.Up;
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector3 proj = vehForward - upOut * vehForward.Dot(upOut);
|
||||
desiredGearFwd = proj.LengthSquared() > 1e-4f ? proj.Normalized() : Vector3.Up;
|
||||
}
|
||||
}
|
||||
|
||||
// Right-handed basis: Y = upOut, Z = desiredGearFwd, X = Y x Z
|
||||
Vector3 rightX = upOut.Cross(desiredGearFwd);
|
||||
if (rightX.LengthSquared() < 1e-5f)
|
||||
{
|
||||
rightX = Vector3.Right;
|
||||
}
|
||||
else
|
||||
{
|
||||
rightX = rightX.Normalized();
|
||||
}
|
||||
desiredGearFwd = rightX.Cross(upOut).Normalized();
|
||||
var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd);
|
||||
|
||||
// If the gear GLB's own muzzle points along -Z (recoilless), rotate 180 deg around Y
|
||||
if (gearTemplate.LocalModelForward.Z < 0f)
|
||||
{
|
||||
desiredModelBasis *= new Basis(Vector3.Up, MathF.PI);
|
||||
}
|
||||
|
||||
Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis;
|
||||
|
||||
// Fit cleanly to the socket's physical rtd.size
|
||||
float sx = MathF.Max(0.25f, anchorInfo.Size.X);
|
||||
float sy = MathF.Max(0.25f, anchorInfo.Size.Y);
|
||||
Vector3 fitScale;
|
||||
if (hp.Kind == HardpointKind.Weapon)
|
||||
{
|
||||
float baseScale = Math.Clamp(MathF.Min(sx, sy) / 0.56f, 0.72f, 1.75f);
|
||||
fitScale = recipe.VariantScale * baseScale;
|
||||
}
|
||||
else
|
||||
{
|
||||
float scaleX = Math.Clamp(sx / 0.48f, 0.72f, 2.15f);
|
||||
float scaleZ = Math.Clamp(sy / 0.45f, 0.72f, 2.15f);
|
||||
float scaleY = Math.Clamp(0.5f * (scaleX + scaleZ), 0.72f, 1.85f);
|
||||
fitScale = new Vector3(
|
||||
recipe.VariantScale.X * scaleX,
|
||||
recipe.VariantScale.Y * scaleY,
|
||||
recipe.VariantScale.Z * scaleZ);
|
||||
}
|
||||
|
||||
gearNode.Basis = localBasis * Basis.FromScale(fitScale);
|
||||
// Seat gear minY right on the anchor collar origin (with slight downward offset if chin flipped)
|
||||
float ySeat = -gearTemplate.MinY * fitScale.Y;
|
||||
gearNode.Position = (anchorModelBasis.Inverse() * upOut) * ySeat;
|
||||
|
||||
ApplyGearVariantTint(gearNode, recipe.PaintTint, recipe.AccentTint, heatMaterialsOut);
|
||||
return gearNode;
|
||||
}
|
||||
|
||||
private static GearVisualRecipe ResolveGearRecipe(ModuleSpec mod)
|
||||
{
|
||||
return mod.Id switch
|
||||
{
|
||||
"mg_762" => new("mg_762", Vector3.One, null, null),
|
||||
"autocannon" => new("autocannon", Vector3.One, null, null),
|
||||
"recoilless" => new("recoilless", Vector3.One, null, null),
|
||||
"copper_rad" => new("copper_rad", Vector3.One, null, null),
|
||||
"gilded_lance" => new("gilded_lance", Vector3.One, null, null),
|
||||
"gold_radiator" => new("gold_radiator", Vector3.One, null, null),
|
||||
|
||||
// Clean tint/scale variants from the 6 real gear GLBs
|
||||
"flak" => new("autocannon", new Vector3(1.12f, 0.92f, 0.68f), Color.FromHtml("#5a4a3f"), Color.FromHtml("#d96c27")),
|
||||
"pd_flak" => new("mg_762", new Vector3(1.22f, 1.10f, 0.85f), Color.FromHtml("#3d4440"), Color.FromHtml("#e08a4a")),
|
||||
"touring_plasma" => new("gilded_lance", new Vector3(1.05f, 0.96f, 0.72f), TouristIvory, Color.FromHtml("#38c9d8")),
|
||||
"aegis_pd" => new("gilded_lance", new Vector3(0.95f, 0.92f, 0.56f), TouristGold, Color.FromHtml("#38c9d8")),
|
||||
"diesel_core" => new("copper_rad", new Vector3(0.92f, 1.15f, 1.05f), Color.FromHtml("#363a38"), Color.FromHtml("#b35a2b")),
|
||||
"turbo_core" => new("copper_rad", new Vector3(1.12f, 1.28f, 1.38f), Color.FromHtml("#2a2f32"), Color.FromHtml("#e07024")),
|
||||
"noble_core" => new("gold_radiator", new Vector3(1.10f, 1.32f, 1.38f), TouristGold, Color.FromHtml("#38c9d8")),
|
||||
"welded_plate" => new("copper_rad", new Vector3(1.30f, 0.34f, 0.95f), Color.FromHtml("#4e5740"), Color.FromHtml("#6a6f66")),
|
||||
"gilded_plate" => new("gold_radiator", new Vector3(1.30f, 0.34f, 0.95f), TouristIvory, TouristGold),
|
||||
_ => new(mod.IsImperial ? "gilded_lance" : "mg_762", Vector3.One, null, null)
|
||||
};
|
||||
}
|
||||
|
||||
private static void ApplyGearVariantTint(
|
||||
Node cur,
|
||||
Color? paintTint,
|
||||
Color? accentTint,
|
||||
List<StandardMaterial3D> trackMaterials)
|
||||
{
|
||||
if (cur is MeshInstance3D mi && mi.Mesh is not null)
|
||||
{
|
||||
int surfCount = mi.Mesh.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
Material? src = mi.GetActiveMaterial(s);
|
||||
if (src is not StandardMaterial3D sm)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var copy = (StandardMaterial3D)sm.Duplicate();
|
||||
string matName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
||||
if (accentTint.HasValue && (matName.Contains("copper") || matName.Contains("signal") || matName.Contains("cyan") || matName.Contains("gold")))
|
||||
{
|
||||
copy.AlbedoColor = accentTint.Value;
|
||||
}
|
||||
else if (paintTint.HasValue && (matName.Contains("olive") || matName.Contains("ivory") || matName.Contains("armor")))
|
||||
{
|
||||
copy.AlbedoColor = paintTint.Value;
|
||||
}
|
||||
|
||||
mi.SetSurfaceOverrideMaterial(s, copy);
|
||||
if (!matName.Contains("rubber") && !matName.Contains("glass"))
|
||||
{
|
||||
trackMaterials.Add(copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
ApplyGearVariantTint(cur.GetChild(i), paintTint, accentTint, trackMaterials);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyRoleTint(Node root, VehicleVisualRole role)
|
||||
{
|
||||
var (armorColor, accentColor) = role switch
|
||||
{
|
||||
VehicleVisualRole.Rival => (RivalArmorColor, RivalAccentColor),
|
||||
VehicleVisualRole.SpectatorTourist => (TouristGold, TouristIvory),
|
||||
VehicleVisualRole.SpectatorPatron => (PatronTeal, PatronBronze),
|
||||
VehicleVisualRole.SpectatorExemplar => (ExemplarObsidian, ExemplarCrimson),
|
||||
VehicleVisualRole.SalvageDrop => (SalvageSteel, SalvageCyan),
|
||||
_ => (RivalArmorColor, RivalAccentColor)
|
||||
};
|
||||
|
||||
var clonedCache = new Dictionary<StandardMaterial3D, StandardMaterial3D>();
|
||||
TintSubtreeRecursive(root, armorColor, accentColor, role, clonedCache);
|
||||
}
|
||||
|
||||
private static void TintSubtreeRecursive(
|
||||
Node cur,
|
||||
Color armorColor,
|
||||
Color accentColor,
|
||||
VehicleVisualRole role,
|
||||
Dictionary<StandardMaterial3D, StandardMaterial3D> clonedCache)
|
||||
{
|
||||
if (cur is MeshInstance3D mi && mi.Mesh is not null)
|
||||
{
|
||||
int surfCount = mi.Mesh.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
if (mi.GetActiveMaterial(s) is not StandardMaterial3D sm)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
||||
bool isPrimaryPaint = mName.Contains("olive") || mName.Contains("khaki");
|
||||
bool isAccentPaint = mName.Contains("signal") || mName.Contains("orange");
|
||||
if (!isPrimaryPaint && !isAccentPaint)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!clonedCache.TryGetValue(sm, out var copy))
|
||||
{
|
||||
copy = (StandardMaterial3D)sm.Duplicate();
|
||||
copy.AlbedoColor = isPrimaryPaint ? armorColor : accentColor;
|
||||
if (role == VehicleVisualRole.SpectatorTourist && isPrimaryPaint)
|
||||
{
|
||||
copy.Metallic = 0.72f;
|
||||
copy.Roughness = 0.30f;
|
||||
}
|
||||
else if (role == VehicleVisualRole.SpectatorExemplar && isAccentPaint)
|
||||
{
|
||||
copy.EmissionEnabled = true;
|
||||
copy.Emission = ExemplarCrimson;
|
||||
copy.EmissionEnergyMultiplier = 0.65f;
|
||||
}
|
||||
clonedCache[sm] = copy;
|
||||
}
|
||||
|
||||
mi.SetSurfaceOverrideMaterial(s, copy);
|
||||
}
|
||||
}
|
||||
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
TintSubtreeRecursive(cur.GetChild(i), armorColor, accentColor, role, clonedCache);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplyCellDamageAndHeat(CellPartBinding binding, float dmgFrac, float heatGlow)
|
||||
{
|
||||
if (binding.Materials.Count == 0 && binding.Node.Mesh is not null)
|
||||
{
|
||||
int surfCount = binding.Node.Mesh.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
Material? src = binding.Node.GetActiveMaterial(s);
|
||||
StandardMaterial3D copy = src is StandardMaterial3D sm
|
||||
? (StandardMaterial3D)sm.Duplicate()
|
||||
: new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f };
|
||||
binding.Node.SetSurfaceOverrideMaterial(s, copy);
|
||||
binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness));
|
||||
}
|
||||
}
|
||||
|
||||
float scorch = Math.Clamp((dmgFrac - 0.25f) / 0.75f, 0f, 1f) * 0.65f;
|
||||
for (int i = 0; i < binding.Materials.Count; i++)
|
||||
{
|
||||
var (mat, baseCol, baseRough) = binding.Materials[i];
|
||||
mat.AlbedoColor = new Color(
|
||||
baseCol.R * (1f - scorch) + 0.05f * scorch,
|
||||
baseCol.G * (1f - scorch) + 0.035f * scorch,
|
||||
baseCol.B * (1f - scorch) + 0.03f * scorch,
|
||||
baseCol.A);
|
||||
mat.Roughness = MathF.Min(0.95f, baseRough + scorch * 0.35f);
|
||||
mat.EmissionEnabled = heatGlow > 0.05f;
|
||||
mat.Emission = new Color(1.0f, 0.32f, 0.08f);
|
||||
mat.EmissionEnergyMultiplier = heatGlow * 1.4f;
|
||||
}
|
||||
}
|
||||
|
||||
private static Node3D? ResolveRelative(Node3D root, NodePath relPath)
|
||||
{
|
||||
if (relPath.IsEmpty)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return relPath.ToString() == "." ? root : root.GetNodeOrNull<Node3D>(relPath);
|
||||
}
|
||||
|
||||
private static void CollectNodeTransforms(Node cur, Transform3D parentXf, Dictionary<Node, Transform3D> map)
|
||||
{
|
||||
Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf;
|
||||
map[cur] = xf;
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
CollectNodeTransforms(cur.GetChild(i), xf, map);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue