diff --git a/Directory.Build.props b/Directory.Build.props index 76736aa..047d29f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,5 +2,7 @@ $(YMIR_ROOT) $(MSBuildThisFileDirectory)..\Ymir + $(CULTLIB_ROOT) + $(MSBuildThisFileDirectory)..\CultLib diff --git a/assets/vehicles/anvil/vehicle.cc b/assets/vehicles/anvil/vehicle.cc new file mode 100644 index 0000000..1e82918 Binary files /dev/null and b/assets/vehicles/anvil/vehicle.cc differ diff --git a/assets/vehicles/bastion/vehicle.cc b/assets/vehicles/bastion/vehicle.cc new file mode 100644 index 0000000..db90253 Binary files /dev/null and b/assets/vehicles/bastion/vehicle.cc differ diff --git a/assets/vehicles/breaker/vehicle.cc b/assets/vehicles/breaker/vehicle.cc new file mode 100644 index 0000000..28f7554 Binary files /dev/null and b/assets/vehicles/breaker/vehicle.cc differ diff --git a/assets/vehicles/condor/vehicle.cc b/assets/vehicles/condor/vehicle.cc new file mode 100644 index 0000000..ba2ef62 Binary files /dev/null and b/assets/vehicles/condor/vehicle.cc differ diff --git a/assets/vehicles/ferret/vehicle.cc b/assets/vehicles/ferret/vehicle.cc new file mode 100644 index 0000000..d2a9452 Binary files /dev/null and b/assets/vehicles/ferret/vehicle.cc differ diff --git a/assets/vehicles/hornet/vehicle.cc b/assets/vehicles/hornet/vehicle.cc new file mode 100644 index 0000000..e3321d1 Binary files /dev/null and b/assets/vehicles/hornet/vehicle.cc differ diff --git a/assets/vehicles/ironclad/vehicle.cc b/assets/vehicles/ironclad/vehicle.cc new file mode 100644 index 0000000..b121484 Binary files /dev/null and b/assets/vehicles/ironclad/vehicle.cc differ diff --git a/assets/vehicles/jackal/vehicle.cc b/assets/vehicles/jackal/vehicle.cc new file mode 100644 index 0000000..86378ee Binary files /dev/null and b/assets/vehicles/jackal/vehicle.cc differ diff --git a/assets/vehicles/kestrel/vehicle.cc b/assets/vehicles/kestrel/vehicle.cc new file mode 100644 index 0000000..f3734f4 Binary files /dev/null and b/assets/vehicles/kestrel/vehicle.cc differ diff --git a/assets/vehicles/mammoth/vehicle.cc b/assets/vehicles/mammoth/vehicle.cc new file mode 100644 index 0000000..00c244d Binary files /dev/null and b/assets/vehicles/mammoth/vehicle.cc differ diff --git a/assets/vehicles/manticore/vehicle.cc b/assets/vehicles/manticore/vehicle.cc new file mode 100644 index 0000000..d740b50 Binary files /dev/null and b/assets/vehicles/manticore/vehicle.cc differ diff --git a/assets/vehicles/mule/vehicle.cc b/assets/vehicles/mule/vehicle.cc new file mode 100644 index 0000000..043b8f1 Binary files /dev/null and b/assets/vehicles/mule/vehicle.cc differ diff --git a/assets/vehicles/paladin/vehicle.cc b/assets/vehicles/paladin/vehicle.cc new file mode 100644 index 0000000..460cd19 Binary files /dev/null and b/assets/vehicles/paladin/vehicle.cc differ diff --git a/assets/vehicles/raptor/vehicle.cc b/assets/vehicles/raptor/vehicle.cc new file mode 100644 index 0000000..faa2ec4 Binary files /dev/null and b/assets/vehicles/raptor/vehicle.cc differ diff --git a/assets/vehicles/spectre/vehicle.cc b/assets/vehicles/spectre/vehicle.cc new file mode 100644 index 0000000..831aaeb Binary files /dev/null and b/assets/vehicles/spectre/vehicle.cc differ diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs index 233ddec..235ebac 100644 --- a/src/RustToDust.Core/GridChassis.cs +++ b/src/RustToDust.Core/GridChassis.cs @@ -9,6 +9,14 @@ namespace RustToDust.Core Coronal } + public enum MobilityKind + { + Wheeled, + Tracked, + Vtol, + Walker + } + public enum HardpointKind { Weapon, @@ -25,7 +33,10 @@ namespace RustToDust.Core int Y, int Width, int Height, - float ArmorBonus); + float ArmorBonus, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f, + bool IsWideArc = false); public sealed record ModuleSpec( string Id, @@ -50,7 +61,10 @@ namespace RustToDust.Core float FireCooldown, float ProjectileSpeed, float SpreadRad, - int BurstCount) + int BurstCount, + bool IsWideArc = false, + float MinPitchDeg = -15f, + float MaxPitchDeg = 45f) { /// /// Exact Aetheria trapezoidal plateau curve: @@ -102,11 +116,18 @@ namespace RustToDust.Core float HalfWidth, float HalfHeight, float HalfLength, - int CargoCapacity) + int CargoCapacity, + MobilityKind Mobility = MobilityKind.Wheeled, + float HoverMaxAltitudeM = 0f, + string VehicleClass = "") { public bool IsWalker => + Mobility == MobilityKind.Walker || Plane == GridPlane.Coronal || - string.Equals(Id, "manticore", StringComparison.OrdinalIgnoreCase); + string.Equals(Id, "manticore", StringComparison.OrdinalIgnoreCase) || + string.Equals(Id, "bastion", StringComparison.OrdinalIgnoreCase); + + public bool IsVtol => Mobility == MobilityKind.Vtol; public bool IsActive(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height && Mask[y * Width + x]; @@ -267,6 +288,32 @@ namespace RustToDust.Core return true; } + public HardpointSpec? FindFirstEmptyCompatibleHardpoint(ModuleSpec mod) + { + for (int i = 0; i < Spec.Hardpoints.Length; i++) + { + var hp = Spec.Hardpoints[i]; + if (GetMountedOn(hp.Id) is null && CanFit(hp, mod)) + { + return hp; + } + } + return null; + } + + public bool TryQuickBoltOrCargo(ModuleSpec mod, out string? boltedHardpointId) + { + var freeHp = FindFirstEmptyCompatibleHardpoint(mod); + if (freeHp is not null && TryMount(mod, freeHp.Id)) + { + boltedHardpointId = freeHp.Id; + return true; + } + + boltedHardpointId = null; + return TryAddCargo(mod); + } + public void InjectHeat(int x, int y, float heat) { if (!Spec.IsActive(x, y) || heat == 0f) diff --git a/src/RustToDust.Core/RustToDust.Core.csproj b/src/RustToDust.Core/RustToDust.Core.csproj index ddca8fa..04d0cf7 100644 --- a/src/RustToDust.Core/RustToDust.Core.csproj +++ b/src/RustToDust.Core/RustToDust.Core.csproj @@ -6,4 +6,9 @@ disable + + + + + diff --git a/src/RustToDust.Core/VehicleCatalogLoader.cs b/src/RustToDust.Core/VehicleCatalogLoader.cs new file mode 100644 index 0000000..3336ffe --- /dev/null +++ b/src/RustToDust.Core/VehicleCatalogLoader.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace RustToDust.Core +{ + public static class VehicleCatalogLoader + { + public static string LocateVehiclesDirectory() + { + string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); + if (!string.IsNullOrWhiteSpace(envRoot)) + { + string envVehicles = Path.Combine(envRoot, "vehicles"); + if (HasVehiclePackages(envVehicles)) + { + return Path.GetFullPath(envVehicles); + } + } + + foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) + { + if (string.IsNullOrWhiteSpace(start) || !Directory.Exists(start)) + { + continue; + } + + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); + if (HasVehiclePackages(candidate)) + { + return candidate; + } + dir = dir.Parent; + } + } + + throw new DirectoryNotFoundException( + $"Could not locate 'assets/vehicles' containing vehicle.cc packages from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); + } + + private static bool HasVehiclePackages(string vehiclesDir) + { + if (!Directory.Exists(vehiclesDir)) + { + return false; + } + return Directory.EnumerateFiles(vehiclesDir, "vehicle.cc", SearchOption.AllDirectories).Any(); + } + + public static IReadOnlyList<(VehiclePackage Package, ChassisSpec Spec)> LoadAll(string? vehiclesDirectory = null) + { + string root = vehiclesDirectory ?? LocateVehiclesDirectory(); + if (!Directory.Exists(root)) + { + throw new DirectoryNotFoundException($"Vehicles directory not found: {root}"); + } + + var results = new List<(VehiclePackage Package, ChassisSpec Spec)>(); + foreach (string dir in Directory.GetDirectories(root).OrderBy(d => d, StringComparer.Ordinal)) + { + string ccPath = Path.Combine(dir, "vehicle.cc"); + if (!File.Exists(ccPath)) + { + continue; + } + + var pkg = VehiclePackageStore.Read(ccPath); + var spec = pkg.ToChassisSpec(); + results.Add((pkg, spec)); + } + + if (results.Count == 0) + { + throw new InvalidOperationException($"No vehicle.cc archives found under {root}."); + } + + return results; + } + } +} diff --git a/src/RustToDust.Core/VehiclePackage.cs b/src/RustToDust.Core/VehiclePackage.cs new file mode 100644 index 0000000..2d8a0b0 --- /dev/null +++ b/src/RustToDust.Core/VehiclePackage.cs @@ -0,0 +1,339 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [CultDocument("rtd.vehicle_package", "1"), MessagePackObject] + public sealed class VehiclePackage + { + [CultName, Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string Name { get; set; } = string.Empty; + [Key(2)] public string VehicleClass { get; set; } = string.Empty; + [Key(3)] public MobilityKind Mobility { get; set; } + [Key(4)] public GridPlane Plane { get; set; } + [Key(5)] public int GridWidth { get; set; } + [Key(6)] public int GridHeight { get; set; } + [Key(7)] public string[] Mask { get; set; } = Array.Empty(); + [Key(8)] public float MassKg { get; set; } + [Key(9)] public float MaxSpeed { get; set; } + [Key(10)] public float TurnRate { get; set; } + [Key(11)] public float ThrustNewtons { get; set; } + [Key(12)] public float HoverMaxAltitudeM { get; set; } + [Key(13)] public float ArmorPerCell { get; set; } + [Key(14)] public float Conductivity { get; set; } + [Key(15)] public int CargoCapacity { get; set; } + [Key(16)] public float HalfWidth { get; set; } + [Key(17)] public float HalfHeight { get; set; } + [Key(18)] public float HalfLength { get; set; } + [Key(19)] public string ModelAsset { get; set; } = string.Empty; + [Key(20)] public Dictionary DefaultLoadout { get; set; } = new(); + [Key(21)] public List Hardpoints { get; set; } = new(); + [Key(22)] public List Joints { get; set; } = new(); + [Key(23)] public VehicleMechanismsRecord? Mechanisms { get; set; } + [Key(24)] public List PartCells { get; set; } = new(); + [Key(25)] public float BaseCellThermalMass { get; set; } = 12f; + + public ChassisSpec ToChassisSpec() + { + bool[] boolMask = ParseMaskRows(Mask, GridWidth, GridHeight); + var hps = new HardpointSpec[Hardpoints.Count]; + for (int i = 0; i < Hardpoints.Count; i++) + { + var hp = Hardpoints[i]; + hps[i] = new HardpointSpec( + Id: hp.Id, + Kind: hp.Kind, + X: hp.X, + Y: hp.Y, + Width: hp.W, + Height: hp.H, + ArmorBonus: hp.ArmorBonus, + MinPitchDeg: hp.MinPitchDeg, + MaxPitchDeg: hp.MaxPitchDeg, + IsWideArc: hp.IsWideArc); + } + + return new ChassisSpec( + Id: Id, + Name: Name, + Plane: Plane, + Width: GridWidth, + Height: GridHeight, + Mask: boolMask, + Hardpoints: hps, + HullConductivity: Conductivity, + BaseCellThermalMass: BaseCellThermalMass, + BaseCellArmor: ArmorPerCell, + MassKg: MassKg, + BaseThrust: ThrustNewtons, + BaseTurnRate: TurnRate, + MaxSpeed: MaxSpeed, + HalfWidth: HalfWidth, + HalfHeight: HalfHeight, + HalfLength: HalfLength, + CargoCapacity: CargoCapacity, + Mobility: Mobility, + HoverMaxAltitudeM: HoverMaxAltitudeM, + VehicleClass: VehicleClass); + } + + public static bool[] ParseMaskRows(string[] rows, int width, int height) + { + if (rows.Length != height) + { + throw new InvalidOperationException($"Mask row count {rows.Length} != GridHeight {height}."); + } + + var mask = new bool[width * height]; + for (int y = 0; y < height; y++) + { + if (rows[y].Length != width) + { + throw new InvalidOperationException($"Mask row {y} length {rows[y].Length} != GridWidth {width}."); + } + for (int x = 0; x < width; x++) + { + mask[y * width + x] = rows[y][x] == '#'; + } + } + return mask; + } + } + + [MessagePackObject] + public sealed class VehicleHardpointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string AnchorId { get; set; } = string.Empty; + [Key(2)] public HardpointKind Kind { get; set; } + [Key(3)] public int X { get; set; } + [Key(4)] public int Y { get; set; } + [Key(5)] public int W { get; set; } + [Key(6)] public int H { get; set; } + [Key(7)] public float MinPitchDeg { get; set; } + [Key(8)] public float MaxPitchDeg { get; set; } + [Key(9)] public bool IsWideArc { get; set; } + [Key(10)] public float ArmorBonus { get; set; } + [Key(11), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleJointRecord + { + [Key(0)] public string Id { get; set; } = string.Empty; + [Key(1)] public string NodeName { get; set; } = string.Empty; + [Key(2)] public float[] Axis { get; set; } = Array.Empty(); + [Key(3)] public float MinVal { get; set; } + [Key(4)] public float MaxVal { get; set; } + [Key(5), CultElementId(nameof(Id))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehiclePartCellRecord + { + [Key(0)] public string NodeName { get; set; } = string.Empty; + [Key(1)] public int CellX { get; set; } + [Key(2)] public int CellY { get; set; } + [Key(3)] public string Kind { get; set; } = string.Empty; + [Key(4), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class VehicleMechanismsRecord + { + [Key(0)] public string Frame { get; set; } = string.Empty; + [Key(1)] public float[] RootOrigin { get; set; } = Array.Empty(); + [Key(2)] public List Dofs { get; set; } = new(); + [Key(3)] public List Rams { get; set; } = new(); + [Key(4)] public List Scissors { get; set; } = new(); + [Key(5)] public List Struts { get; set; } = new(); + } + + [MessagePackObject] + public sealed class MechanismDofRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public int Parent { get; set; } + [Key(2)] public string Kind { get; set; } = string.Empty; + [Key(3)] public string? Mechanism { get; set; } + [Key(4)] public string? Side { get; set; } + [Key(5)] public float[] Origin { get; set; } = Array.Empty(); + [Key(6)] public float[] Axis { get; set; } = Array.Empty(); + [Key(7)] public float Lo { get; set; } + [Key(8)] public float Hi { get; set; } + [Key(9)] public int Depth { get; set; } + [Key(10)] public string? StoppedBy { get; set; } + [Key(11)] public float? ComplianceDampingRatio { get; set; } + [Key(12)] public float? ComplianceHertz { get; set; } + [Key(13), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismRamRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string BarrelBone { get; set; } = string.Empty; + [Key(2)] public string RodBone { get; set; } = string.Empty; + [Key(3)] public string[] Spans { get; set; } = Array.Empty(); + [Key(4)] public float Bore { get; set; } + [Key(5)] public float Body { get; set; } + [Key(6)] public float Inner { get; set; } + [Key(7)] public float Extension { get; set; } + [Key(8)] public float Rest { get; set; } + [Key(9)] public float[] Stroke { get; set; } = Array.Empty(); + [Key(10)] public int? AParentDof { get; set; } + [Key(11)] public float[]? APos { get; set; } + [Key(12)] public int? BParentDof { get; set; } + [Key(13)] public float[]? BPos { get; set; } + [Key(14)] public float[]? PinDir { get; set; } + [Key(15), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismScissorRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string UpperBone { get; set; } = string.Empty; + [Key(2)] public string LowerBone { get; set; } = string.Empty; + [Key(3)] public float Arm { get; set; } + [Key(4)] public int? AParentDof { get; set; } + [Key(5)] public float[]? APos { get; set; } + [Key(6)] public int? BParentDof { get; set; } + [Key(7)] public float[]? BPos { get; set; } + [Key(8)] public float[]? OutDir { get; set; } + [Key(9), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class MechanismStrutRecord + { + [Key(0)] public string Name { get; set; } = string.Empty; + [Key(1)] public string? Side { get; set; } + [Key(2)] public string Dof { get; set; } = string.Empty; + [Key(3)] public float Travel { get; set; } + [Key(4)] public float Hertz { get; set; } + [Key(5)] public float DampingRatio { get; set; } + [Key(6), CultElementId(nameof(Name))] public string ElementId { get; set; } = string.Empty; + } + + public static class VehiclePackageStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(VehiclePackage) }); + + public static CultRecordKey PackageKey(string id) => new("vehicle:" + id); + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static VehiclePackage Read(string path) + { + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Vehicle package archive not found: {path}", path); + } + + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length != 1) + { + throw new InvalidOperationException($"{path} must contain exactly 1 VehiclePackage record, found {records.Length}."); + } + + var pkg = records[0]; + Validate(pkg, path); + return pkg; + } + + public static void Write(string path, VehiclePackage pkg) + { + if (pkg is null) throw new ArgumentNullException(nameof(pkg)); + Validate(pkg, path); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "vehicle.cc"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(VehiclePackage), pkg, PackageKey(pkg.Id)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + + public static void Validate(VehiclePackage pkg, string sourcePath) + { + if (string.IsNullOrWhiteSpace(pkg.Id)) + throw new InvalidOperationException($"{sourcePath}: VehiclePackage.Id is empty."); + if (string.IsNullOrWhiteSpace(pkg.ModelAsset)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: ModelAsset is empty."); + if (pkg.GridWidth <= 0 || pkg.GridHeight <= 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: invalid grid dimensions {pkg.GridWidth}x{pkg.GridHeight}."); + + bool[] mask = VehiclePackage.ParseMaskRows(pkg.Mask, pkg.GridWidth, pkg.GridHeight); + foreach (var hp in pkg.Hardpoints) + { + if (string.IsNullOrWhiteSpace(hp.Id) || string.IsNullOrWhiteSpace(hp.AnchorId)) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint has empty Id or AnchorId."); + if (hp.X < 0 || hp.Y < 0 || hp.W <= 0 || hp.H <= 0 || hp.X + hp.W > pkg.GridWidth || hp.Y + hp.H > pkg.GridHeight) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} out of grid bounds."); + for (int cy = hp.Y; cy < hp.Y + hp.H; cy++) + { + for (int cx = hp.X; cx < hp.X + hp.W; cx++) + { + if (!mask[cy * pkg.GridWidth + cx]) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: hardpoint {hp.Id} covers inactive cell ({cx},{cy})."); + } + } + } + + if (pkg.PartCells.Count == 0) + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCells is empty."); + + foreach (var pc in pkg.PartCells) + { + if (pc.CellX < 0 || pc.CellX >= pkg.GridWidth || pc.CellY < 0 || pc.CellY >= pkg.GridHeight || !mask[pc.CellY * pkg.GridWidth + pc.CellX]) + { + throw new InvalidOperationException($"{sourcePath}: {pkg.Id}: PartCell '{pc.NodeName}' mapped to inactive/out-of-bounds cell ({pc.CellX},{pc.CellY})."); + } + } + } + } +} diff --git a/tools/VehiclePacker/Program.cs b/tools/VehiclePacker/Program.cs new file mode 100644 index 0000000..7e0d6af --- /dev/null +++ b/tools/VehiclePacker/Program.cs @@ -0,0 +1,924 @@ +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) + }), + }; + } + } +} diff --git a/tools/VehiclePacker/VehiclePacker.csproj b/tools/VehiclePacker/VehiclePacker.csproj new file mode 100644 index 0000000..a53a965 --- /dev/null +++ b/tools/VehiclePacker/VehiclePacker.csproj @@ -0,0 +1,14 @@ + + + + Exe + net10.0 + enable + disable + + + + + + +