using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.Json; using RustToDust.Core; namespace VehiclePacker { internal sealed record HardpointTune( float ArmorBonus, float MinPitchDeg = -15f, float MaxPitchDeg = 45f, bool IsWideArc = false); internal sealed record VehicleTuning( MobilityKind Mobility, float MassKg, float MaxSpeed, float TurnRate, float ThrustNewtons, float HoverMaxAltitudeM, float ArmorPerCell, float Conductivity, float BaseCellThermalMass, int CargoCapacity, Dictionary DefaultLoadout, Dictionary HardpointTuning); internal static class Program { private static readonly Dictionary Tunings = BuildTunings(); private static int Main(string[] args) { string vehiclesRoot = args.Length > 0 ? Path.GetFullPath(args[0]) : LocateDefaultVehiclesRoot(); if (!Directory.Exists(vehiclesRoot)) { Console.Error.WriteLine($"Vehicles directory not found: {vehiclesRoot}"); return 1; } int packedCount = 0; foreach (string dir in Directory.GetDirectories(vehiclesRoot).OrderBy(d => d, StringComparer.Ordinal)) { string id = Path.GetFileName(dir); string manifestPath = Path.Combine(dir, "manifest.json"); string glbPath = Path.Combine(dir, $"{id}.glb"); if (!File.Exists(manifestPath) || !File.Exists(glbPath)) { continue; } if (!Tunings.TryGetValue(id, out var tuning)) { Console.Error.WriteLine($"Missing gameplay tuning entry for vehicle '{id}'."); return 2; } var pkg = BuildPackage(id, manifestPath, glbPath, tuning); string outPath = Path.Combine(dir, "vehicle.cc"); VehiclePackageStore.Write(outPath, pkg); var roundTrip = VehiclePackageStore.Read(outPath); Console.WriteLine( $"Packed {roundTrip.Id,-10} | {roundTrip.Mobility,-7} | {roundTrip.Plane,-7} | " + $"{roundTrip.GridWidth}x{roundTrip.GridHeight} | arm={roundTrip.ArmorPerCell,2:F0} | " + $"hps={roundTrip.Hardpoints.Count} | joints={roundTrip.Joints.Count,2} | " + $"partCells={roundTrip.PartCells.Count,3} | {new FileInfo(outPath).Length / 1024.0:F1} KiB"); packedCount++; } Console.WriteLine($"Done: packed {packedCount} vehicle.cc archives."); return packedCount == 15 ? 0 : 3; } private static string LocateDefaultVehiclesRoot() { foreach (string start in new[] { Directory.GetCurrentDirectory(), AppContext.BaseDirectory }) { var dir = new DirectoryInfo(Path.GetFullPath(start)); while (dir is not null) { string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); if (Directory.Exists(candidate)) { return candidate; } dir = dir.Parent; } } throw new DirectoryNotFoundException("Could not locate assets/vehicles directory."); } private static VehiclePackage BuildPackage(string id, string manifestPath, string glbPath, VehicleTuning tuning) { using var manifestDoc = JsonDocument.Parse(File.ReadAllText(manifestPath, Encoding.UTF8)); var root = manifestDoc.RootElement; string manifestId = root.GetProperty("id").GetString()!; if (!string.Equals(manifestId, id, StringComparison.Ordinal)) { throw new InvalidOperationException($"{manifestPath}: id '{manifestId}' != directory '{id}'."); } string name = root.GetProperty("name").GetString()!; string vClass = root.GetProperty("class").GetString()!; var plane = Enum.Parse(root.GetProperty("plane").GetString()!, ignoreCase: true); int gw = root.GetProperty("gridWidth").GetInt32(); int gh = root.GetProperty("gridHeight").GetInt32(); var maskBools = root.GetProperty("mask").EnumerateArray().Select(e => e.GetBoolean()).ToArray(); if (maskBools.Length != gw * gh) { throw new InvalidOperationException($"{id}: mask length {maskBools.Length} != {gw * gh}."); } var maskRows = new string[gh]; for (int y = 0; y < gh; y++) { var sb = new StringBuilder(gw); for (int x = 0; x < gw; x++) { sb.Append(maskBools[y * gw + x] ? '#' : '.'); } maskRows[y] = sb.ToString(); } var boundsSize = root.GetProperty("bounds").GetProperty("size").EnumerateArray().Select(e => e.GetSingle()).ToArray(); var boundsMin = root.GetProperty("bounds").GetProperty("min").EnumerateArray().Select(e => e.GetSingle()).ToArray(); var boundsMax = root.GetProperty("bounds").GetProperty("max").EnumerateArray().Select(e => e.GetSingle()).ToArray(); var (gltfJsonBytes, binBlob) = ReadGlbChunks(glbPath); using var gltfDoc = JsonDocument.Parse(gltfJsonBytes); var gltf = gltfDoc.RootElement; var hardpoints = ParseHardpoints(id, root.GetProperty("hardpoints"), gltf, tuning); var joints = ParseJoints(id, root.GetProperty("joints"), gltf); var mechanisms = root.TryGetProperty("mechanisms", out var mechElem) && mechElem.ValueKind == JsonValueKind.Object ? ParseMechanisms(mechElem) : null; var partCells = ComputePartCells(gltf, binBlob, plane, gw, gh, maskBools, boundsMin, boundsMax); return new VehiclePackage { Id = id, Name = name, VehicleClass = vClass, Mobility = tuning.Mobility, Plane = plane, GridWidth = gw, GridHeight = gh, Mask = maskRows, MassKg = tuning.MassKg, MaxSpeed = tuning.MaxSpeed, TurnRate = tuning.TurnRate, ThrustNewtons = tuning.ThrustNewtons, HoverMaxAltitudeM = tuning.HoverMaxAltitudeM, ArmorPerCell = tuning.ArmorPerCell, Conductivity = tuning.Conductivity, BaseCellThermalMass = tuning.BaseCellThermalMass, CargoCapacity = tuning.CargoCapacity, HalfWidth = boundsSize[0] * 0.5f, HalfHeight = boundsSize[1] * 0.5f, HalfLength = boundsSize[2] * 0.5f, ModelAsset = $"{id}.glb", DefaultLoadout = new Dictionary(tuning.DefaultLoadout, StringComparer.Ordinal), Hardpoints = hardpoints, Joints = joints, Mechanisms = mechanisms, PartCells = partCells }; } private static List ParseHardpoints( string vehicleId, JsonElement hpsElem, JsonElement gltf, VehicleTuning tuning) { var rtdAnchors = new HashSet(StringComparer.Ordinal); if (gltf.TryGetProperty("nodes", out var nodes)) { foreach (var n in nodes.EnumerateArray()) { if (n.TryGetProperty("extras", out var ex) && ex.TryGetProperty("rtd.id", out var rtdId) && rtdId.ValueKind == JsonValueKind.String) { rtdAnchors.Add(rtdId.GetString()!); } } } var list = new List(); foreach (var hp in hpsElem.EnumerateArray()) { string hpId = hp.GetProperty("id").GetString()!; string modelNodeId = hp.GetProperty("modelNodeId").GetString()!; if (!rtdAnchors.Contains(modelNodeId)) { throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.id\"] == '{modelNodeId}'."); } var kind = Enum.Parse(hp.GetProperty("kind").GetString()!, ignoreCase: true); int x = hp.GetProperty("x").GetInt32(); int y = hp.GetProperty("y").GetInt32(); int w = hp.GetProperty("w").GetInt32(); int h = hp.GetProperty("h").GetInt32(); HardpointTune tune = tuning.HardpointTuning.TryGetValue(hpId, out var found) ? found : new HardpointTune(ArmorBonus: kind == HardpointKind.Armor ? 14f : (kind == HardpointKind.Engine ? 8f : 6f)); list.Add(new VehicleHardpointRecord { Id = hpId, AnchorId = modelNodeId, Kind = kind, X = x, Y = y, W = w, H = h, MinPitchDeg = tune.MinPitchDeg, MaxPitchDeg = tune.MaxPitchDeg, IsWideArc = tune.IsWideArc, ArmorBonus = tune.ArmorBonus }); } return list; } private static List ParseJoints(string vehicleId, JsonElement jointsElem, JsonElement gltf) { var nodeByJointId = new Dictionary(StringComparer.Ordinal); if (gltf.TryGetProperty("nodes", out var nodes)) { foreach (var n in nodes.EnumerateArray()) { if (n.TryGetProperty("extras", out var ex) && ex.TryGetProperty("rtd.joint", out var rtdJoint) && rtdJoint.ValueKind == JsonValueKind.String) { string jid = rtdJoint.GetString()!; string nodeName = n.TryGetProperty("name", out var nm) ? nm.GetString() ?? jid : jid; nodeByJointId[jid] = nodeName; } } } var list = new List(); foreach (var j in jointsElem.EnumerateArray()) { string jid = j.GetProperty("id").GetString()!; if (!nodeByJointId.TryGetValue(jid, out var nodeName)) { throw new InvalidOperationException($"{vehicleId}: GLB missing extras[\"rtd.joint\"] == '{jid}'."); } list.Add(new VehicleJointRecord { Id = jid, NodeName = nodeName, Axis = j.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), MinVal = j.GetProperty("min").GetSingle(), MaxVal = j.GetProperty("max").GetSingle() }); } return list; } private static VehicleMechanismsRecord ParseMechanisms(JsonElement mechElem) { var rec = new VehicleMechanismsRecord { Frame = mechElem.GetProperty("frame").GetString() ?? string.Empty, RootOrigin = mechElem.GetProperty("rootOrigin").EnumerateArray().Select(e => e.GetSingle()).ToArray() }; if (mechElem.TryGetProperty("dofs", out var dofsElem)) { foreach (var d in dofsElem.EnumerateArray()) { float? damp = null; float? hz = null; if (d.TryGetProperty("compliance", out var comp) && comp.ValueKind == JsonValueKind.Object) { if (comp.TryGetProperty("damping_ratio", out var dr)) damp = dr.GetSingle(); if (comp.TryGetProperty("hertz", out var h)) hz = h.GetSingle(); } rec.Dofs.Add(new MechanismDofRecord { Name = d.GetProperty("name").GetString()!, Parent = d.GetProperty("parent").GetInt32(), Kind = d.GetProperty("kind").GetString()!, Mechanism = d.TryGetProperty("mechanism", out var m) && m.ValueKind == JsonValueKind.String ? m.GetString() : null, Side = d.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, Origin = d.GetProperty("origin").EnumerateArray().Select(e => e.GetSingle()).ToArray(), Axis = d.GetProperty("axis").EnumerateArray().Select(e => e.GetSingle()).ToArray(), Lo = d.GetProperty("lo").GetSingle(), Hi = d.GetProperty("hi").GetSingle(), Depth = d.GetProperty("depth").GetInt32(), StoppedBy = d.TryGetProperty("stopped_by", out var sb) && sb.ValueKind == JsonValueKind.String ? sb.GetString() : null, ComplianceDampingRatio = damp, ComplianceHertz = hz }); } } if (mechElem.TryGetProperty("rams", out var ramsElem)) { foreach (var r in ramsElem.EnumerateArray()) { rec.Rams.Add(new MechanismRamRecord { Name = r.GetProperty("name").GetString()!, BarrelBone = r.GetProperty("barrel_bone").GetString()!, RodBone = r.GetProperty("rod_bone").GetString()!, Spans = r.TryGetProperty("spans", out var sp) ? sp.EnumerateArray().Select(e => e.GetString()!).ToArray() : Array.Empty(), Bore = r.TryGetProperty("bore", out var br) && br.ValueKind == JsonValueKind.Number ? br.GetSingle() : 0f, Body = r.TryGetProperty("body", out var bd) && bd.ValueKind == JsonValueKind.Number ? bd.GetSingle() : 0f, Inner = r.TryGetProperty("inner", out var inn) && inn.ValueKind == JsonValueKind.Number ? inn.GetSingle() : 0f, Extension = r.TryGetProperty("extension", out var ext) && ext.ValueKind == JsonValueKind.Number ? ext.GetSingle() : 0f, Rest = r.TryGetProperty("rest", out var rst) && rst.ValueKind == JsonValueKind.Number ? rst.GetSingle() : 0f, Stroke = r.TryGetProperty("stroke", out var st) && st.ValueKind == JsonValueKind.Array ? st.EnumerateArray().Select(e => e.GetSingle()).ToArray() : Array.Empty(), AParentDof = r.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, APos = r.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, BParentDof = r.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, BPos = r.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, PinDir = r.TryGetProperty("pin_dir", out var pd) && pd.ValueKind == JsonValueKind.Array ? pd.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null }); } } if (mechElem.TryGetProperty("scissors", out var scissorsElem)) { foreach (var sc in scissorsElem.EnumerateArray()) { rec.Scissors.Add(new MechanismScissorRecord { Name = sc.GetProperty("name").GetString()!, UpperBone = sc.GetProperty("upper_bone").GetString()!, LowerBone = sc.GetProperty("lower_bone").GetString()!, Arm = sc.TryGetProperty("arm", out var arm) && arm.ValueKind == JsonValueKind.Number ? arm.GetSingle() : 0f, AParentDof = sc.TryGetProperty("a_parent_dof", out var apd) && apd.ValueKind == JsonValueKind.Number ? apd.GetInt32() : null, APos = sc.TryGetProperty("a_pos", out var ap) && ap.ValueKind == JsonValueKind.Array ? ap.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, BParentDof = sc.TryGetProperty("b_parent_dof", out var bpd) && bpd.ValueKind == JsonValueKind.Number ? bpd.GetInt32() : null, BPos = sc.TryGetProperty("b_pos", out var bp) && bp.ValueKind == JsonValueKind.Array ? bp.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null, OutDir = sc.TryGetProperty("out_dir", out var od) && od.ValueKind == JsonValueKind.Array ? od.EnumerateArray().Select(e => e.GetSingle()).ToArray() : null }); } } if (mechElem.TryGetProperty("struts", out var strutsElem)) { foreach (var st in strutsElem.EnumerateArray()) { rec.Struts.Add(new MechanismStrutRecord { Name = st.GetProperty("name").GetString()!, Side = st.TryGetProperty("side", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null, Dof = st.GetProperty("dof").GetString()!, Travel = st.GetProperty("travel").GetSingle(), Hertz = st.GetProperty("hertz").GetSingle(), DampingRatio = st.GetProperty("damping_ratio").GetSingle() }); } } return rec; } private static (byte[] JsonBytes, byte[] BinBytes) ReadGlbChunks(string glbPath) { byte[] data = File.ReadAllBytes(glbPath); if (data.Length < 20) throw new InvalidDataException($"{glbPath}: GLB too small."); 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."); uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4)); uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4)); if (jsonType != 0x4E4F534A) throw new InvalidDataException($"{glbPath}: first chunk is not JSON."); byte[] jsonBytes = data.AsSpan(20, (int)jsonLen).ToArray(); byte[] binBytes = Array.Empty(); int binOff = 20 + (int)jsonLen; if (binOff + 8 <= data.Length) { uint binLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff, 4)); uint binType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(binOff + 4, 4)); if (binType == 0x004E4942) { binBytes = data.AsSpan(binOff + 8, (int)binLen).ToArray(); } } return (jsonBytes, binBytes); } private static List ComputePartCells( JsonElement gltf, byte[] binBlob, GridPlane plane, int gw, int gh, bool[] mask, float[] boundsMin, float[] boundsMax) { var nodes = gltf.GetProperty("nodes").EnumerateArray().ToArray(); var meshes = gltf.GetProperty("meshes").EnumerateArray().ToArray(); var accessors = gltf.GetProperty("accessors").EnumerateArray().ToArray(); var bufferViews = gltf.GetProperty("bufferViews").EnumerateArray().ToArray(); var parentOf = new Dictionary(); for (int i = 0; i < nodes.Length; i++) { if (nodes[i].TryGetProperty("children", out var ch)) { foreach (var c in ch.EnumerateArray()) { parentOf[c.GetInt32()] = i; } } } // Exclude hardpoint slot_frame.* subtrees and rtd.id anchor subtrees var hpNodeSet = new HashSet(); void MarkSubtree(int idx) { if (!hpNodeSet.Add(idx)) return; if (nodes[idx].TryGetProperty("children", out var ch)) { foreach (var c in ch.EnumerateArray()) { MarkSubtree(c.GetInt32()); } } } for (int i = 0; i < nodes.Length; i++) { string nodeName = nodes[i].TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : ""; bool isSlotFrame = nodeName.StartsWith("slot_frame.", StringComparison.Ordinal); bool hasRtdId = nodes[i].TryGetProperty("extras", out var ex) && ex.TryGetProperty("rtd.id", out _); if (isSlotFrame || hasRtdId) { if (parentOf.TryGetValue(i, out int p) && nodes[p].TryGetProperty("name", out var pnm) && (pnm.GetString() ?? "").StartsWith("slot_frame.", StringComparison.Ordinal)) { MarkSubtree(p); } else { MarkSubtree(i); } } } var rootIndices = new List(); if (gltf.TryGetProperty("scenes", out var scenes) && scenes.GetArrayLength() > 0) { int sceneIdx = gltf.TryGetProperty("scene", out var si) ? si.GetInt32() : 0; foreach (var r in scenes[sceneIdx].GetProperty("nodes").EnumerateArray()) { rootIndices.Add(r.GetInt32()); } } else { for (int i = 0; i < nodes.Length; i++) { if (!parentOf.ContainsKey(i)) rootIndices.Add(i); } } float spanX = MathF.Max(1e-4f, boundsMax[0] - boundsMin[0]); float spanY = MathF.Max(1e-4f, boundsMax[1] - boundsMin[1]); float spanZ = MathF.Max(1e-4f, boundsMax[2] - boundsMin[2]); var results = new List(); var visited = new HashSet(); void Walk(int nodeIdx, Matrix4x4 parentWorld) { if (!visited.Add(nodeIdx)) return; var node = nodes[nodeIdx]; Matrix4x4 local = ReadNodeLocalMatrix(node); // Column-vector math: world = parentWorld * local; System.Numerics uses row-vectors for Transform, so multiply in reverse order Matrix4x4 world = local * parentWorld; if (!hpNodeSet.Contains(nodeIdx) && node.TryGetProperty("mesh", out var meshProp)) { int meshIdx = meshProp.GetInt32(); Vector3 centroid = ComputeMeshWorldCentroid(meshes[meshIdx], accessors, bufferViews, binBlob, world); // +X is vehicle LEFT (cell x=0), -X is vehicle RIGHT (cell x=gw-1) float ux = Math.Clamp((boundsMax[0] - centroid.X) / spanX, 0f, 1f); // Dorsal: +Z is FRONT (cell y=0), -Z is REAR (cell y=gh-1) // Coronal: +Y is TOP (cell y=0), minY is FEET (cell y=gh-1) float uy = plane == GridPlane.Dorsal ? Math.Clamp((boundsMax[2] - centroid.Z) / spanZ, 0f, 1f) : Math.Clamp((boundsMax[1] - centroid.Y) / spanY, 0f, 1f); float targetX = ux * (gw - 1); float targetY = uy * (gh - 1); (int cellX, int cellY) = FindNearestActiveCell(targetX, targetY, gw, gh, mask); string nodeName = node.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{nodeIdx}" : $"node_{nodeIdx}"; string partKind = ClassifyPartKind(nodeName); results.Add(new VehiclePartCellRecord { NodeName = nodeName, CellX = cellX, CellY = cellY, Kind = partKind }); } if (node.TryGetProperty("children", out var ch)) { foreach (var c in ch.EnumerateArray()) { Walk(c.GetInt32(), world); } } } foreach (int r in rootIndices) { Walk(r, Matrix4x4.Identity); } return results; } private static Matrix4x4 ReadNodeLocalMatrix(JsonElement node) { if (node.TryGetProperty("matrix", out var mElem)) { float[] m = mElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); // glTF stores column-major 4x4; System.Numerics Matrix4x4 fields M11..M44 match row-major so transpose on construction return new Matrix4x4( m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } Vector3 scale = Vector3.One; if (node.TryGetProperty("scale", out var sElem)) { float[] s = sElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); scale = new Vector3(s[0], s[1], s[2]); } Quaternion rot = Quaternion.Identity; if (node.TryGetProperty("rotation", out var rElem)) { float[] r = rElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); rot = new Quaternion(r[0], r[1], r[2], r[3]); } Vector3 trans = Vector3.Zero; if (node.TryGetProperty("translation", out var tElem)) { float[] t = tElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); trans = new Vector3(t[0], t[1], t[2]); } return Matrix4x4.CreateScale(scale) * Matrix4x4.CreateFromQuaternion(rot) * Matrix4x4.CreateTranslation(trans); } private static Vector3 ComputeMeshWorldCentroid( JsonElement mesh, JsonElement[] accessors, JsonElement[] bufferViews, byte[] binBlob, Matrix4x4 world) { Vector3 sum = Vector3.Zero; long count = 0; foreach (var prim in mesh.GetProperty("primitives").EnumerateArray()) { if (!prim.TryGetProperty("attributes", out var attrs) || !attrs.TryGetProperty("POSITION", out var posIdxElem)) { continue; } var acc = accessors[posIdxElem.GetInt32()]; int accCount = acc.GetProperty("count").GetInt32(); int compType = acc.GetProperty("componentType").GetInt32(); string accType = acc.GetProperty("type").GetString() ?? ""; if (binBlob.Length > 0 && acc.TryGetProperty("bufferView", out var bvIdxElem) && compType == 5126 && accType == "VEC3") { var bv = bufferViews[bvIdxElem.GetInt32()]; int bvOff = bv.TryGetProperty("byteOffset", out var bo) ? bo.GetInt32() : 0; int accOff = acc.TryGetProperty("byteOffset", out var ao) ? ao.GetInt32() : 0; int stride = bv.TryGetProperty("byteStride", out var bs) ? bs.GetInt32() : 12; int offset = bvOff + accOff; for (int i = 0; i < accCount; i++) { int p = offset + i * stride; float x = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p, 4)); float y = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 4, 4)); float z = BinaryPrimitives.ReadSingleLittleEndian(binBlob.AsSpan(p + 8, 4)); sum += Vector3.Transform(new Vector3(x, y, z), world); count++; } } else if (acc.TryGetProperty("min", out var minElem) && acc.TryGetProperty("max", out var maxElem)) { float[] mn = minElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); float[] mx = maxElem.EnumerateArray().Select(e => e.GetSingle()).ToArray(); var mid = new Vector3((mn[0] + mx[0]) * 0.5f, (mn[1] + mx[1]) * 0.5f, (mn[2] + mx[2]) * 0.5f); sum += Vector3.Transform(mid, world); count++; } } return count > 0 ? sum / count : world.Translation; } private static (int X, int Y) FindNearestActiveCell(float targetX, float targetY, int gw, int gh, bool[] mask) { int bestX = 0; int bestY = 0; float bestDistSq = float.PositiveInfinity; for (int y = 0; y < gh; y++) { for (int x = 0; x < gw; x++) { if (!mask[y * gw + x]) continue; float dx = x - targetX; float dy = y - targetY; float d2 = dx * dx + dy * dy; if (d2 < bestDistSq) { bestDistSq = d2; bestX = x; bestY = y; } } } return (bestX, bestY); } private static string ClassifyPartKind(string nodeName) { string lower = nodeName.ToLowerInvariant(); if (lower.StartsWith("shroud.", StringComparison.Ordinal) || lower.Contains("shroud")) return "shroud"; if (lower.Contains("armor") || lower.Contains("plate") || lower.Contains("glacis") || lower.Contains("skirt") || lower.Contains("shield") || lower.Contains("fender") || lower.Contains("bullbar") || lower.Contains("bumper") || lower.Contains("collar") || lower.Contains("cheek") || lower.Contains("cowling") || lower.Contains("greave")) return "armor"; if (lower.Contains("wheel") || lower.Contains("tire") || lower.Contains("track") || lower.Contains("rotor") || lower.Contains("blade") || lower.Contains("spinner") || lower.Contains("nacelle")) return "mobility"; return "hull"; } private static Dictionary BuildTunings() { return new Dictionary(StringComparer.Ordinal) { ["jackal"] = new( Mobility: MobilityKind.Wheeled, MassKg: 950f, MaxSpeed: 34f, TurnRate: 4.2f, ThrustNewtons: 14500f, HoverMaxAltitudeM: 0f, ArmorPerCell: 24f, Conductivity: 8.0f, BaseCellThermalMass: 10f, CargoCapacity: 4, DefaultLoadout: new() { ["hp.weapon.roof"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.rear"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.roof"] = new(5f, -15f, 45f), ["hp.engine.rear"] = new(5f), ["hp.radiator.rear"] = new(0f) }), ["mule"] = new( Mobility: MobilityKind.Wheeled, MassKg: 1850f, MaxSpeed: 29f, TurnRate: 3.3f, ThrustNewtons: 23500f, HoverMaxAltitudeM: 0f, ArmorPerCell: 34f, Conductivity: 8.5f, BaseCellThermalMass: 13f, CargoCapacity: 6, DefaultLoadout: new() { ["hp.weapon.cab"] = "mg_762", ["hp.weapon.bed_main"] = "autocannon", ["hp.engine.front"] = "turbo_core", ["hp.radiator.left"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.front"] = new(12f), ["hp.radiator.left"] = new(0f), ["hp.engine.front"] = new(6f), ["hp.radiator.right"] = new(0f), ["hp.weapon.cab"] = new(6f, -15f, 45f), ["hp.weapon.bed_main"] = new(8f, -12f, 35f) }), ["ferret"] = new( Mobility: MobilityKind.Tracked, MassKg: 1450f, MaxSpeed: 28f, TurnRate: 3.8f, ThrustNewtons: 21000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 32f, Conductivity: 8.5f, BaseCellThermalMass: 12f, CargoCapacity: 5, DefaultLoadout: new() { ["hp.weapon.turret"] = "autocannon", ["hp.weapon.pod"] = "mg_762", ["hp.engine.rear"] = "diesel_core", ["hp.radiator.deck"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.glacis"] = new(14f), ["hp.weapon.pod"] = new(6f, -15f, 45f), ["hp.weapon.turret"] = new(10f, -10f, 32f), ["hp.engine.rear"] = new(6f), ["hp.radiator.deck"] = new(0f) }), ["ironclad"] = new( Mobility: MobilityKind.Tracked, MassKg: 3600f, MaxSpeed: 22f, TurnRate: 2.4f, ThrustNewtons: 34000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 54f, Conductivity: 9.5f, BaseCellThermalMass: 17f, CargoCapacity: 8, DefaultLoadout: new() { ["hp.weapon.main"] = "recoilless", ["hp.weapon.coax"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.front"] = new(22f), ["hp.weapon.coax"] = new(10f, -10f, 40f), ["hp.weapon.main"] = new(18f, -10f, 30f), ["hp.armor.skirts"] = new(14f), ["hp.radiator.l"] = new(0f), ["hp.engine.rear"] = new(10f), ["hp.radiator.r"] = new(0f) }), ["mammoth"] = new( Mobility: MobilityKind.Wheeled, MassKg: 3900f, MaxSpeed: 24f, TurnRate: 2.3f, ThrustNewtons: 37000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 52f, Conductivity: 9.5f, BaseCellThermalMass: 16f, CargoCapacity: 8, DefaultLoadout: new() { ["hp.weapon.turret_l"] = "autocannon", ["hp.weapon.turret_r"] = "autocannon", ["hp.weapon.bow"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.glacis"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.glacis"] = new(20f), ["hp.weapon.bow"] = new(10f, -15f, 45f), ["hp.weapon.turret_l"] = new(15f, -10f, 30f), ["hp.weapon.turret_r"] = new(15f, -10f, 30f), ["hp.armor.flanks"] = new(14f), ["hp.engine.rear"] = new(10f), ["hp.radiator.l"] = new(0f), ["hp.radiator.r"] = new(0f) }), ["anvil"] = new( Mobility: MobilityKind.Tracked, MassKg: 4800f, MaxSpeed: 19f, TurnRate: 2.0f, ThrustNewtons: 42000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 66f, Conductivity: 9.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, DefaultLoadout: new() { ["hp.weapon.siege_l"] = "autocannon", ["hp.weapon.siege_r"] = "autocannon", ["hp.weapon.sponson_l"] = "mg_762", ["hp.engine.rear"] = "turbo_core", ["hp.radiator.l"] = "copper_rad", ["hp.armor.front"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.front"] = new(26f), ["hp.weapon.sponson_l"] = new(14f, -10f, 30f), ["hp.weapon.siege_l"] = new(18f, -10f, 30f), ["hp.armor.sides"] = new(18f), ["hp.weapon.siege_r"] = new(18f, -10f, 30f), ["hp.weapon.sponson_r"] = new(14f, -10f, 30f), ["hp.engine.rear"] = new(12f), ["hp.radiator.l"] = new(0f), ["hp.radiator.r"] = new(0f) }), ["hornet"] = new( Mobility: MobilityKind.Vtol, MassKg: 820f, MaxSpeed: 42f, TurnRate: 4.8f, ThrustNewtons: 18500f, HoverMaxAltitudeM: 42f, ArmorPerCell: 14f, Conductivity: 9.0f, BaseCellThermalMass: 9f, CargoCapacity: 4, DefaultLoadout: new() { ["hp.weapon.chin"] = "autocannon", ["hp.weapon.wing_l"] = "mg_762", ["hp.weapon.wing_r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.nacelle_l"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.chin"] = new(2f, -55f, 20f), ["hp.radiator.nacelle_l"] = new(0f), ["hp.radiator.nacelle_r"] = new(0f), ["hp.weapon.wing_l"] = new(2f, -55f, 20f), ["hp.engine.core"] = new(4f), ["hp.weapon.wing_r"] = new(2f, -55f, 20f) }), ["condor"] = new( Mobility: MobilityKind.Vtol, MassKg: 1950f, MaxSpeed: 35f, TurnRate: 3.6f, ThrustNewtons: 32000f, HoverMaxAltitudeM: 36f, ArmorPerCell: 22f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 7, DefaultLoadout: new() { ["hp.weapon.sponson_l"] = "autocannon", ["hp.weapon.sponson_r"] = "autocannon", ["hp.weapon.nose"] = "mg_762", ["hp.weapon.dorsal"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.spine_l"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.nose"] = new(4f, -55f, 20f), ["hp.armor.hull"] = new(8f), ["hp.weapon.sponson_l"] = new(4f, -55f, 20f), ["hp.weapon.dorsal"] = new(4f, -10f, 85f, IsWideArc: true), ["hp.weapon.sponson_r"] = new(4f, -55f, 20f), ["hp.engine.core"] = new(6f), ["hp.radiator.spine_l"] = new(0f), ["hp.radiator.spine_r"] = new(0f) }), ["manticore"] = new( Mobility: MobilityKind.Walker, MassKg: 2800f, MaxSpeed: 26f, TurnRate: 3.6f, ThrustNewtons: 34500f, HoverMaxAltitudeM: 0f, ArmorPerCell: 46f, Conductivity: 11.0f, BaseCellThermalMass: 15f, CargoCapacity: 7, DefaultLoadout: new() { ["hp.weapon.chin"] = "flak", ["hp.weapon.l"] = "mg_762", ["hp.weapon.r"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.flank_l"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.chin"] = new(10f, -15f, 45f), ["hp.radiator.flank_l"] = new(4f), ["hp.engine.core"] = new(12f), ["hp.radiator.flank_r"] = new(4f), ["hp.weapon.l"] = new(8f, -15f, 45f), ["hp.weapon.r"] = new(8f, -15f, 45f), ["hp.armor.prow"] = new(18f) }), ["bastion"] = new( Mobility: MobilityKind.Walker, MassKg: 4600f, MaxSpeed: 20f, TurnRate: 2.4f, ThrustNewtons: 46000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 64f, Conductivity: 11.5f, BaseCellThermalMass: 19f, CargoCapacity: 9, DefaultLoadout: new() { ["hp.weapon.turret_main"] = "recoilless", ["hp.weapon.turret_pd"] = "pd_flak", ["hp.weapon.flank_l"] = "autocannon", ["hp.engine.core"] = "turbo_core", ["hp.radiator.rear_l"] = "copper_rad", ["hp.armor.prow"] = "welded_plate" }, HardpointTuning: new() { ["hp.armor.prow"] = new(24f), ["hp.weapon.turret_pd"] = new(10f, -10f, 85f, IsWideArc: true), ["hp.weapon.turret_main"] = new(20f, -10f, 30f), ["hp.weapon.flank_l"] = new(12f, -10f, 35f), ["hp.weapon.flank_r"] = new(12f, -10f, 35f), ["hp.engine.core"] = new(14f), ["hp.radiator.rear_l"] = new(0f), ["hp.radiator.rear_r"] = new(0f) }), ["kestrel"] = new( Mobility: MobilityKind.Walker, MassKg: 1650f, MaxSpeed: 34f, TurnRate: 4.6f, ThrustNewtons: 27500f, HoverMaxAltitudeM: 0f, ArmorPerCell: 32f, Conductivity: 10.0f, BaseCellThermalMass: 12f, CargoCapacity: 5, DefaultLoadout: new() { ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.dorsal"] = "mg_762", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.dorsal"] = new(8f, -10f, 85f, IsWideArc: true), ["hp.armor.chest"] = new(14f), ["hp.radiator.back"] = new(4f), ["hp.engine.core"] = new(10f), ["hp.weapon.arm_r"] = new(8f, -15f, 45f) }), ["raptor"] = new( Mobility: MobilityKind.Walker, MassKg: 2300f, MaxSpeed: 30f, TurnRate: 4.1f, ThrustNewtons: 33000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 42f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.sh_l"] = "copper_rad" }, HardpointTuning: new() { ["hp.radiator.sh_l"] = new(4f), ["hp.radiator.sh_r"] = new(4f), ["hp.weapon.arm_l"] = new(8f, -15f, 45f), ["hp.engine.chest"] = new(12f), ["hp.weapon.arm_r"] = new(8f, -15f, 45f) }), ["spectre"] = new( Mobility: MobilityKind.Walker, MassKg: 2450f, MaxSpeed: 31f, TurnRate: 4.2f, ThrustNewtons: 35000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 44f, Conductivity: 10.5f, BaseCellThermalMass: 14f, CargoCapacity: 6, DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "pd_flak", ["hp.engine.core"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad" }, HardpointTuning: new() { ["hp.weapon.shoulder_l"] = new(8f, -10f, 85f, IsWideArc: true), ["hp.armor.torso"] = new(16f), ["hp.weapon.arm_l"] = new(10f, -15f, 45f), ["hp.radiator.back_l"] = new(4f), ["hp.engine.core"] = new(12f), ["hp.radiator.back_r"] = new(4f), ["hp.weapon.arm_r"] = new(10f, -15f, 45f) }), ["breaker"] = new( Mobility: MobilityKind.Walker, MassKg: 3800f, MaxSpeed: 24f, TurnRate: 3.0f, ThrustNewtons: 41000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 56f, Conductivity: 11.0f, BaseCellThermalMass: 17f, CargoCapacity: 8, DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.shoulder_l"] = "mg_762", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, HardpointTuning: new() { ["hp.weapon.arm_l"] = new(12f, -15f, 45f), ["hp.weapon.arm_r"] = new(12f, -15f, 45f), ["hp.weapon.shoulder_l"] = new(10f, -10f, 85f, IsWideArc: true), ["hp.armor.torso"] = new(20f), ["hp.engine.chest"] = new(14f), ["hp.radiator.back_l"] = new(6f), ["hp.radiator.back_r"] = new(6f) }), ["paladin"] = new( Mobility: MobilityKind.Walker, MassKg: 4100f, MaxSpeed: 22f, TurnRate: 2.7f, ThrustNewtons: 43000f, HoverMaxAltitudeM: 0f, ArmorPerCell: 58f, Conductivity: 11.5f, BaseCellThermalMass: 18f, CargoCapacity: 9, DefaultLoadout: new() { ["hp.weapon.arm_l"] = "autocannon", ["hp.weapon.arm_r"] = "autocannon", ["hp.weapon.sh_l"] = "pd_flak", ["hp.engine.chest"] = "turbo_core", ["hp.radiator.back_l"] = "copper_rad", ["hp.armor.torso"] = "welded_plate" }, HardpointTuning: new() { ["hp.weapon.sh_l"] = new(12f, -10f, 85f, IsWideArc: true), ["hp.armor.torso"] = new(22f), ["hp.weapon.sh_r"] = new(12f, -10f, 85f, IsWideArc: true), ["hp.weapon.arm_l"] = new(12f, -15f, 45f), ["hp.engine.chest"] = new(16f), ["hp.weapon.arm_r"] = new(12f, -15f, 45f), ["hp.radiator.back_l"] = new(6f), ["hp.armor.legs"] = new(20f), ["hp.radiator.back_r"] = new(6f) }), }; } } }